forge
Explore
Log in

Don't you dare go Hollow

The reference rendition converts a film at the peak the film declares

Browse files at this commit

27097e2c80908d6c18a149045fa278b421613241Ahmet Kaan GümüşParent: 2e53106
  • feat
    • the reference rendition converts a film at the peak the film declares
Show full message
✨ feat(tonemap): the reference rendition converts a film at the peak the film declares

`Demuxer::light().peak()` -- a stream's MaxCLL, or its mastering display's
maximum -- has been read at every open and dropped on the floor. It now reaches
`ToneMapper::new` as `declared_peak`, and `Preset::master_nits_for` is the whole
composition rule: `Reference` takes the film's number (1000 stays the fallback
for a file that declared nothing), `Standard` and `Vivid` keep their fixed 400
and 250, because a picked exposure that moved per file would not be a pick.

One HDR film declares 1759 cd/m^2, so its 1000-nit highlights
land at SDR 215 instead of clipping at white, and BT.2408 diffuse white at 145
instead of 166.

Both sites that build a table have the demuxer in hand already, so nothing is
promoted through `VideoMeta`: the decode funnel reads it before the worker takes
the demuxer, and `source_rate` returns it off the header parse export already
did -- which is what keeps preview and export on one number.

A declared peak is a stranger's number and is checked before it becomes a
divisor: outside 100..=10000, or a NaN, is treated as not declared.

