From f8dea1c8a81ae36914b67ba84cef1b4c41b8e360 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 20:40:56 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(color):=20an=20HDR=20film=20re?= =?UTF-8?q?aches=20the=20window=20tone-mapped,=20and=20an=20SDR=20one=20is?= =?UTF-8?q?=20untouched?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The tone map existed and nothing called it: a PQ or HLG stream was converted with its own matrix and then shown as if its curve were SDR -- flat, grey-washed, half the brightness a player gives it. `Render` now builds one `ToneMapper` per stream (the transfer is a property of the file, and the LUT is float work over 9 537 nodes) and maps the source planes into BT.709 SDR before anything else looks at them, in both branches of the funnel: the fused passthrough conversion and the graded-then-placed one. The grade lands *after* the map, on the one scratch copy the placed path already made -- a look means what it says in the SDR a viewer is shown, not in the ten stops the file was in. An SDR stream takes neither the copy nor the map and is byte for byte the picture it was, asserted against hashes measured before this change (`tonemap_render`). `MASTER_NITS` is 400, not the 1000 an HDR10 grade is mastered to. Told 1000, BT.2446 Method A puts 203-nit diffuse white on code 166, which reads as broadcast-dark; told 400 it lands on 205, which is the brightness mpv shows. The anchor tests carry the recomputed codes rather than wider tolerances, and HLG's OOTF now follows the assumed peak through BT.2100's own log term -- its relative diffuse white is 19% of whatever peak the display has, so it comes out at 170 and no longer agrees with PQ's absolute 203, which is the standard's behaviour and is written down beside the assert. Measured on the real 4K HDR10 film (`hw_decode`, existence-gated): frame 3000 saturation 34.8 -> 98.9, mean luma 107.6 -> 122.2, and 32.5 ms/frame for the map plus the conversion at 3840x1600, inside the 39 ms budget. New fixture `test_pq.mp4`: four flat patches whose codes are written into the planes by hand, so a test names the code it feeds and the code it expects back. --- crates/engine/src/decode.rs | 86 +++++++--- crates/engine/src/export.rs | 5 +- crates/engine/src/tonemap.rs | 96 ++++++----- crates/engine/tests/hw_decode.rs | 98 +++++++++++- crates/engine/tests/tonemap_render.rs | 220 ++++++++++++++++++++++++++ scripts/gen_fixtures.sh | 16 ++ 6 files changed, 462 insertions(+), 59 deletions(-) create mode 100644 crates/engine/tests/tonemap_render.rs diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 9f4e083..caf67e0 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -10,11 +10,12 @@ use std::thread; use rusty_h264::Decoder; use crate::color::ColorParams; -use crate::colorspace::ColorDescription; +use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::convert::{i420_to_bgra, i420_to_bgra_with}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::hw::HwSession; use crate::scale::Composer; +use crate::tonemap::{self, ToneMapper}; /// One decoded picture, ready to hand to a renderer. pub struct Frame { @@ -496,18 +497,42 @@ struct Render { /// 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* - /// placed, which is the only case that needs it. + /// This stream's HDR-to-SDR map, built once here because building it is + /// float work over 9 537 grid nodes and the transfer is a property of the + /// stream. `None` for an SDR stream, which is what keeps that path exactly + /// the one it was. + tone: Option, + /// The working copy of the source planes, refilled per frame and kept + /// across the worker's whole range. Empty unless the clip needs one: it is + /// tone-mapped in place, graded in place, or both. graded: (Vec, Vec, Vec), } +/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's +/// output contract ([`crate::tonemap`]), and no longer the HDR space the file +/// declared. +const TONE_MAPPED: ColorDescription = ColorDescription { + matrix: Matrix::Bt709, + transfer: Transfer::Sdr, + full_range: false, +}; + impl Render { fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self { Self { color, desc, canvas, + // ponytail: the ceiling is that the map reads limited-range codes + // (`tonemap`'s input contract), so a full-range PQ file -- which + // no encoder writes and no camera produces -- is mapped as if it + // were limited and comes out slightly crushed. The upgrade is a + // range argument to `ToneMapper::new`. + tone: match desc.transfer { + Transfer::Sdr => None, + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)), + }, graded: (Vec::new(), Vec::new(), Vec::new()), } } @@ -521,13 +546,47 @@ impl Render { width: u32, height: u32, ) -> Frame { - if self.canvas.is_passthrough(width, height) { + let passthrough = self.canvas.is_passthrough(width, height); + // Everything that has to happen to the samples before the canvas sees + // them, on one copy: the tone map (HDR streams only) and, unless the + // conversion below can fuse it, the grade. An SDR stream that is either + // ungraded or passing through takes neither and never allocates. + // + // The grade lands *after* the map on purpose: it is a look on the + // picture a viewer is shown, so its brightness and saturation mean what + // they say in the SDR the tone map just produced, not in the 10-stop + // HDR the file was in. + let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity()) + { + let (gy, gu, gv) = &mut self.graded; + gy.clear(); + gy.extend_from_slice(y); + gu.clear(); + gu.extend_from_slice(u); + gv.clear(); + gv.extend_from_slice(v); + if let Some(tone) = &self.tone { + tone.map(gy, gu, gv, width as usize, height as usize); + } + if !passthrough && !self.color.is_identity() { + crate::color::apply_yuv(&self.color, gy, gu, gv); + } + let desc = if self.tone.is_some() { + TONE_MAPPED + } else { + self.desc + }; + (&gy[..], &gu[..], &gv[..], desc) + } else { + (y, u, v, self.desc) + }; + if passthrough { return Frame { index, width, height, bgra: i420_to_bgra_with( - &self.desc, + &desc, &self.color, y, u, @@ -537,19 +596,6 @@ impl Render { ), }; } - let (gy, gu, gv) = &mut self.graded; - let (y, u, v) = if self.color.is_identity() { - (y, u, v) - } else { - gy.clear(); - gy.extend_from_slice(y); - gu.clear(); - gu.extend_from_slice(u); - gv.clear(); - gv.extend_from_slice(v); - crate::color::apply_yuv(&self.color, gy, gu, gv); - (&gy[..], &gu[..], &gv[..]) - }; let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height); Frame { index, @@ -557,7 +603,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(&self.desc, y, u, v, width as usize, height as usize), + bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize), } } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 512d7d6..8cc333e 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1015,7 +1015,10 @@ fn run( // // ponytail: an HDR source is composited with the matrix treatment alone // and still looks washed out; the tonemap lands here, ahead of this, and - // is a sibling task's. + // is a sibling task's. Until it does, the sentence above holds for SDR + // only: playback now maps an HDR clip to SDR *before* grading it + // (`decode::Render::frame`), so an exported HDR grade is not the picture + // the canvas showed either. let remap = color .map(|c| c.matrix) .filter(|&m| m != out_color.matrix) diff --git a/crates/engine/src/tonemap.rs b/crates/engine/src/tonemap.rs index f594737..a54c88b 100644 --- a/crates/engine/src/tonemap.rs +++ b/crates/engine/src/tonemap.rs @@ -32,12 +32,12 @@ //! BT.1886 -- the SDR display's own curve, so peak stays peak and black stays //! black -- and back to limited-range BT.709 Y'C'bC'r. //! -//! Method A is conservative on mid-tones by construction: with the standard +//! Method A is conservative on mid-tones by construction: told the standard //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code -//! 166 (about 40 cd/m^2), not at SDR white. [`MASTER_NITS`] is the exposure -//! knob -- a lower assumed peak lifts everything -- and is a constant here -//! because this module is handed pixels, never the stream metadata that would -//! carry the real one. +//! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark. +//! [`MASTER_NITS`] is the exposure knob that answers it: a lower assumed peak +//! lifts everything, and it is a constant here because this module is handed +//! pixels, never the stream metadata that would carry the real one. //! //! # Why a 3D LUT //! @@ -50,11 +50,11 @@ //! //! The axes are deliberately uneven. A node every 8th code on luma and every //! 16th on chroma was measured against a uniform 33^3 and a uniform 17^3 on -//! this machine: 17^3 puts the assumed peak (1000 cd/m^2, code 181) 5 codes -//! shy of SDR white, because the curve's knee falls inside a 16-code luma -//! cell, while a full 33^3 costs 30.7 ms a 4K frame against this one's 19.3 -- -//! four times the table, out of cache and out of budget. Fine where the eye -//! is, coarse where the format already is. +//! this machine, back when the assumed peak was 1000 cd/m^2: 17^3 put that +//! peak's own code 5 codes shy of SDR white, because the curve's knee falls +//! inside a 16-code luma cell, while a full 33^3 costs 30.7 ms a 4K frame +//! against this one's 19.3 -- four times the table, out of cache and out of +//! budget. Fine where the eye is, coarse where the format already is. //! //! Nodes are `u8`, the output's own precision, and the interpolation rounds //! once at the end in `u32` fixed point. On a node the grid *is* the pipeline; @@ -71,10 +71,13 @@ //! pixels is mapped in the same visit, sharing the block's bilinear chroma //! weights, which is what keeps a 4K frame inside a frame's time budget. -/// The mastering peak Method A is told to assume, cd/m^2. 1000 is what HDR10 -/// grades are mastered to in practice and what BT.2446's own worked example -/// uses. See the module note: this is the exposure knob. -const MASTER_NITS: f32 = 1000.0; +/// The mastering peak Method A is told to assume, cd/m^2. Not the 1000 an HDR10 +/// grade is mastered to and not BT.2446's own worked example: the goal here is +/// what a *viewer* sees on an SDR screen next to mpv, and told 1000 the method +/// lands 203-nit diffuse white on code 166, which reads as broadcast-dark. +/// Told 400 it lands near 205 -- display-referred, the brightness a player +/// shows -- which is what this constant buys. See the module note. +const MASTER_NITS: f32 = 400.0; /// The SDR display peak Method A targets, cd/m^2. const SDR_NITS: f32 = 100.0; /// Method A's working gamma. Not a display curve here -- it is the domain the @@ -103,7 +106,8 @@ pub enum Transfer { /// SMPTE ST 2084 / BT.2100 PQ, absolute: a code *is* a luminance. Pq, /// BT.2100 HLG, relative: a code is scene light, and the OOTF (system gamma - /// 1.2 at a 1000 cd/m^2 display) turns it into display light. + /// 1.2 at a 1000 cd/m^2 display, less at a dimmer one) turns it into + /// display light. Hlg, } @@ -299,10 +303,12 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] { // Clamping instead walks a too-bright pixel toward white, which is what a // highlight past the display's reach should do. // - // ponytail: the ceiling is that MASTER_NITS is a guess. Content mastered - // brighter than 1000 cd/m^2 loses its top stops to white here. The upgrade - // is the stream's own MaxCLL/mastering-display metadata reaching this - // module as a `new` argument -- nothing else in the pipeline changes. + // ponytail: the ceiling is that MASTER_NITS is an exposure choice, not a + // measurement. Everything the content masters above it -- which at 400 is + // most of an HDR10 grade's highlight range -- walks to white here. The + // upgrade is the stream's own MaxCLL/mastering-display metadata reaching + // this module as a `new` argument, with 400 as the fallback: nothing else + // in the pipeline changes. let lin = display_light(transfer, [r, g, b]); let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA)); @@ -351,11 +357,14 @@ fn display_light(transfer: Transfer, rgb: [f32; 3]) -> [f32; 3] { Transfer::Pq => rgb.map(pq_eotf), Transfer::Hlg => { // BT.2100: inverse OETF to scene light, then the OOTF, whose system - // gamma is 1.2 at a 1000 cd/m^2 display -- which is the peak this - // module assumes anyway, so no log term is needed for it. + // gamma is 1.2 at a 1000 cd/m^2 display and follows the display + // peak from there by the standard's own log term -- so the peak + // [`MASTER_NITS`] names is the peak the OOTF is built for, rather + // than a number the constant silently invalidates. let scene = rgb.map(hlg_scene); let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2]; - let gain = MASTER_NITS * ys.max(0.0).powf(0.2); + let gamma = 1.2 + 0.42 * (MASTER_NITS / 1000.0).log10(); + let gain = MASTER_NITS * ys.max(0.0).powf(gamma - 1.0); scene.map(|c| gain * c) } } @@ -435,16 +444,26 @@ mod tests { (y[0], u[0], v[0]) } - /// The three anchors, in cd/m^2, against codes worked out by hand from the - /// stages in the module note. Black is pinned by the curve (0 in, 0 out); - /// 1000 nits is the assumed peak and must reach SDR white; 203 nits is - /// BT.2408 diffuse white, which Method A deliberately does *not* put at SDR - /// white -- 166 is what the published maths gives, and the day that number - /// moves, the transcription moved with it. + /// The anchors, in cd/m^2, against the codes the stages in the module note + /// give for [`MASTER_NITS`]. Black is pinned by the curve (0 in, 0 out); + /// [`MASTER_NITS`] itself is the assumed peak and must reach SDR white; + /// 203 nits is BT.2408 diffuse white, and 205 is where a 400 cd/m^2 peak + /// puts it -- a picture as bright as a player shows, which is the whole + /// reason that constant is not 1000 (where the same maths gives 166). The + /// day one of these moves, the transcription moved with it. + /// + /// 1000 nits is the ceiling the `map_code` ponytail names, asserted rather + /// than described: everything above the assumed peak is white. #[test] fn pq_anchors_land_where_method_a_puts_them() { let mapper = ToneMapper::new(Transfer::Pq); - for (nits, expected) in [(0.0, 16u8), (26.0, 89), (203.0, 166), (1000.0, 235)] { + for (nits, expected) in [ + (0.0, 16u8), + (26.0, 108), + (203.0, 205), + (MASTER_NITS, 235), + (1000.0, 235), + ] { let code = byte(pq_code(nits)); let (y, _, _) = mapped(&mapper, code, 128, 128); assert!( @@ -571,13 +590,16 @@ mod tests { } /// HLG's own anchors. Its signal is relative, so what is worth pinning is - /// where the OOTF puts it: black at black, peak signal at the assumed - /// 1000 cd/m^2 display peak (hence SDR white, the PQ side's 1000-nit - /// anchor), and BT.2408 HLG diffuse white -- signal 0.75, which the inverse - /// OETF and the system-gamma-1.2 OOTF land on 203 cd/m^2, the same light as - /// the PQ side's diffuse white and so the same output code. One pipeline, - /// two front doors: if the HLG stage drifts, that agreement is the first - /// thing to break. + /// where the OOTF puts it: black at black and peak signal at the assumed + /// display peak, hence SDR white -- to the grid's rounding, since code 235 + /// sits between two luma nodes and the one below it is a hair under peak. + /// + /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the + /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of + /// whatever peak the display has -- 76 cd/m^2 of [`MASTER_NITS`]'s 400, + /// against PQ's absolute 203 -- and it comes out darker, at 170. That is + /// the standard's own behaviour and the number to watch: if the OOTF's + /// system gamma stops following the assumed peak, this is what moves. #[test] fn hlg_anchors_are_sane() { let mapper = ToneMapper::new(Transfer::Hlg); @@ -587,7 +609,7 @@ mod tests { let (white, _, _) = mapped(&mapper, code(1.0), 128, 128); assert!(black.abs_diff(16) <= 3, "HLG black -> {black}"); assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}"); - assert!(diffuse.abs_diff(166) <= 3, "HLG diffuse white -> {diffuse}"); + assert!(diffuse.abs_diff(170) <= 3, "HLG diffuse white -> {diffuse}"); } /// A short plane is left alone rather than half mapped, and a frame with no diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index a075a2e..8eea7bc 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -16,10 +16,11 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use engine::DecodeSession; -use engine::colorspace::ColorDescription; +use engine::colorspace::{ColorDescription, Matrix}; use engine::convert::i420_to_bgra; use engine::demux::Demuxer; use engine::hw::HwSession; +use engine::tonemap::{ToneMapper, Transfer}; fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -168,6 +169,101 @@ fn range_stops_at_end() { assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range"); } +/// The real thing: a 4K HDR10 film through the funnel, against the picture the +/// same planes gave before the tone map was in it (BT.2020 matrix, HDR codes +/// shown as if they were SDR -- flat and grey-washed, which is the complaint +/// this whole path answers). Colour has to come *up*, not down, and the picture +/// has to land somewhere a display can show rather than at either rail. +/// +/// Gated on the film being here: it is a 20 GB download, not a fixture. HEVC +/// Main 10, so this is a hardware-only test in every sense. +#[test] +#[ignore = "needs libengine_hw.so, a VA-API driver and the film"] +fn the_hdr_film_renders_tone_mapped() { + // Two minutes in: past the studio logos, inside lit footage. + const TARGET: u32 = 3000; + let path = Path::new( + "/path/to/a-real-4k-hdr10-film.mkv", + ); + if !path.exists() { + eprintln!("skipped: {} is not on this machine", path.display()); + return; + } + // SAFETY: --test-threads=1. There is no software HEVC decoder, so a pinned + // VE_SW from another test in this binary would refuse the file outright. + unsafe { std::env::remove_var("VE_SW") }; + + // The old picture, by hand off the plugin's own planes: the funnel did + // exactly this before the tone map, and it is what the comparison needs. + let mut hw = HwSession::open_at(path, TARGET).expect("no plugin/driver available"); + let (y, u, v, w, h) = hw + .next_frame() + .expect("hardware decode") + .expect("no frame at the seek"); + let (w, h) = (w as usize, h as usize); + let (y, u, v) = (y.to_vec(), u.to_vec(), v.to_vec()); + let untouched = i420_to_bgra(&color_of(path), &y, &u, &v, w, h); + + // ...and the picture the engine shows now, through the funnel itself. + let (_, rx, _cancel) = DecodeSession::open_at(path, TARGET).expect("open the film"); + let shown = rx.recv().expect("a frame off the funnel").bgra; + assert_eq!(shown.len(), untouched.len(), "frame size"); + + // Saturation, as the mean distance from grey per pixel... + let spread = |bgra: &[u8]| -> f64 { + let total: u64 = bgra + .chunks_exact(4) + .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap())) + .sum(); + total as f64 / (bgra.len() / 4) as f64 + }; + // ...and mean luma, in the limited-range code the tone map's anchors are in. + let luma = |bgra: &[u8]| -> f64 { + let total: f64 = bgra + .chunks_exact(4) + .map(|px| { + 0.2126 * f64::from(px[2]) + 0.7152 * f64::from(px[1]) + 0.0722 * f64::from(px[0]) + }) + .sum(); + 16.0 + 219.0 * (total / (bgra.len() / 4) as f64) / 255.0 + }; + let (was, now) = (spread(&untouched), spread(&shown)); + eprintln!( + "frame {TARGET}: saturation {was:.1} -> {now:.1}, mean luma {:.1} -> {:.1}", + luma(&untouched), + luma(&shown) + ); + assert!( + now > was, + "the tone-mapped frame is no more colourful: {now}" + ); + let mean = luma(&shown); + assert!( + (24.0..=200.0).contains(&mean), + "the tone-mapped frame sits at one end of the scale: mean luma {mean}" + ); + + // The funnel's own budget at this size: the map plus the conversion, which + // is what an HDR frame costs on top of the decode. Fastest of five, for the + // reason `tonemap::perf_4k_and_1080p` documents. + let mapper = ToneMapper::new(Transfer::Pq); + let sdr = ColorDescription { + matrix: Matrix::Bt709, + transfer: engine::colorspace::Transfer::Sdr, + full_range: false, + }; + let mut best = f64::MAX; + for _ in 0..5 { + let (mut my, mut mu, mut mv) = (y.clone(), u.clone(), v.clone()); + let t = Instant::now(); + mapper.map(&mut my, &mut mu, &mut mv, w, h); + let _ = i420_to_bgra(&sdr, &my, &mu, &mv, w, h); + best = best.min(t.elapsed().as_secs_f64() * 1000.0); + } + eprintln!("{w}x{h} tone map + convert: {best:.1} ms/frame"); + assert!(best <= 39.0, "{best:.1} ms/frame over the 39 ms budget"); +} + /// H.264 8-bit decode is bit-exact by conformance, so the two backends must /// agree. A mismatch means a driver deviation and is reported, not swallowed. #[test] diff --git a/crates/engine/tests/tonemap_render.rs b/crates/engine/tests/tonemap_render.rs new file mode 100644 index 0000000..b6e6307 --- /dev/null +++ b/crates/engine/tests/tonemap_render.rs @@ -0,0 +1,220 @@ +//! An HDR stream reaching the window tone-mapped, through the door the window +//! itself opens ([`PlaybackSession`]) rather than through [`engine::tonemap`] +//! alone -- which is the whole of the claim: a PQ file used to be shown as if +//! its curve were SDR, i.e. grey-washed and flat, and the map has to run inside +//! the decode funnel for that to stop. +//! +//! `test_pq.mp4` is four flat patches whose codes `scripts/gen_fixtures.sh` +//! writes into the planes by hand, so every number below is named rather than +//! measured-and-blessed: BT.2408 diffuse white (203 cd/m^2 is PQ code 144), the +//! 1000 cd/m^2 highlight (code 181) and a saturated BT.2020 red. +//! +//! ```text +//! cargo test -p engine --release --test tonemap_render -- --test-threads=1 +//! ``` + +use std::path::PathBuf; +use std::thread::sleep; +use std::time::{Duration, Instant}; + +use engine::PlaybackSession; +use engine::color::{ColorParams, apply_yuv}; +use engine::colorspace::{ColorDescription, Matrix, Transfer}; +use engine::convert::i420_to_bgra; +use engine::project::Lane; +use engine::tonemap::{ToneMapper, Transfer as Hdr}; + +/// The fixture's patches: the source codes, and where the centre of each one +/// sits in the 320x240 picture. +const DIFFUSE: ([u8; 3], (usize, usize)) = ([144, 128, 128], (80, 60)); +const HIGHLIGHT: ([u8; 3], (usize, usize)) = ([181, 128, 128], (240, 60)); +const RED: ([u8; 3], (usize, usize)) = ([100, 90, 200], (160, 180)); + +/// What the tone map hands the rest of the funnel: BT.709, SDR, limited range. +const SDR: ColorDescription = ColorDescription { + matrix: Matrix::Bt709, + transfer: Transfer::Sdr, + full_range: false, +}; + +/// Frame 0 of `test_h264.mkv` as this engine rendered it before the tone map +/// existed -- passthrough, ungraded -- and the same file on a 640x360 canvas +/// with a grade on it, which is the other branch of the funnel. Measured on +/// `main`; an SDR stream may not move by one byte. +const SDR_PASSTHROUGH: u64 = 0x9EF1_6F6F_5310_BCEE; +const SDR_GRADED_AND_PLACED: u64 = 0xAFA6_6394_3937_DE5B; + +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) + }) +} + +/// Silent and software-decoded: the fixture is H.264 on purpose, so the bytes +/// are the same on a machine with a VA-API plugin and one without (hence +/// `--test-threads=1`). +fn open(name: &str) -> PlaybackSession { + unsafe { std::env::set_var("VE_SW", "1") }; + let session = PlaybackSession::open(asset(name)).expect("open"); + session.set_gain(0.0); + session +} + +fn next_frame(session: &mut PlaybackSession, what: &str) -> engine::Frame { + let deadline = Instant::now() + Duration::from_secs(30); + loop { + if let Some(frame) = session.try_frame() { + return frame; + } + assert!(Instant::now() < deadline, "no frame after {what}"); + sleep(Duration::from_millis(4)); + } +} + +/// One pixel of a rendered frame, as (B, G, R). +fn pixel(frame: &engine::Frame, (x, y): (usize, usize)) -> [u8; 3] { + let at = (y * frame.width as usize + x) * 4; + [frame.bgra[at], frame.bgra[at + 1], frame.bgra[at + 2]] +} + +/// The limited-range BT.709 luma code a rendered pixel carries: the unit the +/// tone map's own anchors are named in, read back off the BGRA the window gets. +fn luma_code(bgra: [u8; 3]) -> u8 { + let (b, g, r) = (f32::from(bgra[0]), f32::from(bgra[1]), f32::from(bgra[2])); + (16.0 + 219.0 * (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0).round() as u8 +} + +/// How far one pixel is from grey. +fn spread(px: [u8; 3]) -> u8 { + px.iter().max().unwrap() - px.iter().min().unwrap() +} + +/// One flat patch of `codes`, rendered by hand the way the funnel is supposed +/// to render it: tone-mapped first, then graded, then converted as BT.709 SDR. +/// `grade` is applied in whichever domain `before` says -- which is the point of +/// [`the_grade_lands_after_the_tone_map`]. +fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] { + let (w, h) = (8usize, 8usize); + let mut y = vec![codes[0]; w * h]; + let mut u = vec![codes[1]; w / 2 * h / 2]; + let mut v = vec![codes[2]; w / 2 * h / 2]; + if before { + apply_yuv(grade, &mut y, &mut u, &mut v); + } + ToneMapper::new(Hdr::Pq).map(&mut y, &mut u, &mut v, w, h); + if !before { + apply_yuv(grade, &mut y, &mut u, &mut v); + } + let bgra = i420_to_bgra(&SDR, &y, &u, &v, w, h); + [bgra[0], bgra[1], bgra[2]] +} + +/// The claim itself: a PQ stream is shown as an SDR display can show it. +/// Diffuse white lands where a viewer expects white-ish paper (~205, not the +/// 144 an untouched code would convert to and not clipped white), the 1000 +/// cd/m^2 highlight stays a highlight, and the saturated red is still red -- +/// a grey wash is exactly what the missing map looked like. +#[test] +fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() { + let mut session = open("test_pq.mp4"); + assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags"); + assert_eq!( + session.meta().color.matrix, + Matrix::Bt2020Ncl, + "fixture tags" + ); + + let frame = next_frame(&mut session, "an open"); + assert_eq!((frame.width, frame.height), (320, 240)); + + let diffuse = luma_code(pixel(&frame, DIFFUSE.1)); + assert!( + (200..=210).contains(&diffuse), + "diffuse white (code {}) rendered at {diffuse}, wanted 200..=210", + DIFFUSE.0[0] + ); + let highlight = luma_code(pixel(&frame, HIGHLIGHT.1)); + assert!( + (225..=239).contains(&highlight) && highlight > diffuse, + "the 1000 cd/m^2 highlight rendered at {highlight}" + ); + let red = pixel(&frame, RED.1); + assert!( + spread(red) > 60 && red[2] > red[0] && red[2] > red[1], + "the saturated red washed out to {red:?}" + ); +} + +/// The other half: an SDR stream may not move by one byte for any of this. +/// Both branches of the funnel -- the fused passthrough conversion and the +/// graded-then-placed one -- against hashes measured before the tone map was +/// wired in. +#[test] +fn an_sdr_stream_is_byte_for_byte_the_picture_it_was() { + let mut session = open("test_h264.mkv"); + assert_eq!(session.meta().color.transfer, Transfer::Sdr); + let plain = next_frame(&mut session, "an open"); + assert_eq!(fnv(&plain.bgra), SDR_PASSTHROUGH, "the passthrough branch"); + + assert!(session.set_resolution(640, 360), "shrink the canvas"); + assert!( + session.set_color( + Lane::V1, + 0, + Some(ColorParams { + saturation: 1.4, + brightness: 0.1, + ..Default::default() + }) + ), + "grade the clip" + ); + let placed = next_frame(&mut session, "a resize and a grade"); + assert_eq!((placed.width, placed.height), (640, 360)); + assert_eq!( + fnv(&placed.bgra), + SDR_GRADED_AND_PLACED, + "the graded-and-placed branch" + ); +} + +/// Order: the grade is a look applied to the picture the viewer sees, so it +/// lands on the *tone-mapped* samples. Graded before the map instead, the same +/// numbers give a different pixel -- the second assert is what makes the first +/// one mean anything. +#[test] +fn the_grade_lands_after_the_tone_map() { + let grade = ColorParams { + saturation: 1.5, + brightness: 0.08, + ..Default::default() + }; + let mut session = open("test_pq.mp4"); + assert!( + session.set_color(Lane::V1, 0, Some(grade)), + "grade the clip" + ); + let frame = next_frame(&mut session, "a grade"); + + for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] { + let shown = pixel(&frame, patch.1); + let after = by_hand(patch.0, &grade, false); + let before = by_hand(patch.0, &grade, true); + for (i, channel) in ["B", "G", "R"].iter().enumerate() { + assert!( + shown[i].abs_diff(after[i]) <= 2, + "{name} {channel}: shown {shown:?}, tone-map-then-grade {after:?}" + ); + } + assert!( + after.iter().zip(&before).any(|(a, b)| a.abs_diff(*b) > 4), + "{name}: grading before the map gives the same pixel, so this proves nothing" + ); + } +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index ce4af3b..4ae0b0b 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -250,6 +250,22 @@ ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \ -c:v libsvtav1 -preset 8 -pix_fmt yuv420p \ -svtav1-params color-primaries=1:transfer-characteristics=1:matrix-coefficients=1 \ assets/test_vui_av1.mp4 +# The HDR fixture, and the one place in this set where the *picture* is the +# point: four flat patches written straight into the planes by `geq`, so a test +# can name the code it feeds the tone map (`engine::tonemap`) and the code it +# expects back. Top left is BT.2408 diffuse white -- 203 cd/m^2 is PQ signal +# 0.584, limited-range code 144 -- top right the 1000 cd/m^2 the grade is +# mastered against (code 181), and the bottom half a saturated BT.2020 red, +# which is what a grey-washed render loses. H.264 rather than HEVC so the +# software decoder can read it on a machine with no VA-API plugin: the tone map +# is fed by the tags, not by the codec. `-qp 1` on flat patches is exact to the +# code, so the numbers a test names are the numbers that arrive; the tags go on +# through `setparams` rather than through the encoder's own `-colorspace`, +# because that one makes ffmpeg *convert* into BT.2020 and the patches would no +# longer be the codes written above. +ffmpeg -y -f lavfi -i "color=c=black:s=320x240:rate=25:duration=1,format=yuv420p,geq=lum='if(lt(Y,H/2),if(lt(X,W/2),144,181),100)':cb='if(lt(Y,H/2),128,90)':cr='if(lt(Y,H/2),128,200)',setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc:range=tv" \ + -c:v libx264 -profile:v high -qp 1 -pix_fmt yuv420p \ + assets/test_pq.mp4 # Sync fixture: one flash and one beep, at the same instant. Black picture with # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that # stretch — so a test can find each of them and say how far apart they came out.