forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

convert.rs359 lines, 13.9 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/// One row band's worth of the conversion: `rows` are absolute row indices
67/// into `y`/`u`/`v` (chroma read at half resolution as ever), written into
68/// `out` from its own start (`out[0]` is the first row in `rows`). Pulled out
69/// of `i420_to_bgra`/`i420_to_bgra_with` so both can run it across disjoint
70/// row ranges on separate threads -- each row is independent (chroma only
71/// ever reads `row / 2`, never a neighbouring output row), so splitting the
72/// row loop changes nothing about what a pixel comes out as.
73/// The three I420 planes of one frame and the strides they are read at.
74#[derive(Clone, Copy)]
75struct Planes<'a> {
76 y: &'a [u8],
77 u: &'a [u8],
78 v: &'a [u8],
79 width: usize,
80 cw: usize,
81}
82
83fn convert_rows(
84 k: &Coeffs,
85 lut: Option<&crate::color::Lut>,
86 planes: Planes<'_>,
87 rows: std::ops::Range<usize>,
88 out: &mut [u8],
89) {
90 let Planes { y, u, v, width, cw } = planes;
91 for (i, row) in rows.enumerate() {
92 let y_row = row * width;
93 let c_row = (row / 2) * cw;
94 let o_row = i * width * 4;
95 for col in 0..width {
96 let ci = c_row + col / 2;
97 let (c, d, e) = match lut {
98 Some(lut) => (
99 lut.y[y[y_row + col] as usize] as i32 - k.y_off,
100 lut.u[u[ci] as usize] as i32 - 128,
101 lut.v[v[ci] as usize] as i32 - 128,
102 ),
103 None => (
104 y[y_row + col] as i32 - k.y_off,
105 u[ci] as i32 - 128,
106 v[ci] as i32 - 128,
107 ),
108 };
109
110 let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8;
111 let g = ((k.y * c - k.gu * d - k.gv * e + 128) >> 8).clamp(0, 255) as u8;
112 let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8;
113
114 let o = o_row + col * 4;
115 out[o] = b;
116 out[o + 1] = g;
117 out[o + 2] = r;
118 out[o + 3] = 255;
119 }
120 }
121}
122
123/// `convert_rows`, fanned out over as many threads as the machine has: rows
124/// split into one contiguous band per lane (`std::thread::scope`, the same
125/// pattern `HevcEnc::code_batch` uses, borrowing the planes rather than
126/// copying them), each lane writing straight into its own slice of `out`. A
127/// frame too short to be worth the spawn (or a machine that only reports one
128/// core) falls back to running the whole thing on the calling thread.
129fn convert_parallel(
130 k: &Coeffs,
131 lut: Option<&crate::color::Lut>,
132 y: &[u8],
133 u: &[u8],
134 v: &[u8],
135 width: usize,
136 height: usize,
137) -> Vec<u8> {
138 let cw = width.div_ceil(2);
139 let planes = Planes { y, u, v, width, cw };
140 let mut out = vec![0u8; width * height * 4];
141 let lanes = std::thread::available_parallelism()
142 .map_or(1, |n| n.get())
143 .min(height);
144 if lanes <= 1 {
145 convert_rows(k, lut, planes, 0..height, &mut out);
146 return out;
147 }
148 let rows_per_lane = height.div_ceil(lanes);
149 std::thread::scope(|scope| {
150 let mut rest = &mut out[..];
151 let mut start = 0;
152 while start < height {
153 let end = (start + rows_per_lane).min(height);
154 let (chunk, remainder) = rest.split_at_mut((end - start) * width * 4);
155 rest = remainder;
156 scope.spawn(move || convert_rows(k, lut, planes, start..end, chunk));
157 start = end;
158 }
159 });
160 out
161}
162
163/// Converts a planar I420 frame (stride == width, chroma at half resolution)
164/// into tightly packed BGRA8. Returns `width * height * 4` bytes.
165pub fn i420_to_bgra(
166 color: &ColorDescription,
167 y: &[u8],
168 u: &[u8],
169 v: &[u8],
170 width: usize,
171 height: usize,
172) -> Vec<u8> {
173 let k = Coeffs::new(color);
174 convert_parallel(&k, None, y, u, v, width, height)
175}
176
177/// The same conversion with a segment's colour grade folded in: the grade is
178/// three table lookups per pixel inside the loop that was reading those samples
179/// anyway, and measured free: 4.73 ms/frame against 4.74 for the ungraded
180/// conversion, where grading a scratch copy of the planes first costs a further
181/// 0.61 (1920x1080, release, `perf_1080p` below).
182///
183/// Identity params take the ungraded loop above, byte for byte.
184pub fn i420_to_bgra_with(
185 color: &ColorDescription,
186 params: &crate::color::ColorParams,
187 y: &[u8],
188 u: &[u8],
189 v: &[u8],
190 width: usize,
191 height: usize,
192) -> Vec<u8> {
193 if params.is_identity() {
194 return i420_to_bgra(color, y, u, v, width, height);
195 }
196 let k = Coeffs::new(color);
197 let lut = (!params.sliders_identity()).then(|| crate::color::Lut::new(params, color.full_range));
198 if params.look.is_identity() {
199 return convert_parallel(&k, lut.as_ref(), y, u, v, width, height);
200 }
201 // The look's RGB stage pairs every luma sample with its chroma, which this
202 // loop's table lookups cannot: it runs on a copy first, the sliders still
203 // fold into the conversion.
204 let looked = crate::color::ColorParams { look: params.look, ..Default::default() };
205 let (mut gy, mut gu, mut gv) = (y.to_vec(), u.to_vec(), v.to_vec());
206 crate::color::apply_yuv(&looked, &mut gy, &mut gu, &mut gv, width, false);
207 convert_parallel(&k, lut.as_ref(), &gy, &gu, &gv, width, height)
208}
209
210#[cfg(test)]
211mod tests {
212 use super::*;
213 use crate::color::ColorParams;
214
215 /// BT.601 limited: what the tests that predate the colour tags measured,
216 /// and what they have to keep measuring.
217 const SD: ColorDescription = ColorDescription {
218 matrix: Matrix::Bt601,
219 transfer: crate::colorspace::Transfer::Sdr,
220 full_range: false,
221 };
222
223 /// Limited-range BT.601, the one every stream was converted as before the
224 /// colour tags were read: the derivation has to land on the exact integers
225 /// that were hardcoded, or SD material shifts under a change that was only
226 /// ever meant to leave it alone.
227 #[test]
228 fn bt601_limited_is_the_legacy_matrix() {
229 let k = Coeffs::new(&ColorDescription::default());
230 assert_eq!(
231 (k.y_off, k.y, k.rv, k.gu, k.gv, k.bu),
232 (16, 298, 409, 100, 208, 516)
233 );
234 }
235
236 /// The render path's half of the charter invariant: an ungraded segment is
237 /// the untouched converter, not a grade that happens to round back.
238 #[test]
239 fn identity_grade_converts_identically() {
240 let y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
241 let u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
242 let v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
243 assert_eq!(
244 i420_to_bgra_with(&SD, &ColorParams::default(), &y, &u, &v, 64, 48),
245 i420_to_bgra(&SD, &y, &u, &v, 64, 48)
246 );
247 }
248
249 /// Fused must equal grading the planes first and converting after -- that is
250 /// what makes the export path (which grades a scratch copy before the
251 /// encoder) and the render path show the same picture.
252 #[test]
253 fn fused_matches_grade_then_convert() {
254 let params = ColorParams {
255 brightness: 0.1,
256 contrast: 1.3,
257 saturation: 0.4,
258 tint: 0.25,
259 ..Default::default()
260 };
261 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
262 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
263 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
264 let fused = i420_to_bgra_with(&SD, &params, &y, &u, &v, 64, 48);
265 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v, 64, false);
266 assert_eq!(fused, i420_to_bgra(&SD, &y, &u, &v, 64, 48));
267 }
268
269 /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come
270 /// from here. `cargo test -p engine --release convert:: -- --nocapture`.
271 #[test]
272 #[ignore = "perf: run with --ignored"]
273 fn perf_1080p() {
274 let (w, h) = (1920usize, 1080usize);
275 let y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
276 let u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
277 let v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
278 let params = ColorParams {
279 brightness: 0.1,
280 contrast: 1.2,
281 saturation: 1.3,
282 tint: 0.2,
283 ..Default::default()
284 };
285 let runs = 20;
286 let bench = |name: &str, mut f: Box<dyn FnMut()>| {
287 let t = std::time::Instant::now();
288 for _ in 0..runs {
289 f();
290 }
291 println!(
292 "{name} 1920x1080: {:.3} ms/frame",
293 t.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)
294 );
295 };
296 bench(
297 "i420_to_bgra ",
298 Box::new(|| {
299 std::hint::black_box(i420_to_bgra(&SD, &y, &u, &v, w, h));
300 }),
301 );
302 bench(
303 "i420_to_bgra_with ",
304 Box::new(|| {
305 std::hint::black_box(i420_to_bgra_with(&SD, &params, &y, &u, &v, w, h));
306 }),
307 );
308 bench(
309 "copy + apply_yuv ",
310 Box::new(|| {
311 let (mut y, mut u, mut v) = (y.clone(), u.clone(), v.clone());
312 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v, 64, false);
313 std::hint::black_box((y, u, v));
314 }),
315 );
316 }
317
318 fn desc(matrix: Matrix, full_range: bool) -> ColorDescription {
319 ColorDescription {
320 matrix,
321 full_range,
322 ..ColorDescription::default()
323 }
324 }
325
326 /// Each matrix against its own red primary -- the sample the matrices
327 /// disagree about most, and the one a wrong matrix turns visibly orange --
328 /// plus the two neutrals, which is where a wrong *range* shows instead.
329 #[test]
330 fn known_colors() {
331 // 2x2 blocks so each shares one chroma sample.
332 let cases: [(ColorDescription, [u8; 3], [u8; 3]); 9] = [
333 // Limited range: black is Y=16, white Y=235.
334 (desc(Matrix::Bt601, false), [16, 128, 128], [0, 0, 0]),
335 (desc(Matrix::Bt601, false), [235, 128, 128], [255, 255, 255]),
336 (desc(Matrix::Bt601, false), [82, 90, 240], [255, 0, 0]),
337 (desc(Matrix::Bt709, false), [16, 128, 128], [0, 0, 0]),
338 (desc(Matrix::Bt709, false), [235, 128, 128], [255, 255, 255]),
339 // BT.709's red primary sits at a *lower* luma than BT.601's (0.2126
340 // against 0.299): read with the 601 matrix it comes out dark.
341 (desc(Matrix::Bt709, false), [63, 102, 240], [255, 0, 0]),
342 (desc(Matrix::Bt2020Ncl, false), [74, 97, 240], [255, 0, 0]),
343 // Full range: no headroom, so Y=16 is a dark grey rather than black
344 // -- the case a limited-range conversion crushes to 0.
345 (desc(Matrix::Bt601, true), [16, 128, 128], [16, 16, 16]),
346 (desc(Matrix::Bt601, true), [76, 85, 255], [255, 0, 0]),
347 ];
348 for (color, [yv, uv, vv], [r, g, b]) in cases {
349 let out = i420_to_bgra(&color, &[yv; 4], &[uv], &[vv], 2, 2);
350 assert_eq!(out.len(), 2 * 2 * 4);
351 for px in out.as_chunks::<4>().0 {
352 assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);
353 assert!(px[1].abs_diff(g) <= 2, "G {} vs {}", px[1], g);
354 assert!(px[2].abs_diff(r) <= 2, "R {} vs {}", px[2], r);
355 assert_eq!(px[3], 255);
356 }
357 }
358 }
359}