forge
Explore
Log in

Don't you dare go Hollow

An HDR film reaches the window tone-mapped, and an SDR one is untouched

Browse files at this commit

f8dea1c8a81ae36914b67ba84cef1b4c41b8e360Ahmet Kaan GümüşParent: 86c11d8
  • feat
    • an HDR film reaches the window tone-mapped, and an SDR one is untouched
Show full message
✨ feat(color): an HDR film reaches the window tone-mapped, and an SDR one is untouched

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.rsmodified+66 -20
@@ -10,11 +10,12 @@ 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::colorspace::{ColorDescription, Matrix, Transfer};
14 use crate::convert::{i420_to_bgra, i420_to_bgra_with};14 use crate::convert::{i420_to_bgra, i420_to_bgra_with};
15 use crate::demux::{Codec, Demuxer, VideoMeta};15 use crate::demux::{Codec, Demuxer, VideoMeta};
16 use crate::hw::HwSession;16 use crate::hw::HwSession;
17 use crate::scale::Composer;17 use crate::scale::Composer;
18+use crate::tonemap::{self, ToneMapper};
18 19
19 /// One decoded picture, ready to hand to a renderer.20 /// One decoded picture, ready to hand to a renderer.
20 pub struct Frame {21 pub struct Frame {
@@ -496,18 +497,42 @@ struct Render {
496 /// used to assume of every file.497 /// used to assume of every file.
497 desc: ColorDescription,498 desc: ColorDescription,
498 canvas: Composer,499 canvas: Composer,
499- /// The graded copy of the source planes, refilled per frame and kept across500+ /// This stream's HDR-to-SDR map, built once here because building it is
500- /// the worker's whole range. Empty unless the clip is both graded *and*501+ /// float work over 9 537 grid nodes and the transfer is a property of the
501- /// placed, which is the only case that needs it.502+ /// stream. `None` for an SDR stream, which is what keeps that path exactly
503+ /// the one it was.
504+ tone: Option<ToneMapper>,
505+ /// The working copy of the source planes, refilled per frame and kept
506+ /// across the worker's whole range. Empty unless the clip needs one: it is
507+ /// tone-mapped in place, graded in place, or both.
502 graded: (Vec<u8>, Vec<u8>, Vec<u8>),508 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
503 }509 }
504 510
511+/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
512+/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
513+/// declared.
514+const TONE_MAPPED: ColorDescription = ColorDescription {
515+ matrix: Matrix::Bt709,
516+ transfer: Transfer::Sdr,
517+ full_range: false,
518+};
519+
505 impl Render {520 impl Render {
506 fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self {521 fn new(color: ColorParams, desc: ColorDescription, canvas: Composer) -> Self {
507 Self {522 Self {
508 color,523 color,
509 desc,524 desc,
510 canvas,525 canvas,
526+ // ponytail: the ceiling is that the map reads limited-range codes
527+ // (`tonemap`'s input contract), so a full-range PQ file -- which
528+ // no encoder writes and no camera produces -- is mapped as if it
529+ // were limited and comes out slightly crushed. The upgrade is a
530+ // range argument to `ToneMapper::new`.
531+ tone: match desc.transfer {
532+ Transfer::Sdr => None,
533+ Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq)),
534+ Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg)),
535+ },
511 graded: (Vec::new(), Vec::new(), Vec::new()),536 graded: (Vec::new(), Vec::new(), Vec::new()),
512 }537 }
513 }538 }
@@ -521,13 +546,47 @@ impl Render {
521 width: u32,546 width: u32,
522 height: u32,547 height: u32,
523 ) -> Frame {548 ) -> Frame {
524- if self.canvas.is_passthrough(width, height) {549+ let passthrough = self.canvas.is_passthrough(width, height);
550+ // Everything that has to happen to the samples before the canvas sees
551+ // them, on one copy: the tone map (HDR streams only) and, unless the
552+ // conversion below can fuse it, the grade. An SDR stream that is either
553+ // ungraded or passing through takes neither and never allocates.
554+ //
555+ // The grade lands *after* the map on purpose: it is a look on the
556+ // picture a viewer is shown, so its brightness and saturation mean what
557+ // they say in the SDR the tone map just produced, not in the 10-stop
558+ // HDR the file was in.
559+ let (y, u, v, desc) = if self.tone.is_some() || (!passthrough && !self.color.is_identity())
560+ {
561+ let (gy, gu, gv) = &mut self.graded;
562+ gy.clear();
563+ gy.extend_from_slice(y);
564+ gu.clear();
565+ gu.extend_from_slice(u);
566+ gv.clear();
567+ gv.extend_from_slice(v);
568+ if let Some(tone) = &self.tone {
569+ tone.map(gy, gu, gv, width as usize, height as usize);
570+ }
571+ if !passthrough && !self.color.is_identity() {
572+ crate::color::apply_yuv(&self.color, gy, gu, gv);
573+ }
574+ let desc = if self.tone.is_some() {
575+ TONE_MAPPED
576+ } else {
577+ self.desc
578+ };
579+ (&gy[..], &gu[..], &gv[..], desc)
580+ } else {
581+ (y, u, v, self.desc)
582+ };
583+ if passthrough {
525 return Frame {584 return Frame {
526 index,585 index,
527 width,586 width,
528 height,587 height,
529 bgra: i420_to_bgra_with(588 bgra: i420_to_bgra_with(
530- &self.desc,589+ &desc,
531 &self.color,590 &self.color,
532 y,591 y,
533 u,592 u,
@@ -537,19 +596,6 @@ impl Render {
537 ),596 ),
538 };597 };
539 }598 }
540- let (gy, gu, gv) = &mut self.graded;
541- let (y, u, v) = if self.color.is_identity() {
542- (y, u, v)
543- } else {
544- gy.clear();
545- gy.extend_from_slice(y);
546- gu.clear();
547- gu.extend_from_slice(u);
548- gv.clear();
549- gv.extend_from_slice(v);
550- crate::color::apply_yuv(&self.color, gy, gu, gv);
551- (&gy[..], &gu[..], &gv[..])
552- };
553 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);599 let (y, u, v, width, height) = self.canvas.place(y, u, v, width, height);
554 Frame {600 Frame {
555 index,601 index,
@@ -557,7 +603,7 @@ impl Render {
557 height,603 height,
558 // Ungraded on purpose: the grade is already in the pixels above and604 // Ungraded on purpose: the grade is already in the pixels above and
559 // the canvas around them must stay the black it was filled with.605 // the canvas around them must stay the black it was filled with.
560- bgra: i420_to_bgra(&self.desc, y, u, v, width as usize, height as usize),606+ bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
561 }607 }
562 }608 }
563 }609 }
crates/engine/src/export.rsmodified+4 -1
@@ -1015,7 +1015,10 @@ fn run(
1015 //1015 //
1016 // ponytail: an HDR source is composited with the matrix treatment alone1016 // ponytail: an HDR source is composited with the matrix treatment alone
1017 // and still looks washed out; the tonemap lands here, ahead of this, and1017 // and still looks washed out; the tonemap lands here, ahead of this, and
1018- // is a sibling task's.1018+ // is a sibling task's. Until it does, the sentence above holds for SDR
1019+ // only: playback now maps an HDR clip to SDR *before* grading it
1020+ // (`decode::Render::frame`), so an exported HDR grade is not the picture
1021+ // the canvas showed either.
1019 let remap = color1022 let remap = color
1020 .map(|c| c.matrix)1023 .map(|c| c.matrix)
1021 .filter(|&m| m != out_color.matrix)1024 .filter(|&m| m != out_color.matrix)
crates/engine/src/tonemap.rsmodified+59 -37
@@ -32,12 +32,12 @@
32 //! BT.1886 -- the SDR display's own curve, so peak stays peak and black stays32 //! BT.1886 -- the SDR display's own curve, so peak stays peak and black stays
33 //! black -- and back to limited-range BT.709 Y'C'bC'r.33 //! black -- and back to limited-range BT.709 Y'C'bC'r.
34 //!34 //!
35-//! Method A is conservative on mid-tones by construction: with the standard35+//! Method A is conservative on mid-tones by construction: told the standard
36 //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code36 //! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code
37-//! 166 (about 40 cd/m^2), not at SDR white. [`MASTER_NITS`] is the exposure37+//! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark.
38-//! knob -- a lower assumed peak lifts everything -- and is a constant here38+//! [`MASTER_NITS`] is the exposure knob that answers it: a lower assumed peak
39-//! because this module is handed pixels, never the stream metadata that would39+//! lifts everything, and it is a constant here because this module is handed
40-//! carry the real one.40+//! pixels, never the stream metadata that would carry the real one.
41 //!41 //!
42 //! # Why a 3D LUT42 //! # Why a 3D LUT
43 //!43 //!
@@ -50,11 +50,11 @@
50 //!50 //!
51 //! The axes are deliberately uneven. A node every 8th code on luma and every51 //! The axes are deliberately uneven. A node every 8th code on luma and every
52 //! 16th on chroma was measured against a uniform 33^3 and a uniform 17^3 on52 //! 16th on chroma was measured against a uniform 33^3 and a uniform 17^3 on
53-//! this machine: 17^3 puts the assumed peak (1000 cd/m^2, code 181) 5 codes53+//! this machine, back when the assumed peak was 1000 cd/m^2: 17^3 put that
54-//! shy of SDR white, because the curve's knee falls inside a 16-code luma54+//! peak's own code 5 codes shy of SDR white, because the curve's knee falls
55-//! cell, while a full 33^3 costs 30.7 ms a 4K frame against this one's 19.3 --55+//! inside a 16-code luma cell, while a full 33^3 costs 30.7 ms a 4K frame
56-//! four times the table, out of cache and out of budget. Fine where the eye56+//! against this one's 19.3 -- four times the table, out of cache and out of
57-//! is, coarse where the format already is.57+//! budget. Fine where the eye is, coarse where the format already is.
58 //!58 //!
59 //! Nodes are `u8`, the output's own precision, and the interpolation rounds59 //! Nodes are `u8`, the output's own precision, and the interpolation rounds
60 //! once at the end in `u32` fixed point. On a node the grid *is* the pipeline;60 //! once at the end in `u32` fixed point. On a node the grid *is* the pipeline;
@@ -71,10 +71,13 @@
71 //! pixels is mapped in the same visit, sharing the block's bilinear chroma71 //! pixels is mapped in the same visit, sharing the block's bilinear chroma
72 //! weights, which is what keeps a 4K frame inside a frame's time budget.72 //! weights, which is what keeps a 4K frame inside a frame's time budget.
73 73
74-/// The mastering peak Method A is told to assume, cd/m^2. 1000 is what HDR1074+/// The mastering peak Method A is told to assume, cd/m^2. Not the 1000 an HDR10
75-/// grades are mastered to in practice and what BT.2446's own worked example75+/// grade is mastered to and not BT.2446's own worked example: the goal here is
76-/// uses. See the module note: this is the exposure knob.76+/// what a *viewer* sees on an SDR screen next to mpv, and told 1000 the method
77-const MASTER_NITS: f32 = 1000.0;77+/// lands 203-nit diffuse white on code 166, which reads as broadcast-dark.
78+/// Told 400 it lands near 205 -- display-referred, the brightness a player
79+/// shows -- which is what this constant buys. See the module note.
80+const MASTER_NITS: f32 = 400.0;
78 /// The SDR display peak Method A targets, cd/m^2.81 /// The SDR display peak Method A targets, cd/m^2.
79 const SDR_NITS: f32 = 100.0;82 const SDR_NITS: f32 = 100.0;
80 /// Method A's working gamma. Not a display curve here -- it is the domain the83 /// Method A's working gamma. Not a display curve here -- it is the domain the
@@ -103,7 +106,8 @@ pub enum Transfer {
103 /// SMPTE ST 2084 / BT.2100 PQ, absolute: a code *is* a luminance.106 /// SMPTE ST 2084 / BT.2100 PQ, absolute: a code *is* a luminance.
104 Pq,107 Pq,
105 /// BT.2100 HLG, relative: a code is scene light, and the OOTF (system gamma108 /// BT.2100 HLG, relative: a code is scene light, and the OOTF (system gamma
106- /// 1.2 at a 1000 cd/m^2 display) turns it into display light.109+ /// 1.2 at a 1000 cd/m^2 display, less at a dimmer one) turns it into
110+ /// display light.
107 Hlg,111 Hlg,
108 }112 }
109 113
@@ -299,10 +303,12 @@ fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] {
299 // Clamping instead walks a too-bright pixel toward white, which is what a303 // Clamping instead walks a too-bright pixel toward white, which is what a
300 // highlight past the display's reach should do.304 // highlight past the display's reach should do.
301 //305 //
302- // ponytail: the ceiling is that MASTER_NITS is a guess. Content mastered306+ // ponytail: the ceiling is that MASTER_NITS is an exposure choice, not a
303- // brighter than 1000 cd/m^2 loses its top stops to white here. The upgrade307+ // measurement. Everything the content masters above it -- which at 400 is
304- // is the stream's own MaxCLL/mastering-display metadata reaching this308+ // most of an HDR10 grade's highlight range -- walks to white here. The
305- // module as a `new` argument -- nothing else in the pipeline changes.309+ // upgrade is the stream's own MaxCLL/mastering-display metadata reaching
310+ // this module as a `new` argument, with 400 as the fallback: nothing else
311+ // in the pipeline changes.
306 let lin = display_light(transfer, [r, g, b]);312 let lin = display_light(transfer, [r, g, b]);
307 let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA));313 let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA));
308 314
@@ -351,11 +357,14 @@ fn display_light(transfer: Transfer, rgb: [f32; 3]) -> [f32; 3] {
351 Transfer::Pq => rgb.map(pq_eotf),357 Transfer::Pq => rgb.map(pq_eotf),
352 Transfer::Hlg => {358 Transfer::Hlg => {
353 // BT.2100: inverse OETF to scene light, then the OOTF, whose system359 // BT.2100: inverse OETF to scene light, then the OOTF, whose system
354- // gamma is 1.2 at a 1000 cd/m^2 display -- which is the peak this360+ // gamma is 1.2 at a 1000 cd/m^2 display and follows the display
355- // module assumes anyway, so no log term is needed for it.361+ // peak from there by the standard's own log term -- so the peak
362+ // [`MASTER_NITS`] names is the peak the OOTF is built for, rather
363+ // than a number the constant silently invalidates.
356 let scene = rgb.map(hlg_scene);364 let scene = rgb.map(hlg_scene);
357 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];365 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
358- let gain = MASTER_NITS * ys.max(0.0).powf(0.2);366+ let gamma = 1.2 + 0.42 * (MASTER_NITS / 1000.0).log10();
367+ let gain = MASTER_NITS * ys.max(0.0).powf(gamma - 1.0);
359 scene.map(|c| gain * c)368 scene.map(|c| gain * c)
360 }369 }
361 }370 }
@@ -435,16 +444,26 @@ mod tests {
435 (y[0], u[0], v[0])444 (y[0], u[0], v[0])
436 }445 }
437 446
438- /// The three anchors, in cd/m^2, against codes worked out by hand from the447+ /// The anchors, in cd/m^2, against the codes the stages in the module note
439- /// stages in the module note. Black is pinned by the curve (0 in, 0 out);448+ /// give for [`MASTER_NITS`]. Black is pinned by the curve (0 in, 0 out);
440- /// 1000 nits is the assumed peak and must reach SDR white; 203 nits is449+ /// [`MASTER_NITS`] itself is the assumed peak and must reach SDR white;
441- /// BT.2408 diffuse white, which Method A deliberately does *not* put at SDR450+ /// 203 nits is BT.2408 diffuse white, and 205 is where a 400 cd/m^2 peak
442- /// white -- 166 is what the published maths gives, and the day that number451+ /// puts it -- a picture as bright as a player shows, which is the whole
443- /// moves, the transcription moved with it.452+ /// reason that constant is not 1000 (where the same maths gives 166). The
453+ /// day one of these moves, the transcription moved with it.
454+ ///
455+ /// 1000 nits is the ceiling the `map_code` ponytail names, asserted rather
456+ /// than described: everything above the assumed peak is white.
444 #[test]457 #[test]
445 fn pq_anchors_land_where_method_a_puts_them() {458 fn pq_anchors_land_where_method_a_puts_them() {
446 let mapper = ToneMapper::new(Transfer::Pq);459 let mapper = ToneMapper::new(Transfer::Pq);
447- for (nits, expected) in [(0.0, 16u8), (26.0, 89), (203.0, 166), (1000.0, 235)] {460+ for (nits, expected) in [
461+ (0.0, 16u8),
462+ (26.0, 108),
463+ (203.0, 205),
464+ (MASTER_NITS, 235),
465+ (1000.0, 235),
466+ ] {
448 let code = byte(pq_code(nits));467 let code = byte(pq_code(nits));
449 let (y, _, _) = mapped(&mapper, code, 128, 128);468 let (y, _, _) = mapped(&mapper, code, 128, 128);
450 assert!(469 assert!(
@@ -571,13 +590,16 @@ mod tests {
571 }590 }
572 591
573 /// HLG's own anchors. Its signal is relative, so what is worth pinning is592 /// HLG's own anchors. Its signal is relative, so what is worth pinning is
574- /// where the OOTF puts it: black at black, peak signal at the assumed593+ /// where the OOTF puts it: black at black and peak signal at the assumed
575- /// 1000 cd/m^2 display peak (hence SDR white, the PQ side's 1000-nit594+ /// display peak, hence SDR white -- to the grid's rounding, since code 235
576- /// anchor), and BT.2408 HLG diffuse white -- signal 0.75, which the inverse595+ /// sits between two luma nodes and the one below it is a hair under peak.
577- /// OETF and the system-gamma-1.2 OOTF land on 203 cd/m^2, the same light as596+ ///
578- /// the PQ side's diffuse white and so the same output code. One pipeline,597+ /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the
579- /// two front doors: if the HLG stage drifts, that agreement is the first598+ /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of
580- /// thing to break.599+ /// whatever peak the display has -- 76 cd/m^2 of [`MASTER_NITS`]'s 400,
600+ /// against PQ's absolute 203 -- and it comes out darker, at 170. That is
601+ /// the standard's own behaviour and the number to watch: if the OOTF's
602+ /// system gamma stops following the assumed peak, this is what moves.
581 #[test]603 #[test]
582 fn hlg_anchors_are_sane() {604 fn hlg_anchors_are_sane() {
583 let mapper = ToneMapper::new(Transfer::Hlg);605 let mapper = ToneMapper::new(Transfer::Hlg);
@@ -587,7 +609,7 @@ mod tests {
587 let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);609 let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);
588 assert!(black.abs_diff(16) <= 3, "HLG black -> {black}");610 assert!(black.abs_diff(16) <= 3, "HLG black -> {black}");
589 assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}");611 assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}");
590- assert!(diffuse.abs_diff(166) <= 3, "HLG diffuse white -> {diffuse}");612+ assert!(diffuse.abs_diff(170) <= 3, "HLG diffuse white -> {diffuse}");
591 }613 }
592 614
593 /// A short plane is left alone rather than half mapped, and a frame with no615 /// A short plane is left alone rather than half mapped, and a frame with no
crates/engine/tests/hw_decode.rsmodified+97 -1
@@ -16,10 +16,11 @@ 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::colorspace::{ColorDescription, Matrix};
20 use engine::convert::i420_to_bgra;20 use engine::convert::i420_to_bgra;
21 use engine::demux::Demuxer;21 use engine::demux::Demuxer;
22 use engine::hw::HwSession;22 use engine::hw::HwSession;
23+use engine::tonemap::{ToneMapper, Transfer};
23 24
24 fn asset(name: &str) -> PathBuf {25 fn asset(name: &str) -> PathBuf {
25 PathBuf::from(env!("CARGO_MANIFEST_DIR"))26 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -168,6 +169,101 @@ fn range_stops_at_end() {
168 assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range");169 assert_eq!(range_indices(&path, 148, 999).len(), 2, "clamped range");
169 }170 }
170 171
172+/// The real thing: a 4K HDR10 film through the funnel, against the picture the
173+/// same planes gave before the tone map was in it (BT.2020 matrix, HDR codes
174+/// shown as if they were SDR -- flat and grey-washed, which is the complaint
175+/// this whole path answers). Colour has to come *up*, not down, and the picture
176+/// has to land somewhere a display can show rather than at either rail.
177+///
178+/// Gated on the film being here: it is a 20 GB download, not a fixture. HEVC
179+/// Main 10, so this is a hardware-only test in every sense.
180+#[test]
181+#[ignore = "needs libengine_hw.so, a VA-API driver and the film"]
182+fn the_hdr_film_renders_tone_mapped() {
183+ // Two minutes in: past the studio logos, inside lit footage.
184+ const TARGET: u32 = 3000;
185+ let path = Path::new(
186+ "/path/to/a-real-4k-hdr10-film.mkv",
187+ );
188+ if !path.exists() {
189+ eprintln!("skipped: {} is not on this machine", path.display());
190+ return;
191+ }
192+ // SAFETY: --test-threads=1. There is no software HEVC decoder, so a pinned
193+ // VE_SW from another test in this binary would refuse the file outright.
194+ unsafe { std::env::remove_var("VE_SW") };
195+
196+ // The old picture, by hand off the plugin's own planes: the funnel did
197+ // exactly this before the tone map, and it is what the comparison needs.
198+ let mut hw = HwSession::open_at(path, TARGET).expect("no plugin/driver available");
199+ let (y, u, v, w, h) = hw
200+ .next_frame()
201+ .expect("hardware decode")
202+ .expect("no frame at the seek");
203+ let (w, h) = (w as usize, h as usize);
204+ let (y, u, v) = (y.to_vec(), u.to_vec(), v.to_vec());
205+ let untouched = i420_to_bgra(&color_of(path), &y, &u, &v, w, h);
206+
207+ // ...and the picture the engine shows now, through the funnel itself.
208+ let (_, rx, _cancel) = DecodeSession::open_at(path, TARGET).expect("open the film");
209+ let shown = rx.recv().expect("a frame off the funnel").bgra;
210+ assert_eq!(shown.len(), untouched.len(), "frame size");
211+
212+ // Saturation, as the mean distance from grey per pixel...
213+ let spread = |bgra: &[u8]| -> f64 {
214+ let total: u64 = bgra
215+ .chunks_exact(4)
216+ .map(|px| u64::from(px[..3].iter().max().unwrap() - px[..3].iter().min().unwrap()))
217+ .sum();
218+ total as f64 / (bgra.len() / 4) as f64
219+ };
220+ // ...and mean luma, in the limited-range code the tone map's anchors are in.
221+ let luma = |bgra: &[u8]| -> f64 {
222+ let total: f64 = bgra
223+ .chunks_exact(4)
224+ .map(|px| {
225+ 0.2126 * f64::from(px[2]) + 0.7152 * f64::from(px[1]) + 0.0722 * f64::from(px[0])
226+ })
227+ .sum();
228+ 16.0 + 219.0 * (total / (bgra.len() / 4) as f64) / 255.0
229+ };
230+ let (was, now) = (spread(&untouched), spread(&shown));
231+ eprintln!(
232+ "frame {TARGET}: saturation {was:.1} -> {now:.1}, mean luma {:.1} -> {:.1}",
233+ luma(&untouched),
234+ luma(&shown)
235+ );
236+ assert!(
237+ now > was,
238+ "the tone-mapped frame is no more colourful: {now}"
239+ );
240+ let mean = luma(&shown);
241+ assert!(
242+ (24.0..=200.0).contains(&mean),
243+ "the tone-mapped frame sits at one end of the scale: mean luma {mean}"
244+ );
245+
246+ // The funnel's own budget at this size: the map plus the conversion, which
247+ // is what an HDR frame costs on top of the decode. Fastest of five, for the
248+ // reason `tonemap::perf_4k_and_1080p` documents.
249+ let mapper = ToneMapper::new(Transfer::Pq);
250+ let sdr = ColorDescription {
251+ matrix: Matrix::Bt709,
252+ transfer: engine::colorspace::Transfer::Sdr,
253+ full_range: false,
254+ };
255+ let mut best = f64::MAX;
256+ for _ in 0..5 {
257+ let (mut my, mut mu, mut mv) = (y.clone(), u.clone(), v.clone());
258+ let t = Instant::now();
259+ mapper.map(&mut my, &mut mu, &mut mv, w, h);
260+ let _ = i420_to_bgra(&sdr, &my, &mu, &mv, w, h);
261+ best = best.min(t.elapsed().as_secs_f64() * 1000.0);
262+ }
263+ eprintln!("{w}x{h} tone map + convert: {best:.1} ms/frame");
264+ assert!(best <= 39.0, "{best:.1} ms/frame over the 39 ms budget");
265+}
266+
171 /// H.264 8-bit decode is bit-exact by conformance, so the two backends must267 /// H.264 8-bit decode is bit-exact by conformance, so the two backends must
172 /// agree. A mismatch means a driver deviation and is reported, not swallowed.268 /// agree. A mismatch means a driver deviation and is reported, not swallowed.
173 #[test]269 #[test]
crates/engine/tests/tonemap_render.rsadded+220 -0
@@ -0,0 +1,220 @@
1+//! An HDR stream reaching the window tone-mapped, through the door the window
2+//! itself opens ([`PlaybackSession`]) rather than through [`engine::tonemap`]
3+//! alone -- which is the whole of the claim: a PQ file used to be shown as if
4+//! its curve were SDR, i.e. grey-washed and flat, and the map has to run inside
5+//! the decode funnel for that to stop.
6+//!
7+//! `test_pq.mp4` is four flat patches whose codes `scripts/gen_fixtures.sh`
8+//! writes into the planes by hand, so every number below is named rather than
9+//! measured-and-blessed: BT.2408 diffuse white (203 cd/m^2 is PQ code 144), the
10+//! 1000 cd/m^2 highlight (code 181) and a saturated BT.2020 red.
11+//!
12+//! ```text
13+//! cargo test -p engine --release --test tonemap_render -- --test-threads=1
14+//! ```
15+
16+use std::path::PathBuf;
17+use std::thread::sleep;
18+use std::time::{Duration, Instant};
19+
20+use engine::PlaybackSession;
21+use engine::color::{ColorParams, apply_yuv};
22+use engine::colorspace::{ColorDescription, Matrix, Transfer};
23+use engine::convert::i420_to_bgra;
24+use engine::project::Lane;
25+use engine::tonemap::{ToneMapper, Transfer as Hdr};
26+
27+/// The fixture's patches: the source codes, and where the centre of each one
28+/// sits in the 320x240 picture.
29+const DIFFUSE: ([u8; 3], (usize, usize)) = ([144, 128, 128], (80, 60));
30+const HIGHLIGHT: ([u8; 3], (usize, usize)) = ([181, 128, 128], (240, 60));
31+const RED: ([u8; 3], (usize, usize)) = ([100, 90, 200], (160, 180));
32+
33+/// What the tone map hands the rest of the funnel: BT.709, SDR, limited range.
34+const SDR: ColorDescription = ColorDescription {
35+ matrix: Matrix::Bt709,
36+ transfer: Transfer::Sdr,
37+ full_range: false,
38+};
39+
40+/// Frame 0 of `test_h264.mkv` as this engine rendered it before the tone map
41+/// existed -- passthrough, ungraded -- and the same file on a 640x360 canvas
42+/// with a grade on it, which is the other branch of the funnel. Measured on
43+/// `main`; an SDR stream may not move by one byte.
44+const SDR_PASSTHROUGH: u64 = 0x9EF1_6F6F_5310_BCEE;
45+const SDR_GRADED_AND_PLACED: u64 = 0xAFA6_6394_3937_DE5B;
46+
47+fn asset(name: &str) -> PathBuf {
48+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
49+ .join("../../assets")
50+ .join(name)
51+}
52+
53+fn fnv(b: &[u8]) -> u64 {
54+ b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &x| {
55+ (h ^ u64::from(x)).wrapping_mul(0x100_0000_01b3)
56+ })
57+}
58+
59+/// Silent and software-decoded: the fixture is H.264 on purpose, so the bytes
60+/// are the same on a machine with a VA-API plugin and one without (hence
61+/// `--test-threads=1`).
62+fn open(name: &str) -> PlaybackSession {
63+ unsafe { std::env::set_var("VE_SW", "1") };
64+ let session = PlaybackSession::open(asset(name)).expect("open");
65+ session.set_gain(0.0);
66+ session
67+}
68+
69+fn next_frame(session: &mut PlaybackSession, what: &str) -> engine::Frame {
70+ let deadline = Instant::now() + Duration::from_secs(30);
71+ loop {
72+ if let Some(frame) = session.try_frame() {
73+ return frame;
74+ }
75+ assert!(Instant::now() < deadline, "no frame after {what}");
76+ sleep(Duration::from_millis(4));
77+ }
78+}
79+
80+/// One pixel of a rendered frame, as (B, G, R).
81+fn pixel(frame: &engine::Frame, (x, y): (usize, usize)) -> [u8; 3] {
82+ let at = (y * frame.width as usize + x) * 4;
83+ [frame.bgra[at], frame.bgra[at + 1], frame.bgra[at + 2]]
84+}
85+
86+/// The limited-range BT.709 luma code a rendered pixel carries: the unit the
87+/// tone map's own anchors are named in, read back off the BGRA the window gets.
88+fn luma_code(bgra: [u8; 3]) -> u8 {
89+ let (b, g, r) = (f32::from(bgra[0]), f32::from(bgra[1]), f32::from(bgra[2]));
90+ (16.0 + 219.0 * (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0).round() as u8
91+}
92+
93+/// How far one pixel is from grey.
94+fn spread(px: [u8; 3]) -> u8 {
95+ px.iter().max().unwrap() - px.iter().min().unwrap()
96+}
97+
98+/// One flat patch of `codes`, rendered by hand the way the funnel is supposed
99+/// to render it: tone-mapped first, then graded, then converted as BT.709 SDR.
100+/// `grade` is applied in whichever domain `before` says -- which is the point of
101+/// [`the_grade_lands_after_the_tone_map`].
102+fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool) -> [u8; 3] {
103+ let (w, h) = (8usize, 8usize);
104+ let mut y = vec![codes[0]; w * h];
105+ let mut u = vec![codes[1]; w / 2 * h / 2];
106+ let mut v = vec![codes[2]; w / 2 * h / 2];
107+ if before {
108+ apply_yuv(grade, &mut y, &mut u, &mut v);
109+ }
110+ ToneMapper::new(Hdr::Pq).map(&mut y, &mut u, &mut v, w, h);
111+ if !before {
112+ apply_yuv(grade, &mut y, &mut u, &mut v);
113+ }
114+ let bgra = i420_to_bgra(&SDR, &y, &u, &v, w, h);
115+ [bgra[0], bgra[1], bgra[2]]
116+}
117+
118+/// The claim itself: a PQ stream is shown as an SDR display can show it.
119+/// Diffuse white lands where a viewer expects white-ish paper (~205, not the
120+/// 144 an untouched code would convert to and not clipped white), the 1000
121+/// cd/m^2 highlight stays a highlight, and the saturated red is still red --
122+/// a grey wash is exactly what the missing map looked like.
123+#[test]
124+fn a_pq_stream_is_tone_mapped_on_its_way_to_the_window() {
125+ let mut session = open("test_pq.mp4");
126+ assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags");
127+ assert_eq!(
128+ session.meta().color.matrix,
129+ Matrix::Bt2020Ncl,
130+ "fixture tags"
131+ );
132+
133+ let frame = next_frame(&mut session, "an open");
134+ assert_eq!((frame.width, frame.height), (320, 240));
135+
136+ let diffuse = luma_code(pixel(&frame, DIFFUSE.1));
137+ assert!(
138+ (200..=210).contains(&diffuse),
139+ "diffuse white (code {}) rendered at {diffuse}, wanted 200..=210",
140+ DIFFUSE.0[0]
141+ );
142+ let highlight = luma_code(pixel(&frame, HIGHLIGHT.1));
143+ assert!(
144+ (225..=239).contains(&highlight) && highlight > diffuse,
145+ "the 1000 cd/m^2 highlight rendered at {highlight}"
146+ );
147+ let red = pixel(&frame, RED.1);
148+ assert!(
149+ spread(red) > 60 && red[2] > red[0] && red[2] > red[1],
150+ "the saturated red washed out to {red:?}"
151+ );
152+}
153+
154+/// The other half: an SDR stream may not move by one byte for any of this.
155+/// Both branches of the funnel -- the fused passthrough conversion and the
156+/// graded-then-placed one -- against hashes measured before the tone map was
157+/// wired in.
158+#[test]
159+fn an_sdr_stream_is_byte_for_byte_the_picture_it_was() {
160+ let mut session = open("test_h264.mkv");
161+ assert_eq!(session.meta().color.transfer, Transfer::Sdr);
162+ let plain = next_frame(&mut session, "an open");
163+ assert_eq!(fnv(&plain.bgra), SDR_PASSTHROUGH, "the passthrough branch");
164+
165+ assert!(session.set_resolution(640, 360), "shrink the canvas");
166+ assert!(
167+ session.set_color(
168+ Lane::V1,
169+ 0,
170+ Some(ColorParams {
171+ saturation: 1.4,
172+ brightness: 0.1,
173+ ..Default::default()
174+ })
175+ ),
176+ "grade the clip"
177+ );
178+ let placed = next_frame(&mut session, "a resize and a grade");
179+ assert_eq!((placed.width, placed.height), (640, 360));
180+ assert_eq!(
181+ fnv(&placed.bgra),
182+ SDR_GRADED_AND_PLACED,
183+ "the graded-and-placed branch"
184+ );
185+}
186+
187+/// Order: the grade is a look applied to the picture the viewer sees, so it
188+/// lands on the *tone-mapped* samples. Graded before the map instead, the same
189+/// numbers give a different pixel -- the second assert is what makes the first
190+/// one mean anything.
191+#[test]
192+fn the_grade_lands_after_the_tone_map() {
193+ let grade = ColorParams {
194+ saturation: 1.5,
195+ brightness: 0.08,
196+ ..Default::default()
197+ };
198+ let mut session = open("test_pq.mp4");
199+ assert!(
200+ session.set_color(Lane::V1, 0, Some(grade)),
201+ "grade the clip"
202+ );
203+ let frame = next_frame(&mut session, "a grade");
204+
205+ for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {
206+ let shown = pixel(&frame, patch.1);
207+ let after = by_hand(patch.0, &grade, false);
208+ let before = by_hand(patch.0, &grade, true);
209+ for (i, channel) in ["B", "G", "R"].iter().enumerate() {
210+ assert!(
211+ shown[i].abs_diff(after[i]) <= 2,
212+ "{name} {channel}: shown {shown:?}, tone-map-then-grade {after:?}"
213+ );
214+ }
215+ assert!(
216+ after.iter().zip(&before).any(|(a, b)| a.abs_diff(*b) > 4),
217+ "{name}: grading before the map gives the same pixel, so this proves nothing"
218+ );
219+ }
220+}
scripts/gen_fixtures.shmodified+16 -0
@@ -250,6 +250,22 @@ ffmpeg -y -f lavfi -i testsrc2=size=640x480:rate=30:duration=1 \
250 -c:v libsvtav1 -preset 8 -pix_fmt yuv420p \250 -c:v libsvtav1 -preset 8 -pix_fmt yuv420p \
251 -svtav1-params color-primaries=1:transfer-characteristics=1:matrix-coefficients=1 \251 -svtav1-params color-primaries=1:transfer-characteristics=1:matrix-coefficients=1 \
252 assets/test_vui_av1.mp4252 assets/test_vui_av1.mp4
253+# The HDR fixture, and the one place in this set where the *picture* is the
254+# point: four flat patches written straight into the planes by `geq`, so a test
255+# can name the code it feeds the tone map (`engine::tonemap`) and the code it
256+# expects back. Top left is BT.2408 diffuse white -- 203 cd/m^2 is PQ signal
257+# 0.584, limited-range code 144 -- top right the 1000 cd/m^2 the grade is
258+# mastered against (code 181), and the bottom half a saturated BT.2020 red,
259+# which is what a grey-washed render loses. H.264 rather than HEVC so the
260+# software decoder can read it on a machine with no VA-API plugin: the tone map
261+# is fed by the tags, not by the codec. `-qp 1` on flat patches is exact to the
262+# code, so the numbers a test names are the numbers that arrive; the tags go on
263+# through `setparams` rather than through the encoder's own `-colorspace`,
264+# because that one makes ffmpeg *convert* into BT.2020 and the patches would no
265+# longer be the codes written above.
266+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" \
267+ -c:v libx264 -profile:v high -qp 1 -pix_fmt yuv420p \
268+ assets/test_pq.mp4
253 # Sync fixture: one flash and one beep, at the same instant. Black picture with269 # Sync fixture: one flash and one beep, at the same instant. Black picture with
254 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that270 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
255 # stretch — so a test can find each of them and say how far apart they came out.271 # stretch — so a test can find each of them and say how far apart they came out.