forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

tonemap.rs1023 lines, 48.7 KiBHistoryRawDownload
1//! HDR to SDR: BT.2020 PQ or HLG in, BT.709 SDR out, on the 8-bit limited-range
2//! planar YUV every path here already has in hand.
3//!
4//! The curve is **BT.2446 Method A** -- the published ITU-R conversion, chosen
5//! because it is written down: given the same input codes this file produces the
6//! same output codes on every machine and every run, and a reader can check the
7//! stages below against the document. mpv's default tone curve is a hand-tuned
8//! spline that is *not* published anywhere normative, so it cannot be
9//! transcribed honestly; Hable is published but is a film-look approximation
10//! with no gamut or chroma stage at all. Method A brings all three (tone curve,
11//! colour-difference scaling, gamut) and is LUT-friendly, which is the whole
12//! design here.
13//!
14//! Method A, in the order the code runs it:
15//!
16//! 1. limited-range Y'C'bC'r (BT.2020) -> R'G'B' signal, clipped to 0..1,
17//! 2. the transfer's EOTF -> display light in cd/m^2 (PQ per ST 2084, HLG per
18//! BT.2100 including its OOTF, which is why HLG costs almost nothing extra:
19//! it is one more EOTF feeding the same pipe),
20//! 3. normalise by the assumed mastering peak ([`Preset`]) and take the 1/2.4
21//! root -- Method A does its
22//! work in a gamma-2.4 domain, not in linear light,
23//! 4. BT.2020 luma + colour differences in that domain,
24//! 5. the tone curve: a logarithmic lift keyed on the HDR peak, a three-piece
25//! polynomial, then the matching exponential pull-down keyed on the SDR peak.
26//! Both ends are constrained to map peak to peak and black to black,
27//! 6. colour-difference scaling by `Y'sdr / (1.075 * Y'hdr)`, then the
28//! `- max(0, 0.1 * C'r)` luma correction the method uses to pay back the
29//! luminance that non-constant-luminance chroma scaling adds to reds,
30//! 7. back to R'G'B', linearise, BT.2020 -> BT.709 primaries, **clip** (a simple
31//! clip, as charted: gamut *compression* is a second research problem and
32//! Method A does not specify one), re-encode with the 1/2.4 inverse of
33//! BT.1886 -- the SDR display's own curve, so peak stays peak and black stays
34//! black -- and back to limited-range BT.709 Y'C'bC'r.
35//!
36//! Method A is conservative on mid-tones by construction: told the standard
37//! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code
38//! 166 (about 40 cd/m^2), not at SDR white -- a picture a viewer reads as dark.
39//! The assumed peak is the exposure knob that answers it -- a lower one lifts
40//! 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 pictures
42//! of the same film. So it is a [`Preset`] the viewer picks rather than a
43//! constant -- read, on the faithful one, against the peak the film itself
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.
47//!
48//! # Why a 3D LUT
49//!
50//! Every stage above is float, transcendental and per-pixel-dependent on all
51//! three components (the chroma scale reads the pixel's own luma). Running it
52//! per pixel is out of the question at 4K. So it runs 9 537 times per stream
53//! instead -- a grid over the *input codes*, 33 luma nodes by 17 by 17 -- and
54//! the pixel loop is a trilinear interpolation between neighbouring nodes:
55//! byte loads, integer multiplies, no float and no branch.
56//!
57//! The axes are deliberately uneven. A node every 8th code on luma and every
58//! 16th on chroma was measured against a uniform 33^3 and a uniform 17^3 on
59//! this machine, back when the assumed peak was 1000 cd/m^2: 17^3 put that
60//! peak's own code 5 codes shy of SDR white, because the curve's knee falls
61//! inside a 16-code luma cell, while a full 33^3 costs 30.7 ms a 4K frame
62//! against this one's 19.3 -- four times the table, out of cache and out of
63//! budget. Fine where the eye is, coarse where the format already is.
64//!
65//! Nodes are `u8`, the output's own precision, and the interpolation rounds
66//! once at the end in `u32` fixed point. On a node the grid *is* the pipeline;
67//! between nodes it is a straight line, and the pipeline is not straight
68//! wherever a channel is against a rail -- the 709 gamut clip in step 7 turns
69//! a range of saturated BT.2020 inputs into one clipped output, a plateau no
70//! line can follow. Measured worst case 42 codes, all of it inside that
71//! plateau, on colours the clip has already crushed; away from the rails the
72//! grid tracks the float pipeline within 3. The `tests` below pin both halves.
73//!
74//! Chroma is quarter-resolution and stays that way: one lookup per chroma
75//! *sample*, keyed on the mean luma of its 2x2 block, rather than upsampling to
76//! 4x the work for detail the format does not carry. The luma of those four
77//! pixels is mapped in the same visit, sharing the block's bilinear chroma
78//! weights, which is what keeps a 4K frame inside a frame's time budget.
79
80/// The SDR display peak Method A targets, cd/m^2.
81const SDR_NITS: f32 = 100.0;
82/// Method A's working gamma. Not a display curve here -- it is the domain the
83/// tone curve and the colour-difference scaling are defined in.
84const GAMMA: f32 = 2.4;
85
86/// Nodes along the luma axis: 33, one every 8th code.
87const LUMA_NODES: usize = 33;
88/// `256 / (LUMA_NODES - 1)` as a shift, so the node index is a shift and the
89/// fraction a mask.
90const LUMA_STEP: u32 = 3;
91/// `1 << LUMA_STEP`.
92const LUMA_FRAC: u32 = 8;
93/// Nodes along each chroma axis: 17, one every 16th code. Coarser than luma on
94/// purpose -- see the module note on the grid.
95const CHROMA_NODES: usize = 17;
96/// `256 / (CHROMA_NODES - 1)`, as a shift.
97const CHROMA_STEP: u32 = 4;
98/// `1 << CHROMA_STEP`.
99const CHROMA_FRAC: u32 = 16;
100
101/// Which rendition of the same conversion a project is watching: two numbers,
102/// the assumed mastering peak and a chroma gain, and *only* those two -- every
103/// preset runs the very same BT.2446 Method A stages, so the hue relationships
104/// the method is chosen for hold whichever one is picked.
105///
106/// The peak is Method A's exposure knob (see the module note): told the 1000
107/// cd/m^2 an HDR10 grade is really mastered to, the published conversion lands
108/// 203-nit diffuse white on code 166 -- broadcast-faithful, and darker than a
109/// player looks; told a lower one it lifts the whole picture. The gain is
110/// applied *after* the map, on the SDR colour differences, so it enriches the
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.
125#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
126pub enum Preset {
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).
129 /// The default: what the document says, and what a second reference can be
130 /// checked against.
131 #[default]
132 Reference,
133 /// Display-referred: the peak lowered to 400 so diffuse white lands near SDR
134 /// white and the picture reads as bright as a player shows it.
135 Standard,
136 /// Brighter again, and slightly richer -- the colour differences scaled up a
137 /// tenth after the map.
138 Vivid,
139}
140
141impl Preset {
142 /// Every preset, in the order a list offers them: reference first, brightest
143 /// last.
144 pub const ALL: [Preset; 3] = [Preset::Reference, Preset::Standard, Preset::Vivid];
145
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`]).
148 pub fn master_nits(self) -> f32 {
149 match self {
150 Preset::Reference => 1000.0,
151 Preset::Standard => 400.0,
152 Preset::Vivid => 250.0,
153 }
154 }
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
173 /// What the SDR colour differences are multiplied by after the map. `1.0`
174 /// leaves the method's own output untouched, byte for byte.
175 pub fn chroma_gain(self) -> f32 {
176 match self {
177 Preset::Reference | Preset::Standard => 1.0,
178 Preset::Vivid => 1.10,
179 }
180 }
181
182 /// The name a project file carries ([`crate::edith`]) -- lower case, one
183 /// word, and the inverse of [`from_name`](Preset::from_name).
184 pub fn name(self) -> &'static str {
185 match self {
186 Preset::Reference => "reference",
187 Preset::Standard => "standard",
188 Preset::Vivid => "vivid",
189 }
190 }
191
192 /// Reads one back. `None` for anything else, which a project file refuses by
193 /// name rather than silently rendering another way.
194 pub fn from_name(name: &[u8]) -> Option<Self> {
195 Preset::ALL.into_iter().find(|p| p.name().as_bytes() == name)
196 }
197}
198
199/// Which HDR transfer the incoming codes carry. Both feed the same Method A
200/// pipeline; they differ only in how a code becomes display light.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum Transfer {
203 /// SMPTE ST 2084 / BT.2100 PQ, absolute: a code *is* a luminance.
204 Pq,
205 /// BT.2100 HLG, relative: a code is scene light, and the OOTF (system gamma
206 /// 1.2 at a 1000 cd/m^2 display, less at a dimmer one) turns it into
207 /// display light.
208 Hlg,
209}
210
211/// One stream's tone map. Build once (the float pipeline runs 9 537 times, a
212/// couple of milliseconds), then map every frame through it.
213pub struct ToneMapper {
214 /// Output Y at luma node `i` and at `i + 1`, packed into one word 16 bits
215 /// apart. The luma axis is the fastest one, so a pixel's two neighbours are
216 /// one entry: one load and one multiply per grid corner instead of two of
217 /// each, and the weighted sum of four corners tops out at `255 * 256` per
218 /// field, exactly what a 16-bit field holds: no carry into the next one.
219 luma: Box<[u32]>,
220 /// The same for chroma, four fields: U at `i`, U at `i + 1`, V at `i`, V at
221 /// `i + 1`. One `u64` multiply does what four `u8` ones did.
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,
227}
228
229impl ToneMapper {
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);
235 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
236 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);
237 for kv in 0..CHROMA_NODES {
238 for ju in 0..CHROMA_NODES {
239 for iy in 0..LUMA_NODES {
240 // A node sits on code `n << STEP`; the last one on each axis
241 // is code 256, one past the top, which is the upper end of
242 // the interpolation for code 255 and never a lookup of its
243 // own.
244 let out = map_code(
245 transfer,
246 preset,
247 peak,
248 (iy << LUMA_STEP) as f32,
249 (ju << CHROMA_STEP) as f32,
250 (kv << CHROMA_STEP) as f32,
251 );
252 let at = index(iy, ju, kv);
253 y_node[at] = byte(out[0]);
254 uv_node[at] = [byte(out[1]), byte(out[2])];
255 }
256 }
257 }
258 let (mut luma, mut chroma) = (vec![0u32; cells], vec![0u64; cells]);
259 for kv in 0..CHROMA_NODES {
260 for ju in 0..CHROMA_NODES {
261 for iy in 0..LUMA_NODES {
262 let at = index(iy, ju, kv);
263 // The top node of a column has no neighbour above it and is
264 // never the lower end of an interpolation (code 255 lands on
265 // the node below it with a fraction), so it pairs with
266 // itself.
267 let up = if iy + 1 < LUMA_NODES { at + 1 } else { at };
268 luma[at] = u32::from(y_node[at]) | u32::from(y_node[up]) << 16;
269 chroma[at] = u64::from(uv_node[at][0])
270 | u64::from(uv_node[up][0]) << 16
271 | u64::from(uv_node[at][1]) << 32
272 | u64::from(uv_node[up][1]) << 48;
273 }
274 }
275 }
276 Self {
277 luma: luma.into_boxed_slice(),
278 chroma: chroma.into_boxed_slice(),
279 peak,
280 }
281 }
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
290 /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width *
291 /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`,
292 /// no padding (the shape [`crate::convert`], the decoders and the export
293 /// path all pass around). A frame that does not measure up is left
294 /// untouched rather than half-mapped -- callers hand these in from decoders
295 /// and files, and a short plane is a bug upstream, not a picture worth
296 /// guessing at.
297 ///
298 /// In place because both integration sites already own a scratch copy of
299 /// the planes at this point (`decode::Render::graded`, and the export
300 /// path's grade buffer): they can map that copy and keep the decoder's
301 /// frame intact for free.
302 pub fn map(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize, height: usize) {
303 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
304 // A frame with no width is not a short plane, it is not a frame; it
305 // also makes the band size below zero, which `chunks_mut` panics on.
306 if width == 0 || height == 0 {
307 return;
308 }
309 if y.len() < width * height || u.len() < cw * ch || v.len() < cw * ch {
310 return;
311 }
312 // Row slices rather than indices: the plane bounds are checked once per
313 // band, not once per sample, which is most of the difference between
314 // this and a frame's time budget.
315 let bands = y[..width * height].chunks_mut(2 * width);
316 let chroma_rows = u[..cw * ch].chunks_mut(cw).zip(v[..cw * ch].chunks_mut(cw));
317 for (band, (u_row, v_row)) in bands.zip(chroma_rows) {
318 // The bottom half is empty on an odd frame's last band.
319 let (top, bottom) = band.split_at_mut(width.min(band.len()));
320 let mut tops = top.chunks_mut(2);
321 let mut bottoms = bottom.chunks_mut(2);
322 for (u_site, v_site) in u_row.iter_mut().zip(v_row) {
323 // Odd widths leave a one-pixel block at the end of the row.
324 let top = tops.next().unwrap_or_default();
325 let bottom = bottoms.next().unwrap_or_default();
326
327 // The block's chroma, bilinear: four node columns and their
328 // weights, shared by every lookup this block makes.
329 let (uc, vc) = (u32::from(*u_site), u32::from(*v_site));
330 let (ju, fu) = ((uc >> CHROMA_STEP) as usize, uc & (CHROMA_FRAC - 1));
331 let (kv, fv) = ((vc >> CHROMA_STEP) as usize, vc & (CHROMA_FRAC - 1));
332 let corners = [
333 index(0, ju, kv),
334 index(0, ju + 1, kv),
335 index(0, ju, kv + 1),
336 index(0, ju + 1, kv + 1),
337 ];
338 let weights = [
339 (CHROMA_FRAC - fu) * (CHROMA_FRAC - fv),
340 fu * (CHROMA_FRAC - fv),
341 (CHROMA_FRAC - fu) * fv,
342 fu * fv,
343 ];
344
345 // Read the block's luma before writing any of it back: the
346 // chroma lookup is keyed on the *source* luma of the block.
347 let mut src = [0u32; 4];
348 let mut count = 0u32;
349 let mut sum = 0u32;
350 for (slot, sample) in src.iter_mut().zip(top.iter().chain(bottom.iter())) {
351 *slot = u32::from(*sample);
352 sum += *slot;
353 count += 1;
354 }
355 let mean = (sum + count / 2) / count;
356
357 let (iy, fy) = ((mean >> LUMA_STEP) as usize, mean & (LUMA_FRAC - 1));
358 let mut acc = 0u64;
359 for (corner, weight) in corners.iter().zip(&weights) {
360 acc += u64::from(*weight) * self.chroma[corner + iy];
361 }
362 *u_site = fade((acc & 0xffff) as u32, (acc >> 16 & 0xffff) as u32, fy);
363 *v_site = fade((acc >> 32 & 0xffff) as u32, (acc >> 48) as u32, fy);
364
365 for (sample, s) in top.iter_mut().chain(bottom).zip(src) {
366 let (iy, fy) = ((s >> LUMA_STEP) as usize, s & (LUMA_FRAC - 1));
367 let mut acc = 0u32;
368 for (corner, weight) in corners.iter().zip(&weights) {
369 acc += weight * self.luma[corner + iy];
370 }
371 *sample = fade(acc & 0xffff, acc >> 16, fy);
372 }
373 }
374 }
375 }
376}
377
378/// Node offset. Luma is the fastest axis on purpose -- see [`ToneMapper::luma`].
379fn index(iy: usize, ju: usize, kv: usize) -> usize {
380 (kv * CHROMA_NODES + ju) * LUMA_NODES + iy
381}
382
383/// The last leg of the trilinear tap: `lo` and `hi` are the chroma-bilinear
384/// collapse at the two luma nodes (each already carrying the `CHROMA_FRAC^2`
385/// chroma scale), `fy` the pixel's fraction between them. Rounds once, at the
386/// end, over the whole scale -- truncating here is what puts a step in a
387/// gradient.
388fn fade(lo: u32, hi: u32, fy: u32) -> u8 {
389 const SHIFT: u32 = LUMA_STEP + 2 * CHROMA_STEP;
390 ((lo * (LUMA_FRAC - fy) + hi * fy + (1 << (SHIFT - 1))) >> SHIFT) as u8
391}
392
393fn byte(value: f32) -> u8 {
394 value.round().clamp(0.0, 255.0) as u8
395}
396
397/// The whole float pipeline, from one triple of input codes to one triple of
398/// BT.709 limited-range output codes. Runs at build time only; the module note
399/// walks the stages.
400fn map_code(
401 transfer: Transfer,
402 preset: Preset,
403 master_nits: f32,
404 yc: f32,
405 uc: f32,
406 vc: f32,
407) -> [f32; 3] {
408 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.
409 let luma = (yc - 16.0) / 219.0;
410 let cb = (uc - 128.0) / 224.0;
411 let cr = (vc - 128.0) / 224.0;
412 let r = (luma + 1.4746 * cr).clamp(0.0, 1.0);
413 let b = (luma + 1.8814 * cb).clamp(0.0, 1.0);
414 let g = ((luma - 0.2627 * r - 0.0593 * b) / 0.6780).clamp(0.0, 1.0);
415
416 // 2/3. display light, then Method A's gamma-2.4 working domain, normalised
417 // to the assumed mastering peak.
418 //
419 // Clamped at that peak, per channel, and this clamp is load-bearing: Method
420 // A tone-maps *luma*, so a channel left above 1.0 comes back out of step 6
421 // above 1.0 too, and the per-channel gamut clip in step 7 then keeps one
422 // channel and drops another -- which does not make a highlight, it makes a
423 // hole. A 2800 cd/m^2 near-white measured code 189 with a neighbouring code
424 // at 78, a hundred-code cliff on a smooth ramp, before this line existed.
425 // Clamping instead walks a too-bright pixel toward white, which is what a
426 // highlight past the display's reach should do.
427 //
428 // The reference rendition is now told the film's own declared peak
429 // ([`Preset::master_nits_for`]), so what walks to white here is what the
430 // film says it never masters above; the two fixed renditions keep their
431 // exposure and still clamp an HDR10 grade's top end into white on purpose.
432 let lin = display_light(transfer, master_nits, [r, g, b]);
433 let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA));
434
435 // 4. BT.2020 luma and colour differences, in that domain.
436 let y_hdr = 0.2627 * gam[0] + 0.6780 * gam[1] + 0.0593 * gam[2];
437 let cb_hdr = (gam[2] - y_hdr) / 1.8814;
438 let cr_hdr = (gam[0] - y_hdr) / 1.4746;
439
440 // 5/6. the curve, then colour-difference scaling and its luma payback.
441 let y_sdr = tone_curve(y_hdr, master_nits);
442 let scale = if y_hdr > 1e-6 {
443 y_sdr / (1.075 * y_hdr)
444 } else {
445 0.0
446 };
447 let (cb_t, cr_t) = (cb_hdr * scale, cr_hdr * scale);
448 let y_t = y_sdr - (0.1 * cr_t).max(0.0);
449
450 // 7. back to R'G'B' (still BT.2020, still gamma 2.4), linearise, convert
451 // primaries, clip, re-encode.
452 let r = y_t + 1.4746 * cr_t;
453 let b = y_t + 1.8814 * cb_t;
454 let g = (y_t - 0.2627 * r - 0.0593 * b) / 0.6780;
455 // Clipped in the BT.2020 signal domain first, the same way step 1 clips:
456 // the colour-difference scaling can push a channel past the primaries it
457 // came from, and a channel that leaves the *source* gamut only makes the
458 // 709 clip below wilder.
459 let [r, g, b] = [r, g, b].map(|c| c.clamp(0.0, 1.0).powf(GAMMA));
460 let r709 = (1.6605 * r - 0.5876 * g - 0.0728 * b).clamp(0.0, 1.0);
461 let g709 = (-0.1246 * r + 1.1329 * g - 0.0083 * b).clamp(0.0, 1.0);
462 let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0);
463 let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA));
464
465 // 8. BT.709 limited-range codes, the preset's chroma gain on the two colour
466 // differences.
467 //
468 // A *scale* about 128 and never a shift, applied here and nowhere earlier:
469 // 128 is neutral, so a grey stays exactly grey at any gain (`128 - 128` is
470 // zero however it is multiplied) and only a pixel that already had colour
471 // gets more of it. Clamped to the legal 16..240 chroma range, which at gain
472 // 1.0 is a clamp the maths above cannot reach -- the untouched presets come
473 // out byte for byte what Method A produced.
474 let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
475 let gain = preset.chroma_gain();
476 [
477 16.0 + 219.0 * luma,
478 (128.0 + gain * 224.0 * (b - luma) / 1.8556).clamp(16.0, 240.0),
479 (128.0 + gain * 224.0 * (r - luma) / 1.5748).clamp(16.0, 240.0),
480 ]
481}
482
483/// Signal -> display light in cd/m^2.
484fn display_light(transfer: Transfer, master_nits: f32, rgb: [f32; 3]) -> [f32; 3] {
485 match transfer {
486 Transfer::Pq => rgb.map(pq_eotf),
487 Transfer::Hlg => {
488 // BT.2100: inverse OETF to scene light, then the OOTF, whose system
489 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display
490 // peak from there by the standard's own log term -- so the peak in
491 // force, the picked rendition's read against the film's declared
492 // one, is the peak the OOTF is built for rather than a number the
493 // choice or the metadata silently invalidates.
494 let scene = rgb.map(hlg_scene);
495 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
496 let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10();
497 // Black is black, said outright rather than left to the arithmetic:
498 // below a 1000 cd/m^2 peak the system gamma is *under* 1, so the
499 // `ys^(gamma - 1)` term diverges as the scene goes black and the
500 // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts
501 // a hole where black belongs (measured: HLG black rendered code 0
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.
505 let ys = ys.max(0.0);
506 let gain = match ys > 0.0 {
507 true => master_nits * ys.powf(gamma - 1.0),
508 false => 0.0,
509 };
510 scene.map(|c| gain * c)
511 }
512 }
513}
514
515/// SMPTE ST 2084 EOTF. Constants are the standard's exact rationals.
516fn pq_eotf(n: f32) -> f32 {
517 const M1: f32 = 2610.0 / 16384.0;
518 const M2: f32 = 2523.0 / 4096.0 * 128.0;
519 const C1: f32 = 3424.0 / 4096.0;
520 const C2: f32 = 2413.0 / 4096.0 * 32.0;
521 const C3: f32 = 2392.0 / 4096.0 * 32.0;
522 let p = n.max(0.0).powf(1.0 / M2);
523 10000.0 * ((p - C1).max(0.0) / (C2 - C3 * p)).powf(1.0 / M1)
524}
525
526/// BT.2100 HLG inverse OETF: signal -> scene light, 0..1 where 1 is the
527/// nominal white the OOTF then scales to the display peak.
528fn hlg_scene(e: f32) -> f32 {
529 const A: f32 = 0.17883277;
530 const B: f32 = 1.0 - 4.0 * A;
531 let e = e.clamp(0.0, 1.0);
532 if e <= 0.5 {
533 e * e / 3.0
534 } else {
535 // BT.2100 quotes `c` as 0.55991073; derived instead, because that is
536 // where the number comes from and an `f32` cannot hold all eight
537 // digits anyway. Build-time only, so the `ln` is free.
538 let c = 0.5 - A * (4.0 * A).ln();
539 (((e - c) / A).exp() + B) / 12.0
540 }
541}
542
543/// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR
544/// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms
545/// and the three-piece polynomial between them.
546fn tone_curve(y_hdr: f32, master_nits: f32) -> f32 {
547 let p_hdr = 1.0 + 32.0 * (master_nits / 10000.0).powf(1.0 / GAMMA);
548 let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA);
549 let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln();
550 let yc = if yp <= 0.7399 {
551 1.0770 * yp
552 } else if yp < 0.9909 {
553 (-1.1510 * yp + 2.7811) * yp - 0.6302
554 } else {
555 0.5 * yp + 0.5
556 };
557 (p_sdr.powf(yc) - 1.0) / (p_sdr - 1.0)
558}
559
560#[cfg(test)]
561mod tests {
562 use super::*;
563
564 /// Inverse of [`pq_eotf`]: nits -> PQ signal, so an anchor can be named in
565 /// cd/m^2 the way the standards name them.
566 fn pq_code(nits: f32) -> f32 {
567 const M1: f32 = 2610.0 / 16384.0;
568 const M2: f32 = 2523.0 / 4096.0 * 128.0;
569 const C1: f32 = 3424.0 / 4096.0;
570 const C2: f32 = 2413.0 / 4096.0 * 32.0;
571 const C3: f32 = 2392.0 / 4096.0 * 32.0;
572 let y = (nits / 10000.0).powf(M1);
573 let signal = ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2);
574 16.0 + 219.0 * signal
575 }
576
577 /// One flat frame at a single YUV triple, mapped, handed back as its (Y, U,
578 /// V) output. Goes through [`ToneMapper::map`], so it measures the shipped
579 /// path -- LUT, interpolation and all -- not the float reference.
580 fn mapped(mapper: &ToneMapper, yc: u8, uc: u8, vc: u8) -> (u8, u8, u8) {
581 let (w, h) = (8usize, 8usize);
582 let mut y = vec![yc; w * h];
583 let mut u = vec![uc; w / 2 * h / 2];
584 let mut v = vec![vc; w / 2 * h / 2];
585 mapper.map(&mut y, &mut u, &mut v, w, h);
586 (y[0], u[0], v[0])
587 }
588
589 /// The anchors, in cd/m^2, against the codes the stages in the module note
590 /// give for each preset's assumed peak. Black is pinned by the curve (0 in,
591 /// 0 out); the assumed peak itself must reach SDR white; 203 nits is BT.2408
592 /// diffuse white, and *where it lands is the whole difference between the
593 /// presets* -- 166 at the published 1000 cd/m^2 (broadcast-faithful, and the
594 /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The
595 /// day one of these moves, the transcription moved with it.
596 ///
597 /// The last row of each says what happens above the assumed peak, asserted
598 /// rather than described: it is white.
599 #[test]
600 fn pq_anchors_land_where_method_a_puts_them() {
601 for (preset, diffuse) in [
602 (Preset::Reference, 166u8),
603 (Preset::Standard, 205),
604 (Preset::Vivid, 226),
605 ] {
606 let peak = preset.master_nits();
607 let mapper = ToneMapper::new(Transfer::Pq, preset, None);
608 for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] {
609 let code = byte(pq_code(nits));
610 let (y, _, _) = mapped(&mapper, code, 128, 128);
611 assert!(
612 y.abs_diff(expected) <= 3,
613 "{preset:?}: {nits} cd/m^2 (code {code}) -> {y}, expected {expected}"
614 );
615 }
616 }
617 }
618
619 /// What the presets are *for*, on one code: brighter is brighter, and the
620 /// vivid one has more colour in it. A preset that renamed the same numbers
621 /// would pass every other test in this module and fail this one.
622 ///
623 /// The chroma reading is the distance from neutral, which is the thing the
624 /// gain scales; the grey beside it is the neutrality that must survive it,
625 /// so "richer" cannot have been bought with a tint.
626 #[test]
627 fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() {
628 // BT.2408 diffuse white, and a saturated BT.2020 red beside it.
629 let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8));
630 let luma = |preset| {
631 mapped(
632 &ToneMapper::new(Transfer::Pq, preset, None),
633 diffuse,
634 128,
635 128,
636 )
637 .0
638 };
639 let (reference, standard, vivid) = (
640 luma(Preset::Reference),
641 luma(Preset::Standard),
642 luma(Preset::Vivid),
643 );
644 assert!(
645 reference < standard && standard < vivid,
646 "reference {reference}, standard {standard}, vivid {vivid}"
647 );
648 let colour = |preset| {
649 let (_, u, v) = mapped(
650 &ToneMapper::new(Transfer::Pq, preset, None),
651 red.0,
652 red.1,
653 red.2,
654 );
655 (u.abs_diff(128), v.abs_diff(128))
656 };
657 let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid));
658 // Both differences read together, and neither of them allowed to shrink:
659 // this red is saturated enough that its V is already against the legal
660 // 240 rail under both presets, so the gain has nowhere to take *that*
661 // one -- which is the clamp doing its job, not the gain failing to.
662 assert!(
663 rich.0 + rich.1 > flat.0 + flat.1 && rich.0 >= flat.0 && rich.1 >= flat.1,
664 "vivid's red {rich:?} is no further from neutral than standard's {flat:?}"
665 );
666 }
667
668 /// On its nodes the grid is not an approximation at all: no interpolation
669 /// runs, so the byte a picture gets is the byte the float pipeline
670 /// computed. This is the half of the accuracy claim that is exact, and it
671 /// covers every node of every axis for both transfers.
672 #[test]
673 fn the_grid_is_the_pipeline_on_its_nodes() {
674 for preset in Preset::ALL {
675 for transfer in [Transfer::Pq, Transfer::Hlg] {
676 let mapper = ToneMapper::new(transfer, preset, None);
677 for yc in (0..=248u8).step_by(1 << LUMA_STEP) {
678 for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {
679 for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {
680 let got = mapped(&mapper, yc, uc, vc);
681 let want = map_code(
682 transfer,
683 preset,
684 mapper.peak(),
685 yc.into(),
686 uc.into(),
687 vc.into(),
688 );
689 let want = (byte(want[0]), byte(want[1]), byte(want[2]));
690 assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}");
691 }
692 }
693 }
694 }
695 }
696 }
697
698 /// Between the nodes the grid is a straight line through the eight that
699 /// surround the sample, so every output it can produce lies inside the box
700 /// those eight span -- an index off by one axis stride, a fraction taken
701 /// from the wrong shift, or a carry between the packed fields all break
702 /// this immediately, and none of them would move an on-node value.
703 ///
704 /// Deliberately *not* an epsilon against the float pipeline off the nodes:
705 /// see the module note. Where the 709 clip flattens a range of inputs onto
706 /// one output, a straight line between two nodes is up to 42 codes off that
707 /// plateau and is the better-behaved of the two -- it ramps where the
708 /// pipeline steps.
709 #[test]
710 fn between_nodes_the_grid_stays_inside_its_own_cell() {
711 // Every preset, since the vivid one's chroma gain is a stage the nodes
712 // carry and the interpolation between them must not exaggerate.
713 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
714 .into_iter()
715 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
716 {
717 let mapper = ToneMapper::new(transfer, preset, None);
718 for yc in (3..=255u8).step_by(23) {
719 for uc in (5..=255u8).step_by(29) {
720 for vc in (7..=255u8).step_by(31) {
721 let got = [
722 mapped(&mapper, yc, uc, vc).0,
723 mapped(&mapper, yc, uc, vc).1,
724 mapped(&mapper, yc, uc, vc).2,
725 ];
726 // The eight enclosing nodes, from the same float
727 // pipeline the table was built with.
728 let (mut lo, mut hi) = ([255u8; 3], [0u8; 3]);
729 let node = |c: u8, step: u32| f32::from((c >> step) << step);
730 for dy in [0.0, f32::from(1u8 << LUMA_STEP)] {
731 for du in [0.0, f32::from(1u8 << CHROMA_STEP)] {
732 for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] {
733 let out = map_code(
734 transfer,
735 preset,
736 mapper.peak(),
737 node(yc, LUMA_STEP) + dy,
738 node(uc, CHROMA_STEP) + du,
739 node(vc, CHROMA_STEP) + dv,
740 );
741 for (i, c) in out.iter().enumerate() {
742 lo[i] = lo[i].min(byte(*c));
743 hi[i] = hi[i].max(byte(*c));
744 }
745 }
746 }
747 }
748 for (i, name) in ["Y", "U", "V"].iter().enumerate() {
749 // One code of slack: the nodes are rounded bytes
750 // and the interpolation rounds once more.
751 assert!(
752 got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1,
753 "{preset:?} {transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}",
754 got[i],
755 lo[i],
756 hi[i]
757 );
758 }
759 }
760 }
761 }
762 }
763 }
764
765 /// A grey ramp may not fold back on itself: an inversion anywhere is a
766 /// posterised or solarised picture, and it is exactly what a badly built
767 /// grid or a truncating interpolation produces.
768 #[test]
769 fn a_grey_ramp_never_inverts() {
770 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
771 .into_iter()
772 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
773 {
774 let mapper = ToneMapper::new(transfer, preset, None);
775 let mut last = 0u8;
776 for code in 0..=255u8 {
777 let (y, _, _) = mapped(&mapper, code, 128, 128);
778 assert!(
779 y >= last,
780 "{preset:?} {transfer:?}: code {code} darkened to {y} < {last}"
781 );
782 last = y;
783 }
784 }
785 }
786
787 /// Grey in, grey out: any chroma the pipeline invents on a neutral is a
788 /// tint across the whole picture -- and a chroma *gain* that was written as
789 /// a shift, or applied anywhere but about 128, is exactly that tint, which
790 /// is why the vivid preset is in this loop.
791 #[test]
792 fn neutral_input_stays_neutral() {
793 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
794 .into_iter()
795 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
796 {
797 let mapper = ToneMapper::new(transfer, preset, None);
798 for code in (16..=235u8).step_by(7) {
799 let (_, u, v) = mapped(&mapper, code, 128, 128);
800 assert!(
801 u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2,
802 "{preset:?} {transfer:?}: grey {code} tinted to U{u} V{v}"
803 );
804 }
805 }
806 }
807
808 /// HLG's own anchors. Its signal is relative, so what is worth pinning is
809 /// where the OOTF puts it: black at black and peak signal at the assumed
810 /// display peak, hence SDR white -- to the grid's rounding, since code 235
811 /// sits between two luma nodes and the one below it is a hair under peak.
812 ///
813 /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the
814 /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of
815 /// whatever peak the display has -- 76 cd/m^2 of the standard preset's 400,
816 /// against PQ's absolute 203 -- and it comes out darker. That is the
817 /// standard's own behaviour and the number to watch: if the OOTF's system
818 /// gamma stops following the assumed peak, this is what moves, and it moves
819 /// per preset because the peak is what a preset picks.
820 #[test]
821 fn hlg_anchors_are_sane() {
822 for (preset, expected) in [
823 (Preset::Reference, 170u8),
824 (Preset::Standard, 170),
825 (Preset::Vivid, 170),
826 ] {
827 let mapper = ToneMapper::new(Transfer::Hlg, preset, None);
828 let code = |signal: f32| byte(16.0 + 219.0 * signal);
829 let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);
830 let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);
831 let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);
832 assert!(black.abs_diff(16) <= 3, "{preset:?} HLG black -> {black}");
833 assert!(white.abs_diff(235) <= 3, "{preset:?} HLG peak -> {white}");
834 assert!(
835 diffuse.abs_diff(expected) <= 3,
836 "{preset:?} HLG diffuse white -> {diffuse}, expected {expected}"
837 );
838 }
839 }
840
841 /// A short plane is left alone rather than half mapped, and a frame with no
842 /// size at all returns instead of panicking on a zero-length band.
843 #[test]
844 fn a_frame_that_does_not_measure_up_is_untouched() {
845 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
846 let mut y = vec![128u8; 8 * 8 - 1];
847 let mut u = vec![128u8; 4 * 4];
848 let mut v = vec![128u8; 4 * 4];
849 mapper.map(&mut y, &mut u, &mut v, 8, 8);
850 assert!(y.iter().all(|&s| s == 128), "short plane was mapped");
851 mapper.map(&mut y, &mut u, &mut v, 0, 8);
852 mapper.map(&mut y, &mut u, &mut v, 8, 0);
853 mapper.map(&mut [], &mut [], &mut [], 0, 0);
854 }
855
856 /// Odd sizes: the edge block covers one row or one column and must not run
857 /// off the end.
858 #[test]
859 fn odd_sizes_map_every_pixel() {
860 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
861 let (w, h) = (7usize, 5usize);
862 let mut y = vec![200u8; w * h];
863 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
864 let mut v = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
865 mapper.map(&mut y, &mut u, &mut v, w, h);
866 assert!(y.iter().all(|&s| s != 200), "a pixel was skipped");
867 }
868
869 /// The cost gate, asserted in release only: a debug build is an order of
870 /// magnitude off and the number only means something optimised. Run with
871 /// `cargo test -p engine --release --lib tonemap:: -- --nocapture`.
872 ///
873 /// The *fastest* frame of a two-second window, not the mean of a fixed
874 /// count: this test shares a six-core machine with the other 200 in the
875 /// binary, and measured against them a 19.0 ms frame reads as 29.7. Kept
876 /// running until they are done, the tail iterations get a core to
877 /// themselves and the minimum is the machine's real cost -- which is the
878 /// question the gate asks, "can one core carry a 4K frame in a frame's
879 /// time", and the reason a plain mean here would be a coin flip.
880 #[test]
881 fn perf_4k_and_1080p() {
882 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
883 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {
884 let mut y: Vec<u8> = (0..w * h).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();
886 let mut v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
887 let mut best = f64::MAX;
888 let window = std::time::Instant::now();
889 let mut runs = 0;
890 while runs < 10 || window.elapsed().as_secs_f64() < 1.0 {
891 let t = std::time::Instant::now();
892 mapper.map(&mut y, &mut u, &mut v, w, h);
893 best = best.min(t.elapsed().as_secs_f64() * 1000.0);
894 runs += 1;
895 }
896 println!("tonemap::map {w}x{h}: {best:.3} ms/frame");
897 if !cfg!(debug_assertions) {
898 assert!(
899 best <= budget,
900 "{w}x{h}: {best:.3} ms/frame over {budget} ms"
901 );
902 }
903 }
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 a
908 /// real HDR10 grade, 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 }
1023}