forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

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