forge
Explore
Log in

Don't you dare go Hollow

A picture is converted in the matrix its own file names, not in BT.601

Browse files at this commit

55b1c8dc45581413e522d4bfc9095d533b50e069Ahmet Kaan GümüşParent: 070ffe6
  • feat
    • a picture is converted in the matrix its own file names, not in BT.601
Show full message
✨ feat(colorspace): a picture is converted in the matrix its own file names, not in BT.601

Every displayed frame went through one hardcoded integer matrix -- BT.601
limited, 298/409/-100/-208/516 -- whatever the stream said it was. An HD or
UHD file read that way shifts: BT.709's red weight is 0.2126 against 0.601's
0.299, which is a visible cast on faces and saturated colour.

The two converters now take the `ColorDescription` the demuxers already
resolved, and derive their 8.8 coefficients from that matrix's two luma
weights and its range once per frame, so the pixel loop is the same
multiply-and-shift it was. BT.601 limited rounds to exactly the integers that
were hardcoded, so SD material is byte for byte the picture it always was.

Stills keep BT.601 on purpose: `rgb_to_i420` writes them in it, and the pair
round-trips. Transfer curves are untouched -- a PQ or HLG stream gets the
BT.2020 matrix and is still shown as SDR, with the seam marked.
crates/engine/src/convert.rsmodified+139 -24
@@ -1,8 +1,79 @@
1-//! I420 -> BGRA8 (straight alpha), BT.601 limited range.1+//! I420 -> BGRA8 (straight alpha), in the matrix and range the *stream* says
2+//! its samples were coded against (see [`crate::colorspace`]).
3+
4+use 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.
8+struct 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+
18+impl 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+}
2 65
3 /// Converts a planar I420 frame (stride == width, chroma at half resolution)66 /// Converts a planar I420 frame (stride == width, chroma at half resolution)
4 /// into tightly packed BGRA8. Returns `width * height * 4` bytes.67 /// into tightly packed BGRA8. Returns `width * height * 4` bytes.
5-pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -> Vec<u8> {68+pub 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);
6 let cw = width.div_ceil(2);77 let cw = width.div_ceil(2);
7 let mut out = vec![0u8; width * height * 4];78 let mut out = vec![0u8; width * height * 4];
8 79
@@ -10,14 +81,14 @@ pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -
10 let y_row = row * width;81 let y_row = row * width;
11 let c_row = (row / 2) * cw;82 let c_row = (row / 2) * cw;
12 for col in 0..width {83 for col in 0..width {
13- let c = y[y_row + col] as i32 - 16;84+ let c = y[y_row + col] as i32 - k.y_off;
14 let ci = c_row + col / 2;85 let ci = c_row + col / 2;
15 let d = u[ci] as i32 - 128;86 let d = u[ci] as i32 - 128;
16 let e = v[ci] as i32 - 128;87 let e = v[ci] as i32 - 128;
17 88
18- let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8;89+ let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8;
19- let g = ((298 * c - 100 * d - 208 * 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;
20- let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8;91+ let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8;
21 92
22 let o = (y_row + col) * 4;93 let o = (y_row + col) * 4;
23 out[o] = b;94 out[o] = b;
@@ -37,6 +108,7 @@ pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -
37 ///108 ///
38 /// Identity params take the ungraded loop above, byte for byte.109 /// Identity params take the ungraded loop above, byte for byte.
39 pub fn i420_to_bgra_with(110 pub fn i420_to_bgra_with(
111+ color: &ColorDescription,
40 params: &crate::color::ColorParams,112 params: &crate::color::ColorParams,
41 y: &[u8],113 y: &[u8],
42 u: &[u8],114 u: &[u8],
@@ -45,8 +117,9 @@ pub fn i420_to_bgra_with(
45 height: usize,117 height: usize,
46 ) -> Vec<u8> {118 ) -> Vec<u8> {
47 if params.is_identity() {119 if params.is_identity() {
48- return i420_to_bgra(y, u, v, width, height);120+ return i420_to_bgra(color, y, u, v, width, height);
49 }121 }
122+ let k = Coeffs::new(color);
50 let lut = crate::color::Lut::new(params);123 let lut = crate::color::Lut::new(params);
51 let cw = width.div_ceil(2);124 let cw = width.div_ceil(2);
52 let mut out = vec![0u8; width * height * 4];125 let mut out = vec![0u8; width * height * 4];
@@ -55,14 +128,14 @@ pub fn i420_to_bgra_with(
55 let y_row = row * width;128 let y_row = row * width;
56 let c_row = (row / 2) * cw;129 let c_row = (row / 2) * cw;
57 for col in 0..width {130 for col in 0..width {
58- let c = lut.y[y[y_row + col] as usize] as i32 - 16;131+ let c = lut.y[y[y_row + col] as usize] as i32 - k.y_off;
59 let ci = c_row + col / 2;132 let ci = c_row + col / 2;
60 let d = lut.u[u[ci] as usize] as i32 - 128;133 let d = lut.u[u[ci] as usize] as i32 - 128;
61 let e = lut.v[v[ci] as usize] as i32 - 128;134 let e = lut.v[v[ci] as usize] as i32 - 128;
62 135
63- let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8;136+ let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8;
64- let g = ((298 * c - 100 * d - 208 * 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;
65- let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8;138+ let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8;
66 139
67 let o = (y_row + col) * 4;140 let o = (y_row + col) * 4;
68 out[o] = b;141 out[o] = b;
@@ -79,6 +152,27 @@ mod tests {
79 use super::*;152 use super::*;
80 use crate::color::ColorParams;153 use crate::color::ColorParams;
81 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+
82 /// The render path's half of the charter invariant: an ungraded segment is176 /// The render path's half of the charter invariant: an ungraded segment is
83 /// the untouched converter, not a grade that happens to round back.177 /// the untouched converter, not a grade that happens to round back.
84 #[test]178 #[test]
@@ -87,8 +181,8 @@ mod tests {
87 let u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();181 let u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
88 let v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();182 let v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
89 assert_eq!(183 assert_eq!(
90- i420_to_bgra_with(&ColorParams::default(), &y, &u, &v, 64, 48),184+ i420_to_bgra_with(&SD, &ColorParams::default(), &y, &u, &v, 64, 48),
91- i420_to_bgra(&y, &u, &v, 64, 48)185+ i420_to_bgra(&SD, &y, &u, &v, 64, 48)
92 );186 );
93 }187 }
94 188
@@ -106,9 +200,9 @@ mod tests {
106 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();200 let mut y: Vec<u8> = (0..64 * 48).map(|i| (i % 256) as u8).collect();
107 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();201 let mut u: Vec<u8> = (0..32 * 24).map(|i| (i % 256) as u8).collect();
108 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();202 let mut v: Vec<u8> = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect();
109- let fused = i420_to_bgra_with(&params, &y, &u, &v, 64, 48);203+ let fused = i420_to_bgra_with(&SD, &params, &y, &u, &v, 64, 48);
110 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);204 crate::color::apply_yuv(&params, &mut y, &mut u, &mut v);
111- assert_eq!(fused, i420_to_bgra(&y, &u, &v, 64, 48));205+ assert_eq!(fused, i420_to_bgra(&SD, &y, &u, &v, 64, 48));
112 }206 }
113 207
114 /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come208 /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come
@@ -139,13 +233,13 @@ mod tests {
139 bench(233 bench(
140 "i420_to_bgra ",234 "i420_to_bgra ",
141 Box::new(|| {235 Box::new(|| {
142- std::hint::black_box(i420_to_bgra(&y, &u, &v, w, h));236+ std::hint::black_box(i420_to_bgra(&SD, &y, &u, &v, w, h));
143 }),237 }),
144 );238 );
145 bench(239 bench(
146 "i420_to_bgra_with ",240 "i420_to_bgra_with ",
147 Box::new(|| {241 Box::new(|| {
148- std::hint::black_box(i420_to_bgra_with(&params, &y, &u, &v, w, h));242+ std::hint::black_box(i420_to_bgra_with(&SD, &params, &y, &u, &v, w, h));
149 }),243 }),
150 );244 );
151 bench(245 bench(
@@ -158,17 +252,38 @@ mod tests {
158 );252 );
159 }253 }
160 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.
161 #[test]266 #[test]
162 fn known_colors() {267 fn known_colors() {
163 // 2x2 blocks so each shares one chroma sample.268 // 2x2 blocks so each shares one chroma sample.
164- // Black (limited range Y=16), white (Y=235), and a saturated red.269+ let cases: [(ColorDescription, [u8; 3], [u8; 3]); 9] = [
165- let cases: [([u8; 3], [u8; 3]); 3] = [270+ // Limited range: black is Y=16, white Y=235.
166- ([16, 128, 128], [0, 0, 0]),271+ (desc(Matrix::Bt601, false), [16, 128, 128], [0, 0, 0]),
167- ([235, 128, 128], [255, 255, 255]),272+ (desc(Matrix::Bt601, false), [235, 128, 128], [255, 255, 255]),
168- ([82, 90, 240], [255, 0, 0]), // BT.601 red primary -> R=255,G~0,B~0273+ (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]),
169 ];284 ];
170- for ([yv, uv, vv], [r, g, b]) in cases {285+ for (color, [yv, uv, vv], [r, g, b]) in cases {
171- let out = i420_to_bgra(&[yv; 4], &[uv], &[vv], 2, 2);286+ let out = i420_to_bgra(&color, &[yv; 4], &[uv], &[vv], 2, 2);
172 assert_eq!(out.len(), 2 * 2 * 4);287 assert_eq!(out.len(), 2 * 2 * 4);
173 for px in out.chunks_exact(4) {288 for px in out.chunks_exact(4) {
174 assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);289 assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b);
crates/engine/src/decode.rsmodified+30 -7
@@ -10,6 +10,7 @@ use std::thread;
10 use rusty_h264::Decoder;10 use rusty_h264::Decoder;
11 11
12 use crate::color::ColorParams;12 use crate::color::ColorParams;
13+use crate::colorspace::ColorDescription;
13 use crate::convert::{i420_to_bgra, i420_to_bgra_with};14 use crate::convert::{i420_to_bgra, i420_to_bgra_with};
14 use crate::demux::{Codec, Demuxer, VideoMeta};15 use crate::demux::{Codec, Demuxer, VideoMeta};
15 use crate::hw::HwSession;16 use crate::hw::HwSession;
@@ -319,7 +320,10 @@ impl DecodeSession {
319 }320 }
320 // The one conversion, on this thread: it is a few milliseconds and the321 // The one conversion, on this thread: it is a few milliseconds and the
321 // error it could raise has already been raised by `Still::open`.322 // error it could raise has already been raised by `Still::open`.
322- let first = Render::new(color, canvas).frame(323+ // BT.601 limited, because that is what `rgb_to_i420` above wrote these
324+ // planes in: a still round-trips through the pair, not through the
325+ // colour of whatever file is on the timeline beside it.
326+ let first = Render::new(color, ColorDescription::default(), canvas).frame(
323 start_frame,327 start_frame,
324 &still.y,328 &still.y,
325 &still.u,329 &still.u,
@@ -388,6 +392,9 @@ impl DecodeSession {
388 return Err(meta.codec.needs_plugin().into());392 return Err(meta.codec.needs_plugin().into());
389 }393 }
390 let end_frame = end_frame.min(meta.frame_count);394 let end_frame = end_frame.min(meta.frame_count);
395+ // Read off the file once, here, and carried into the worker: it is a
396+ // property of the stream, so it cannot change while one range decodes.
397+ let source_color = meta.color;
391 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the398 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
392 // decoder run ahead of the display without limit.399 // decoder run ahead of the display without limit.
393 let (tx, rx) = sync_channel(2);400 let (tx, rx) = sync_channel(2);
@@ -422,7 +429,7 @@ impl DecodeSession {
422 if worker_cancel.load(Ordering::Relaxed) {429 if worker_cancel.load(Ordering::Relaxed) {
423 return;430 return;
424 }431 }
425- let mut render = Render::new(color, canvas);432+ let mut render = Render::new(color, source_color, canvas);
426 // The plugin has to be opened on the thread that uses it: its433 // The plugin has to be opened on the thread that uses it: its
427 // VA-API state is not `Send`-safe across a later hand-off.434 // VA-API state is not `Send`-safe across a later hand-off.
428 if let Some(hw) = open_hw(&path, start_frame) {435 if let Some(hw) = open_hw(&path, start_frame) {
@@ -484,6 +491,10 @@ impl DecodeSession {
484 /// project resolution, byte for byte and allocation for allocation.491 /// project resolution, byte for byte and allocation for allocation.
485 struct Render {492 struct Render {
486 color: ColorParams,493 color: ColorParams,
494+ /// What the source's samples mean -- the stream's own matrix and range,
495+ /// which is what the conversion below is done in rather than the BT.601 it
496+ /// used to assume of every file.
497+ desc: ColorDescription,
487 canvas: Composer,498 canvas: Composer,
488 /// The graded copy of the source planes, refilled per frame and kept across499 /// The graded copy of the source planes, refilled per frame and kept across
489 /// the worker's whole range. Empty unless the clip is both graded *and*500 /// the worker's whole range. Empty unless the clip is both graded *and*
@@ -492,9 +503,10 @@ struct Render {
492 }503 }
493 504
494 impl Render {505 impl Render {
495- fn new(color: ColorParams, canvas: Composer) -> Self {506+ fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self {
496 Self {507 Self {
497 color,508 color,
509+ desc,
498 canvas,510 canvas,
499 graded: (Vec::new(), Vec::new(), Vec::new()),511 graded: (Vec::new(), Vec::new(), Vec::new()),
500 }512 }
@@ -514,7 +526,15 @@ impl Render {
514 index,526 index,
515 width,527 width,
516 height,528 height,
517- bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize),529+ bgra: i420_to_bgra_with(
530+ &self.desc,
531+ &self.color,
532+ y,
533+ u,
534+ v,
535+ width as usize,
536+ height as usize,
537+ ),
518 };538 };
519 }539 }
520 let (gy, gu, gv) = &mut self.graded;540 let (gy, gu, gv) = &mut self.graded;
@@ -537,7 +557,7 @@ impl Render {
537 height,557 height,
538 // Ungraded on purpose: the grade is already in the pixels above and558 // Ungraded on purpose: the grade is already in the pixels above and
539 // the canvas around them must stay the black it was filled with.559 // the canvas around them must stay the black it was filled with.
540- bgra: i420_to_bgra(y, u, v, width as usize, height as usize),560+ bgra: i420_to_bgra(&self.desc, y, u, v, width as usize, height as usize),
541 }561 }
542 }562 }
543 }563 }
@@ -612,8 +632,11 @@ pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
612 }632 }
613 633
614 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse634 /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
615-/// of [`crate::convert::i420_to_bgra`], so a still round-trips to the colour it635+/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
616-/// was authored in (`images::still_pixels_match_the_source_image` measures it).636+/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
637+/// not the timeline's. A still has no stream to be tagged by; it round-trips to
638+/// the colour it was authored in through this pair and nothing else sees these
639+/// planes (`images::still_pixels_match_the_source_image` measures it).
617 ///640 ///
618 /// Chroma is the 2x2 box average, and an odd edge averages the samples it has --641 /// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
619 /// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape642 /// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
crates/engine/tests/hw_decode.rsmodified+11 -2
@@ -16,7 +16,9 @@ use std::path::{Path, PathBuf};
16 use std::time::Instant;16 use std::time::Instant;
17 17
18 use engine::DecodeSession;18 use engine::DecodeSession;
19+use engine::colorspace::ColorDescription;
19 use engine::convert::i420_to_bgra;20 use engine::convert::i420_to_bgra;
21+use engine::demux::Demuxer;
20 use engine::hw::HwSession;22 use engine::hw::HwSession;
21 23
22 fn asset(name: &str) -> PathBuf {24 fn asset(name: &str) -> PathBuf {
@@ -25,6 +27,12 @@ fn asset(name: &str) -> PathBuf {
25 .join(name)27 .join(name)
26 }28 }
27 29
30+/// What the decode funnel converts this file's planes in, so a conversion done
31+/// by hand here is the one `DecodeSession` would have done.
32+fn color_of(path: &Path) -> ColorDescription {
33+ Demuxer::open(path).expect("open for colour").0.color
34+}
35+
28 fn open_hw(path: &Path) -> HwSession {36 fn open_hw(path: &Path) -> HwSession {
29 HwSession::open(path).expect("no hardware decode plugin/driver available")37 HwSession::open(path).expect("no hardware decode plugin/driver available")
30 }38 }
@@ -32,6 +40,7 @@ fn open_hw(path: &Path) -> HwSession {
32 /// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA).40 /// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA).
33 fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {41 fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
34 let path = asset(name);42 let path = asset(name);
43+ let color = color_of(&path);
35 let mut hw = open_hw(&path);44 let mut hw = open_hw(&path);
36 let meta = hw.meta().expect("meta");45 let meta = hw.meta().expect("meta");
37 assert_eq!(46 assert_eq!(
@@ -46,7 +55,7 @@ fn decode_all_hw(name: &str) -> (usize, Vec<u8>) {
46 while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") {55 while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") {
47 assert_eq!((w, h), (1280, 720), "{name} frame {count} dims");56 assert_eq!((w, h), (1280, 720), "{name} frame {count} dims");
48 if count == 30 {57 if count == 30 {
49- frame_30 = i420_to_bgra(y, u, v, w as usize, h as usize);58+ frame_30 = i420_to_bgra(&color, y, u, v, w as usize, h as usize);
50 }59 }
51 count += 1;60 count += 1;
52 }61 }
@@ -117,7 +126,7 @@ fn seek_matches_linear() {
117 .expect("no frame after hardware seek");126 .expect("no frame after hardware seek");
118 eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed());127 eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed());
119 assert_eq!(128 assert_eq!(
120- i420_to_bgra(y, u, v, w as usize, h as usize),129+ i420_to_bgra(&color_of(&path), y, u, v, w as usize, h as usize),
121 linear,130 linear,
122 "hardware seek != software linear"131 "hardware seek != software linear"
123 );132 );
crates/engine/tests/matrix_render.rsadded+91 -0
@@ -0,0 +1,91 @@
1+//! The stream's matrix reaching the picture a player shows, through the door
2+//! the window itself opens ([`PlaybackSession`]) rather than through the
3+//! converter alone.
4+//!
5+//! Two fixtures, one picture: `test_bt601.mkv` and `test_h264.mkv` are the same
6+//! `testsrc2` at 1280x720 through the same encoder, and their first frames were
7+//! byte-identical while every file was converted as BT.601 -- the FNV constant
8+//! below is that shared frame, measured before this change. What separates them
9+//! now is only what they *say*: the first tags SMPTE 170M in its container, the
10+//! second tags nothing and is 720 lines, so the heuristic calls it BT.709.
11+//!
12+//! ```text
13+//! cargo test -p engine --release --test matrix_render -- --test-threads=1
14+//! ```
15+
16+use std::path::PathBuf;
17+use std::time::{Duration, Instant};
18+
19+use engine::PlaybackSession;
20+use engine::colorspace::Matrix;
21+
22+/// Frame 0 of either fixture as the engine converted it before it read a single
23+/// colour tag: BT.601 limited, both files.
24+const LEGACY_601_FRAME: u64 = 0x872e_4f9c_4165_0c9e;
25+
26+fn asset(name: &str) -> PathBuf {
27+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
28+ .join("../../assets")
29+ .join(name)
30+}
31+
32+fn fnv(b: &[u8]) -> u64 {
33+ b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| {
34+ (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)
35+ })
36+}
37+
38+/// The first frame of `name`, and the matrix the engine resolved for it. Pinned
39+/// to the software decoder so the bytes are the same on a machine with a VA-API
40+/// plugin and one without -- hence `--test-threads=1`.
41+fn frame0(name: &str) -> (Matrix, Vec<u8>) {
42+ unsafe { std::env::set_var("VE_SW", "1") };
43+ let mut session = PlaybackSession::open(asset(name)).expect("open");
44+ session.set_gain(0.0);
45+ let matrix = session.meta().color.matrix;
46+ let deadline = Instant::now() + Duration::from_secs(60);
47+ loop {
48+ if let Some(frame) = session.try_frame() {
49+ assert_eq!(frame.index, 0, "{name}: not the first frame");
50+ assert_eq!((frame.width, frame.height), (1280, 720), "{name}");
51+ return (matrix, frame.bgra);
52+ }
53+ assert!(Instant::now() < deadline, "no frame for {name} in 60 s");
54+ std::thread::sleep(Duration::from_millis(10));
55+ }
56+}
57+
58+#[test]
59+fn the_streams_matrix_reaches_the_rendered_frame() {
60+ let (sd_matrix, sd) = frame0("test_bt601.mkv");
61+ let (hd_matrix, hd) = frame0("test_h264.mkv");
62+ assert_eq!(sd_matrix, Matrix::Bt601, "the tagged fixture");
63+ assert_eq!(hd_matrix, Matrix::Bt709, "the untagged 720-line fixture");
64+
65+ // The half that must not move: BT.601 content is the picture it always was,
66+ // to the byte (`convert::bt601_limited_is_the_legacy_matrix` is why).
67+ assert_eq!(fnv(&sd), LEGACY_601_FRAME, "the BT.601 fixture shifted");
68+
69+ // ...and the half that must: the same picture, read as HD, is not it.
70+ assert_ne!(
71+ fnv(&hd),
72+ LEGACY_601_FRAME,
73+ "the BT.709 stream is still being converted as BT.601"
74+ );
75+
76+ // A matrix, not a mangling: every pixel moves a little and none of it moves
77+ // far. (BT.709's red weight is 0.2126 against BT.601's 0.299, so the
78+ // saturated bars of `testsrc2` are where the shift lands.)
79+ let moved = sd.iter().zip(&hd).filter(|(a, b)| a != b).count();
80+ let worst = sd
81+ .iter()
82+ .zip(&hd)
83+ .map(|(a, b)| a.abs_diff(*b))
84+ .max()
85+ .expect("a frame");
86+ assert!(
87+ (0.05 * sd.len() as f64) < moved as f64 && worst <= 60,
88+ "{moved} of {} bytes moved, worst by {worst}",
89+ sd.len()
90+ );
91+}