forge
Explore
Log in

Don't you dare go Hollow

PQ and HLG become BT.709 through a published curve, not a guess

Browse files at this commit

0a02d34f1dda61bce174dd3c16a372b0937d0333Ahmet Kaan GümüşParent: 5c39124
  • feat
    • PQ and HLG become BT.709 through a published curve, not a guess
Show full message
✨ feat(tonemap): PQ and HLG become BT.709 through a published curve, not a guess

BT.2446 Method A, whole: the tone curve, the colour-difference scaling with
its luma payback, and BT.2020 -> BT.709 with a simple clip. Written down, so
it can be checked against the document instead of against a screenshot.

The maths is float and transcendental, so it runs 9537 times per stream --
a 33 x 17 x 17 grid over the input codes -- and the pixel loop is a trilinear
interpolation with the two luma neighbours packed into one word. 18.7 ms a
3840x1600 frame, 6.3 ms at 1080p, single core, release.

Uneven axes on purpose: 17 luma nodes leave the assumed 1000 cd/m^2 peak five
codes shy of SDR white, and a full 33^3 costs 30.7 ms. Above-peak light is
clamped before the curve rather than extrapolated through it -- extrapolating
sent one channel over the gamut rail and the next under it, a hundred-code
hole in a smooth ramp.

Standalone: no decoder or export path calls it yet.
crates/engine/src/lib.rsmodified+1 -0
@@ -20,6 +20,7 @@ pub mod scale;
20 pub mod scratch;20 pub mod scratch;
21 pub mod silence;21 pub mod silence;
22 pub mod subtitle;22 pub mod subtitle;
23+pub mod tonemap;
23 pub mod waveform;24 pub mod waveform;
24 25
25 pub use audio::{26 pub use audio::{
crates/engine/src/tonemap.rsadded+657 -0
@@ -0,0 +1,657 @@
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 [`MASTER_NITS`] and take the 1/2.4 root -- Method A does its
21+//! work in a gamma-2.4 domain, not in linear light,
22+//! 4. BT.2020 luma + colour differences in that domain,
23+//! 5. the tone curve: a logarithmic lift keyed on the HDR peak, a three-piece
24+//! polynomial, then the matching exponential pull-down keyed on the SDR peak.
25+//! Both ends are constrained to map peak to peak and black to black,
26+//! 6. colour-difference scaling by `Y'sdr / (1.075 * Y'hdr)`, then the
27+//! `- max(0, 0.1 * C'r)` luma correction the method uses to pay back the
28+//! luminance that non-constant-luminance chroma scaling adds to reds,
29+//! 7. back to R'G'B', linearise, BT.2020 -> BT.709 primaries, **clip** (a simple
30+//! clip, as charted: gamut *compression* is a second research problem and
31+//! Method A does not specify one), re-encode with the 1/2.4 inverse of
32+//! BT.1886 -- the SDR display's own curve, so peak stays peak and black stays
33+//! black -- and back to limited-range BT.709 Y'C'bC'r.
34+//!
35+//! Method A is conservative on mid-tones by construction: with the standard
36+//! 1000 cd/m^2 mastering peak it puts 203-nit HDR diffuse white near SDR code
37+//! 166 (about 40 cd/m^2), not at SDR white. [`MASTER_NITS`] is the exposure
38+//! knob -- a lower assumed peak lifts everything -- and is a constant here
39+//! because this module is handed pixels, never the stream metadata that would
40+//! carry the real one.
41+//!
42+//! # Why a 3D LUT
43+//!
44+//! Every stage above is float, transcendental and per-pixel-dependent on all
45+//! three components (the chroma scale reads the pixel's own luma). Running it
46+//! per pixel is out of the question at 4K. So it runs 9 537 times per stream
47+//! instead -- a grid over the *input codes*, 33 luma nodes by 17 by 17 -- and
48+//! the pixel loop is a trilinear interpolation between neighbouring nodes:
49+//! byte loads, integer multiplies, no float and no branch.
50+//!
51+//! The axes are deliberately uneven. A node every 8th code on luma and every
52+//! 16th on chroma was measured against a uniform 33^3 and a uniform 17^3 on
53+//! this machine: 17^3 puts the assumed peak (1000 cd/m^2, code 181) 5 codes
54+//! shy of SDR white, because the curve's knee falls inside a 16-code luma
55+//! cell, while a full 33^3 costs 30.7 ms a 4K frame against this one's 19.3 --
56+//! four times the table, out of cache and out of budget. Fine where the eye
57+//! is, coarse where the format already is.
58+//!
59+//! Nodes are `u8`, the output's own precision, and the interpolation rounds
60+//! once at the end in `u32` fixed point. On a node the grid *is* the pipeline;
61+//! between nodes it is a straight line, and the pipeline is not straight
62+//! wherever a channel is against a rail -- the 709 gamut clip in step 7 turns
63+//! a range of saturated BT.2020 inputs into one clipped output, a plateau no
64+//! line can follow. Measured worst case 42 codes, all of it inside that
65+//! plateau, on colours the clip has already crushed; away from the rails the
66+//! grid tracks the float pipeline within 3. The `tests` below pin both halves.
67+//!
68+//! Chroma is quarter-resolution and stays that way: one lookup per chroma
69+//! *sample*, keyed on the mean luma of its 2x2 block, rather than upsampling to
70+//! 4x the work for detail the format does not carry. The luma of those four
71+//! pixels is mapped in the same visit, sharing the block's bilinear chroma
72+//! weights, which is what keeps a 4K frame inside a frame's time budget.
73+
74+/// The mastering peak Method A is told to assume, cd/m^2. 1000 is what HDR10
75+/// grades are mastered to in practice and what BT.2446's own worked example
76+/// uses. See the module note: this is the exposure knob.
77+const MASTER_NITS: f32 = 1000.0;
78+/// The SDR display peak Method A targets, cd/m^2.
79+const SDR_NITS: f32 = 100.0;
80+/// Method A's working gamma. Not a display curve here -- it is the domain the
81+/// tone curve and the colour-difference scaling are defined in.
82+const GAMMA: f32 = 2.4;
83+
84+/// Nodes along the luma axis: 33, one every 8th code.
85+const LUMA_NODES: usize = 33;
86+/// `256 / (LUMA_NODES - 1)` as a shift, so the node index is a shift and the
87+/// fraction a mask.
88+const LUMA_STEP: u32 = 3;
89+/// `1 << LUMA_STEP`.
90+const LUMA_FRAC: u32 = 8;
91+/// Nodes along each chroma axis: 17, one every 16th code. Coarser than luma on
92+/// purpose -- see the module note on the grid.
93+const CHROMA_NODES: usize = 17;
94+/// `256 / (CHROMA_NODES - 1)`, as a shift.
95+const CHROMA_STEP: u32 = 4;
96+/// `1 << CHROMA_STEP`.
97+const CHROMA_FRAC: u32 = 16;
98+
99+/// Which HDR transfer the incoming codes carry. Both feed the same Method A
100+/// pipeline; they differ only in how a code becomes display light.
101+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102+pub enum Transfer {
103+ /// SMPTE ST 2084 / BT.2100 PQ, absolute: a code *is* a luminance.
104+ Pq,
105+ /// BT.2100 HLG, relative: a code is scene light, and the OOTF (system gamma
106+ /// 1.2 at a 1000 cd/m^2 display) turns it into display light.
107+ Hlg,
108+}
109+
110+/// One stream's tone map. Build once (the float pipeline runs 9 537 times, a
111+/// couple of milliseconds), then map every frame through it.
112+pub struct ToneMapper {
113+ /// Output Y at luma node `i` and at `i + 1`, packed into one word 16 bits
114+ /// apart. The luma axis is the fastest one, so a pixel's two neighbours are
115+ /// one entry: one load and one multiply per grid corner instead of two of
116+ /// each, and the weighted sum of four corners tops out at `255 * 256` per
117+ /// field, exactly what a 16-bit field holds: no carry into the next one.
118+ luma: Box<[u32]>,
119+ /// The same for chroma, four fields: U at `i`, U at `i + 1`, V at `i`, V at
120+ /// `i + 1`. One `u64` multiply does what four `u8` ones did.
121+ chroma: Box<[u64]>,
122+}
123+
124+impl ToneMapper {
125+ pub fn new(transfer: Transfer) -> Self {
126+ let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
127+ let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);
128+ for kv in 0..CHROMA_NODES {
129+ for ju in 0..CHROMA_NODES {
130+ for iy in 0..LUMA_NODES {
131+ // A node sits on code `n << STEP`; the last one on each axis
132+ // is code 256, one past the top, which is the upper end of
133+ // the interpolation for code 255 and never a lookup of its
134+ // own.
135+ let out = map_code(
136+ transfer,
137+ (iy << LUMA_STEP) as f32,
138+ (ju << CHROMA_STEP) as f32,
139+ (kv << CHROMA_STEP) as f32,
140+ );
141+ let at = index(iy, ju, kv);
142+ y_node[at] = byte(out[0]);
143+ uv_node[at] = [byte(out[1]), byte(out[2])];
144+ }
145+ }
146+ }
147+ let (mut luma, mut chroma) = (vec![0u32; cells], vec![0u64; cells]);
148+ for kv in 0..CHROMA_NODES {
149+ for ju in 0..CHROMA_NODES {
150+ for iy in 0..LUMA_NODES {
151+ let at = index(iy, ju, kv);
152+ // The top node of a column has no neighbour above it and is
153+ // never the lower end of an interpolation (code 255 lands on
154+ // the node below it with a fraction), so it pairs with
155+ // itself.
156+ let up = if iy + 1 < LUMA_NODES { at + 1 } else { at };
157+ luma[at] = u32::from(y_node[at]) | u32::from(y_node[up]) << 16;
158+ chroma[at] = u64::from(uv_node[at][0])
159+ | u64::from(uv_node[up][0]) << 16
160+ | u64::from(uv_node[at][1]) << 32
161+ | u64::from(uv_node[up][1]) << 48;
162+ }
163+ }
164+ }
165+ Self {
166+ luma: luma.into_boxed_slice(),
167+ chroma: chroma.into_boxed_slice(),
168+ }
169+ }
170+
171+ /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width *
172+ /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`,
173+ /// no padding (the shape [`crate::convert`], the decoders and the export
174+ /// path all pass around). A frame that does not measure up is left
175+ /// untouched rather than half-mapped -- callers hand these in from decoders
176+ /// and files, and a short plane is a bug upstream, not a picture worth
177+ /// guessing at.
178+ ///
179+ /// In place because both integration sites already own a scratch copy of
180+ /// the planes at this point (`decode::Render::graded`, and the export
181+ /// path's grade buffer): they can map that copy and keep the decoder's
182+ /// frame intact for free.
183+ pub fn map(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize, height: usize) {
184+ let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
185+ // A frame with no width is not a short plane, it is not a frame; it
186+ // also makes the band size below zero, which `chunks_mut` panics on.
187+ if width == 0 || height == 0 {
188+ return;
189+ }
190+ if y.len() < width * height || u.len() < cw * ch || v.len() < cw * ch {
191+ return;
192+ }
193+ // Row slices rather than indices: the plane bounds are checked once per
194+ // band, not once per sample, which is most of the difference between
195+ // this and a frame's time budget.
196+ let bands = y[..width * height].chunks_mut(2 * width);
197+ let chroma_rows = u[..cw * ch].chunks_mut(cw).zip(v[..cw * ch].chunks_mut(cw));
198+ for (band, (u_row, v_row)) in bands.zip(chroma_rows) {
199+ // The bottom half is empty on an odd frame's last band.
200+ let (top, bottom) = band.split_at_mut(width.min(band.len()));
201+ let mut tops = top.chunks_mut(2);
202+ let mut bottoms = bottom.chunks_mut(2);
203+ for (u_site, v_site) in u_row.iter_mut().zip(v_row) {
204+ // Odd widths leave a one-pixel block at the end of the row.
205+ let top = tops.next().unwrap_or_default();
206+ let bottom = bottoms.next().unwrap_or_default();
207+
208+ // The block's chroma, bilinear: four node columns and their
209+ // weights, shared by every lookup this block makes.
210+ let (uc, vc) = (u32::from(*u_site), u32::from(*v_site));
211+ let (ju, fu) = ((uc >> CHROMA_STEP) as usize, uc & (CHROMA_FRAC - 1));
212+ let (kv, fv) = ((vc >> CHROMA_STEP) as usize, vc & (CHROMA_FRAC - 1));
213+ let corners = [
214+ index(0, ju, kv),
215+ index(0, ju + 1, kv),
216+ index(0, ju, kv + 1),
217+ index(0, ju + 1, kv + 1),
218+ ];
219+ let weights = [
220+ (CHROMA_FRAC - fu) * (CHROMA_FRAC - fv),
221+ fu * (CHROMA_FRAC - fv),
222+ (CHROMA_FRAC - fu) * fv,
223+ fu * fv,
224+ ];
225+
226+ // Read the block's luma before writing any of it back: the
227+ // chroma lookup is keyed on the *source* luma of the block.
228+ let mut src = [0u32; 4];
229+ let mut count = 0u32;
230+ let mut sum = 0u32;
231+ for (slot, sample) in src.iter_mut().zip(top.iter().chain(bottom.iter())) {
232+ *slot = u32::from(*sample);
233+ sum += *slot;
234+ count += 1;
235+ }
236+ let mean = (sum + count / 2) / count;
237+
238+ let (iy, fy) = ((mean >> LUMA_STEP) as usize, mean & (LUMA_FRAC - 1));
239+ let mut acc = 0u64;
240+ for (corner, weight) in corners.iter().zip(&weights) {
241+ acc += u64::from(*weight) * self.chroma[corner + iy];
242+ }
243+ *u_site = fade((acc & 0xffff) as u32, (acc >> 16 & 0xffff) as u32, fy);
244+ *v_site = fade((acc >> 32 & 0xffff) as u32, (acc >> 48) as u32, fy);
245+
246+ for (sample, s) in top.iter_mut().chain(bottom).zip(src) {
247+ let (iy, fy) = ((s >> LUMA_STEP) as usize, s & (LUMA_FRAC - 1));
248+ let mut acc = 0u32;
249+ for (corner, weight) in corners.iter().zip(&weights) {
250+ acc += weight * self.luma[corner + iy];
251+ }
252+ *sample = fade(acc & 0xffff, acc >> 16, fy);
253+ }
254+ }
255+ }
256+ }
257+}
258+
259+/// Node offset. Luma is the fastest axis on purpose -- see [`ToneMapper::luma`].
260+fn index(iy: usize, ju: usize, kv: usize) -> usize {
261+ (kv * CHROMA_NODES + ju) * LUMA_NODES + iy
262+}
263+
264+/// The last leg of the trilinear tap: `lo` and `hi` are the chroma-bilinear
265+/// collapse at the two luma nodes (each already carrying the `CHROMA_FRAC^2`
266+/// chroma scale), `fy` the pixel's fraction between them. Rounds once, at the
267+/// end, over the whole scale -- truncating here is what puts a step in a
268+/// gradient.
269+fn fade(lo: u32, hi: u32, fy: u32) -> u8 {
270+ const SHIFT: u32 = LUMA_STEP + 2 * CHROMA_STEP;
271+ ((lo * (LUMA_FRAC - fy) + hi * fy + (1 << (SHIFT - 1))) >> SHIFT) as u8
272+}
273+
274+fn byte(value: f32) -> u8 {
275+ value.round().clamp(0.0, 255.0) as u8
276+}
277+
278+/// The whole float pipeline, from one triple of input codes to one triple of
279+/// BT.709 limited-range output codes. Runs at build time only; the module note
280+/// walks the stages.
281+fn map_code(transfer: Transfer, yc: f32, uc: f32, vc: f32) -> [f32; 3] {
282+ // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.
283+ let luma = (yc - 16.0) / 219.0;
284+ let cb = (uc - 128.0) / 224.0;
285+ let cr = (vc - 128.0) / 224.0;
286+ let r = (luma + 1.4746 * cr).clamp(0.0, 1.0);
287+ let b = (luma + 1.8814 * cb).clamp(0.0, 1.0);
288+ let g = ((luma - 0.2627 * r - 0.0593 * b) / 0.6780).clamp(0.0, 1.0);
289+
290+ // 2/3. display light, then Method A's gamma-2.4 working domain, normalised
291+ // to the assumed mastering peak.
292+ //
293+ // Clamped at that peak, per channel, and this clamp is load-bearing: Method
294+ // A tone-maps *luma*, so a channel left above 1.0 comes back out of step 6
295+ // above 1.0 too, and the per-channel gamut clip in step 7 then keeps one
296+ // channel and drops another -- which does not make a highlight, it makes a
297+ // hole. A 2800 cd/m^2 near-white measured code 189 with a neighbouring code
298+ // at 78, a hundred-code cliff on a smooth ramp, before this line existed.
299+ // Clamping instead walks a too-bright pixel toward white, which is what a
300+ // highlight past the display's reach should do.
301+ //
302+ // ponytail: the ceiling is that MASTER_NITS is a guess. Content mastered
303+ // brighter than 1000 cd/m^2 loses its top stops to white here. The upgrade
304+ // is the stream's own MaxCLL/mastering-display metadata reaching this
305+ // module as a `new` argument -- nothing else in the pipeline changes.
306+ let lin = display_light(transfer, [r, g, b]);
307+ let gam = lin.map(|c| (c / MASTER_NITS).clamp(0.0, 1.0).powf(1.0 / GAMMA));
308+
309+ // 4. BT.2020 luma and colour differences, in that domain.
310+ let y_hdr = 0.2627 * gam[0] + 0.6780 * gam[1] + 0.0593 * gam[2];
311+ let cb_hdr = (gam[2] - y_hdr) / 1.8814;
312+ let cr_hdr = (gam[0] - y_hdr) / 1.4746;
313+
314+ // 5/6. the curve, then colour-difference scaling and its luma payback.
315+ let y_sdr = tone_curve(y_hdr);
316+ let scale = if y_hdr > 1e-6 {
317+ y_sdr / (1.075 * y_hdr)
318+ } else {
319+ 0.0
320+ };
321+ let (cb_t, cr_t) = (cb_hdr * scale, cr_hdr * scale);
322+ let y_t = y_sdr - (0.1 * cr_t).max(0.0);
323+
324+ // 7. back to R'G'B' (still BT.2020, still gamma 2.4), linearise, convert
325+ // primaries, clip, re-encode.
326+ let r = y_t + 1.4746 * cr_t;
327+ let b = y_t + 1.8814 * cb_t;
328+ let g = (y_t - 0.2627 * r - 0.0593 * b) / 0.6780;
329+ // Clipped in the BT.2020 signal domain first, the same way step 1 clips:
330+ // the colour-difference scaling can push a channel past the primaries it
331+ // came from, and a channel that leaves the *source* gamut only makes the
332+ // 709 clip below wilder.
333+ let [r, g, b] = [r, g, b].map(|c| c.clamp(0.0, 1.0).powf(GAMMA));
334+ let r709 = (1.6605 * r - 0.5876 * g - 0.0728 * b).clamp(0.0, 1.0);
335+ let g709 = (-0.1246 * r + 1.1329 * g - 0.0083 * b).clamp(0.0, 1.0);
336+ let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0);
337+ let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA));
338+
339+ // 8. BT.709 limited-range codes.
340+ let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
341+ [
342+ 16.0 + 219.0 * luma,
343+ 128.0 + 224.0 * (b - luma) / 1.8556,
344+ 128.0 + 224.0 * (r - luma) / 1.5748,
345+ ]
346+}
347+
348+/// Signal -> display light in cd/m^2.
349+fn display_light(transfer: Transfer, rgb: [f32; 3]) -> [f32; 3] {
350+ match transfer {
351+ Transfer::Pq => rgb.map(pq_eotf),
352+ Transfer::Hlg => {
353+ // BT.2100: inverse OETF to scene light, then the OOTF, whose system
354+ // gamma is 1.2 at a 1000 cd/m^2 display -- which is the peak this
355+ // module assumes anyway, so no log term is needed for it.
356+ let scene = rgb.map(hlg_scene);
357+ let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
358+ let gain = MASTER_NITS * ys.max(0.0).powf(0.2);
359+ scene.map(|c| gain * c)
360+ }
361+ }
362+}
363+
364+/// SMPTE ST 2084 EOTF. Constants are the standard's exact rationals.
365+fn pq_eotf(n: f32) -> f32 {
366+ const M1: f32 = 2610.0 / 16384.0;
367+ const M2: f32 = 2523.0 / 4096.0 * 128.0;
368+ const C1: f32 = 3424.0 / 4096.0;
369+ const C2: f32 = 2413.0 / 4096.0 * 32.0;
370+ const C3: f32 = 2392.0 / 4096.0 * 32.0;
371+ let p = n.max(0.0).powf(1.0 / M2);
372+ 10000.0 * ((p - C1).max(0.0) / (C2 - C3 * p)).powf(1.0 / M1)
373+}
374+
375+/// BT.2100 HLG inverse OETF: signal -> scene light, 0..1 where 1 is the
376+/// nominal white the OOTF then scales to the display peak.
377+fn hlg_scene(e: f32) -> f32 {
378+ const A: f32 = 0.17883277;
379+ const B: f32 = 1.0 - 4.0 * A;
380+ let e = e.clamp(0.0, 1.0);
381+ if e <= 0.5 {
382+ e * e / 3.0
383+ } else {
384+ // BT.2100 quotes `c` as 0.55991073; derived instead, because that is
385+ // where the number comes from and an `f32` cannot hold all eight
386+ // digits anyway. Build-time only, so the `ln` is free.
387+ let c = 0.5 - A * (4.0 * A).ln();
388+ (((e - c) / A).exp() + B) / 12.0
389+ }
390+}
391+
392+/// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR
393+/// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms
394+/// and the three-piece polynomial between them.
395+fn tone_curve(y_hdr: f32) -> f32 {
396+ let p_hdr = 1.0 + 32.0 * (MASTER_NITS / 10000.0).powf(1.0 / GAMMA);
397+ let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA);
398+ let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln();
399+ let yc = if yp <= 0.7399 {
400+ 1.0770 * yp
401+ } else if yp < 0.9909 {
402+ (-1.1510 * yp + 2.7811) * yp - 0.6302
403+ } else {
404+ 0.5 * yp + 0.5
405+ };
406+ (p_sdr.powf(yc) - 1.0) / (p_sdr - 1.0)
407+}
408+
409+#[cfg(test)]
410+mod tests {
411+ use super::*;
412+
413+ /// Inverse of [`pq_eotf`]: nits -> PQ signal, so an anchor can be named in
414+ /// cd/m^2 the way the standards name them.
415+ fn pq_code(nits: f32) -> f32 {
416+ const M1: f32 = 2610.0 / 16384.0;
417+ const M2: f32 = 2523.0 / 4096.0 * 128.0;
418+ const C1: f32 = 3424.0 / 4096.0;
419+ const C2: f32 = 2413.0 / 4096.0 * 32.0;
420+ const C3: f32 = 2392.0 / 4096.0 * 32.0;
421+ let y = (nits / 10000.0).powf(M1);
422+ let signal = ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2);
423+ 16.0 + 219.0 * signal
424+ }
425+
426+ /// One flat frame at a single YUV triple, mapped, handed back as its (Y, U,
427+ /// V) output. Goes through [`ToneMapper::map`], so it measures the shipped
428+ /// path -- LUT, interpolation and all -- not the float reference.
429+ fn mapped(mapper: &ToneMapper, yc: u8, uc: u8, vc: u8) -> (u8, u8, u8) {
430+ let (w, h) = (8usize, 8usize);
431+ let mut y = vec![yc; w * h];
432+ let mut u = vec![uc; w / 2 * h / 2];
433+ let mut v = vec![vc; w / 2 * h / 2];
434+ mapper.map(&mut y, &mut u, &mut v, w, h);
435+ (y[0], u[0], v[0])
436+ }
437+
438+ /// The three anchors, in cd/m^2, against codes worked out by hand from the
439+ /// stages in the module note. Black is pinned by the curve (0 in, 0 out);
440+ /// 1000 nits is the assumed peak and must reach SDR white; 203 nits is
441+ /// BT.2408 diffuse white, which Method A deliberately does *not* put at SDR
442+ /// white -- 166 is what the published maths gives, and the day that number
443+ /// moves, the transcription moved with it.
444+ #[test]
445+ fn pq_anchors_land_where_method_a_puts_them() {
446+ let mapper = ToneMapper::new(Transfer::Pq);
447+ for (nits, expected) in [(0.0, 16u8), (26.0, 89), (203.0, 166), (1000.0, 235)] {
448+ let code = byte(pq_code(nits));
449+ let (y, _, _) = mapped(&mapper, code, 128, 128);
450+ assert!(
451+ y.abs_diff(expected) <= 3,
452+ "{nits} cd/m^2 (code {code}) -> {y}, expected {expected}"
453+ );
454+ }
455+ }
456+
457+ /// On its nodes the grid is not an approximation at all: no interpolation
458+ /// runs, so the byte a picture gets is the byte the float pipeline
459+ /// computed. This is the half of the accuracy claim that is exact, and it
460+ /// covers every node of every axis for both transfers.
461+ #[test]
462+ fn the_grid_is_the_pipeline_on_its_nodes() {
463+ for transfer in [Transfer::Pq, Transfer::Hlg] {
464+ let mapper = ToneMapper::new(transfer);
465+ for yc in (0..=248u8).step_by(1 << LUMA_STEP) {
466+ for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {
467+ for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {
468+ let got = mapped(&mapper, yc, uc, vc);
469+ let want = map_code(transfer, yc.into(), uc.into(), vc.into());
470+ let want = (byte(want[0]), byte(want[1]), byte(want[2]));
471+ assert_eq!(got, want, "{transfer:?} node {yc}/{uc}/{vc}");
472+ }
473+ }
474+ }
475+ }
476+ }
477+
478+ /// Between the nodes the grid is a straight line through the eight that
479+ /// surround the sample, so every output it can produce lies inside the box
480+ /// those eight span -- an index off by one axis stride, a fraction taken
481+ /// from the wrong shift, or a carry between the packed fields all break
482+ /// this immediately, and none of them would move an on-node value.
483+ ///
484+ /// Deliberately *not* an epsilon against the float pipeline off the nodes:
485+ /// see the module note. Where the 709 clip flattens a range of inputs onto
486+ /// one output, a straight line between two nodes is up to 42 codes off that
487+ /// plateau and is the better-behaved of the two -- it ramps where the
488+ /// pipeline steps.
489+ #[test]
490+ fn between_nodes_the_grid_stays_inside_its_own_cell() {
491+ for transfer in [Transfer::Pq, Transfer::Hlg] {
492+ let mapper = ToneMapper::new(transfer);
493+ for yc in (3..=255u8).step_by(23) {
494+ for uc in (5..=255u8).step_by(29) {
495+ for vc in (7..=255u8).step_by(31) {
496+ let got = [
497+ mapped(&mapper, yc, uc, vc).0,
498+ mapped(&mapper, yc, uc, vc).1,
499+ mapped(&mapper, yc, uc, vc).2,
500+ ];
501+ // The eight enclosing nodes, from the same float
502+ // pipeline the table was built with.
503+ let (mut lo, mut hi) = ([255u8; 3], [0u8; 3]);
504+ let node = |c: u8, step: u32| f32::from((c >> step) << step);
505+ for dy in [0.0, f32::from(1u8 << LUMA_STEP)] {
506+ for du in [0.0, f32::from(1u8 << CHROMA_STEP)] {
507+ for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] {
508+ let out = map_code(
509+ transfer,
510+ node(yc, LUMA_STEP) + dy,
511+ node(uc, CHROMA_STEP) + du,
512+ node(vc, CHROMA_STEP) + dv,
513+ );
514+ for (i, c) in out.iter().enumerate() {
515+ lo[i] = lo[i].min(byte(*c));
516+ hi[i] = hi[i].max(byte(*c));
517+ }
518+ }
519+ }
520+ }
521+ for (i, name) in ["Y", "U", "V"].iter().enumerate() {
522+ // One code of slack: the nodes are rounded bytes
523+ // and the interpolation rounds once more.
524+ assert!(
525+ got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1,
526+ "{transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}",
527+ got[i],
528+ lo[i],
529+ hi[i]
530+ );
531+ }
532+ }
533+ }
534+ }
535+ }
536+ }
537+
538+ /// A grey ramp may not fold back on itself: an inversion anywhere is a
539+ /// posterised or solarised picture, and it is exactly what a badly built
540+ /// grid or a truncating interpolation produces.
541+ #[test]
542+ fn a_grey_ramp_never_inverts() {
543+ for transfer in [Transfer::Pq, Transfer::Hlg] {
544+ let mapper = ToneMapper::new(transfer);
545+ let mut last = 0u8;
546+ for code in 0..=255u8 {
547+ let (y, _, _) = mapped(&mapper, code, 128, 128);
548+ assert!(
549+ y >= last,
550+ "{transfer:?}: code {code} darkened to {y} < {last}"
551+ );
552+ last = y;
553+ }
554+ }
555+ }
556+
557+ /// Grey in, grey out: any chroma the pipeline invents on a neutral is a
558+ /// tint across the whole picture.
559+ #[test]
560+ fn neutral_input_stays_neutral() {
561+ for transfer in [Transfer::Pq, Transfer::Hlg] {
562+ let mapper = ToneMapper::new(transfer);
563+ for code in (16..=235u8).step_by(7) {
564+ let (_, u, v) = mapped(&mapper, code, 128, 128);
565+ assert!(
566+ u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2,
567+ "{transfer:?}: grey {code} tinted to U{u} V{v}"
568+ );
569+ }
570+ }
571+ }
572+
573+ /// HLG's own anchors. Its signal is relative, so what is worth pinning is
574+ /// where the OOTF puts it: black at black, peak signal at the assumed
575+ /// 1000 cd/m^2 display peak (hence SDR white, the PQ side's 1000-nit
576+ /// anchor), and BT.2408 HLG diffuse white -- signal 0.75, which the inverse
577+ /// OETF and the system-gamma-1.2 OOTF land on 203 cd/m^2, the same light as
578+ /// the PQ side's diffuse white and so the same output code. One pipeline,
579+ /// two front doors: if the HLG stage drifts, that agreement is the first
580+ /// thing to break.
581+ #[test]
582+ fn hlg_anchors_are_sane() {
583+ let mapper = ToneMapper::new(Transfer::Hlg);
584+ let code = |signal: f32| byte(16.0 + 219.0 * signal);
585+ let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);
586+ let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);
587+ let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);
588+ assert!(black.abs_diff(16) <= 3, "HLG black -> {black}");
589+ assert!(white.abs_diff(235) <= 3, "HLG peak -> {white}");
590+ assert!(diffuse.abs_diff(166) <= 3, "HLG diffuse white -> {diffuse}");
591+ }
592+
593+ /// A short plane is left alone rather than half mapped, and a frame with no
594+ /// size at all returns instead of panicking on a zero-length band.
595+ #[test]
596+ fn a_frame_that_does_not_measure_up_is_untouched() {
597+ let mapper = ToneMapper::new(Transfer::Pq);
598+ let mut y = vec![128u8; 8 * 8 - 1];
599+ let mut u = vec![128u8; 4 * 4];
600+ let mut v = vec![128u8; 4 * 4];
601+ mapper.map(&mut y, &mut u, &mut v, 8, 8);
602+ assert!(y.iter().all(|&s| s == 128), "short plane was mapped");
603+ mapper.map(&mut y, &mut u, &mut v, 0, 8);
604+ mapper.map(&mut y, &mut u, &mut v, 8, 0);
605+ mapper.map(&mut [], &mut [], &mut [], 0, 0);
606+ }
607+
608+ /// Odd sizes: the edge block covers one row or one column and must not run
609+ /// off the end.
610+ #[test]
611+ fn odd_sizes_map_every_pixel() {
612+ let mapper = ToneMapper::new(Transfer::Pq);
613+ let (w, h) = (7usize, 5usize);
614+ let mut y = vec![200u8; w * h];
615+ let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
616+ let mut v = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
617+ mapper.map(&mut y, &mut u, &mut v, w, h);
618+ assert!(y.iter().all(|&s| s != 200), "a pixel was skipped");
619+ }
620+
621+ /// The cost gate, asserted in release only: a debug build is an order of
622+ /// magnitude off and the number only means something optimised. Run with
623+ /// `cargo test -p engine --release --lib tonemap:: -- --nocapture`.
624+ ///
625+ /// The *fastest* frame of a two-second window, not the mean of a fixed
626+ /// count: this test shares a six-core machine with the other 200 in the
627+ /// binary, and measured against them a 19.0 ms frame reads as 29.7. Kept
628+ /// running until they are done, the tail iterations get a core to
629+ /// themselves and the minimum is the machine's real cost -- which is the
630+ /// question the gate asks, "can one core carry a 4K frame in a frame's
631+ /// time", and the reason a plain mean here would be a coin flip.
632+ #[test]
633+ fn perf_4k_and_1080p() {
634+ let mapper = ToneMapper::new(Transfer::Pq);
635+ for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {
636+ let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
637+ let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
638+ let mut v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
639+ let mut best = f64::MAX;
640+ let window = std::time::Instant::now();
641+ let mut runs = 0;
642+ while runs < 10 || window.elapsed().as_secs_f64() < 1.0 {
643+ let t = std::time::Instant::now();
644+ mapper.map(&mut y, &mut u, &mut v, w, h);
645+ best = best.min(t.elapsed().as_secs_f64() * 1000.0);
646+ runs += 1;
647+ }
648+ println!("tonemap::map {w}x{h}: {best:.3} ms/frame");
649+ if !cfg!(debug_assertions) {
650+ assert!(
651+ best <= budget,
652+ "{w}x{h}: {best:.3} ms/frame over {budget} ms"
653+ );
654+ }
655+ }
656+ }
657+}