forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6dae2b4Tahinli3 months ago555 commits

convert.rs296 lines, 11.3 KiBHistoryRawDownload
1//! I420 -> BGRA8 (straight alpha), in the matrix and range the *stream* says
2//! its samples were coded against (see [`crate::colorspace`]).
3
4use crate::colorspace::{ColorDescription, Matrix};
5
6/// One stream's YUV->RGB matrix as 8.8 fixed point, derived once per frame so
7/// the loop below stays the multiply-and-shift it always was.
8struct Coeffs {
9 /// What luma is measured from: 16 for limited range, 0 for full.
10 y_off: i32,
11 y: i32,
12 rv: i32,
13 gu: i32,
14 gv: i32,
15 bu: i32,
16}
17
18impl Coeffs {
19 /// The inverse of the matrix itself, out of its two luma weights (ITU-R
20 /// BT.601 §2.5.1, BT.709 §3, BT.2020 Table 4), with `Kg = 1 - Kr - Kb`:
21 ///
22 /// ```text
23 /// R = Y + 2(1 - Kr) Cr
24 /// G = Y - 2Kb(1 - Kb)/Kg Cb - 2Kr(1 - Kr)/Kg Cr
25 /// B = Y + 2(1 - Kb) Cb
26 /// ```
27 ///
28 /// where `Y` is 0..1 and `Cb`/`Cr` are -0.5..0.5. What turns bytes into
29 /// those is the *range* (ITU-T H.273 §5.4): limited-range luma spans codes
30 /// 16..235 and chroma 16..240, so a code is worth 255/219 and 255/224 of
31 /// the scale respectively; full-range samples span the whole byte and both
32 /// scales are 1, which is what a JFIF still or a `-color_range pc` encode
33 /// carries.
34 ///
35 /// BT.601 limited comes out as exactly the 298/409/-100/-208/516 this
36 /// engine hardcoded before it read a single colour tag, so SD material is
37 /// byte for byte the picture it always was (`bt601_limited_is_the_legacy_matrix`).
38 fn new(color: &ColorDescription) -> Self {
39 // tonemap lands here: a PQ or HLG stream is converted with its own
40 // matrix and then shown as if its curve were SDR -- which is what this
41 // engine did with it before, only in the wrong matrix. The curve is a
42 // pass over the RGB coming out of the loop, not a coefficient.
43 let (kr, kb) = match color.matrix {
44 Matrix::Bt601 => (0.299, 0.114),
45 Matrix::Bt709 => (0.2126, 0.0722),
46 Matrix::Bt2020Ncl => (0.2627, 0.0593),
47 };
48 let kg = 1.0 - kr - kb;
49 let (y_off, y_scale, c_scale) = if color.full_range {
50 (0, 1.0, 1.0)
51 } else {
52 (16, 255.0 / 219.0, 255.0 / 224.0)
53 };
54 let q = |v: f64| (v * 256.0).round() as i32;
55 Self {
56 y_off,
57 y: q(y_scale),
58 rv: q(2.0 * (1.0 - kr) * c_scale),
59 gu: q(2.0 * kb * (1.0 - kb) / kg * c_scale),
60 gv: q(2.0 * kr * (1.0 - kr) / kg * c_scale),
61 bu: q(2.0 * (1.0 - kb) * c_scale),
62 }
63 }
64}
65
66/// Converts a planar I420 frame (stride == width, chroma at half resolution)
67/// into tightly packed BGRA8. Returns `width * height * 4` bytes.
68pub fn i420_to_bgra(
69 color: &ColorDescription,
70 y: &[u8],
71 u: &[u8],
72 v: &[u8],
73 width: usize,
74 height: usize,
75) -> Vec<u8> {
76 let k = Coeffs::new(color);
77 let cw = width.div_ceil(2);
78 let mut out = vec![0u8; width * height * 4];
79
80 for row in 0..height {
81 let y_row = row * width;
82 let c_row = (row / 2) * cw;
83 for col in 0..width {
84 let c = y[y_row + col] as i32 - k.y_off;
85 let ci = c_row + col / 2;
86 let d = u[ci] as i32 - 128;
87 let e = v[ci] as i32 - 128;
88
89 let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8;
90 let g = ((k.y * c - k.gu * d - k.gv * e + 128) >> 8).clamp(0, 255) as u8;
91 let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8;
92
93 let o = (y_row + col) * 4;
94 out[o] = b;
95 out[o + 1] = g;
96 out[o + 2] = r;
97 out[o + 3] = 255;
98 }
99 }
100 out
101}
102
103/// The same conversion with a segment's colour grade folded in: the grade is
104/// three table lookups per pixel inside the loop that was reading those samples
105/// anyway, and measured free: 4.73 ms/frame against 4.74 for the ungraded
106/// conversion, where grading a scratch copy of the planes first costs a further
107/// 0.61 (1920x1080, release, `perf_1080p` below).
108///
109/// Identity params take the ungraded loop above, byte for byte.
110pub fn i420_to_bgra_with(
111 color: &ColorDescription,
112 params: &crate::color::ColorParams,
113 y: &[u8],
114 u: &[u8],
115 v: &[u8],
116 width: usize,
117 height: usize,
118) -> Vec<u8> {
119 if params.is_identity() {
120 return i420_to_bgra(color, y, u, v, width, height);
121 }
122 let k = Coeffs::new(color);
123 let lut = crate::color::Lut::new(params);
124 let cw = width.div_ceil(2);
125 let mut out = vec![0u8; width * height * 4];
126
127 for row in 0..height {
128 let y_row = row * width;
129 let c_row = (row / 2) * cw;
130 for col in 0..width {
131 let c = lut.y[y[y_row + col] as usize] as i32 - k.y_off;
132 let ci = c_row + col / 2;
133 let d = lut.u[u[ci] as usize] as i32 - 128;
134 let e = lut.v[v[ci] as usize] as i32 - 128;
135
136 let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8;
137 let g = ((k.y * c - k.gu * d - k.gv * e + 128) >> 8).clamp(0, 255) as u8;
138 let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8;
139
140 let o = (y_row + col) * 4;
141 out[o] = b;
142 out[o + 1] = g;
143 out[o + 2] = r;
144 out[o + 3] = 255;
145 }
146 }
147 out
148}
149
150#[cfg(test)]
151mod tests {
152 use super::*;
153 use crate::color::ColorParams;
154
155 /// BT.601 limited: what the tests that predate the colour tags measured,
156 /// and what they have to keep measuring.
157 const SD: ColorDescription = ColorDescription {
158 matrix: Matrix::Bt601,
159 transfer: crate::colorspace::Transfer::Sdr,
160 full_range: false,
161 };
162
163 /// Limited-range BT.601, the one every stream was converted as before the
164 /// colour tags were read: the derivation has to land on the exact integers
165 /// that were hardcoded, or SD material shifts under a change that was only
166 /// ever meant to leave it alone.
167 #[test]
168 fn bt601_limited_is_the_legacy_matrix() {
169 let k = Coeffs::new(&ColorDescription::default());
170 assert_eq!(
171 (k.y_off, k.y, k.rv, k.gu, k.gv, k.bu),
172 (16, 298, 409, 100, 208, 516)
173 );
174 }
175
176 /// The render path's half of the charter invariant: an ungraded segment is
177 /// the untouched converter, not a grade that happens to round back.
178 #[test]
179 fn identity_grade_converts_identically() {
180 let y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
181 let u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
182 let v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
183 assert_eq!(
184 i420_to_bgra_with(&SD, &ColorParams::default(), &y, &u, &v, 64, 48),
185 i420_to_bgra(&SD, &y, &u, &v, 64, 48)
186 );
187 }
188
189 /// Fused must equal grading the planes first and converting after -- that is
190 /// what makes the export path (which grades a scratch copy before the
191 /// encoder) and the render path show the same picture.
192 #[test]
193 fn fused_matches_grade_then_convert() {
194 let params = ColorParams {
195 brightness: 0.1,
196 contrast: 1.3,
197 saturation: 0.4,
198 tint: 0.25,
199 };
200 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
201 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
202 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
203 let fused = i420_to_bgra_with(&SD, &params, &y, &u, &v, 64, 48);
204 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);
205 assert_eq!(fused, i420_to_bgra(&SD, &y, &u, &v, 64, 48));
206 }
207
208 /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come
209 /// from here. `cargo test -p engine --release convert:: -- --nocapture`.
210 #[test]
211 fn perf_1080p() {
212 let (w, h) = (1920usize, 1080usize);
213 let y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
214 let u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
215 let v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
216 let params = ColorParams {
217 brightness: 0.1,
218 contrast: 1.2,
219 saturation: 1.3,
220 tint: 0.2,
221 };
222 let runs = 20;
223 let bench = |name: &str, mut f: Box<dyn FnMut()>| {
224 let t = std::time::Instant::now();
225 for _ in 0..runs {
226 f();
227 }
228 println!(
229 "{name} 1920x1080: {:.3} ms/frame",
230 t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)
231 );
232 };
233 bench(
234 "i420_to_bgra ",
235 Box::new(|| {
236 std::hint::black_box(i420_to_bgra(&SD, &y, &u, &v, w, h));
237 }),
238 );
239 bench(
240 "i420_to_bgra_with ",
241 Box::new(|| {
242 std::hint::black_box(i420_to_bgra_with(&SD, &params, &y, &u, &v, w, h));
243 }),
244 );
245 bench(
246 "copy + apply_yuv ",
247 Box::new(|| {
248 let (mut y, mut u, mut v) = (y.clone(), u.clone(), v.clone());
249 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);
250 std::hint::black_box((y, u, v));
251 }),
252 );
253 }
254
255 fn desc(matrix: Matrix, full_range: bool) -> ColorDescription {
256 ColorDescription {
257 matrix,
258 full_range,
259 ..ColorDescription::default()
260 }
261 }
262
263 /// Each matrix against its own red primary -- the sample the matrices
264 /// disagree about most, and the one a wrong matrix turns visibly orange --
265 /// plus the two neutrals, which is where a wrong *range* shows instead.
266 #[test]
267 fn known_colors() {
268 // 2x2 blocks so each shares one chroma sample.
269 let cases: [(ColorDescription, [u8; 3], [u8; 3]); 9] = [
270 // Limited range: black is Y=16, white Y=235.
271 (desc(Matrix::Bt601, false), [16, 128, 128], [0, 0, 0]),
272 (desc(Matrix::Bt601, false), [235, 128, 128], [255, 255, 255]),
273 (desc(Matrix::Bt601, false), [82, 90, 240], [255, 0, 0]),
274 (desc(Matrix::Bt709, false), [16, 128, 128], [0, 0, 0]),
275 (desc(Matrix::Bt709, false), [235, 128, 128], [255, 255, 255]),
276 // BT.709's red primary sits at a *lower* luma than BT.601's (0.2126
277 // against 0.299): read with the 601 matrix it comes out dark.
278 (desc(Matrix::Bt709, false), [63, 102, 240], [255, 0, 0]),
279 (desc(Matrix::Bt2020Ncl, false), [74, 97, 240], [255, 0, 0]),
280 // Full range: no headroom, so Y=16 is a dark grey rather than black
281 // -- the case a limited-range conversion crushes to 0.
282 (desc(Matrix::Bt601, true), [16, 128, 128], [16, 16, 16]),
283 (desc(Matrix::Bt601, true), [76, 85, 255], [255, 0, 0]),
284 ];
285 for (color, [yv, uv, vv], [r, g, b]) in cases {
286 let out = i420_to_bgra(&color, &[yv; 4], &[uv], &[vv], 2, 2);
287 assert_eq!(out.len(), 2 * 2 * 4);
288 for px in out.chunks_exact(4) {
289 assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);
290 assert!(px[1].abs_diff(g) <= 2, "G {} vs {}", px[1], g);
291 assert!(px[2].abs_diff(r) <= 2, "R {} vs {}", px[2], r);
292 assert_eq!(px[3], 255);
293 }
294 }
295 }
296}