forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

convert.rs56 lines, 2.0 KiBHistoryRawDownload
1//! I420 -> BGRA8 (straight alpha), BT.601 limited range.
2
3/// Converts a planar I420 frame (stride == width, chroma at half resolution)
4/// into tightly packed BGRA8. Returns `width * height * 4` bytes.
5pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -> Vec<u8> {
6 let cw = width.div_ceil(2);
7 let mut out = vec![0u8; width * height * 4];
8
9 for row in 0..height {
10 let y_row = row * width;
11 let c_row = (row / 2) * cw;
12 for col in 0..width {
13 let c = y[y_row + col] as i32 - 16;
14 let ci = c_row + col / 2;
15 let d = u[ci] as i32 - 128;
16 let e = v[ci] as i32 - 128;
17
18 let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8;
19 let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8;
20 let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8;
21
22 let o = (y_row + col) * 4;
23 out[o] = b;
24 out[o + 1] = g;
25 out[o + 2] = r;
26 out[o + 3] = 255;
27 }
28 }
29 out
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35
36 #[test]
37 fn known_colors() {
38 // 2x2 blocks so each shares one chroma sample.
39 // Black (limited range Y=16), white (Y=235), and a saturated red.
40 let cases: [([u8; 3], [u8; 3]); 3] = [
41 ([16, 128, 128], [0, 0, 0]),
42 ([235, 128, 128], [255, 255, 255]),
43 ([82, 90, 240], [255, 0, 0]), // BT.601 red primary -> R=255,G~0,B~0
44 ];
45 for ([yv, uv, vv], [r, g, b]) in cases {
46 let out = i420_to_bgra(&[yv; 4], &[uv], &[vv], 2, 2);
47 assert_eq!(out.len(), 2 * 2 * 4);
48 for px in out.chunks_exact(4) {
49 assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);
50 assert!(px[1].abs_diff(g) <= 2, "G {} vs {}", px[1], g);
51 assert!(px[2].abs_diff(r) <= 2, "R {} vs {}", px[2], r);
52 assert_eq!(px[3], 255);
53 }
54 }
55 }
56}