diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 89ac776..2d28302 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -335,6 +335,9 @@ impl DecodeSession { ColorDescription::default(), canvas, tonemap::Preset::default(), + // ...and no declared peak either, for the same reason: there is no + // tone map on this path to hand one to. + None, ) .frame( start_frame, @@ -414,6 +417,12 @@ impl DecodeSession { // 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; + // ...and with it what the film says its own brightest picture is + // ([`Demuxer::light`]): the tone map's assumed peak on the reference + // rendition, so a 1759 cd/m^2 grade is converted at 1759 rather than at + // the 1000 a file that declared nothing is assumed at. Read here + // because the demuxer is moved into the worker below. + let declared_peak = demuxer.light().peak(); // 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); @@ -448,7 +457,7 @@ impl DecodeSession { if worker_cancel.load(Ordering::Relaxed) { return; } - let mut render = Render::new(color, source_color, canvas, tone); + let mut render = Render::new(color, source_color, canvas, tone, declared_peak); // 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) { @@ -536,11 +545,15 @@ const TONE_MAPPED: ColorDescription = ColorDescription { }; impl Render { + /// `peak` is what the file declared about its own brightness + /// ([`Demuxer::light`]), which only an HDR stream has and only the + /// reference rendition reads (see [`tonemap::Preset`]). fn new( color: ColorParams, desc: ColorDescription, canvas: Composer, preset: tonemap::Preset, + peak: Option, ) -> Self { Self { color, @@ -553,8 +566,8 @@ impl Render { // range argument to `ToneMapper::new`. tone: match desc.transfer { Transfer::Sdr => None, - Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)), - Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)), + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), }, graded: (Vec::new(), Vec::new(), Vec::new()), } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 59c13e0..fed72f5 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -95,9 +95,11 @@ impl Demuxer { /// read at open out of the container and -- for an HEVC stream whose /// container said nothing -- out of the first access unit's SEI. /// - /// Not part of [`VideoMeta`] for the reason [`Self::bit_depth`] is not: - /// nothing above reads it yet. [`crate::tonemap`] is where it goes, and that - /// is a change of its own. + /// Read by the two sites that build a tone map -- the decode funnel + /// (`decode::DecodeSession::open_worker`) and the export table -- as the + /// assumed peak of [`crate::tonemap::Preset::Reference`]. Still not part of + /// [`VideoMeta`]: both of them have the demuxer itself in hand, so the + /// number travels no further than the open that read it. pub fn light(&self) -> ContentLight { match self { Self::Mp4(d) => d.light, diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 3926cbf..ee3a361 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -959,7 +959,7 @@ fn run( // samples *mean* ([`ColorDescription`]), which is what decides whether they // are remapped on the way in. Real time for a still, a song and a // single-rate project, where every conversion below is the identity. - let rates: Vec<(Rate, ColorDescription)> = sources + let rates: Vec<(Rate, ColorDescription, Option)> = sources .iter() .map(|source| source_rate(&source.path, meta.frame_rate)) .collect(); @@ -970,17 +970,18 @@ fn run( // is the difference between paying that once and paying it per cut. An SDR // source -- the whole of an ordinary project -- builds no table at all. // - // Through the project's own preset ([`tonemap::Preset`]), which is the same - // one playback's decode funnel builds its tables with: preview and export - // are the same rendition of the same film because they are told the same - // thing, not because two numbers happen to agree. + // Through the project's own preset ([`tonemap::Preset`]) and each source's + // own declared peak, which is the pair playback's decode funnel builds its + // tables with: preview and export are the same rendition of the same film + // because they are told the same two things, not because two numbers happen + // to agree. let preset = project.tone(); let tone: Vec> = rates .iter() - .map(|(_, color)| match color.transfer { + .map(|(_, color, peak)| match color.transfer { Transfer::Sdr => None, - Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)), - Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)), + Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), + Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), }) .collect(); // ...and the one space they are all written in, the same rule a reader with @@ -1016,7 +1017,7 @@ fn run( let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - let (rate, color) = rates[source]; + let (rate, color, _peak) = rates[source]; // Opened at the file's own frame, which is the only place the // file's numbering is used -- the span's are the timeline's. let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; @@ -1233,24 +1234,29 @@ fn remap_into( /// -- a still, a song -- and for one that will not open here: the decoder is /// opened a few lines later and fails the export by name, which is a better /// error than this one could raise. -fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription) { +fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option) { if crate::is_image(path) || crate::is_audio(path) { // A still is BT.601 by construction whatever it was authored as: // `decode::rgb_to_i420` is the one matrix that turns its pixels into // planes. A song has no picture and the answer is never read. - return (Rate::REAL_TIME, ColorDescription::default()); + return (Rate::REAL_TIME, ColorDescription::default(), None); } match Demuxer::open(path) { // ...and one whose rate cannot be named against the timeline's, which // `matches_timeline` refuses at import, so nothing on a timeline is on // this arm either. - Ok((meta, _)) => ( + // + // The declared peak comes off the same open the space does, which is + // what keeps export on the number playback's decode funnel read: one + // header parse, both answers. + Ok((meta, demuxer)) => ( Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), meta.color, + demuxer.light().peak(), ), // Unreadable here means unreadable below too, where the span dies with a // real message; the file's own space is the least of that. - Err(_) => (Rate::REAL_TIME, ColorDescription::default()), + Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None), } } diff --git a/crates/engine/src/tonemap.rs b/crates/engine/src/tonemap.rs index 826d9cb..4edec43 100644 --- a/crates/engine/src/tonemap.rs +++ b/crates/engine/src/tonemap.rs @@ -40,8 +40,10 @@ //! everything -- and *which* answer a project wants is a matter of taste, not of //! correctness: a reference rendition and a vivid one are both honest pictures //! of the same film. So it is a [`Preset`] the viewer picks rather than a -//! constant, and never the stream's own metadata, which this module is never -//! handed (it is given pixels). +//! constant -- read, on the faithful one, against the peak the film itself +//! declares (`declared_peak` at [`ToneMapper::new`], the demuxer's MaxCLL or +//! mastering-display maximum). The picked rendition still decides; the metadata +//! only says what "the peak the content really has" is for this film. //! //! # Why a 3D LUT //! @@ -107,9 +109,23 @@ const CHROMA_FRAC: u32 = 16; /// player looks; told a lower one it lifts the whole picture. The gain is /// applied *after* the map, on the SDR colour differences, so it enriches the /// picture a viewer is shown rather than bending a stage of the standard. +/// +/// # How a film's own metadata composes with the pick +/// +/// Only [`Reference`](Preset::Reference) reads it, and that is the rule rather +/// than an omission: it is the rendition that promises *the mastering peak the +/// content really has*, so a film that declares 1759 cd/m^2 is converted at +/// 1759 and its 1000 is a fallback for a file that declared nothing. +/// [`Standard`](Preset::Standard) and [`Vivid`](Preset::Vivid) name a fixed +/// exposure -- 400 and 250 -- which is the whole of what a viewer picks them +/// for; letting a film's metadata move those numbers would make the same pick +/// mean a different brightness on every file, which is the opposite of what +/// picking one is for. So: metadata is read *against* the picked preset, never +/// in place of it, and two of the three are deliberately deaf to it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Preset { - /// The published conversion, at the mastering peak the content really has. + /// The published conversion, at the mastering peak the content really has + /// -- the film's own declared peak where it has one (see the note above). /// The default: what the document says, and what a second reference can be /// checked against. #[default] @@ -127,7 +143,8 @@ impl Preset { /// last. pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid]; - /// The mastering peak Method A is told to assume, cd/m^2. + /// The mastering peak Method A is told to assume, cd/m^2: this rendition's + /// own number, before a file gets a say ([`Self::master_nits_for`]). pub fn master_nits(self) -> f32 { match self { Preset::Reference => 1000.0, @@ -136,6 +153,23 @@ impl Preset { } } + /// The peak Method A is really run at, given what the file declared + /// ([`crate::demux::Demuxer::light`] -> [`crate::colorspace::ContentLight::peak`]). + /// The composition rule is on the enum: the reference rendition takes the + /// film's number, the other two keep their own. + /// + /// A declared peak is a stranger's number, so it is checked before it + /// becomes the divisor of every pixel: below SDR white the whole picture + /// clips to white, and a NaN would poison the entire table into black. + /// Out of range -- or a NaN, which no comparison admits -- is treated as + /// not declared. The ceiling is PQ's own 10 000 cd/m^2. + pub fn master_nits_for(self, declared_peak: Option) -> f32 { + match (self, declared_peak) { + (Preset::Reference, Some(peak)) if (SDR_NITS..=10_000.0).contains(&peak) => peak, + _ => self.master_nits(), + } + } + /// What the SDR colour differences are multiplied by after the map. `1.0` /// leaves the method's own output untouched, byte for byte. pub fn chroma_gain(self) -> f32 { @@ -186,10 +220,18 @@ pub struct ToneMapper { /// The same for chroma, four fields: U at `i`, U at `i + 1`, V at `i`, V at /// `i + 1`. One `u64` multiply does what four `u8` ones did. chroma: Box<[u64]>, + /// The peak this table was really built at, cd/m^2 -- the picked preset's + /// read against what the file declared ([`Preset::master_nits_for`]). Kept + /// so a caller can say which number a picture came out of. + peak: f32, } impl ToneMapper { - pub fn new(transfer: Transfer, preset: Preset) -> Self { + /// `declared_peak` is the film's own peak brightness where it has one + /// ([`crate::demux::Demuxer::light`]), [`None`] for a file that declared + /// nothing. Which renditions act on it is [`Preset`]'s composition rule. + pub fn new(transfer: Transfer, preset: Preset, declared_peak: Option) -> Self { + let peak = preset.master_nits_for(declared_peak); let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES; let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]); for kv in 0..CHROMA_NODES { @@ -202,6 +244,7 @@ impl ToneMapper { let out = map_code( transfer, preset, + peak, (iy << LUMA_STEP) as f32, (ju << CHROMA_STEP) as f32, (kv << CHROMA_STEP) as f32, @@ -233,9 +276,17 @@ impl ToneMapper { Self { luma: luma.into_boxed_slice(), chroma: chroma.into_boxed_slice(), + peak, } } + /// The mastering peak this table was built at, cd/m^2: the film's own where + /// the rendition reads it, the rendition's own otherwise. What a test -- or + /// a caller wanting to say which number a picture came out of -- asks. + pub fn peak(&self) -> f32 { + self.peak + } + /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width * /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`, /// no padding (the shape [`crate::convert`], the decoders and the export @@ -346,8 +397,14 @@ fn byte(value: f32) -> u8 { /// The whole float pipeline, from one triple of input codes to one triple of /// BT.709 limited-range output codes. Runs at build time only; the module note /// walks the stages. -fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f32; 3] { - let master_nits = preset.master_nits(); +fn map_code( + transfer: Transfer, + preset: Preset, + master_nits: f32, + yc: f32, + uc: f32, + vc: f32, +) -> [f32; 3] { // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal. let luma = (yc - 16.0) / 219.0; let cb = (uc - 128.0) / 224.0; @@ -368,14 +425,11 @@ fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f // 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 the assumed peak is an exposure *choice* - // (now the viewer's, [`Preset`]), 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 beside the preset, - // as the measured ceiling the picked one is read against: nothing else in - // the pipeline changes. - let lin = display_light(transfer, preset, [r, g, b]); + // The reference rendition is now told the film's own declared peak + // ([`Preset::master_nits_for`]), so what walks to white here is what the + // film says it never masters above; the two fixed renditions keep their + // exposure and still clamp an HDR10 grade's top end into white on purpose. + let lin = display_light(transfer, master_nits, [r, g, b]); let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA)); // 4. BT.2020 luma and colour differences, in that domain. @@ -427,16 +481,16 @@ fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f } /// Signal -> display light in cd/m^2. -fn display_light(transfer: Transfer, preset: Preset, rgb: [f32; 3]) -> [f32; 3] { +fn display_light(transfer: Transfer, master_nits: f32, rgb: [f32; 3]) -> [f32; 3] { match transfer { 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 and follows the display - // peak from there by the standard's own log term -- so the peak the - // preset names is the peak the OOTF is built for, rather than a - // number the choice silently invalidates. - let master_nits = preset.master_nits(); + // peak from there by the standard's own log term -- so the peak in + // force, the picked rendition's read against the film's declared + // one, is the peak the OOTF is built for rather than a number the + // choice or the metadata silently invalidates. let scene = rgb.map(hlg_scene); let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2]; let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10(); @@ -445,7 +499,9 @@ fn display_light(transfer: Transfer, preset: Preset, rgb: [f32; 3]) -> [f32; 3] // `ys^(gamma - 1)` term diverges as the scene goes black and the // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts // a hole where black belongs (measured: HLG black rendered code 0 - // under the vivid preset before this line). + // under the vivid preset before this line). Kept above 1000 too, + // where a declared peak puts the gamma over 1 and the term is + // merely 0: the guard costs one comparison at build time. let ys = ys.max(0.0); let gain = match ys > 0.0 { true => master_nits * ys.powf(gamma - 1.0), @@ -538,9 +594,8 @@ mod tests { /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The /// day one of these moves, the transcription moved with it. /// - /// The last row of each is the ceiling the `map_code` ponytail names, - /// asserted rather than described: everything above the assumed peak is - /// white. + /// The last row of each says what happens above the assumed peak, asserted + /// rather than described: it is white. #[test] fn pq_anchors_land_where_method_a_puts_them() { for (preset, diffuse) in [ @@ -549,7 +604,7 @@ mod tests { (Preset::Vivid, 226), ] { let peak = preset.master_nits(); - let mapper = ToneMapper::new(Transfer::Pq, preset); + let mapper = ToneMapper::new(Transfer::Pq, preset, None); for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] { let code = byte(pq_code(nits)); let (y, _, _) = mapped(&mapper, code, 128, 128); @@ -572,7 +627,15 @@ mod tests { fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() { // BT.2408 diffuse white, and a saturated BT.2020 red beside it. let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8)); - let luma = |preset| mapped(&ToneMapper::new(Transfer::Pq, preset), diffuse, 128, 128).0; + let luma = |preset| { + mapped( + &ToneMapper::new(Transfer::Pq, preset, None), + diffuse, + 128, + 128, + ) + .0 + }; let (reference, standard, vivid) = ( luma(Preset::Reference), luma(Preset::Standard), @@ -583,7 +646,12 @@ mod tests { "reference {reference}, standard {standard}, vivid {vivid}" ); let colour = |preset| { - let (_, u, v) = mapped(&ToneMapper::new(Transfer::Pq, preset), red.0, red.1, red.2); + let (_, u, v) = mapped( + &ToneMapper::new(Transfer::Pq, preset, None), + red.0, + red.1, + red.2, + ); (u.abs_diff(128), v.abs_diff(128)) }; let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid)); @@ -605,12 +673,19 @@ mod tests { fn the_grid_is_the_pipeline_on_its_nodes() { for preset in Preset::ALL { for transfer in [Transfer::Pq, Transfer::Hlg] { - let mapper = ToneMapper::new(transfer, preset); + let mapper = ToneMapper::new(transfer, preset, None); for yc in (0..=248u8).step_by(1 << LUMA_STEP) { for uc in (0..=240u8).step_by(1 << CHROMA_STEP) { for vc in (0..=240u8).step_by(1 << CHROMA_STEP) { let got = mapped(&mapper, yc, uc, vc); - let want = map_code(transfer, preset, yc.into(), uc.into(), vc.into()); + let want = map_code( + transfer, + preset, + mapper.peak(), + yc.into(), + uc.into(), + vc.into(), + ); let want = (byte(want[0]), byte(want[1]), byte(want[2])); assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}"); } @@ -639,7 +714,7 @@ mod tests { .into_iter() .flat_map(|t| Preset::ALL.map(|p| (t, p))) { - let mapper = ToneMapper::new(transfer, preset); + let mapper = ToneMapper::new(transfer, preset, None); for yc in (3..=255u8).step_by(23) { for uc in (5..=255u8).step_by(29) { for vc in (7..=255u8).step_by(31) { @@ -658,6 +733,7 @@ mod tests { let out = map_code( transfer, preset, + mapper.peak(), node(yc, LUMA_STEP) + dy, node(uc, CHROMA_STEP) + du, node(vc, CHROMA_STEP) + dv, @@ -695,7 +771,7 @@ mod tests { .into_iter() .flat_map(|t| Preset::ALL.map(|p| (t, p))) { - let mapper = ToneMapper::new(transfer, preset); + let mapper = ToneMapper::new(transfer, preset, None); let mut last = 0u8; for code in 0..=255u8 { let (y, _, _) = mapped(&mapper, code, 128, 128); @@ -718,7 +794,7 @@ mod tests { .into_iter() .flat_map(|t| Preset::ALL.map(|p| (t, p))) { - let mapper = ToneMapper::new(transfer, preset); + let mapper = ToneMapper::new(transfer, preset, None); for code in (16..=235u8).step_by(7) { let (_, u, v) = mapped(&mapper, code, 128, 128); assert!( @@ -748,7 +824,7 @@ mod tests { (Preset::Standard, 170), (Preset::Vivid, 170), ] { - let mapper = ToneMapper::new(Transfer::Hlg, preset); + let mapper = ToneMapper::new(Transfer::Hlg, preset, None); let code = |signal: f32| byte(16.0 + 219.0 * signal); let (black, _, _) = mapped(&mapper, code(0.0), 128, 128); let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128); @@ -766,7 +842,7 @@ mod tests { /// size at all returns instead of panicking on a zero-length band. #[test] fn a_frame_that_does_not_measure_up_is_untouched() { - let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None); let mut y = vec![128u8; 8 * 8 - 1]; let mut u = vec![128u8; 4 * 4]; let mut v = vec![128u8; 4 * 4]; @@ -781,7 +857,7 @@ mod tests { /// off the end. #[test] fn odd_sizes_map_every_pixel() { - let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None); let (w, h) = (7usize, 5usize); let mut y = vec![200u8; w * h]; let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)]; @@ -803,7 +879,7 @@ mod tests { /// time", and the reason a plain mean here would be a coin flip. #[test] fn perf_4k_and_1080p() { - let mapper = ToneMapper::new(Transfer::Pq, Preset::default()); + let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None); for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] { let mut y: Vec = (0..w * h).map(|i| (i % 256) as u8).collect(); let mut u: Vec = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect(); @@ -826,4 +902,122 @@ mod tests { } } } + + /// The paid debt: the film's own declared peak is what the reference + /// rendition converts at. 1759 cd/m^2 is a real number -- the MaxCLL of the + /// HDR10 grade of *a real film*, which the container never says + /// and the HEVC SEI does -- and every anchor moves with it, downward, + /// because a peak this far above the 1000 an undeclared file is assumed at + /// is *headroom*: the same code is a smaller fraction of a brighter peak. + /// + /// The row that matters most is 1000 cd/m^2. Told 1000, Method A puts it at + /// SDR white and everything above it is gone; told the film's 1759 it lands + /// at 215 and the 759 nits above it are still a picture. That is the whole + /// of what reading the metadata buys. + #[test] + fn the_reference_rendition_converts_at_the_films_own_peak() { + const FILM: f32 = 1759.0; + let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(FILM)); + assert_eq!( + mapper.peak(), + FILM, + "the table was built at the film's peak" + ); + // Anchors, cd/m^2 -> limited-range SDR luma, at 1759 rather than 1000: + // black is still black, the film's own peak is SDR white, and BT.2408 + // diffuse white lands at 145 instead of 166. + for (nits, expected) in [ + (0.0, 16u8), + (203.0, 145), + (1000.0, 215), + (FILM, 235), + (10000.0, 235), + ] { + let code = byte(pq_code(nits)); + let (y, _, _) = mapped(&mapper, code, 128, 128); + assert!( + y.abs_diff(expected) <= 3, + "{nits} cd/m^2 (code {code}) -> {y}, expected {expected} at a {FILM} peak" + ); + } + // ...and the direction, on every code rather than on the anchors: a + // higher assumed peak is never brighter, and somewhere it is plainly + // darker. The fallback is what the same file gets with its metadata + // stripped, which is the control. + let fallback = ToneMapper::new(Transfer::Pq, Preset::Reference, None); + assert_eq!(fallback.peak(), 1000.0, "an undeclared file's assumption"); + let mut lower = 0; + for code in 0..=255u8 { + let (declared, _, _) = mapped(&mapper, code, 128, 128); + let (assumed, _, _) = mapped(&fallback, code, 128, 128); + assert!( + declared <= assumed, + "code {code}: the film's peak lifted it, {declared} over {assumed}" + ); + lower += u32::from(declared < assumed); + } + assert!(lower > 128, "only {lower} of 256 codes moved at all"); + // HLG's OOTF follows the same peak, and the black guard has to hold + // above 1000 as well as below it: a system gamma over 1 makes the + // `ys^(gamma - 1)` term zero rather than infinite, and a hole where + // black belongs is the failure either way. + let hlg = ToneMapper::new(Transfer::Hlg, Preset::Reference, Some(FILM)); + let (black, _, _) = mapped(&hlg, byte(16.0), 128, 128); + let (near_black, _, _) = mapped(&hlg, byte(16.0 + 219.0 * 0.02), 128, 128); + let (white, _, _) = mapped(&hlg, 235, 128, 128); + assert!(black.abs_diff(16) <= 3, "HLG black at {FILM} -> {black}"); + assert!(near_black > 16, "HLG near-black at {FILM} -> {near_black}"); + assert!(white.abs_diff(235) <= 3, "HLG peak at {FILM} -> {white}"); + } + + /// The composition rule on [`Preset`], asserted: the two fixed renditions + /// are deaf to the metadata, byte for byte, and the reference one is not. + /// A "read the peak" change that reached all three would make the same pick + /// mean a different exposure on every file, and this is what catches it. + #[test] + fn only_the_reference_rendition_reads_the_declared_peak() { + for transfer in [Transfer::Pq, Transfer::Hlg] { + for preset in Preset::ALL { + let declared = ToneMapper::new(transfer, preset, Some(1759.0)); + let assumed = ToneMapper::new(transfer, preset, None); + let deaf = preset != Preset::Reference; + assert_eq!( + declared.peak() == assumed.peak(), + deaf, + "{preset:?} {transfer:?}: peak {} against {}", + declared.peak(), + assumed.peak() + ); + assert_eq!( + declared.luma == assumed.luma && declared.chroma == assumed.chroma, + deaf, + "{preset:?} {transfer:?}: the tables" + ); + } + } + } + + /// A declared peak is a number out of a stranger's file, so the two ways it + /// can be nonsense are checked rather than divided by: a peak under SDR + /// white would clip the whole picture to white, and a NaN -- which no + /// comparison admits, hence no clamp catches -- would build a table of + /// zeroes, i.e. a black frame. Both fall back to the rendition's own. + #[test] + fn a_nonsense_declared_peak_is_not_believed() { + for junk in [0.0, 1.0, 99.0, 10_001.0, f32::NAN, f32::INFINITY] { + let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(junk)); + assert_eq!(mapper.peak(), 1000.0, "declared {junk} was believed"); + let (white, _, _) = mapped(&mapper, byte(pq_code(1000.0)), 128, 128); + assert!( + white.abs_diff(235) <= 3, + "declared {junk}: 1000 nits -> {white}" + ); + } + // ...and the range's own ends are believed, which is what says the + // guard rejects nonsense rather than everything unusual. + for good in [100.0, 4000.0, 10_000.0] { + let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(good)); + assert_eq!(mapper.peak(), good, "declared {good} was refused"); + } + } } diff --git a/crates/engine/tests/export_color.rs b/crates/engine/tests/export_color.rs index ccdaac5..57fc949 100644 --- a/crates/engine/tests/export_color.rs +++ b/crates/engine/tests/export_color.rs @@ -442,7 +442,9 @@ fn an_hdr_clip_is_tone_mapped_before_it_is_graded() { let got = raw_yuv(&out).expect("ffmpeg read the export"); let (width, height) = (1280usize, 720usize); - let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset); + // No declared peak: the fixture's tags say PQ and nothing about how + // bright it is, so both sides are on the rendition's own number. + let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset, None); // The same bytes twice, through the two orders. Whichever preset is in // force, both sides move with it -- what is asserted is which of them // the export sits on, not where either lands. @@ -495,6 +497,19 @@ fn a_real_hdr_film_exports_as_a_picture() { } let mut session = PlaybackSession::open(film).expect("open the film"); assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR10 film"); + // What this film declares about itself, and therefore what the reference + // rendition converts it at: 1759 cd/m^2 of MaxCLL, which its Matroska never + // says and its HEVC SEI does. Both the funnel and the export table below + // build their tables off this same number. + let (_, demuxer) = Demuxer::open(film).expect("reopen the film"); + let peak = demuxer.light().peak(); + assert_eq!(peak, Some(1759.0), "the film's declared peak"); + let mapper = ToneMapper::new(tonemap::Transfer::Pq, session.tone(), peak); + assert_eq!( + mapper.peak(), + 1759.0, + "the reference rendition converts this film at its own peak" + ); // A five-second window out of the middle: cut both ends, drop them, and the // delete closes the gap ahead of what is left, so the export is those five // seconds and no leading black. @@ -586,3 +601,32 @@ fn a_graded_clip_exports_the_picture_the_preview_showed() { std::fs::remove_file(&out).unwrap(); } } + +/// Preview and export agree on the film's own peak, not merely on the preset: +/// `test_hdr_bright.mkv` declares 4000 cd/m^2, and the two sides read it in +/// different places -- the decode funnel off the demuxer it already opened, the +/// export table off `source_rate`'s. One of them left on the 1000 an undeclared +/// file is assumed at would be a preview the export does not match, which is +/// exactly the failure this file exists to refuse. +/// +/// Measured as everywhere else here: this engine's own decode of its own export +/// against the canvas the preview showed. +#[test] +fn a_declared_peak_exports_the_picture_the_preview_showed() { + let mut session = two_frames(&asset("test_hdr_bright.mkv")); + assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR fixture"); + let preview = frame0_bgra(&mut session); + let out = out_path("declared_peak", "mp4"); + export(&session, &out, Format::Mp4); + + let mut reopened = PlaybackSession::open(&*out).expect("reopen the export"); + let exported = frame0_bgra(&mut reopened); + let diff = mean_abs_diff(&preview, &exported); + eprintln!("declared peak 4000: preview vs export {diff:.2} mean codes"); + assert!( + diff <= 2.0, + "the export is {diff:.2} codes from what the preview showed" + ); + drop(reopened); + std::fs::remove_file(&out).unwrap(); +} diff --git a/crates/engine/tests/hw_decode.rs b/crates/engine/tests/hw_decode.rs index 2b1ca3f..3fbf5fc 100644 --- a/crates/engine/tests/hw_decode.rs +++ b/crates/engine/tests/hw_decode.rs @@ -246,7 +246,7 @@ fn the_hdr_film_renders_tone_mapped() { // 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, engine::tonemap::Preset::default()); + let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default(), None); let sdr = ColorDescription { matrix: Matrix::Bt709, transfer: engine::colorspace::Transfer::Sdr, diff --git a/crates/engine/tests/tonemap_render.rs b/crates/engine/tests/tonemap_render.rs index e38ad02..fd13f22 100644 --- a/crates/engine/tests/tonemap_render.rs +++ b/crates/engine/tests/tonemap_render.rs @@ -99,7 +99,13 @@ fn spread(px: [u8; 3]) -> u8 { /// 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, preset: Preset) -> [u8; 3] { +fn by_hand( + codes: [u8; 3], + grade: &ColorParams, + before: bool, + preset: Preset, + peak: Option, +) -> [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]; @@ -107,7 +113,7 @@ fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool, preset: Preset) -> if before { apply_yuv(grade, &mut y, &mut u, &mut v); } - ToneMapper::new(Hdr::Pq, preset).map(&mut y, &mut u, &mut v, w, h); + ToneMapper::new(Hdr::Pq, preset, peak).map(&mut y, &mut u, &mut v, w, h); if !before { apply_yuv(grade, &mut y, &mut u, &mut v); } @@ -256,8 +262,8 @@ fn the_grade_lands_after_the_tone_map() { for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] { let shown = pixel(&frame, patch.1); - let after = by_hand(patch.0, &grade, false, Preset::default()); - let before = by_hand(patch.0, &grade, true, Preset::default()); + let after = by_hand(patch.0, &grade, false, Preset::default(), None); + let before = by_hand(patch.0, &grade, true, Preset::default(), None); for (i, channel) in ["B", "G", "R"].iter().enumerate() { assert!( shown[i].abs_diff(after[i]) <= 2, @@ -270,3 +276,65 @@ fn the_grade_lands_after_the_tone_map() { ); } } + +/// The film's own declared peak, all the way to the window: `test_hdr_bright.mkv` +/// carries the same four patches as `test_pq.mp4` and a container MaxCLL of +/// 4000 cd/m^2, so a funnel that read the metadata renders it at 4000 and one +/// that ignored it renders it at the 1000 an undeclared file is assumed at -- +/// two plainly different pictures, which is why that fixture says 4000 and the +/// older metadata ones say the 1000 nothing can tell apart from the fallback. +/// +/// Both sides are computed by hand through the same `ToneMapper`, so what is +/// asserted is which number the *funnel* built its table with, not where Method +/// A puts a patch. +#[test] +fn a_films_declared_peak_reaches_the_window() { + let mut session = open("test_hdr_bright.mkv"); + assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags"); + assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet"); + let frame = next_frame(&mut session, "an open"); + let flat = ColorParams::default(); + for (patch, name) in [(DIFFUSE, "diffuse white"), (HIGHLIGHT, "the highlight")] { + let shown = luma_code(pixel(&frame, patch.1)); + let declared = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, Some(4000.0))); + let ignored = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, None)); + assert!( + shown.abs_diff(declared) <= 2, + "{name} rendered at {shown}, {declared} at the film's declared 4000 cd/m^2" + ); + assert!( + shown.abs_diff(ignored) > 8, + "{name}: {shown} is indistinguishable from the {ignored} of an ignored peak" + ); + } +} + +/// ...and both tiers a peak can live in reach the table, on the fixtures that +/// exist for each: `test_hdr_meta.mkv` declares its 1000 in the container, +/// `test_hdr_sei.mkv` only inside the HEVC bitstream. Neither can be told apart +/// from the fallback in a *picture* (1000 is what an undeclared file is assumed +/// at, and both are black), so what is asserted is the number the table is +/// built at -- the same `Demuxer::light().peak()` hand-off the decode funnel +/// and the export table make. +#[test] +fn either_tier_of_metadata_is_what_the_table_is_built_at() { + for (name, tier) in [ + ("test_hdr_meta.mkv", "container"), + ("test_hdr_meta.mp4", "container"), + ("test_hdr_sei.mkv", "bitstream SEI"), + ("test_hdr_bright.mkv", "container"), + ] { + let (_, demuxer) = engine::demux::Demuxer::open(&asset(name)).expect("open"); + let peak = demuxer.light().peak(); + let want = match name { + "test_hdr_bright.mkv" => 4000.0, + _ => 1000.0, + }; + assert_eq!(peak, Some(want), "{name} ({tier} tier)"); + let mapper = ToneMapper::new(Hdr::Pq, Preset::Reference, peak); + assert_eq!(mapper.peak(), want, "{name}: the table's assumed peak"); + } + // An SDR file declares nothing, and nothing is what the map is told. + let (_, demuxer) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open"); + assert_eq!(demuxer.light().peak(), None, "an SDR file's peak"); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 27319ca..42afd4d 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -287,6 +287,25 @@ ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \ assets/test_hdr_meta.mkv ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \ assets/test_hdr_meta.mp4 +# ...and one whose declared peak is a number nothing assumes: the three above +# say 1000, which is exactly what a file that declared *nothing* is assumed at, +# so no picture made from them can show that the metadata was read. This one is +# mastered at 4000 (`L(40000000,50)`, MaxCLL 4000) over the same four patches +# `test_pq.mp4` carries -- ten-bit codes here, four times the eight-bit ones -- +# so a tone map told 4000 lands them visibly elsewhere than one told 1000. +# +# Same two passes for the same reason, and the H.264 second one is what makes it +# software-decodable: the render tests that read it must not need a VA-API +# plugin. `-qp 1` on flat patches so the codes arrive as written (measured: 144, +# 181 and 100 come back exactly). +bright_sei="$(mktemp -t edith_hdr_bright_XXXXXX.mkv)" +ffmpeg -y -f lavfi -i "color=c=black:s=320x240:rate=25:duration=0.4,format=yuv420p10le,geq=lum='if(lt(Y,H/2),if(lt(X,W/2),576,724),400)':cb='if(lt(Y,H/2),512,360)':cr='if(lt(Y,H/2),512,800)',setparams=color_primaries=bt2020:color_trc=smpte2084:colorspace=bt2020nc:range=tv" \ + -c:v libx265 -pix_fmt yuv420p10le \ + -x265-params "log-level=error:master-display=G(8500,39850)B(6550,2300)R(35400,14600)WP(15635,16450)L(40000000,50):max-cll=4000,400" \ + "$bright_sei" +ffmpeg -y -i "$bright_sei" -c:v libx264 -qp 1 -pix_fmt yuv420p \ + assets/test_hdr_bright.mkv +rm -f "$bright_sei" # 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.