From 55b1c8dc45581413e522d4bfc9095d533b50e069 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 11 Aug 2026 19:33:02 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(colorspace):=20a=20picture=20i?= =?UTF-8?q?s=20converted=20in=20the=20matrix=20its=20own=20file=20names,?= =?UTF-8?q?=20not=20in=20BT.601?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 163 +++++++++++++++++++++++---- crates/engine/src/decode.rs | 37 ++++-- crates/engine/tests/hw_decode.rs | 13 ++- crates/engine/tests/matrix_render.rs | 91 +++++++++++++++ 4 files changed, 271 insertions(+), 33 deletions(-) create mode 100644 crates/engine/tests/matrix_render.rs diff --git a/crates/engine/src/convert.rs b/crates/engine/src/convert.rs index 67e8ede..833a3bc 100644 --- a/crates/engine/src/convert.rs +++ b/crates/engine/src/convert.rs @@ -1,8 +1,79 @@ -//! I420 -> BGRA8 (straight alpha), BT.601 limited range. +//! I420 -> BGRA8 (straight alpha), in the matrix and range the *stream* says +//! its samples were coded against (see [`crate::colorspace`]). + +use crate::colorspace::{ColorDescription, Matrix}; + +/// One stream's YUV->RGB matrix as 8.8 fixed point, derived once per frame so +/// the loop below stays the multiply-and-shift it always was. +struct Coeffs { + /// What luma is measured from: 16 for limited range, 0 for full. + y_off: i32, + y: i32, + rv: i32, + gu: i32, + gv: i32, + bu: i32, +} + +impl Coeffs { + /// The inverse of the matrix itself, out of its two luma weights (ITU-R + /// BT.601 §2.5.1, BT.709 §3, BT.2020 Table 4), with `Kg = 1 - Kr - Kb`: + /// + /// ```text + /// R = Y + 2(1 - Kr) Cr + /// G = Y - 2Kb(1 - Kb)/Kg Cb - 2Kr(1 - Kr)/Kg Cr + /// B = Y + 2(1 - Kb) Cb + /// ``` + /// + /// where `Y` is 0..1 and `Cb`/`Cr` are -0.5..0.5. What turns bytes into + /// those is the *range* (ITU-T H.273 §5.4): limited-range luma spans codes + /// 16..235 and chroma 16..240, so a code is worth 255/219 and 255/224 of + /// the scale respectively; full-range samples span the whole byte and both + /// scales are 1, which is what a JFIF still or a `-color_range pc` encode + /// carries. + /// + /// BT.601 limited comes out as exactly the 298/409/-100/-208/516 this + /// engine hardcoded before it read a single colour tag, so SD material is + /// byte for byte the picture it always was (`bt601_limited_is_the_legacy_matrix`). + fn new(color: &ColorDescription) -> Self { + // tonemap lands here: a PQ or HLG stream is converted with its own + // matrix and then shown as if its curve were SDR -- which is what this + // engine did with it before, only in the wrong matrix. The curve is a + // pass over the RGB coming out of the loop, not a coefficient. + let (kr, kb) = match color.matrix { + Matrix::Bt601 => (0.299, 0.114), + Matrix::Bt709 => (0.2126, 0.0722), + Matrix::Bt2020Ncl => (0.2627, 0.0593), + }; + let kg = 1.0 - kr - kb; + let (y_off, y_scale, c_scale) = if color.full_range { + (0, 1.0, 1.0) + } else { + (16, 255.0 / 219.0, 255.0 / 224.0) + }; + let q = |v: f64| (v * 256.0).round() as i32; + Self { + y_off, + y: q(y_scale), + rv: q(2.0 * (1.0 - kr) * c_scale), + gu: q(2.0 * kb * (1.0 - kb) / kg * c_scale), + gv: q(2.0 * kr * (1.0 - kr) / kg * c_scale), + bu: q(2.0 * (1.0 - kb) * c_scale), + } + } +} /// Converts a planar I420 frame (stride == width, chroma at half resolution) /// into tightly packed BGRA8. Returns `width * height * 4` bytes. -pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) -> Vec { +pub fn i420_to_bgra( + color: &ColorDescription, + y: &[u8], + u: &[u8], + v: &[u8], + width: usize, + height: usize, +) -> Vec { + let k = Coeffs::new(color); let cw = width.div_ceil(2); let mut out = vec![0u8; width * height * 4]; @@ -10,14 +81,14 @@ pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) - let y_row = row * width; let c_row = (row / 2) * cw; for col in 0..width { - let c = y[y_row + col] as i32 - 16; + let c = y[y_row + col] as i32 - k.y_off; let ci = c_row + col / 2; let d = u[ci] as i32 - 128; let e = v[ci] as i32 - 128; - let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8; - let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8; - let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8; + let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8; + let g = ((k.y * c - k.gu * d - k.gv * e + 128) >> 8).clamp(0, 255) as u8; + let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8; let o = (y_row + col) * 4; out[o] = b; @@ -37,6 +108,7 @@ pub fn i420_to_bgra(y: &[u8], u: &[u8], v: &[u8], width: usize, height: usize) - /// /// Identity params take the ungraded loop above, byte for byte. pub fn i420_to_bgra_with( + color: &ColorDescription, params: &crate::color::ColorParams, y: &[u8], u: &[u8], @@ -45,8 +117,9 @@ pub fn i420_to_bgra_with( height: usize, ) -> Vec { if params.is_identity() { - return i420_to_bgra(y, u, v, width, height); + return i420_to_bgra(color, y, u, v, width, height); } + let k = Coeffs::new(color); let lut = crate::color::Lut::new(params); let cw = width.div_ceil(2); let mut out = vec![0u8; width * height * 4]; @@ -55,14 +128,14 @@ pub fn i420_to_bgra_with( let y_row = row * width; let c_row = (row / 2) * cw; for col in 0..width { - let c = lut.y[y[y_row + col] as usize] as i32 - 16; + let c = lut.y[y[y_row + col] as usize] as i32 - k.y_off; let ci = c_row + col / 2; let d = lut.u[u[ci] as usize] as i32 - 128; let e = lut.v[v[ci] as usize] as i32 - 128; - let r = ((298 * c + 409 * e + 128) >> 8).clamp(0, 255) as u8; - let g = ((298 * c - 100 * d - 208 * e + 128) >> 8).clamp(0, 255) as u8; - let b = ((298 * c + 516 * d + 128) >> 8).clamp(0, 255) as u8; + let r = ((k.y * c + k.rv * e + 128) >> 8).clamp(0, 255) as u8; + let g = ((k.y * c - k.gu * d - k.gv * e + 128) >> 8).clamp(0, 255) as u8; + let b = ((k.y * c + k.bu * d + 128) >> 8).clamp(0, 255) as u8; let o = (y_row + col) * 4; out[o] = b; @@ -79,6 +152,27 @@ mod tests { use super::*; use crate::color::ColorParams; + /// BT.601 limited: what the tests that predate the colour tags measured, + /// and what they have to keep measuring. + const SD: ColorDescription = ColorDescription { + matrix: Matrix::Bt601, + transfer: crate::colorspace::Transfer::Sdr, + full_range: false, + }; + + /// Limited-range BT.601, the one every stream was converted as before the + /// colour tags were read: the derivation has to land on the exact integers + /// that were hardcoded, or SD material shifts under a change that was only + /// ever meant to leave it alone. + #[test] + fn bt601_limited_is_the_legacy_matrix() { + let k = Coeffs::new(&ColorDescription::default()); + assert_eq!( + (k.y_off, k.y, k.rv, k.gu, k.gv, k.bu), + (16, 298, 409, 100, 208, 516) + ); + } + /// The render path's half of the charter invariant: an ungraded segment is /// the untouched converter, not a grade that happens to round back. #[test] @@ -87,8 +181,8 @@ mod tests { let u: Vec = (0..32 * 24).map(|i| (i % 256) as u8).collect(); let v: Vec = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect(); assert_eq!( - i420_to_bgra_with(&ColorParams::default(), &y, &u, &v, 64, 48), - i420_to_bgra(&y, &u, &v, 64, 48) + i420_to_bgra_with(&SD, &ColorParams::default(), &y, &u, &v, 64, 48), + i420_to_bgra(&SD, &y, &u, &v, 64, 48) ); } @@ -106,9 +200,9 @@ mod tests { let mut y: Vec = (0..64 * 48).map(|i| (i % 256) as u8).collect(); let mut u: Vec = (0..32 * 24).map(|i| (i % 256) as u8).collect(); let mut v: Vec = (0..32 * 24).map(|i| (255 - i % 256) as u8).collect(); - let fused = i420_to_bgra_with(¶ms, &y, &u, &v, 64, 48); + let fused = i420_to_bgra_with(&SD, ¶ms, &y, &u, &v, 64, 48); crate::color::apply_yuv(¶ms, &mut y, &mut u, &mut v); - assert_eq!(fused, i420_to_bgra(&y, &u, &v, 64, 48)); + assert_eq!(fused, i420_to_bgra(&SD, &y, &u, &v, 64, 48)); } /// Not asserted, printed: the numbers in `i420_to_bgra_with`'s docs come @@ -139,13 +233,13 @@ mod tests { bench( "i420_to_bgra ", Box::new(|| { - std::hint::black_box(i420_to_bgra(&y, &u, &v, w, h)); + std::hint::black_box(i420_to_bgra(&SD, &y, &u, &v, w, h)); }), ); bench( "i420_to_bgra_with ", Box::new(|| { - std::hint::black_box(i420_to_bgra_with(¶ms, &y, &u, &v, w, h)); + std::hint::black_box(i420_to_bgra_with(&SD, ¶ms, &y, &u, &v, w, h)); }), ); bench( @@ -158,17 +252,38 @@ mod tests { ); } + fn desc(matrix: Matrix, full_range: bool) -> ColorDescription { + ColorDescription { + matrix, + full_range, + ..ColorDescription::default() + } + } + + /// Each matrix against its own red primary -- the sample the matrices + /// disagree about most, and the one a wrong matrix turns visibly orange -- + /// plus the two neutrals, which is where a wrong *range* shows instead. #[test] fn known_colors() { // 2x2 blocks so each shares one chroma sample. - // Black (limited range Y=16), white (Y=235), and a saturated red. - let cases: [([u8; 3], [u8; 3]); 3] = [ - ([16, 128, 128], [0, 0, 0]), - ([235, 128, 128], [255, 255, 255]), - ([82, 90, 240], [255, 0, 0]), // BT.601 red primary -> R=255,G~0,B~0 + let cases: [(ColorDescription, [u8; 3], [u8; 3]); 9] = [ + // Limited range: black is Y=16, white Y=235. + (desc(Matrix::Bt601, false), [16, 128, 128], [0, 0, 0]), + (desc(Matrix::Bt601, false), [235, 128, 128], [255, 255, 255]), + (desc(Matrix::Bt601, false), [82, 90, 240], [255, 0, 0]), + (desc(Matrix::Bt709, false), [16, 128, 128], [0, 0, 0]), + (desc(Matrix::Bt709, false), [235, 128, 128], [255, 255, 255]), + // BT.709's red primary sits at a *lower* luma than BT.601's (0.2126 + // against 0.299): read with the 601 matrix it comes out dark. + (desc(Matrix::Bt709, false), [63, 102, 240], [255, 0, 0]), + (desc(Matrix::Bt2020Ncl, false), [74, 97, 240], [255, 0, 0]), + // Full range: no headroom, so Y=16 is a dark grey rather than black + // -- the case a limited-range conversion crushes to 0. + (desc(Matrix::Bt601, true), [16, 128, 128], [16, 16, 16]), + (desc(Matrix::Bt601, true), [76, 85, 255], [255, 0, 0]), ]; - for ([yv, uv, vv], [r, g, b]) in cases { - let out = i420_to_bgra(&[yv; 4], &[uv], &[vv], 2, 2); + for (color, [yv, uv, vv], [r, g, b]) in cases { + let out = i420_to_bgra(&color, &[yv; 4], &[uv], &[vv], 2, 2); assert_eq!(out.len(), 2 * 2 * 4); for px in out.chunks_exact(4) { assert!(px[0].abs_diff(b) <= 2, "B {} vs {}", px[0], b); diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 98edef9..9f4e083 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -10,6 +10,7 @@ use std::thread; use rusty_h264::Decoder; use crate::color::ColorParams; +use crate::colorspace::ColorDescription; use crate::convert::{i420_to_bgra, i420_to_bgra_with}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::hw::HwSession; @@ -319,7 +320,10 @@ impl DecodeSession { } // The one conversion, on this thread: it is a few milliseconds and the // error it could raise has already been raised by `Still::open`. - let first = Render::new(color, canvas).frame( + // BT.601 limited, because that is what `rgb_to_i420` above wrote these + // planes in: a still round-trips through the pair, not through the + // colour of whatever file is on the timeline beside it. + let first = Render::new(color, ColorDescription::default(), canvas).frame( start_frame, &still.y, &still.u, @@ -388,6 +392,9 @@ impl DecodeSession { return Err(meta.codec.needs_plugin().into()); } let end_frame = end_frame.min(meta.frame_count); + // Read off the file once, here, and carried into the worker: it is a + // property of the stream, so it cannot change while one range decodes. + let source_color = meta.color; // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); @@ -422,7 +429,7 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } - let mut render = Render::new(color, canvas); + let mut render = Render::new(color, source_color, canvas); // The plugin has to be opened on the thread that uses it: its // VA-API state is not `Send`-safe across a later hand-off. if let Some(hw) = open_hw(&path, start_frame) { @@ -484,6 +491,10 @@ impl DecodeSession { /// project resolution, byte for byte and allocation for allocation. struct Render { color: ColorParams, + /// What the source's samples mean -- the stream's own matrix and range, + /// which is what the conversion below is done in rather than the BT.601 it + /// used to assume of every file. + desc: ColorDescription, canvas: Composer, /// The graded copy of the source planes, refilled per frame and kept across /// the worker's whole range. Empty unless the clip is both graded *and* @@ -492,9 +503,10 @@ struct Render { } impl Render { - fn new(color: ColorParams, canvas: Composer) -> Self { + fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self { Self { color, + desc, canvas, graded: (Vec::new(), Vec::new(), Vec::new()), } @@ -514,7 +526,15 @@ impl Render { index, width, height, - bgra: i420_to_bgra_with(&self.color, y, u, v, width as usize, height as usize), + bgra: i420_to_bgra_with( + &self.desc, + &self.color, + y, + u, + v, + width as usize, + height as usize, + ), }; } let (gy, gu, gv) = &mut self.graded; @@ -537,7 +557,7 @@ impl Render { height, // Ungraded on purpose: the grade is already in the pixels above and // the canvas around them must stay the black it was filled with. - bgra: i420_to_bgra(y, u, v, width as usize, height as usize), + bgra: i420_to_bgra(&self.desc, y, u, v, width as usize, height as usize), } } } @@ -612,8 +632,11 @@ pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { } /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse -/// of [`crate::convert::i420_to_bgra`], so a still round-trips to the colour it -/// was authored in (`images::still_pixels_match_the_source_image` measures it). +/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why +/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and +/// not the timeline's. A still has no stream to be tagged by; it round-trips to +/// the colour it was authored in through this pair and nothing else sees these +/// planes (`images::still_pixels_match_the_source_image` measures it). /// /// Chroma is the 2x2 box average, and an odd edge averages the samples it has -- /// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index 240a74e..a075a2e 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -16,7 +16,9 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use engine::DecodeSession; +use engine::colorspace::ColorDescription; use engine::convert::i420_to_bgra; +use engine::demux::Demuxer; use engine::hw::HwSession; fn asset(name: &str) -> PathBuf { @@ -25,6 +27,12 @@ fn asset(name: &str) -> PathBuf { .join(name) } +/// What the decode funnel converts this file's planes in, so a conversion done +/// by hand here is the one `DecodeSession` would have done. +fn color_of(path: &Path) -> ColorDescription { + Demuxer::open(path).expect("open for colour").0.color +} + fn open_hw(path: &Path) -> HwSession { HwSession::open(path).expect("no hardware decode plugin/driver available") } @@ -32,6 +40,7 @@ fn open_hw(path: &Path) -> HwSession { /// Decodes the whole file through the plugin, returning (frame count, frame 30 as BGRA). fn decode_all_hw(name: &str) -> (usize, Vec) { let path = asset(name); + let color = color_of(&path); let mut hw = open_hw(&path); let meta = hw.meta().expect("meta"); assert_eq!( @@ -46,7 +55,7 @@ fn decode_all_hw(name: &str) -> (usize, Vec) { while let Some((y, u, v, w, h)) = hw.next_frame().expect("hardware decode") { assert_eq!((w, h), (1280, 720), "{name} frame {count} dims"); if count == 30 { - frame_30 = i420_to_bgra(y, u, v, w as usize, h as usize); + frame_30 = i420_to_bgra(&color, y, u, v, w as usize, h as usize); } count += 1; } @@ -117,7 +126,7 @@ fn seek_matches_linear() { .expect("no frame after hardware seek"); eprintln!("hardware seek to {TARGET} took {:?}", start.elapsed()); assert_eq!( - i420_to_bgra(y, u, v, w as usize, h as usize), + i420_to_bgra(&color_of(&path), y, u, v, w as usize, h as usize), linear, "hardware seek != software linear" ); diff --git a/crates/engine/tests/matrix_render.rs b/crates/engine/tests/matrix_render.rs new file mode 100644 index 0000000..6294c35 --- /dev/null +++ b/crates/engine/tests/matrix_render.rs @@ -0,0 +1,91 @@ +//! The stream's matrix reaching the picture a player shows, through the door +//! the window itself opens ([`PlaybackSession`]) rather than through the +//! converter alone. +//! +//! Two fixtures, one picture: `test_bt601.mkv` and `test_h264.mkv` are the same +//! `testsrc2` at 1280x720 through the same encoder, and their first frames were +//! byte-identical while every file was converted as BT.601 -- the FNV constant +//! below is that shared frame, measured before this change. What separates them +//! now is only what they *say*: the first tags SMPTE 170M in its container, the +//! second tags nothing and is 720 lines, so the heuristic calls it BT.709. +//! +//! ```text +//! cargo test -p engine --release --test matrix_render -- --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::PlaybackSession; +use engine::colorspace::Matrix; + +/// Frame 0 of either fixture as the engine converted it before it read a single +/// colour tag: BT.601 limited, both files. +const LEGACY_601_FRAME: u64 = 0x872e_4f9c_4165_0c9e; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn fnv(b: &[u8]) -> u64 { + b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| { + (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3) + }) +} + +/// The first frame of `name`, and the matrix the engine resolved for it. Pinned +/// to the software decoder so the bytes are the same on a machine with a VA-API +/// plugin and one without -- hence `--test-threads=1`. +fn frame0(name: &str) -> (Matrix, Vec) { + unsafe { std::env::set_var("VE_SW", "1") }; + let mut session = PlaybackSession::open(asset(name)).expect("open"); + session.set_gain(0.0); + let matrix = session.meta().color.matrix; + let deadline = Instant::now() + Duration::from_secs(60); + loop { + if let Some(frame) = session.try_frame() { + assert_eq!(frame.index, 0, "{name}: not the first frame"); + assert_eq!((frame.width, frame.height), (1280, 720), "{name}"); + return (matrix, frame.bgra); + } + assert!(Instant::now() < deadline, "no frame for {name} in 60 s"); + std::thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +fn the_streams_matrix_reaches_the_rendered_frame() { + let (sd_matrix, sd) = frame0("test_bt601.mkv"); + let (hd_matrix, hd) = frame0("test_h264.mkv"); + assert_eq!(sd_matrix, Matrix::Bt601, "the tagged fixture"); + assert_eq!(hd_matrix, Matrix::Bt709, "the untagged 720-line fixture"); + + // The half that must not move: BT.601 content is the picture it always was, + // to the byte (`convert::bt601_limited_is_the_legacy_matrix` is why). + assert_eq!(fnv(&sd), LEGACY_601_FRAME, "the BT.601 fixture shifted"); + + // ...and the half that must: the same picture, read as HD, is not it. + assert_ne!( + fnv(&hd), + LEGACY_601_FRAME, + "the BT.709 stream is still being converted as BT.601" + ); + + // A matrix, not a mangling: every pixel moves a little and none of it moves + // far. (BT.709's red weight is 0.2126 against BT.601's 0.299, so the + // saturated bars of `testsrc2` are where the shift lands.) + let moved = sd.iter().zip(&hd).filter(|(a, b)| a != b).count(); + let worst = sd + .iter() + .zip(&hd) + .map(|(a, b)| a.abs_diff(*b)) + .max() + .expect("a frame"); + assert!( + (0.05 * sd.len() as f64) < moved as f64 && worst <= 60, + "{moved} of {} bytes moved, worst by {worst}", + sd.len() + ); +}