test_hdr_bright.mkv joins the fixtures for it -- the older HDR metadata ones all
say 1000, which no picture can tell apart from the fallback.
crates/engine/src/decode.rsmodified+16 -3
@@ -335,6 +335,9 @@ impl DecodeSession {
335 ColorDescription::default(),335 ColorDescription::default(),
336 canvas,336 canvas,
337 tonemap::Preset::default(),337 tonemap::Preset::default(),
338+ // ...and no declared peak either, for the same reason: there is no
339+ // tone map on this path to hand one to.
340+ None,
338 )341 )
339 .frame(342 .frame(
340 start_frame,343 start_frame,
@@ -414,6 +417,12 @@ impl DecodeSession {
414 // Read off the file once, here, and carried into the worker: it is a417 // Read off the file once, here, and carried into the worker: it is a
415 // property of the stream, so it cannot change while one range decodes.418 // property of the stream, so it cannot change while one range decodes.
416 let source_color = meta.color;419 let source_color = meta.color;
420+ // ...and with it what the film says its own brightest picture is
421+ // ([`Demuxer::light`]): the tone map's assumed peak on the reference
422+ // rendition, so a 1759 cd/m^2 grade is converted at 1759 rather than at
423+ // the 1000 a file that declared nothing is assumed at. Read here
424+ // because the demuxer is moved into the worker below.
425+ let declared_peak = demuxer.light().peak();
417 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the426 // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the
418 // decoder run ahead of the display without limit.427 // decoder run ahead of the display without limit.
419 let (tx, rx) = sync_channel(2);428 let (tx, rx) = sync_channel(2);
@@ -448,7 +457,7 @@ impl DecodeSession {
448 if worker_cancel.load(Ordering::Relaxed) {457 if worker_cancel.load(Ordering::Relaxed) {
449 return;458 return;
450 }459 }
451- let mut render = Render::new(color, source_color, canvas, tone);460+ let mut render = Render::new(color, source_color, canvas, tone, declared_peak);
452 // The plugin has to be opened on the thread that uses it: its461 // The plugin has to be opened on the thread that uses it: its
453 // VA-API state is not `Send`-safe across a later hand-off.462 // VA-API state is not `Send`-safe across a later hand-off.
454 if let Some(hw) = open_hw(&path, start_frame) {463 if let Some(hw) = open_hw(&path, start_frame) {
@@ -536,11 +545,15 @@ const TONE_MAPPED: ColorDescription = ColorDescription {
536 };545 };
537 546
538 impl Render {547 impl Render {
548+ /// `peak` is what the file declared about its own brightness
549+ /// ([`Demuxer::light`]), which only an HDR stream has and only the
550+ /// reference rendition reads (see [`tonemap::Preset`]).
539 fn new(551 fn new(
540 color: ColorParams,552 color: ColorParams,
541 desc: ColorDescription,553 desc: ColorDescription,
542 canvas: Composer,554 canvas: Composer,
543 preset: tonemap::Preset,555 preset: tonemap::Preset,
556+ peak: Option<f32>,
544 ) -> Self {557 ) -> Self {
545 Self {558 Self {
546 color,559 color,
@@ -553,8 +566,8 @@ impl Render {
553 // range argument to `ToneMapper::new`.566 // range argument to `ToneMapper::new`.
554 tone: match desc.transfer {567 tone: match desc.transfer {
555 Transfer::Sdr => None,568 Transfer::Sdr => None,
556- Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)),569+ Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
557- Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)),570+ Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
558 },571 },
559 graded: (Vec::new(), Vec::new(), Vec::new()),572 graded: (Vec::new(), Vec::new(), Vec::new()),
560 }573 }
crates/engine/src/demux.rsmodified+5 -3
@@ -95,9 +95,11 @@ impl Demuxer {
95 /// read at open out of the container and -- for an HEVC stream whose95 /// read at open out of the container and -- for an HEVC stream whose
96 /// container said nothing -- out of the first access unit's SEI.96 /// container said nothing -- out of the first access unit's SEI.
97 ///97 ///
98- /// Not part of [`VideoMeta`] for the reason [`Self::bit_depth`] is not:98+ /// Read by the two sites that build a tone map -- the decode funnel
99- /// nothing above reads it yet. [`crate::tonemap`] is where it goes, and that99+ /// (`decode::DecodeSession::open_worker`) and the export table -- as the
100- /// is a change of its own.100+ /// assumed peak of [`crate::tonemap::Preset::Reference`]. Still not part of
101+ /// [`VideoMeta`]: both of them have the demuxer itself in hand, so the
102+ /// number travels no further than the open that read it.
101 pub fn light(&self) -> ContentLight {103 pub fn light(&self) -> ContentLight {
102 match self {104 match self {
103 Self::Mp4(d) => d.light,105 Self::Mp4(d) => d.light,
crates/engine/src/export.rsmodified+19 -13
@@ -959,7 +959,7 @@ fn run(
959 // samples *mean* ([`ColorDescription`]), which is what decides whether they959 // samples *mean* ([`ColorDescription`]), which is what decides whether they
960 // are remapped on the way in. Real time for a still, a song and a960 // are remapped on the way in. Real time for a still, a song and a
961 // single-rate project, where every conversion below is the identity.961 // single-rate project, where every conversion below is the identity.
962- let rates: Vec<(Rate, ColorDescription)> = sources962+ let rates: Vec<(Rate, ColorDescription, Option<f32>)> = sources
963 .iter()963 .iter()
964 .map(|source| source_rate(&source.path, meta.frame_rate))964 .map(|source| source_rate(&source.path, meta.frame_rate))
965 .collect();965 .collect();
@@ -970,17 +970,18 @@ fn run(
970 // is the difference between paying that once and paying it per cut. An SDR970 // is the difference between paying that once and paying it per cut. An SDR
971 // source -- the whole of an ordinary project -- builds no table at all.971 // source -- the whole of an ordinary project -- builds no table at all.
972 //972 //
973- // Through the project's own preset ([`tonemap::Preset`]), which is the same973+ // Through the project's own preset ([`tonemap::Preset`]) and each source's
974- // one playback's decode funnel builds its tables with: preview and export974+ // own declared peak, which is the pair playback's decode funnel builds its
975- // are the same rendition of the same film because they are told the same975+ // tables with: preview and export are the same rendition of the same film
976- // thing, not because two numbers happen to agree.976+ // because they are told the same two things, not because two numbers happen
977+ // to agree.
977 let preset = project.tone();978 let preset = project.tone();
978 let tone: Vec<Option<ToneMapper>> = rates979 let tone: Vec<Option<ToneMapper>> = rates
979 .iter()980 .iter()
980- .map(|(_, color)| match color.transfer {981+ .map(|(_, color, peak)| match color.transfer {
981 Transfer::Sdr => None,982 Transfer::Sdr => None,
982- Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset)),983+ Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
983- Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset)),984+ Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
984 })985 })
985 .collect();986 .collect();
986 // ...and the one space they are all written in, the same rule a reader with987 // ...and the one space they are all written in, the same rule a reader with
@@ -1016,7 +1017,7 @@ fn run(
1016 let entry = sources1017 let entry = sources
1017 .get(source)1018 .get(source)
1018 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;1019 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
1019- let (rate, color) = rates[source];1020+ let (rate, color, _peak) = rates[source];
1020 // Opened at the file's own frame, which is the only place the1021 // Opened at the file's own frame, which is the only place the
1021 // file's numbering is used -- the span's are the timeline's.1022 // file's numbering is used -- the span's are the timeline's.
1022 let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;1023 let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
@@ -1233,24 +1234,29 @@ fn remap_into(
1233 /// -- a still, a song -- and for one that will not open here: the decoder is1234 /// -- a still, a song -- and for one that will not open here: the decoder is
1234 /// opened a few lines later and fails the export by name, which is a better1235 /// opened a few lines later and fails the export by name, which is a better
1235 /// error than this one could raise.1236 /// error than this one could raise.
1236-fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription) {1237+fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option<f32>) {
1237 if crate::is_image(path) || crate::is_audio(path) {1238 if crate::is_image(path) || crate::is_audio(path) {
1238 // A still is BT.601 by construction whatever it was authored as:1239 // A still is BT.601 by construction whatever it was authored as:
1239 // `decode::rgb_to_i420` is the one matrix that turns its pixels into1240 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
1240 // planes. A song has no picture and the answer is never read.1241 // planes. A song has no picture and the answer is never read.
1241- return (Rate::REAL_TIME, ColorDescription::default());1242+ return (Rate::REAL_TIME, ColorDescription::default(), None);
1242 }1243 }
1243 match Demuxer::open(path) {1244 match Demuxer::open(path) {
1244 // ...and one whose rate cannot be named against the timeline's, which1245 // ...and one whose rate cannot be named against the timeline's, which
1245 // `matches_timeline` refuses at import, so nothing on a timeline is on1246 // `matches_timeline` refuses at import, so nothing on a timeline is on
1246 // this arm either.1247 // this arm either.
1247- Ok((meta, _)) => (1248+ //
1249+ // The declared peak comes off the same open the space does, which is
1250+ // what keeps export on the number playback's decode funnel read: one
1251+ // header parse, both answers.
1252+ Ok((meta, demuxer)) => (
1248 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),1253 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
1249 meta.color,1254 meta.color,
1255+ demuxer.light().peak(),
1250 ),1256 ),
1251 // Unreadable here means unreadable below too, where the span dies with a1257 // Unreadable here means unreadable below too, where the span dies with a
1252 // real message; the file's own space is the least of that.1258 // real message; the file's own space is the least of that.
1253- Err(_) => (Rate::REAL_TIME, ColorDescription::default()),1259+ Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None),
1254 }1260 }
1255 }1261 }
1256 1262
crates/engine/src/tonemap.rsmodified+230 -36
@@ -40,8 +40,10 @@
40 //! everything -- and *which* answer a project wants is a matter of taste, not of40 //! everything -- and *which* answer a project wants is a matter of taste, not of
41 //! correctness: a reference rendition and a vivid one are both honest pictures41 //! correctness: a reference rendition and a vivid one are both honest pictures
42 //! of the same film. So it is a [`Preset`] the viewer picks rather than a42 //! of the same film. So it is a [`Preset`] the viewer picks rather than a
43-//! constant, and never the stream's own metadata, which this module is never43+//! constant -- read, on the faithful one, against the peak the film itself
44-//! handed (it is given pixels).44+//! declares (`declared_peak` at [`ToneMapper::new`], the demuxer's MaxCLL or
45+//! mastering-display maximum). The picked rendition still decides; the metadata
46+//! only says what "the peak the content really has" is for this film.
45 //!47 //!
46 //! # Why a 3D LUT48 //! # Why a 3D LUT
47 //!49 //!
@@ -107,9 +109,23 @@ const CHROMA_FRAC: u32 = 16;
107 /// player looks; told a lower one it lifts the whole picture. The gain is109 /// player looks; told a lower one it lifts the whole picture. The gain is
108 /// applied *after* the map, on the SDR colour differences, so it enriches the110 /// applied *after* the map, on the SDR colour differences, so it enriches the
109 /// picture a viewer is shown rather than bending a stage of the standard.111 /// picture a viewer is shown rather than bending a stage of the standard.
112+///
113+/// # How a film's own metadata composes with the pick
114+///
115+/// Only [`Reference`](Preset::Reference) reads it, and that is the rule rather
116+/// than an omission: it is the rendition that promises *the mastering peak the
117+/// content really has*, so a film that declares 1759 cd/m^2 is converted at
118+/// 1759 and its 1000 is a fallback for a file that declared nothing.
119+/// [`Standard`](Preset::Standard) and [`Vivid`](Preset::Vivid) name a fixed
120+/// exposure -- 400 and 250 -- which is the whole of what a viewer picks them
121+/// for; letting a film's metadata move those numbers would make the same pick
122+/// mean a different brightness on every file, which is the opposite of what
123+/// picking one is for. So: metadata is read *against* the picked preset, never
124+/// in place of it, and two of the three are deliberately deaf to it.
110 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]125 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
111 pub enum Preset {126 pub enum Preset {
112- /// The published conversion, at the mastering peak the content really has.127+ /// The published conversion, at the mastering peak the content really has
128+ /// -- the film's own declared peak where it has one (see the note above).
113 /// The default: what the document says, and what a second reference can be129 /// The default: what the document says, and what a second reference can be
114 /// checked against.130 /// checked against.
115 #[default]131 #[default]
@@ -127,7 +143,8 @@ impl Preset {
127 /// last.143 /// last.
128 pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid];144 pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid];
129 145
130- /// The mastering peak Method A is told to assume, cd/m^2.146+ /// The mastering peak Method A is told to assume, cd/m^2: this rendition's
147+ /// own number, before a file gets a say ([`Self::master_nits_for`]).
131 pub fn master_nits(self) -> f32 {148 pub fn master_nits(self) -> f32 {
132 match self {149 match self {
133 Preset::Reference => 1000.0,150 Preset::Reference => 1000.0,
@@ -136,6 +153,23 @@ impl Preset {
136 }153 }
137 }154 }
138 155
156+ /// The peak Method A is really run at, given what the file declared
157+ /// ([`crate::demux::Demuxer::light`] -> [`crate::colorspace::ContentLight::peak`]).
158+ /// The composition rule is on the enum: the reference rendition takes the
159+ /// film's number, the other two keep their own.
160+ ///
161+ /// A declared peak is a stranger's number, so it is checked before it
162+ /// becomes the divisor of every pixel: below SDR white the whole picture
163+ /// clips to white, and a NaN would poison the entire table into black.
164+ /// Out of range -- or a NaN, which no comparison admits -- is treated as
165+ /// not declared. The ceiling is PQ's own 10 000 cd/m^2.
166+ pub fn master_nits_for(self, declared_peak: Option<f32>) -> f32 {
167+ match (self, declared_peak) {
168+ (Preset::Reference, Some(peak)) if (SDR_NITS..=10_000.0).contains(&peak) => peak,
169+ _ => self.master_nits(),
170+ }
171+ }
172+
139 /// What the SDR colour differences are multiplied by after the map. `1.0`173 /// What the SDR colour differences are multiplied by after the map. `1.0`
140 /// leaves the method's own output untouched, byte for byte.174 /// leaves the method's own output untouched, byte for byte.
141 pub fn chroma_gain(self) -> f32 {175 pub fn chroma_gain(self) -> f32 {
@@ -186,10 +220,18 @@ pub struct ToneMapper {
186 /// The same for chroma, four fields: U at `i`, U at `i + 1`, V at `i`, V at220 /// The same for chroma, four fields: U at `i`, U at `i + 1`, V at `i`, V at
187 /// `i + 1`. One `u64` multiply does what four `u8` ones did.221 /// `i + 1`. One `u64` multiply does what four `u8` ones did.
188 chroma: Box<[u64]>,222 chroma: Box<[u64]>,
223+ /// The peak this table was really built at, cd/m^2 -- the picked preset's
224+ /// read against what the file declared ([`Preset::master_nits_for`]). Kept
225+ /// so a caller can say which number a picture came out of.
226+ peak: f32,
189 }227 }
190 228
191 impl ToneMapper {229 impl ToneMapper {
192- pub fn new(transfer: Transfer, preset: Preset) -> Self {230+ /// `declared_peak` is the film's own peak brightness where it has one
231+ /// ([`crate::demux::Demuxer::light`]), [`None`] for a file that declared
232+ /// nothing. Which renditions act on it is [`Preset`]'s composition rule.
233+ pub fn new(transfer: Transfer, preset: Preset, declared_peak: Option<f32>) -> Self {
234+ let peak = preset.master_nits_for(declared_peak);
193 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;235 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
194 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);236 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);
195 for kv in 0..CHROMA_NODES {237 for kv in 0..CHROMA_NODES {
@@ -202,6 +244,7 @@ impl ToneMapper {
202 let out = map_code(244 let out = map_code(
203 transfer,245 transfer,
204 preset,246 preset,
247+ peak,
205 (iy << LUMA_STEP) as f32,248 (iy << LUMA_STEP) as f32,
206 (ju << CHROMA_STEP) as f32,249 (ju << CHROMA_STEP) as f32,
207 (kv << CHROMA_STEP) as f32,250 (kv << CHROMA_STEP) as f32,
@@ -233,9 +276,17 @@ impl ToneMapper {
233 Self {276 Self {
234 luma: luma.into_boxed_slice(),277 luma: luma.into_boxed_slice(),
235 chroma: chroma.into_boxed_slice(),278 chroma: chroma.into_boxed_slice(),
279+ peak,
236 }280 }
237 }281 }
238 282
283+ /// The mastering peak this table was built at, cd/m^2: the film's own where
284+ /// the rendition reads it, the rendition's own otherwise. What a test -- or
285+ /// a caller wanting to say which number a picture came out of -- asks.
286+ pub fn peak(&self) -> f32 {
287+ self.peak
288+ }
289+
239 /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width *290 /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width *
240 /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`,291 /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`,
241 /// no padding (the shape [`crate::convert`], the decoders and the export292 /// no padding (the shape [`crate::convert`], the decoders and the export
@@ -346,8 +397,14 @@ fn byte(value: f32) -> u8 {
346 /// The whole float pipeline, from one triple of input codes to one triple of397 /// The whole float pipeline, from one triple of input codes to one triple of
347 /// BT.709 limited-range output codes. Runs at build time only; the module note398 /// BT.709 limited-range output codes. Runs at build time only; the module note
348 /// walks the stages.399 /// walks the stages.
349-fn map_code(transfer: Transfer, preset: Preset, yc: f32, uc: f32, vc: f32) -> [f32; 3] {400+fn map_code(
350- let master_nits = preset.master_nits();401+ transfer: Transfer,
402+ preset: Preset,
403+ master_nits: f32,
404+ yc: f32,
405+ uc: f32,
406+ vc: f32,
407+) -> [f32; 3] {
351 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.408 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.
352 let luma = (yc - 16.0) / 219.0;409 let luma = (yc - 16.0) / 219.0;
353 let cb = (uc - 128.0) / 224.0;410 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
368 // Clamping instead walks a too-bright pixel toward white, which is what a425 // Clamping instead walks a too-bright pixel toward white, which is what a
369 // highlight past the display's reach should do.426 // highlight past the display's reach should do.
370 //427 //
371- // ponytail: the ceiling is that the assumed peak is an exposure *choice*428+ // The reference rendition is now told the film's own declared peak
372- // (now the viewer's, [`Preset`]), not a measurement. Everything the content429+ // ([`Preset::master_nits_for`]), so what walks to white here is what the
373- // masters above it -- which at 400 is most of an HDR10 grade's highlight430+ // film says it never masters above; the two fixed renditions keep their
374- // range -- walks to white here. The upgrade is the stream's own431+ // exposure and still clamp an HDR10 grade's top end into white on purpose.
375- // MaxCLL/mastering-display metadata reaching this module beside the preset,432+ let lin = display_light(transfer, master_nits, [r, g, b]);
376- // as the measured ceiling the picked one is read against: nothing else in
377- // the pipeline changes.
378- let lin = display_light(transfer, preset, [r, g, b]);
379 let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA));433 let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA));
380 434
381 // 4. BT.2020 luma and colour differences, in that domain.435 // 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
427 }481 }
428 482
429 /// Signal -> display light in cd/m^2.483 /// Signal -> display light in cd/m^2.
430-fn display_light(transfer: Transfer, preset: Preset, rgb: [f32; 3]) -> [f32; 3] {484+fn display_light(transfer: Transfer, master_nits: f32, rgb: [f32; 3]) -> [f32; 3] {
431 match transfer {485 match transfer {
432 Transfer::Pq => rgb.map(pq_eotf),486 Transfer::Pq => rgb.map(pq_eotf),
433 Transfer::Hlg => {487 Transfer::Hlg => {
434 // BT.2100: inverse OETF to scene light, then the OOTF, whose system488 // BT.2100: inverse OETF to scene light, then the OOTF, whose system
435 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display489 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display
436- // peak from there by the standard's own log term -- so the peak the490+ // peak from there by the standard's own log term -- so the peak in
437- // preset names is the peak the OOTF is built for, rather than a491+ // force, the picked rendition's read against the film's declared
438- // number the choice silently invalidates.492+ // one, is the peak the OOTF is built for rather than a number the
439- let master_nits = preset.master_nits();493+ // choice or the metadata silently invalidates.
440 let scene = rgb.map(hlg_scene);494 let scene = rgb.map(hlg_scene);
441 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];495 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
442 let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10();496 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]
445 // `ys^(gamma - 1)` term diverges as the scene goes black and the499 // `ys^(gamma - 1)` term diverges as the scene goes black and the
446 // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts500 // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts
447 // a hole where black belongs (measured: HLG black rendered code 0501 // a hole where black belongs (measured: HLG black rendered code 0
448- // under the vivid preset before this line).502+ // under the vivid preset before this line). Kept above 1000 too,
503+ // where a declared peak puts the gamma over 1 and the term is
504+ // merely 0: the guard costs one comparison at build time.
449 let ys = ys.max(0.0);505 let ys = ys.max(0.0);
450 let gain = match ys > 0.0 {506 let gain = match ys > 0.0 {
451 true => master_nits * ys.powf(gamma - 1.0),507 true => master_nits * ys.powf(gamma - 1.0),
@@ -538,9 +594,8 @@ mod tests {
538 /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The594 /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The
539 /// day one of these moves, the transcription moved with it.595 /// day one of these moves, the transcription moved with it.
540 ///596 ///
541- /// The last row of each is the ceiling the `map_code` ponytail names,597+ /// The last row of each says what happens above the assumed peak, asserted
542- /// asserted rather than described: everything above the assumed peak is598+ /// rather than described: it is white.
543- /// white.
544 #[test]599 #[test]
545 fn pq_anchors_land_where_method_a_puts_them() {600 fn pq_anchors_land_where_method_a_puts_them() {
546 for (preset, diffuse) in [601 for (preset, diffuse) in [
@@ -549,7 +604,7 @@ mod tests {
549 (Preset::Vivid, 226),604 (Preset::Vivid, 226),
550 ] {605 ] {
551 let peak = preset.master_nits();606 let peak = preset.master_nits();
552- let mapper = ToneMapper::new(Transfer::Pq, preset);607+ let mapper = ToneMapper::new(Transfer::Pq, preset, None);
553 for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] {608 for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] {
554 let code = byte(pq_code(nits));609 let code = byte(pq_code(nits));
555 let (y, _, _) = mapped(&mapper, code, 128, 128);610 let (y, _, _) = mapped(&mapper, code, 128, 128);
@@ -572,7 +627,15 @@ mod tests {
572 fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() {627 fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() {
573 // BT.2408 diffuse white, and a saturated BT.2020 red beside it.628 // BT.2408 diffuse white, and a saturated BT.2020 red beside it.
574 let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8));629 let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8));
575- let luma = |preset| mapped(&ToneMapper::new(Transfer::Pq, preset), diffuse, 128, 128).0;630+ let luma = |preset| {
631+ mapped(
632+ &ToneMapper::new(Transfer::Pq, preset, None),
633+ diffuse,
634+ 128,
635+ 128,
636+ )
637+ .0
638+ };
576 let (reference, standard, vivid) = (639 let (reference, standard, vivid) = (
577 luma(Preset::Reference),640 luma(Preset::Reference),
578 luma(Preset::Standard),641 luma(Preset::Standard),
@@ -583,7 +646,12 @@ mod tests {
583 "reference {reference}, standard {standard}, vivid {vivid}"646 "reference {reference}, standard {standard}, vivid {vivid}"
584 );647 );
585 let colour = |preset| {648 let colour = |preset| {
586- let (_, u, v) = mapped(&ToneMapper::new(Transfer::Pq, preset), red.0, red.1, red.2);649+ let (_, u, v) = mapped(
650+ &ToneMapper::new(Transfer::Pq, preset, None),
651+ red.0,
652+ red.1,
653+ red.2,
654+ );
587 (u.abs_diff(128), v.abs_diff(128))655 (u.abs_diff(128), v.abs_diff(128))
588 };656 };
589 let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid));657 let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid));
@@ -605,12 +673,19 @@ mod tests {
605 fn the_grid_is_the_pipeline_on_its_nodes() {673 fn the_grid_is_the_pipeline_on_its_nodes() {
606 for preset in Preset::ALL {674 for preset in Preset::ALL {
607 for transfer in [Transfer::Pq, Transfer::Hlg] {675 for transfer in [Transfer::Pq, Transfer::Hlg] {
608- let mapper = ToneMapper::new(transfer, preset);676+ let mapper = ToneMapper::new(transfer, preset, None);
609 for yc in (0..=248u8).step_by(1 << LUMA_STEP) {677 for yc in (0..=248u8).step_by(1 << LUMA_STEP) {
610 for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {678 for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {
611 for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {679 for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {
612 let got = mapped(&mapper, yc, uc, vc);680 let got = mapped(&mapper, yc, uc, vc);
613- let want = map_code(transfer, preset, yc.into(), uc.into(), vc.into());681+ let want = map_code(
682+ transfer,
683+ preset,
684+ mapper.peak(),
685+ yc.into(),
686+ uc.into(),
687+ vc.into(),
688+ );
614 let want = (byte(want[0]), byte(want[1]), byte(want[2]));689 let want = (byte(want[0]), byte(want[1]), byte(want[2]));
615 assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}");690 assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}");
616 }691 }
@@ -639,7 +714,7 @@ mod tests {
639 .into_iter()714 .into_iter()
640 .flat_map(|t| Preset::ALL.map(|p| (t, p)))715 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
641 {716 {
642- let mapper = ToneMapper::new(transfer, preset);717+ let mapper = ToneMapper::new(transfer, preset, None);
643 for yc in (3..=255u8).step_by(23) {718 for yc in (3..=255u8).step_by(23) {
644 for uc in (5..=255u8).step_by(29) {719 for uc in (5..=255u8).step_by(29) {
645 for vc in (7..=255u8).step_by(31) {720 for vc in (7..=255u8).step_by(31) {
@@ -658,6 +733,7 @@ mod tests {
658 let out = map_code(733 let out = map_code(
659 transfer,734 transfer,
660 preset,735 preset,
736+ mapper.peak(),
661 node(yc, LUMA_STEP) + dy,737 node(yc, LUMA_STEP) + dy,
662 node(uc, CHROMA_STEP) + du,738 node(uc, CHROMA_STEP) + du,
663 node(vc, CHROMA_STEP) + dv,739 node(vc, CHROMA_STEP) + dv,
@@ -695,7 +771,7 @@ mod tests {
695 .into_iter()771 .into_iter()
696 .flat_map(|t| Preset::ALL.map(|p| (t, p)))772 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
697 {773 {
698- let mapper = ToneMapper::new(transfer, preset);774+ let mapper = ToneMapper::new(transfer, preset, None);
699 let mut last = 0u8;775 let mut last = 0u8;
700 for code in 0..=255u8 {776 for code in 0..=255u8 {
701 let (y, _, _) = mapped(&mapper, code, 128, 128);777 let (y, _, _) = mapped(&mapper, code, 128, 128);
@@ -718,7 +794,7 @@ mod tests {
718 .into_iter()794 .into_iter()
719 .flat_map(|t| Preset::ALL.map(|p| (t, p)))795 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
720 {796 {
721- let mapper = ToneMapper::new(transfer, preset);797+ let mapper = ToneMapper::new(transfer, preset, None);
722 for code in (16..=235u8).step_by(7) {798 for code in (16..=235u8).step_by(7) {
723 let (_, u, v) = mapped(&mapper, code, 128, 128);799 let (_, u, v) = mapped(&mapper, code, 128, 128);
724 assert!(800 assert!(
@@ -748,7 +824,7 @@ mod tests {
748 (Preset::Standard, 170),824 (Preset::Standard, 170),
749 (Preset::Vivid, 170),825 (Preset::Vivid, 170),
750 ] {826 ] {
751- let mapper = ToneMapper::new(Transfer::Hlg, preset);827+ let mapper = ToneMapper::new(Transfer::Hlg, preset, None);
752 let code = |signal: f32| byte(16.0 + 219.0 * signal);828 let code = |signal: f32| byte(16.0 + 219.0 * signal);
753 let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);829 let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);
754 let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);830 let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);
@@ -766,7 +842,7 @@ mod tests {
766 /// size at all returns instead of panicking on a zero-length band.842 /// size at all returns instead of panicking on a zero-length band.
767 #[test]843 #[test]
768 fn a_frame_that_does_not_measure_up_is_untouched() {844 fn a_frame_that_does_not_measure_up_is_untouched() {
769- let mapper = ToneMapper::new(Transfer::Pq, Preset::default());845+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
770 let mut y = vec![128u8; 8 * 8 - 1];846 let mut y = vec![128u8; 8 * 8 - 1];
771 let mut u = vec![128u8; 4 * 4];847 let mut u = vec![128u8; 4 * 4];
772 let mut v = vec![128u8; 4 * 4];848 let mut v = vec![128u8; 4 * 4];
@@ -781,7 +857,7 @@ mod tests {
781 /// off the end.857 /// off the end.
782 #[test]858 #[test]
783 fn odd_sizes_map_every_pixel() {859 fn odd_sizes_map_every_pixel() {
784- let mapper = ToneMapper::new(Transfer::Pq, Preset::default());860+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
785 let (w, h) = (7usize, 5usize);861 let (w, h) = (7usize, 5usize);
786 let mut y = vec![200u8; w * h];862 let mut y = vec![200u8; w * h];
787 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];863 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
@@ -803,7 +879,7 @@ mod tests {
803 /// time", and the reason a plain mean here would be a coin flip.879 /// time", and the reason a plain mean here would be a coin flip.
804 #[test]880 #[test]
805 fn perf_4k_and_1080p() {881 fn perf_4k_and_1080p() {
806- let mapper = ToneMapper::new(Transfer::Pq, Preset::default());882+ let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
807 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {883 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {
808 let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();884 let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
809 let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();885 let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
@@ -826,4 +902,122 @@ mod tests {
826 }902 }
827 }903 }
828 }904 }
905+
906+ /// The paid debt: the film's own declared peak is what the reference
907+ /// rendition converts at. 1759 cd/m^2 is a real number -- the MaxCLL of the
908+ /// HDR10 grade of *a real film*, which the container never says
909+ /// and the HEVC SEI does -- and every anchor moves with it, downward,
910+ /// because a peak this far above the 1000 an undeclared file is assumed at
911+ /// is *headroom*: the same code is a smaller fraction of a brighter peak.
912+ ///
913+ /// The row that matters most is 1000 cd/m^2. Told 1000, Method A puts it at
914+ /// SDR white and everything above it is gone; told the film's 1759 it lands
915+ /// at 215 and the 759 nits above it are still a picture. That is the whole
916+ /// of what reading the metadata buys.
917+ #[test]
918+ fn the_reference_rendition_converts_at_the_films_own_peak() {
919+ const FILM: f32 = 1759.0;
920+ let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(FILM));
921+ assert_eq!(
922+ mapper.peak(),
923+ FILM,
924+ "the table was built at the film's peak"
925+ );
926+ // Anchors, cd/m^2 -> limited-range SDR luma, at 1759 rather than 1000:
927+ // black is still black, the film's own peak is SDR white, and BT.2408
928+ // diffuse white lands at 145 instead of 166.
929+ for (nits, expected) in [
930+ (0.0, 16u8),
931+ (203.0, 145),
932+ (1000.0, 215),
933+ (FILM, 235),
934+ (10000.0, 235),
935+ ] {
936+ let code = byte(pq_code(nits));
937+ let (y, _, _) = mapped(&mapper, code, 128, 128);
938+ assert!(
939+ y.abs_diff(expected) <= 3,
940+ "{nits} cd/m^2 (code {code}) -> {y}, expected {expected} at a {FILM} peak"
941+ );
942+ }
943+ // ...and the direction, on every code rather than on the anchors: a
944+ // higher assumed peak is never brighter, and somewhere it is plainly
945+ // darker. The fallback is what the same file gets with its metadata
946+ // stripped, which is the control.
947+ let fallback = ToneMapper::new(Transfer::Pq, Preset::Reference, None);
948+ assert_eq!(fallback.peak(), 1000.0, "an undeclared file's assumption");
949+ let mut lower = 0;
950+ for code in 0..=255u8 {
951+ let (declared, _, _) = mapped(&mapper, code, 128, 128);
952+ let (assumed, _, _) = mapped(&fallback, code, 128, 128);
953+ assert!(
954+ declared <= assumed,
955+ "code {code}: the film's peak lifted it, {declared} over {assumed}"
956+ );
957+ lower += u32::from(declared < assumed);
958+ }
959+ assert!(lower > 128, "only {lower} of 256 codes moved at all");
960+ // HLG's OOTF follows the same peak, and the black guard has to hold
961+ // above 1000 as well as below it: a system gamma over 1 makes the
962+ // `ys^(gamma - 1)` term zero rather than infinite, and a hole where
963+ // black belongs is the failure either way.
964+ let hlg = ToneMapper::new(Transfer::Hlg, Preset::Reference, Some(FILM));
965+ let (black, _, _) = mapped(&hlg, byte(16.0), 128, 128);
966+ let (near_black, _, _) = mapped(&hlg, byte(16.0 + 219.0 * 0.02), 128, 128);
967+ let (white, _, _) = mapped(&hlg, 235, 128, 128);
968+ assert!(black.abs_diff(16) <= 3, "HLG black at {FILM} -> {black}");
969+ assert!(near_black > 16, "HLG near-black at {FILM} -> {near_black}");
970+ assert!(white.abs_diff(235) <= 3, "HLG peak at {FILM} -> {white}");
971+ }
972+
973+ /// The composition rule on [`Preset`], asserted: the two fixed renditions
974+ /// are deaf to the metadata, byte for byte, and the reference one is not.
975+ /// A "read the peak" change that reached all three would make the same pick
976+ /// mean a different exposure on every file, and this is what catches it.
977+ #[test]
978+ fn only_the_reference_rendition_reads_the_declared_peak() {
979+ for transfer in [Transfer::Pq, Transfer::Hlg] {
980+ for preset in Preset::ALL {
981+ let declared = ToneMapper::new(transfer, preset, Some(1759.0));
982+ let assumed = ToneMapper::new(transfer, preset, None);
983+ let deaf = preset != Preset::Reference;
984+ assert_eq!(
985+ declared.peak() == assumed.peak(),
986+ deaf,
987+ "{preset:?} {transfer:?}: peak {} against {}",
988+ declared.peak(),
989+ assumed.peak()
990+ );
991+ assert_eq!(
992+ declared.luma == assumed.luma && declared.chroma == assumed.chroma,
993+ deaf,
994+ "{preset:?} {transfer:?}: the tables"
995+ );
996+ }
997+ }
998+ }
999+
1000+ /// A declared peak is a number out of a stranger's file, so the two ways it
1001+ /// can be nonsense are checked rather than divided by: a peak under SDR
1002+ /// white would clip the whole picture to white, and a NaN -- which no
1003+ /// comparison admits, hence no clamp catches -- would build a table of
1004+ /// zeroes, i.e. a black frame. Both fall back to the rendition's own.
1005+ #[test]
1006+ fn a_nonsense_declared_peak_is_not_believed() {
1007+ for junk in [0.0, 1.0, 99.0, 10_001.0, f32::NAN, f32::INFINITY] {
1008+ let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(junk));
1009+ assert_eq!(mapper.peak(), 1000.0, "declared {junk} was believed");
1010+ let (white, _, _) = mapped(&mapper, byte(pq_code(1000.0)), 128, 128);
1011+ assert!(
1012+ white.abs_diff(235) <= 3,
1013+ "declared {junk}: 1000 nits -> {white}"
1014+ );
1015+ }
1016+ // ...and the range's own ends are believed, which is what says the
1017+ // guard rejects nonsense rather than everything unusual.
1018+ for good in [100.0, 4000.0, 10_000.0] {
1019+ let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(good));
1020+ assert_eq!(mapper.peak(), good, "declared {good} was refused");
1021+ }
1022+ }
829 }1023 }
crates/engine/tests/export_color.rsmodified+45 -1
@@ -442,7 +442,9 @@ fn an_hdr_clip_is_tone_mapped_before_it_is_graded() {
442 let got = raw_yuv(&out).expect("ffmpeg read the export");442 let got = raw_yuv(&out).expect("ffmpeg read the export");
443 443
444 let (width, height) = (1280usize, 720usize);444 let (width, height) = (1280usize, 720usize);
445- let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset);445+ // No declared peak: the fixture's tags say PQ and nothing about how
446+ // bright it is, so both sides are on the rendition's own number.
447+ let mapper = ToneMapper::new(tonemap::Transfer::Pq, preset, None);
446 // The same bytes twice, through the two orders. Whichever preset is in448 // The same bytes twice, through the two orders. Whichever preset is in
447 // force, both sides move with it -- what is asserted is which of them449 // force, both sides move with it -- what is asserted is which of them
448 // the export sits on, not where either lands.450 // the export sits on, not where either lands.
@@ -495,6 +497,19 @@ fn a_real_hdr_film_exports_as_a_picture() {
495 }497 }
496 let mut session = PlaybackSession::open(film).expect("open the film");498 let mut session = PlaybackSession::open(film).expect("open the film");
497 assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR10 film");499 assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR10 film");
500+ // What this film declares about itself, and therefore what the reference
501+ // rendition converts it at: 1759 cd/m^2 of MaxCLL, which its Matroska never
502+ // says and its HEVC SEI does. Both the funnel and the export table below
503+ // build their tables off this same number.
504+ let (_, demuxer) = Demuxer::open(film).expect("reopen the film");
505+ let peak = demuxer.light().peak();
506+ assert_eq!(peak, Some(1759.0), "the film's declared peak");
507+ let mapper = ToneMapper::new(tonemap::Transfer::Pq, session.tone(), peak);
508+ assert_eq!(
509+ mapper.peak(),
510+ 1759.0,
511+ "the reference rendition converts this film at its own peak"
512+ );
498 // A five-second window out of the middle: cut both ends, drop them, and the513 // A five-second window out of the middle: cut both ends, drop them, and the
499 // delete closes the gap ahead of what is left, so the export is those five514 // delete closes the gap ahead of what is left, so the export is those five
500 // seconds and no leading black.515 // seconds and no leading black.
@@ -586,3 +601,32 @@ fn a_graded_clip_exports_the_picture_the_preview_showed() {
586 std::fs::remove_file(&out).unwrap();601 std::fs::remove_file(&out).unwrap();
587 }602 }
588 }603 }
604+
605+/// Preview and export agree on the film's own peak, not merely on the preset:
606+/// `test_hdr_bright.mkv` declares 4000 cd/m^2, and the two sides read it in
607+/// different places -- the decode funnel off the demuxer it already opened, the
608+/// export table off `source_rate`'s. One of them left on the 1000 an undeclared
609+/// file is assumed at would be a preview the export does not match, which is
610+/// exactly the failure this file exists to refuse.
611+///
612+/// Measured as everywhere else here: this engine's own decode of its own export
613+/// against the canvas the preview showed.
614+#[test]
615+fn a_declared_peak_exports_the_picture_the_preview_showed() {
616+ let mut session = two_frames(&asset("test_hdr_bright.mkv"));
617+ assert_eq!(session.meta().color.transfer, Transfer::Pq, "an HDR fixture");
618+ let preview = frame0_bgra(&mut session);
619+ let out = out_path("declared_peak", "mp4");
620+ export(&session, &out, Format::Mp4);
621+
622+ let mut reopened = PlaybackSession::open(&*out).expect("reopen the export");
623+ let exported = frame0_bgra(&mut reopened);
624+ let diff = mean_abs_diff(&preview, &exported);
625+ eprintln!("declared peak 4000: preview vs export {diff:.2} mean codes");
626+ assert!(
627+ diff <= 2.0,
628+ "the export is {diff:.2} codes from what the preview showed"
629+ );
630+ drop(reopened);
631+ std::fs::remove_file(&out).unwrap();
632+}
crates/engine/tests/hw_decode.rsmodified+1 -1
@@ -246,7 +246,7 @@ fn the_hdr_film_renders_tone_mapped() {
246 // The funnel's own budget at this size: the map plus the conversion, which246 // 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 the247 // is what an HDR frame costs on top of the decode. Fastest of five, for the
248 // reason `tonemap::perf_4k_and_1080p` documents.248 // reason `tonemap::perf_4k_and_1080p` documents.
249- let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default());249+ let mapper = ToneMapper::new(Transfer::Pq, engine::tonemap::Preset::default(), None);
250 let sdr = ColorDescription {250 let sdr = ColorDescription {
251 matrix: Matrix::Bt709,251 matrix: Matrix::Bt709,
252 transfer: engine::colorspace::Transfer::Sdr,252 transfer: engine::colorspace::Transfer::Sdr,
crates/engine/tests/tonemap_render.rsmodified+72 -4
@@ -99,7 +99,13 @@ fn spread(px: [u8; 3]) -> u8 {
99 /// to render it: tone-mapped first, then graded, then converted as BT.709 SDR.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 of100 /// `grade` is applied in whichever domain `before` says -- which is the point of
101 /// [`the_grade_lands_after_the_tone_map`].101 /// [`the_grade_lands_after_the_tone_map`].
102-fn by_hand(codes: [u8; 3], grade: &ColorParams, before: bool, preset: Preset) -> [u8; 3] {102+fn by_hand(
103+ codes: [u8; 3],
104+ grade: &ColorParams,
105+ before: bool,
106+ preset: Preset,
107+ peak: Option<f32>,
108+) -> [u8; 3] {
103 let (w, h) = (8usize, 8usize);109 let (w, h) = (8usize, 8usize);
104 let mut y = vec![codes[0]; w * h];110 let mut y = vec![codes[0]; w * h];
105 let mut u = vec![codes[1]; w / 2 * h / 2];111 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) ->
107 if before {113 if before {
108 apply_yuv(grade, &mut y, &mut u, &mut v);114 apply_yuv(grade, &mut y, &mut u, &mut v);
109 }115 }
110- ToneMapper::new(Hdr::Pq, preset).map(&mut y, &mut u, &mut v, w, h);116+ ToneMapper::new(Hdr::Pq, preset, peak).map(&mut y, &mut u, &mut v, w, h);
111 if !before {117 if !before {
112 apply_yuv(grade, &mut y, &mut u, &mut v);118 apply_yuv(grade, &mut y, &mut u, &mut v);
113 }119 }
@@ -256,8 +262,8 @@ fn the_grade_lands_after_the_tone_map() {
256 262
257 for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {263 for (name, patch) in [("diffuse white", DIFFUSE), ("red", RED)] {
258 let shown = pixel(&frame, patch.1);264 let shown = pixel(&frame, patch.1);
259- let after = by_hand(patch.0, &grade, false, Preset::default());265+ let after = by_hand(patch.0, &grade, false, Preset::default(), None);
260- let before = by_hand(patch.0, &grade, true, Preset::default());266+ let before = by_hand(patch.0, &grade, true, Preset::default(), None);
261 for (i, channel) in ["B", "G", "R"].iter().enumerate() {267 for (i, channel) in ["B", "G", "R"].iter().enumerate() {
262 assert!(268 assert!(
263 shown[i].abs_diff(after[i]) <= 2,269 shown[i].abs_diff(after[i]) <= 2,
@@ -270,3 +276,65 @@ fn the_grade_lands_after_the_tone_map() {
270 );276 );
271 }277 }
272 }278 }
279+
280+/// The film's own declared peak, all the way to the window: `test_hdr_bright.mkv`
281+/// carries the same four patches as `test_pq.mp4` and a container MaxCLL of
282+/// 4000 cd/m^2, so a funnel that read the metadata renders it at 4000 and one
283+/// that ignored it renders it at the 1000 an undeclared file is assumed at --
284+/// two plainly different pictures, which is why that fixture says 4000 and the
285+/// older metadata ones say the 1000 nothing can tell apart from the fallback.
286+///
287+/// Both sides are computed by hand through the same `ToneMapper`, so what is
288+/// asserted is which number the *funnel* built its table with, not where Method
289+/// A puts a patch.
290+#[test]
291+fn a_films_declared_peak_reaches_the_window() {
292+ let mut session = open("test_hdr_bright.mkv");
293+ assert_eq!(session.meta().color.transfer, Transfer::Pq, "fixture tags");
294+ assert_eq!(session.tone(), Preset::Reference, "nobody has picked yet");
295+ let frame = next_frame(&mut session, "an open");
296+ let flat = ColorParams::default();
297+ for (patch, name) in [(DIFFUSE, "diffuse white"), (HIGHLIGHT, "the highlight")] {
298+ let shown = luma_code(pixel(&frame, patch.1));
299+ let declared = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, Some(4000.0)));
300+ let ignored = luma_code(by_hand(patch.0, &flat, false, Preset::Reference, None));
301+ assert!(
302+ shown.abs_diff(declared) <= 2,
303+ "{name} rendered at {shown}, {declared} at the film's declared 4000 cd/m^2"
304+ );
305+ assert!(
306+ shown.abs_diff(ignored) > 8,
307+ "{name}: {shown} is indistinguishable from the {ignored} of an ignored peak"
308+ );
309+ }
310+}
311+
312+/// ...and both tiers a peak can live in reach the table, on the fixtures that
313+/// exist for each: `test_hdr_meta.mkv` declares its 1000 in the container,
314+/// `test_hdr_sei.mkv` only inside the HEVC bitstream. Neither can be told apart
315+/// from the fallback in a *picture* (1000 is what an undeclared file is assumed
316+/// at, and both are black), so what is asserted is the number the table is
317+/// built at -- the same `Demuxer::light().peak()` hand-off the decode funnel
318+/// and the export table make.
319+#[test]
320+fn either_tier_of_metadata_is_what_the_table_is_built_at() {
321+ for (name, tier) in [
322+ ("test_hdr_meta.mkv", "container"),
323+ ("test_hdr_meta.mp4", "container"),
324+ ("test_hdr_sei.mkv", "bitstream SEI"),
325+ ("test_hdr_bright.mkv", "container"),
326+ ] {
327+ let (_, demuxer) = engine::demux::Demuxer::open(&asset(name)).expect("open");
328+ let peak = demuxer.light().peak();
329+ let want = match name {
330+ "test_hdr_bright.mkv" => 4000.0,
331+ _ => 1000.0,
332+ };
333+ assert_eq!(peak, Some(want), "{name} ({tier} tier)");
334+ let mapper = ToneMapper::new(Hdr::Pq, Preset::Reference, peak);
335+ assert_eq!(mapper.peak(), want, "{name}: the table's assumed peak");
336+ }
337+ // An SDR file declares nothing, and nothing is what the map is told.
338+ let (_, demuxer) = engine::demux::Demuxer::open(&asset("test_av.mp4")).expect("open");
339+ assert_eq!(demuxer.light().peak(), None, "an SDR file's peak");
340+}
scripts/gen_fixtures.shmodified+19 -0
@@ -287,6 +287,25 @@ ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \
287 assets/test_hdr_meta.mkv287 assets/test_hdr_meta.mkv
288 ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \288 ffmpeg -y -i assets/test_hdr_sei.mkv -c:v libx264 -qp 20 -pix_fmt yuv420p \
289 assets/test_hdr_meta.mp4289 assets/test_hdr_meta.mp4
290+# ...and one whose declared peak is a number nothing assumes: the three above
291+# say 1000, which is exactly what a file that declared *nothing* is assumed at,
292+# so no picture made from them can show that the metadata was read. This one is
293+# mastered at 4000 (`L(40000000,50)`, MaxCLL 4000) over the same four patches
294+# `test_pq.mp4` carries -- ten-bit codes here, four times the eight-bit ones --
295+# so a tone map told 4000 lands them visibly elsewhere than one told 1000.
296+#
297+# Same two passes for the same reason, and the H.264 second one is what makes it
298+# software-decodable: the render tests that read it must not need a VA-API
299+# plugin. `-qp 1` on flat patches so the codes arrive as written (measured: 144,
300+# 181 and 100 come back exactly).
301+bright_sei="$(mktemp -t edith_hdr_bright_XXXXXX.mkv)"
302+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" \
303+ -c:v libx265 -pix_fmt yuv420p10le \
304+ -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" \
305+ "$bright_sei"
306+ffmpeg -y -i "$bright_sei" -c:v libx264 -qp 1 -pix_fmt yuv420p \
307+ assets/test_hdr_bright.mkv
308+rm -f "$bright_sei"
290 # Sync fixture: one flash and one beep, at the same instant. Black picture with309 # Sync fixture: one flash and one beep, at the same instant. Black picture with
291 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that310 # a white frame from t=1.0 to t=1.1, silence with a 1 kHz tone over exactly that
292 # stretch — so a test can find each of them and say how far apart they came out.311 # stretch — so a test can find each of them and say how far apart they came out.