forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

tonemap.rs1231 lines, 59.2 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 /// What the 10-bit table ([`ToneMapper::map16`]) is built from, and the table itself,
228 /// built on the first 10-bit picture and never for an 8-bit-only caller.
229 build: (Transfer, Preset),
230 wide: std::sync::OnceLock<WideNodes>,
231}
232
233/// The same grid with 10-bit nodes: output codes at four times the 8-bit scale, so a
234/// 10-bit picture is mapped without the 8-bit rounding of input or output.
235struct WideNodes {
236 y: Box<[u16]>,
237 uv: Box<[[u16; 2]]>,
238}
239
240/// Luma node spacing and chroma node spacing in 10-bit codes: the 8-bit steps, two bits up.
241const LUMA_STEP16: u32 = LUMA_STEP + 2;
242const LUMA_FRAC16: u32 = 1 << LUMA_STEP16;
243const CHROMA_STEP16: u32 = CHROMA_STEP + 2;
244const CHROMA_FRAC16: u32 = 1 << CHROMA_STEP16;
245
246impl ToneMapper {
247 /// `declared_peak` is the film's own peak brightness where it has one
248 /// ([`crate::demux::Demuxer::light`]), [`None`] for a file that declared
249 /// nothing. Which renditions act on it is [`Preset`]'s composition rule.
250 pub fn new(transfer: Transfer, preset: Preset, declared_peak: Option<f32>) -> Self {
251 let peak = preset.master_nits_for(declared_peak);
252 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
253 let (mut y_node, mut uv_node) = (vec![0u8; cells], vec![[0u8; 2]; cells]);
254 for kv in 0..CHROMA_NODES {
255 for ju in 0..CHROMA_NODES {
256 for iy in 0..LUMA_NODES {
257 // A node sits on code `n << STEP`; the last one on each axis
258 // is code 256, one past the top, which is the upper end of
259 // the interpolation for code 255 and never a lookup of its
260 // own.
261 let out = map_code(
262 transfer,
263 preset,
264 peak,
265 (iy << LUMA_STEP) as f32,
266 (ju << CHROMA_STEP) as f32,
267 (kv << CHROMA_STEP) as f32,
268 );
269 let at = index(iy, ju, kv);
270 y_node[at] = byte(out[0]);
271 uv_node[at] = [byte(out[1]), byte(out[2])];
272 }
273 }
274 }
275 let (mut luma, mut chroma) = (vec![0u32; cells], vec![0u64; cells]);
276 for kv in 0..CHROMA_NODES {
277 for ju in 0..CHROMA_NODES {
278 for iy in 0..LUMA_NODES {
279 let at = index(iy, ju, kv);
280 // The top node of a column has no neighbour above it and is
281 // never the lower end of an interpolation (code 255 lands on
282 // the node below it with a fraction), so it pairs with
283 // itself.
284 let up = if iy + 1 < LUMA_NODES { at + 1 } else { at };
285 luma[at] = u32::from(y_node[at]) | u32::from(y_node[up]) << 16;
286 chroma[at] = u64::from(uv_node[at][0])
287 | u64::from(uv_node[up][0]) << 16
288 | u64::from(uv_node[at][1]) << 32
289 | u64::from(uv_node[up][1]) << 48;
290 }
291 }
292 }
293 Self {
294 luma: luma.into_boxed_slice(),
295 chroma: chroma.into_boxed_slice(),
296 peak,
297 build: (transfer, preset),
298 wide: std::sync::OnceLock::new(),
299 }
300 }
301
302 fn wide_nodes(&self) -> &WideNodes {
303 self.wide.get_or_init(|| {
304 let (transfer, preset) = self.build;
305 let cells = LUMA_NODES * CHROMA_NODES * CHROMA_NODES;
306 let (mut y, mut uv) = (vec![0u16; cells], vec![[0u16; 2]; cells]);
307 let code = |v: f32| (v * 4.0).round().clamp(0.0, 1023.0) as u16;
308 for kv in 0..CHROMA_NODES {
309 for ju in 0..CHROMA_NODES {
310 for iy in 0..LUMA_NODES {
311 let out = map_code(
312 transfer,
313 preset,
314 self.peak,
315 (iy << LUMA_STEP) as f32,
316 (ju << CHROMA_STEP) as f32,
317 (kv << CHROMA_STEP) as f32,
318 );
319 let at = index(iy, ju, kv);
320 y[at] = code(out[0]);
321 uv[at] = [code(out[1]), code(out[2])];
322 }
323 }
324 }
325 WideNodes { y: y.into_boxed_slice(), uv: uv.into_boxed_slice() }
326 })
327 }
328
329 /// [`ToneMapper::map`] for a 10-bit I420 frame (codes 0..=1023, limited range): the same
330 /// grid read at 10-bit precision and written at 10-bit precision, so a tone mapped gradient
331 /// keeps its steps finer than 8 bits' instead of being rounded to them twice.
332 pub fn map16(&self, y: &mut [u16], u: &mut [u16], v: &mut [u16], width: usize, height: usize) {
333 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
334 if width == 0 || height == 0 || y.len() < width * height || u.len() < cw * ch || v.len() < cw * ch {
335 return;
336 }
337 let nodes = self.wide_nodes();
338 let y = &mut y[..width * height];
339 let u = &mut u[..cw * ch];
340 let v = &mut v[..cw * ch];
341 let lanes = std::thread::available_parallelism().map_or(1, |n| n.get()).min(ch);
342 if lanes <= 1 {
343 Self::map_bands16(nodes, y, u, v, width, cw);
344 return;
345 }
346 let bands_per_lane = ch.div_ceil(lanes);
347 std::thread::scope(|scope| {
348 let (mut y_rest, mut u_rest, mut v_rest) = (y, u, v);
349 let mut band = 0;
350 while band < ch {
351 let take = bands_per_lane.min(ch - band);
352 let y_len = (take * 2 * width).min(y_rest.len());
353 let u_len = take * cw;
354 let (y_chunk, y_remain) = y_rest.split_at_mut(y_len);
355 let (u_chunk, u_remain) = u_rest.split_at_mut(u_len);
356 let (v_chunk, v_remain) = v_rest.split_at_mut(u_len);
357 (y_rest, u_rest, v_rest) = (y_remain, u_remain, v_remain);
358 scope.spawn(move || Self::map_bands16(nodes, y_chunk, u_chunk, v_chunk, width, cw));
359 band += take;
360 }
361 });
362 }
363
364 fn map_bands16(nodes: &WideNodes, y: &mut [u16], u: &mut [u16], v: &mut [u16], width: usize, cw: usize) {
365 // The trilinear tap at luma code `luma`, chroma sites `corners`/`weights` (the
366 // chroma-bilinear weights sum to CHROMA_FRAC16^2), collapsed over the two luma nodes.
367 let tap = |table: &dyn Fn(usize) -> u32, corners: &[usize; 4], weights: &[u32; 4], luma: u32| -> u16 {
368 let (iy, fy) = ((luma >> LUMA_STEP16) as usize, luma & (LUMA_FRAC16 - 1));
369 let (mut lo, mut hi) = (0u32, 0u32);
370 for (corner, weight) in corners.iter().zip(weights) {
371 lo += weight * table(corner + iy);
372 hi += weight * table(corner + iy + usize::from(iy + 1 < LUMA_NODES));
373 }
374 const SHIFT: u32 = LUMA_STEP16 + 2 * CHROMA_STEP16;
375 ((lo * (LUMA_FRAC16 - fy) + hi * fy + (1 << (SHIFT - 1))) >> SHIFT) as u16
376 };
377 let bands = y.chunks_mut(2 * width);
378 let chroma_rows = u.chunks_mut(cw).zip(v.chunks_mut(cw));
379 for (band, (u_row, v_row)) in bands.zip(chroma_rows) {
380 let (top, bottom) = band.split_at_mut(width.min(band.len()));
381 let mut tops = top.chunks_mut(2);
382 let mut bottoms = bottom.chunks_mut(2);
383 for (u_site, v_site) in u_row.iter_mut().zip(v_row) {
384 let top = tops.next().unwrap_or_default();
385 let bottom = bottoms.next().unwrap_or_default();
386 let (uc, vc) = (u32::from(*u_site).min(1023), u32::from(*v_site).min(1023));
387 let (ju, fu) = ((uc >> CHROMA_STEP16) as usize, uc & (CHROMA_FRAC16 - 1));
388 let (kv, fv) = ((vc >> CHROMA_STEP16) as usize, vc & (CHROMA_FRAC16 - 1));
389 let corners = [
390 index(0, ju, kv),
391 index(0, ju + 1, kv),
392 index(0, ju, kv + 1),
393 index(0, ju + 1, kv + 1),
394 ];
395 let weights = [
396 (CHROMA_FRAC16 - fu) * (CHROMA_FRAC16 - fv),
397 fu * (CHROMA_FRAC16 - fv),
398 (CHROMA_FRAC16 - fu) * fv,
399 fu * fv,
400 ];
401 let mut src = [0u32; 4];
402 let (mut count, mut sum) = (0u32, 0u32);
403 for (slot, sample) in src.iter_mut().zip(top.iter().chain(bottom.iter())) {
404 *slot = u32::from(*sample).min(1023);
405 sum += *slot;
406 count += 1;
407 }
408 let mean = (sum + count / 2) / count;
409 *u_site = tap(&|i| u32::from(nodes.uv[i][0]), &corners, &weights, mean);
410 *v_site = tap(&|i| u32::from(nodes.uv[i][1]), &corners, &weights, mean);
411 for (sample, s) in top.iter_mut().chain(bottom).zip(src) {
412 *sample = tap(&|i| u32::from(nodes.y[i]), &corners, &weights, s);
413 }
414 }
415 }
416 }
417
418 /// The mastering peak this table was built at, cd/m^2: the film's own where
419 /// the rendition reads it, the rendition's own otherwise. What a test -- or
420 /// a caller wanting to say which number a picture came out of -- asks.
421 pub fn peak(&self) -> f32 {
422 self.peak
423 }
424
425 /// Maps one tightly packed 8-bit I420 frame in place: `y` is `width *
426 /// height`, `u` and `v` are each `width.div_ceil(2) * height.div_ceil(2)`,
427 /// no padding (the shape [`crate::convert`], the decoders and the export
428 /// path all pass around). A frame that does not measure up is left
429 /// untouched rather than half-mapped -- callers hand these in from decoders
430 /// and files, and a short plane is a bug upstream, not a picture worth
431 /// guessing at.
432 ///
433 /// In place because both integration sites already own a scratch copy of
434 /// the planes at this point (`decode::Render::graded`, and the export
435 /// path's grade buffer): they can map that copy and keep the decoder's
436 /// frame intact for free.
437 pub fn map(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize, height: usize) {
438 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
439 // A frame with no width is not a short plane, it is not a frame; it
440 // also makes the band size below zero, which `chunks_mut` panics on.
441 if width == 0 || height == 0 {
442 return;
443 }
444 if y.len() < width * height || u.len() < cw * ch || v.len() < cw * ch {
445 return;
446 }
447 let y = &mut y[..width * height];
448 let u = &mut u[..cw * ch];
449 let v = &mut v[..cw * ch];
450
451 // One lane's worth of bands is independent of every other's -- a band
452 // reads only its own chroma samples and its own two luma rows -- so
453 // the band loop below (`map_bands`) fans out over the machine's cores
454 // the same way `HevcEnc::code_batch` does: `std::thread::scope`,
455 // borrowing the planes rather than copying them, one contiguous run
456 // of bands per lane. A frame with fewer chroma rows than cores, or a
457 // machine that only reports one, just runs the whole thing here.
458 let lanes = std::thread::available_parallelism()
459 .map_or(1, |n| n.get())
460 .min(ch);
461 if lanes <= 1 {
462 self.map_bands(y, u, v, width, cw);
463 return;
464 }
465 let bands_per_lane = ch.div_ceil(lanes);
466 std::thread::scope(|scope| {
467 let (mut y_rest, mut u_rest, mut v_rest) = (y, u, v);
468 let mut band = 0;
469 while band < ch {
470 let take = bands_per_lane.min(ch - band);
471 // The last lane's last band is one row short on an odd
472 // frame, which is the only reason `y`'s chunk isn't simply
473 // `take * 2 * width`.
474 let y_len = (take * 2 * width).min(y_rest.len());
475 let u_len = take * cw;
476 let (y_chunk, y_remain) = y_rest.split_at_mut(y_len);
477 let (u_chunk, u_remain) = u_rest.split_at_mut(u_len);
478 let (v_chunk, v_remain) = v_rest.split_at_mut(u_len);
479 (y_rest, u_rest, v_rest) = (y_remain, u_remain, v_remain);
480 scope.spawn(move || self.map_bands(y_chunk, u_chunk, v_chunk, width, cw));
481 band += take;
482 }
483 });
484 }
485
486 /// One contiguous run of bands: the loop `map` used to run over the whole
487 /// frame, unchanged, just handed a slice that may be the whole plane or
488 /// one lane's share of it.
489 fn map_bands(&self, y: &mut [u8], u: &mut [u8], v: &mut [u8], width: usize, cw: usize) {
490 // Row slices rather than indices: the plane bounds are checked once per
491 // band, not once per sample, which is most of the difference between
492 // this and a frame's time budget.
493 let bands = y.chunks_mut(2 * width);
494 let chroma_rows = u.chunks_mut(cw).zip(v.chunks_mut(cw));
495 for (band, (u_row, v_row)) in bands.zip(chroma_rows) {
496 // The bottom half is empty on an odd frame's last band.
497 let (top, bottom) = band.split_at_mut(width.min(band.len()));
498 let mut tops = top.chunks_mut(2);
499 let mut bottoms = bottom.chunks_mut(2);
500 for (u_site, v_site) in u_row.iter_mut().zip(v_row) {
501 // Odd widths leave a one-pixel block at the end of the row.
502 let top = tops.next().unwrap_or_default();
503 let bottom = bottoms.next().unwrap_or_default();
504
505 // The block's chroma, bilinear: four node columns and their
506 // weights, shared by every lookup this block makes.
507 let (uc, vc) = (u32::from(*u_site), u32::from(*v_site));
508 let (ju, fu) = ((uc >> CHROMA_STEP) as usize, uc & (CHROMA_FRAC - 1));
509 let (kv, fv) = ((vc >> CHROMA_STEP) as usize, vc & (CHROMA_FRAC - 1));
510 let corners = [
511 index(0, ju, kv),
512 index(0, ju + 1, kv),
513 index(0, ju, kv + 1),
514 index(0, ju + 1, kv + 1),
515 ];
516 let weights = [
517 (CHROMA_FRAC - fu) * (CHROMA_FRAC - fv),
518 fu * (CHROMA_FRAC - fv),
519 (CHROMA_FRAC - fu) * fv,
520 fu * fv,
521 ];
522
523 // Read the block's luma before writing any of it back: the
524 // chroma lookup is keyed on the *source* luma of the block.
525 let mut src = [0u32; 4];
526 let mut count = 0u32;
527 let mut sum = 0u32;
528 for (slot, sample) in src.iter_mut().zip(top.iter().chain(bottom.iter())) {
529 *slot = u32::from(*sample);
530 sum += *slot;
531 count += 1;
532 }
533 let mean = (sum + count / 2) / count;
534
535 let (iy, fy) = ((mean >> LUMA_STEP) as usize, mean & (LUMA_FRAC - 1));
536 let mut acc = 0u64;
537 for (corner, weight) in corners.iter().zip(&weights) {
538 acc += u64::from(*weight) * self.chroma[corner + iy];
539 }
540 *u_site = fade((acc & 0xffff) as u32, (acc >> 16 & 0xffff) as u32, fy);
541 *v_site = fade((acc >> 32 & 0xffff) as u32, (acc >> 48) as u32, fy);
542
543 for (sample, s) in top.iter_mut().chain(bottom).zip(src) {
544 let (iy, fy) = ((s >> LUMA_STEP) as usize, s & (LUMA_FRAC - 1));
545 let mut acc = 0u32;
546 for (corner, weight) in corners.iter().zip(&weights) {
547 acc += weight * self.luma[corner + iy];
548 }
549 *sample = fade(acc & 0xffff, acc >> 16, fy);
550 }
551 }
552 }
553 }
554}
555
556/// Node offset. Luma is the fastest axis on purpose -- see [`ToneMapper::luma`].
557fn index(iy: usize, ju: usize, kv: usize) -> usize {
558 (kv * CHROMA_NODES + ju) * LUMA_NODES + iy
559}
560
561/// The last leg of the trilinear tap: `lo` and `hi` are the chroma-bilinear
562/// collapse at the two luma nodes (each already carrying the `CHROMA_FRAC^2`
563/// chroma scale), `fy` the pixel's fraction between them. Rounds once, at the
564/// end, over the whole scale -- truncating here is what puts a step in a
565/// gradient.
566fn fade(lo: u32, hi: u32, fy: u32) -> u8 {
567 const SHIFT: u32 = LUMA_STEP + 2 * CHROMA_STEP;
568 ((lo * (LUMA_FRAC - fy) + hi * fy + (1 << (SHIFT - 1))) >> SHIFT) as u8
569}
570
571fn byte(value: f32) -> u8 {
572 value.round().clamp(0.0, 255.0) as u8
573}
574
575/// The whole float pipeline, from one triple of input codes to one triple of
576/// BT.709 limited-range output codes. Runs at build time only; the module note
577/// walks the stages.
578fn map_code(
579 transfer: Transfer,
580 preset: Preset,
581 master_nits: f32,
582 yc: f32,
583 uc: f32,
584 vc: f32,
585) -> [f32; 3] {
586 // 1. limited-range BT.2020 Y'C'bC'r -> R'G'B' signal.
587 let luma = (yc - 16.0) / 219.0;
588 let cb = (uc - 128.0) / 224.0;
589 let cr = (vc - 128.0) / 224.0;
590 let r = (luma + 1.4746 * cr).clamp(0.0, 1.0);
591 let b = (luma + 1.8814 * cb).clamp(0.0, 1.0);
592 let g = ((luma - 0.2627 * r - 0.0593 * b) / 0.6780).clamp(0.0, 1.0);
593
594 // 2/3. display light, then Method A's gamma-2.4 working domain, normalised
595 // to the assumed mastering peak.
596 //
597 // Clamped at that peak, per channel, and this clamp is load-bearing: Method
598 // A tone-maps *luma*, so a channel left above 1.0 comes back out of step 6
599 // above 1.0 too, and the per-channel gamut clip in step 7 then keeps one
600 // channel and drops another -- which does not make a highlight, it makes a
601 // hole. A 2800 cd/m^2 near-white measured code 189 with a neighbouring code
602 // at 78, a hundred-code cliff on a smooth ramp, before this line existed.
603 // Clamping instead walks a too-bright pixel toward white, which is what a
604 // highlight past the display's reach should do.
605 //
606 // The reference rendition is now told the film's own declared peak
607 // ([`Preset::master_nits_for`]), so what walks to white here is what the
608 // film says it never masters above; the two fixed renditions keep their
609 // exposure and still clamp an HDR10 grade's top end into white on purpose.
610 let lin = display_light(transfer, master_nits, [r, g, b]);
611 let gam = lin.map(|c| (c / master_nits).clamp(0.0, 1.0).powf(1.0 / GAMMA));
612
613 // 4. BT.2020 luma and colour differences, in that domain.
614 let y_hdr = 0.2627 * gam[0] + 0.6780 * gam[1] + 0.0593 * gam[2];
615 let cb_hdr = (gam[2] - y_hdr) / 1.8814;
616 let cr_hdr = (gam[0] - y_hdr) / 1.4746;
617
618 // 5/6. the curve, then colour-difference scaling and its luma payback.
619 let y_sdr = tone_curve(y_hdr, master_nits);
620 let scale = if y_hdr > 1e-6 {
621 y_sdr / (1.075 * y_hdr)
622 } else {
623 0.0
624 };
625 let (cb_t, cr_t) = (cb_hdr * scale, cr_hdr * scale);
626 let y_t = y_sdr - (0.1 * cr_t).max(0.0);
627
628 // 7. back to R'G'B' (still BT.2020, still gamma 2.4), linearise, convert
629 // primaries, clip, re-encode.
630 let r = y_t + 1.4746 * cr_t;
631 let b = y_t + 1.8814 * cb_t;
632 let g = (y_t - 0.2627 * r - 0.0593 * b) / 0.6780;
633 // Clipped in the BT.2020 signal domain first, the same way step 1 clips:
634 // the colour-difference scaling can push a channel past the primaries it
635 // came from, and a channel that leaves the *source* gamut only makes the
636 // 709 clip below wilder.
637 let [r, g, b] = [r, g, b].map(|c| c.clamp(0.0, 1.0).powf(GAMMA));
638 let r709 = (1.6605 * r - 0.5876 * g - 0.0728 * b).clamp(0.0, 1.0);
639 let g709 = (-0.1246 * r + 1.1329 * g - 0.0083 * b).clamp(0.0, 1.0);
640 let b709 = (-0.0182 * r - 0.1006 * g + 1.1187 * b).clamp(0.0, 1.0);
641 let [r, g, b] = [r709, g709, b709].map(|c| c.powf(1.0 / GAMMA));
642
643 // 8. BT.709 limited-range codes, the preset's chroma gain on the two colour
644 // differences.
645 //
646 // A *scale* about 128 and never a shift, applied here and nowhere earlier:
647 // 128 is neutral, so a grey stays exactly grey at any gain (`128 - 128` is
648 // zero however it is multiplied) and only a pixel that already had colour
649 // gets more of it. Clamped to the legal 16..240 chroma range, which at gain
650 // 1.0 is a clamp the maths above cannot reach -- the untouched presets come
651 // out byte for byte what Method A produced.
652 let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
653 let gain = preset.chroma_gain();
654 [
655 16.0 + 219.0 * luma,
656 (128.0 + gain * 224.0 * (b - luma) / 1.8556).clamp(16.0, 240.0),
657 (128.0 + gain * 224.0 * (r - luma) / 1.5748).clamp(16.0, 240.0),
658 ]
659}
660
661/// Signal -> display light in cd/m^2.
662fn display_light(transfer: Transfer, master_nits: f32, rgb: [f32; 3]) -> [f32; 3] {
663 match transfer {
664 Transfer::Pq => rgb.map(pq_eotf),
665 Transfer::Hlg => {
666 // BT.2100: inverse OETF to scene light, then the OOTF, whose system
667 // gamma is 1.2 at a 1000 cd/m^2 display and follows the display
668 // peak from there by the standard's own log term -- so the peak in
669 // force, the picked rendition's read against the film's declared
670 // one, is the peak the OOTF is built for rather than a number the
671 // choice or the metadata silently invalidates.
672 let scene = rgb.map(hlg_scene);
673 let ys = 0.2627 * scene[0] + 0.6780 * scene[1] + 0.0593 * scene[2];
674 let gamma = 1.2 + 0.42 * (master_nits / 1000.0).log10();
675 // Black is black, said outright rather than left to the arithmetic:
676 // below a 1000 cd/m^2 peak the system gamma is *under* 1, so the
677 // `ys^(gamma - 1)` term diverges as the scene goes black and the
678 // `0 * inf` that follows is a NaN -- which byte-casts to 0 and puts
679 // a hole where black belongs (measured: HLG black rendered code 0
680 // under the vivid preset before this line). Kept above 1000 too,
681 // where a declared peak puts the gamma over 1 and the term is
682 // merely 0: the guard costs one comparison at build time.
683 let ys = ys.max(0.0);
684 let gain = match ys > 0.0 {
685 true => master_nits * ys.powf(gamma - 1.0),
686 false => 0.0,
687 };
688 scene.map(|c| gain * c)
689 }
690 }
691}
692
693/// SMPTE ST 2084 EOTF. Constants are the standard's exact rationals.
694fn pq_eotf(n: f32) -> f32 {
695 const M1: f32 = 2610.0 / 16384.0;
696 const M2: f32 = 2523.0 / 4096.0 * 128.0;
697 const C1: f32 = 3424.0 / 4096.0;
698 const C2: f32 = 2413.0 / 4096.0 * 32.0;
699 const C3: f32 = 2392.0 / 4096.0 * 32.0;
700 let p = n.max(0.0).powf(1.0 / M2);
701 10000.0 * ((p - C1).max(0.0) / (C2 - C3 * p)).powf(1.0 / M1)
702}
703
704/// BT.2100 HLG inverse OETF: signal -> scene light, 0..1 where 1 is the
705/// nominal white the OOTF then scales to the display peak.
706fn hlg_scene(e: f32) -> f32 {
707 const A: f32 = 0.17883277;
708 const B: f32 = 1.0 - 4.0 * A;
709 let e = e.clamp(0.0, 1.0);
710 if e <= 0.5 {
711 e * e / 3.0
712 } else {
713 // BT.2100 quotes `c` as 0.55991073; derived instead, because that is
714 // where the number comes from and an `f32` cannot hold all eight
715 // digits anyway. Build-time only, so the `ln` is free.
716 let c = 0.5 - A * (4.0 * A).ln();
717 (((e - c) / A).exp() + B) / 12.0
718 }
719}
720
721/// BT.2446 Method A's tone curve, in the gamma-2.4 domain: 1 in is 1 out (HDR
722/// peak to SDR peak) and 0 in is 0 out, which is what pins the two `p` terms
723/// and the three-piece polynomial between them.
724fn tone_curve(y_hdr: f32, master_nits: f32) -> f32 {
725 let p_hdr = 1.0 + 32.0 * (master_nits / 10000.0).powf(1.0 / GAMMA);
726 let p_sdr = 1.0 + 32.0 * (SDR_NITS / 10000.0).powf(1.0 / GAMMA);
727 let yp = (1.0 + (p_hdr - 1.0) * y_hdr.max(0.0)).ln() / p_hdr.ln();
728 let yc = if yp <= 0.7399 {
729 1.0770 * yp
730 } else if yp < 0.9909 {
731 (-1.1510 * yp + 2.7811) * yp - 0.6302
732 } else {
733 0.5 * yp + 0.5
734 };
735 (p_sdr.powf(yc) - 1.0) / (p_sdr - 1.0)
736}
737
738#[cfg(test)]
739mod tests {
740 use super::*;
741
742 /// Inverse of [`pq_eotf`]: nits -> PQ signal, so an anchor can be named in
743 /// cd/m^2 the way the standards name them.
744 fn pq_code(nits: f32) -> f32 {
745 const M1: f32 = 2610.0 / 16384.0;
746 const M2: f32 = 2523.0 / 4096.0 * 128.0;
747 const C1: f32 = 3424.0 / 4096.0;
748 const C2: f32 = 2413.0 / 4096.0 * 32.0;
749 const C3: f32 = 2392.0 / 4096.0 * 32.0;
750 let y = (nits / 10000.0).powf(M1);
751 let signal = ((C1 + C2 * y) / (1.0 + C3 * y)).powf(M2);
752 16.0 + 219.0 * signal
753 }
754
755 /// The 10-bit map is the 8-bit one at four times the precision: a 10-bit ramp comes out
756 /// within a few codes of four times the 8-bit map of the same ramp, and with far more than
757 /// 256 distinct luma codes, where mapping the narrowed ramp has at most 256.
758 #[test]
759 fn the_ten_bit_map_agrees_with_the_eight_bit_one_and_keeps_its_steps() {
760 let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, None);
761 let (w, h) = (256usize, 8usize);
762 let ramp = |x: usize| 64 + (x * 876 / (w - 1)) as u16;
763 let mut y: Vec<u16> = (0..w * h).map(|i| ramp(i % w)).collect();
764 let mut u = vec![512u16; w / 2 * h / 2];
765 let mut v = u.clone();
766 mapper.map16(&mut y, &mut u, &mut v, w, h);
767 let mut y8: Vec<u8> = (0..w * h).map(|i| (ramp(i % w) >> 2) as u8).collect();
768 let mut u8_ = vec![128u8; w / 2 * h / 2];
769 let mut v8 = u8_.clone();
770 mapper.map(&mut y8, &mut u8_, &mut v8, w, h);
771 let worst = y.iter().zip(&y8).map(|(&a, &b)| (i32::from(a) - 4 * i32::from(b)).abs()).max().unwrap();
772 assert!(worst <= 8, "10-bit map off the 8-bit one by {worst} codes");
773 let distinct = y[..w].iter().collect::<std::collections::BTreeSet<_>>().len();
774 let distinct8 = y8[..w].iter().collect::<std::collections::BTreeSet<_>>().len();
775 assert!(distinct >= distinct8, "{distinct} vs {distinct8}");
776 assert!(y[..w].windows(2).all(|p| p[0] <= p[1]), "never inverts");
777 }
778
779 /// One flat frame at a single YUV triple, mapped, handed back as its (Y, U,
780 /// V) output. Goes through [`ToneMapper::map`], so it measures the shipped
781 /// path -- LUT, interpolation and all -- not the float reference.
782 fn mapped(mapper: &ToneMapper, yc: u8, uc: u8, vc: u8) -> (u8, u8, u8) {
783 let (w, h) = (8usize, 8usize);
784 let mut y = vec![yc; w * h];
785 let mut u = vec![uc; w / 2 * h / 2];
786 let mut v = vec![vc; w / 2 * h / 2];
787 mapper.map(&mut y, &mut u, &mut v, w, h);
788 (y[0], u[0], v[0])
789 }
790
791 /// The anchors, in cd/m^2, against the codes the stages in the module note
792 /// give for each preset's assumed peak. Black is pinned by the curve (0 in,
793 /// 0 out); the assumed peak itself must reach SDR white; 203 nits is BT.2408
794 /// diffuse white, and *where it lands is the whole difference between the
795 /// presets* -- 166 at the published 1000 cd/m^2 (broadcast-faithful, and the
796 /// reason the reference rendition reads dark), 205 at 400, 226 at 250. The
797 /// day one of these moves, the transcription moved with it.
798 ///
799 /// The last row of each says what happens above the assumed peak, asserted
800 /// rather than described: it is white.
801 #[test]
802 fn pq_anchors_land_where_method_a_puts_them() {
803 for (preset, diffuse) in [
804 (Preset::Reference, 166u8),
805 (Preset::Standard, 205),
806 (Preset::Vivid, 226),
807 ] {
808 let peak = preset.master_nits();
809 let mapper = ToneMapper::new(Transfer::Pq, preset, None);
810 for (nits, expected) in [(0.0, 16u8), (203.0, diffuse), (peak, 235), (10000.0, 235)] {
811 let code = byte(pq_code(nits));
812 let (y, _, _) = mapped(&mapper, code, 128, 128);
813 assert!(
814 y.abs_diff(expected) <= 3,
815 "{preset:?}: {nits} cd/m^2 (code {code}) -> {y}, expected {expected}"
816 );
817 }
818 }
819 }
820
821 /// What the presets are *for*, on one code: brighter is brighter, and the
822 /// vivid one has more colour in it. A preset that renamed the same numbers
823 /// would pass every other test in this module and fail this one.
824 ///
825 /// The chroma reading is the distance from neutral, which is the thing the
826 /// gain scales; the grey beside it is the neutrality that must survive it,
827 /// so "richer" cannot have been bought with a tint.
828 #[test]
829 fn a_brighter_preset_is_brighter_and_a_vivid_one_is_richer() {
830 // BT.2408 diffuse white, and a saturated BT.2020 red beside it.
831 let (diffuse, red) = (byte(pq_code(203.0)), (100u8, 90u8, 200u8));
832 let luma = |preset| {
833 mapped(
834 &ToneMapper::new(Transfer::Pq, preset, None),
835 diffuse,
836 128,
837 128,
838 )
839 .0
840 };
841 let (reference, standard, vivid) = (
842 luma(Preset::Reference),
843 luma(Preset::Standard),
844 luma(Preset::Vivid),
845 );
846 assert!(
847 reference < standard && standard < vivid,
848 "reference {reference}, standard {standard}, vivid {vivid}"
849 );
850 let colour = |preset| {
851 let (_, u, v) = mapped(
852 &ToneMapper::new(Transfer::Pq, preset, None),
853 red.0,
854 red.1,
855 red.2,
856 );
857 (u.abs_diff(128), v.abs_diff(128))
858 };
859 let (flat, rich) = (colour(Preset::Standard), colour(Preset::Vivid));
860 // Both differences read together, and neither of them allowed to shrink:
861 // this red is saturated enough that its V is already against the legal
862 // 240 rail under both presets, so the gain has nowhere to take *that*
863 // one -- which is the clamp doing its job, not the gain failing to.
864 assert!(
865 rich.0 + rich.1 > flat.0 + flat.1 && rich.0 >= flat.0 && rich.1 >= flat.1,
866 "vivid's red {rich:?} is no further from neutral than standard's {flat:?}"
867 );
868 }
869
870 /// On its nodes the grid is not an approximation at all: no interpolation
871 /// runs, so the byte a picture gets is the byte the float pipeline
872 /// computed. This is the half of the accuracy claim that is exact, and it
873 /// covers every node of every axis for both transfers.
874 #[test]
875 fn the_grid_is_the_pipeline_on_its_nodes() {
876 for preset in Preset::ALL {
877 for transfer in [Transfer::Pq, Transfer::Hlg] {
878 let mapper = ToneMapper::new(transfer, preset, None);
879 for yc in (0..=248u8).step_by(1 << LUMA_STEP) {
880 for uc in (0..=240u8).step_by(1 << CHROMA_STEP) {
881 for vc in (0..=240u8).step_by(1 << CHROMA_STEP) {
882 let got = mapped(&mapper, yc, uc, vc);
883 let want = map_code(
884 transfer,
885 preset,
886 mapper.peak(),
887 yc.into(),
888 uc.into(),
889 vc.into(),
890 );
891 let want = (byte(want[0]), byte(want[1]), byte(want[2]));
892 assert_eq!(got, want, "{preset:?} {transfer:?} node {yc}/{uc}/{vc}");
893 }
894 }
895 }
896 }
897 }
898 }
899
900 /// Between the nodes the grid is a straight line through the eight that
901 /// surround the sample, so every output it can produce lies inside the box
902 /// those eight span -- an index off by one axis stride, a fraction taken
903 /// from the wrong shift, or a carry between the packed fields all break
904 /// this immediately, and none of them would move an on-node value.
905 ///
906 /// Deliberately *not* an epsilon against the float pipeline off the nodes:
907 /// see the module note. Where the 709 clip flattens a range of inputs onto
908 /// one output, a straight line between two nodes is up to 42 codes off that
909 /// plateau and is the better-behaved of the two -- it ramps where the
910 /// pipeline steps.
911 #[test]
912 fn between_nodes_the_grid_stays_inside_its_own_cell() {
913 // Every preset, since the vivid one's chroma gain is a stage the nodes
914 // carry and the interpolation between them must not exaggerate.
915 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
916 .into_iter()
917 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
918 {
919 let mapper = ToneMapper::new(transfer, preset, None);
920 for yc in (3..=255u8).step_by(23) {
921 for uc in (5..=255u8).step_by(29) {
922 for vc in (7..=255u8).step_by(31) {
923 let got = [
924 mapped(&mapper, yc, uc, vc).0,
925 mapped(&mapper, yc, uc, vc).1,
926 mapped(&mapper, yc, uc, vc).2,
927 ];
928 // The eight enclosing nodes, from the same float
929 // pipeline the table was built with.
930 let (mut lo, mut hi) = ([255u8; 3], [0u8; 3]);
931 let node = |c: u8, step: u32| f32::from((c >> step) << step);
932 for dy in [0.0, f32::from(1u8 << LUMA_STEP)] {
933 for du in [0.0, f32::from(1u8 << CHROMA_STEP)] {
934 for dv in [0.0, f32::from(1u8 << CHROMA_STEP)] {
935 let out = map_code(
936 transfer,
937 preset,
938 mapper.peak(),
939 node(yc, LUMA_STEP) + dy,
940 node(uc, CHROMA_STEP) + du,
941 node(vc, CHROMA_STEP) + dv,
942 );
943 for (i, c) in out.iter().enumerate() {
944 lo[i] = lo[i].min(byte(*c));
945 hi[i] = hi[i].max(byte(*c));
946 }
947 }
948 }
949 }
950 for (i, name) in ["Y", "U", "V"].iter().enumerate() {
951 // One code of slack: the nodes are rounded bytes
952 // and the interpolation rounds once more.
953 assert!(
954 got[i] + 1 >= lo[i] && got[i] <= hi[i] + 1,
955 "{preset:?} {transfer:?} {name} at {yc}/{uc}/{vc}: {} outside {}..{}",
956 got[i],
957 lo[i],
958 hi[i]
959 );
960 }
961 }
962 }
963 }
964 }
965 }
966
967 /// A grey ramp may not fold back on itself: an inversion anywhere is a
968 /// posterised or solarised picture, and it is exactly what a badly built
969 /// grid or a truncating interpolation produces.
970 #[test]
971 fn a_grey_ramp_never_inverts() {
972 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
973 .into_iter()
974 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
975 {
976 let mapper = ToneMapper::new(transfer, preset, None);
977 let mut last = 0u8;
978 for code in 0..=255u8 {
979 let (y, _, _) = mapped(&mapper, code, 128, 128);
980 assert!(
981 y >= last,
982 "{preset:?} {transfer:?}: code {code} darkened to {y} < {last}"
983 );
984 last = y;
985 }
986 }
987 }
988
989 /// Grey in, grey out: any chroma the pipeline invents on a neutral is a
990 /// tint across the whole picture -- and a chroma *gain* that was written as
991 /// a shift, or applied anywhere but about 128, is exactly that tint, which
992 /// is why the vivid preset is in this loop.
993 #[test]
994 fn neutral_input_stays_neutral() {
995 for (transfer, preset) in [Transfer::Pq, Transfer::Hlg]
996 .into_iter()
997 .flat_map(|t| Preset::ALL.map(|p| (t, p)))
998 {
999 let mapper = ToneMapper::new(transfer, preset, None);
1000 for code in (16..=235u8).step_by(7) {
1001 let (_, u, v) = mapped(&mapper, code, 128, 128);
1002 assert!(
1003 u.abs_diff(128) <= 2 && v.abs_diff(128) <= 2,
1004 "{preset:?} {transfer:?}: grey {code} tinted to U{u} V{v}"
1005 );
1006 }
1007 }
1008 }
1009
1010 /// HLG's own anchors. Its signal is relative, so what is worth pinning is
1011 /// where the OOTF puts it: black at black and peak signal at the assumed
1012 /// display peak, hence SDR white -- to the grid's rounding, since code 235
1013 /// sits between two luma nodes and the one below it is a hair under peak.
1014 ///
1015 /// BT.2408 HLG diffuse white is signal 0.75, and it does *not* land on the
1016 /// PQ side's 203-nit code: relative is the point of HLG, so 0.75 is 19% of
1017 /// whatever peak the display has -- 76 cd/m^2 of the standard preset's 400,
1018 /// against PQ's absolute 203 -- and it comes out darker. That is the
1019 /// standard's own behaviour and the number to watch: if the OOTF's system
1020 /// gamma stops following the assumed peak, this is what moves, and it moves
1021 /// per preset because the peak is what a preset picks.
1022 #[test]
1023 fn hlg_anchors_are_sane() {
1024 for (preset, expected) in [
1025 (Preset::Reference, 170u8),
1026 (Preset::Standard, 170),
1027 (Preset::Vivid, 170),
1028 ] {
1029 let mapper = ToneMapper::new(Transfer::Hlg, preset, None);
1030 let code = |signal: f32| byte(16.0 + 219.0 * signal);
1031 let (black, _, _) = mapped(&mapper, code(0.0), 128, 128);
1032 let (diffuse, _, _) = mapped(&mapper, code(0.75), 128, 128);
1033 let (white, _, _) = mapped(&mapper, code(1.0), 128, 128);
1034 assert!(black.abs_diff(16) <= 3, "{preset:?} HLG black -> {black}");
1035 assert!(white.abs_diff(235) <= 3, "{preset:?} HLG peak -> {white}");
1036 assert!(
1037 diffuse.abs_diff(expected) <= 3,
1038 "{preset:?} HLG diffuse white -> {diffuse}, expected {expected}"
1039 );
1040 }
1041 }
1042
1043 /// A short plane is left alone rather than half mapped, and a frame with no
1044 /// size at all returns instead of panicking on a zero-length band.
1045 #[test]
1046 fn a_frame_that_does_not_measure_up_is_untouched() {
1047 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
1048 let mut y = vec![128u8; 8 * 8 - 1];
1049 let mut u = vec![128u8; 4 * 4];
1050 let mut v = vec![128u8; 4 * 4];
1051 mapper.map(&mut y, &mut u, &mut v, 8, 8);
1052 assert!(y.iter().all(|&s| s == 128), "short plane was mapped");
1053 mapper.map(&mut y, &mut u, &mut v, 0, 8);
1054 mapper.map(&mut y, &mut u, &mut v, 8, 0);
1055 mapper.map(&mut [], &mut [], &mut [], 0, 0);
1056 }
1057
1058 /// Odd sizes: the edge block covers one row or one column and must not run
1059 /// off the end.
1060 #[test]
1061 fn odd_sizes_map_every_pixel() {
1062 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
1063 let (w, h) = (7usize, 5usize);
1064 let mut y = vec![200u8; w * h];
1065 let mut u = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
1066 let mut v = vec![128u8; w.div_ceil(2) * h.div_ceil(2)];
1067 mapper.map(&mut y, &mut u, &mut v, w, h);
1068 assert!(y.iter().all(|&s| s != 200), "a pixel was skipped");
1069 }
1070
1071 /// The cost gate, asserted in release only: a debug build is an order of
1072 /// magnitude off and the number only means something optimised. Run with
1073 /// `EDITH_PERF=1 cargo test -p engine --release --lib tonemap:: -- --nocapture`
1074 /// (without `EDITH_PERF` the number is printed and not asserted).
1075 ///
1076 /// The *fastest* frame of a two-second window, not the mean of a fixed
1077 /// count: this test shares a six-core machine with the other 200 in the
1078 /// binary, and measured against them a 19.0 ms frame reads as 29.7. Kept
1079 /// running until they are done, the tail iterations get a core to
1080 /// themselves and the minimum is the machine's real cost -- which is the
1081 /// question the gate asks, "can one core carry a 4K frame in a frame's
1082 /// time", and the reason a plain mean here would be a coin flip.
1083 #[test]
1084 #[ignore = "perf: run with --ignored"]
1085 fn perf_4k_and_1080p() {
1086 let mapper = ToneMapper::new(Transfer::Pq, Preset::default(), None);
1087 for (w, h, budget) in [(3840usize, 1600usize, 25.0f64), (1920, 1080, 8.0)] {
1088 let mut y: Vec<u8> = (0..w * h).map(|i| (i % 256) as u8).collect();
1089 let mut u: Vec<u8> = (0..w / 2 * h / 2).map(|i| (i % 256) as u8).collect();
1090 let mut v: Vec<u8> = (0..w / 2 * h / 2).map(|i| (255 - i % 256) as u8).collect();
1091 let mut best = f64::MAX;
1092 let window = std::time::Instant::now();
1093 let mut runs = 0;
1094 while runs < 10 || window.elapsed().as_secs_f64() < 1.0 {
1095 let t = std::time::Instant::now();
1096 mapper.map(&mut y, &mut u, &mut v, w, h);
1097 best = best.min(t.elapsed().as_secs_f64() * 1000.0);
1098 runs += 1;
1099 }
1100 println!("tonemap::map {w}x{h}: {best:.3} ms/frame");
1101 // Wall-clock budgets are for a quiet machine: parallel builds push
1102 // a 4K frame past it with nothing wrong. `EDITH_PERF=1` turns the gate on;
1103 // the map itself still runs every time, and the
1104 // correctness tests above pin what it computes.
1105 if !cfg!(debug_assertions) && std::env::var_os("EDITH_PERF").is_some() {
1106 assert!(
1107 best <= budget,
1108 "{w}x{h}: {best:.3} ms/frame over {budget} ms"
1109 );
1110 }
1111 }
1112 }
1113
1114 /// The paid debt: the film's own declared peak is what the reference
1115 /// rendition converts at. 1759 cd/m^2 is a real number -- the MaxCLL of a
1116 /// real HDR10 grade, which the container never says
1117 /// and the HEVC SEI does -- and every anchor moves with it, downward,
1118 /// because a peak this far above the 1000 an undeclared file is assumed at
1119 /// is *headroom*: the same code is a smaller fraction of a brighter peak.
1120 ///
1121 /// The row that matters most is 1000 cd/m^2. Told 1000, Method A puts it at
1122 /// SDR white and everything above it is gone; told the film's 1759 it lands
1123 /// at 215 and the 759 nits above it are still a picture. That is the whole
1124 /// of what reading the metadata buys.
1125 #[test]
1126 fn the_reference_rendition_converts_at_the_films_own_peak() {
1127 const FILM: f32 = 1759.0;
1128 let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(FILM));
1129 assert_eq!(
1130 mapper.peak(),
1131 FILM,
1132 "the table was built at the film's peak"
1133 );
1134 // Anchors, cd/m^2 -> limited-range SDR luma, at 1759 rather than 1000:
1135 // black is still black, the film's own peak is SDR white, and BT.2408
1136 // diffuse white lands at 145 instead of 166.
1137 for (nits, expected) in [
1138 (0.0, 16u8),
1139 (203.0, 145),
1140 (1000.0, 215),
1141 (FILM, 235),
1142 (10000.0, 235),
1143 ] {
1144 let code = byte(pq_code(nits));
1145 let (y, _, _) = mapped(&mapper, code, 128, 128);
1146 assert!(
1147 y.abs_diff(expected) <= 3,
1148 "{nits} cd/m^2 (code {code}) -> {y}, expected {expected} at a {FILM} peak"
1149 );
1150 }
1151 // ...and the direction, on every code rather than on the anchors: a
1152 // higher assumed peak is never brighter, and somewhere it is plainly
1153 // darker. The fallback is what the same file gets with its metadata
1154 // stripped, which is the control.
1155 let fallback = ToneMapper::new(Transfer::Pq, Preset::Reference, None);
1156 assert_eq!(fallback.peak(), 1000.0, "an undeclared file's assumption");
1157 let mut lower = 0;
1158 for code in 0..=255u8 {
1159 let (declared, _, _) = mapped(&mapper, code, 128, 128);
1160 let (assumed, _, _) = mapped(&fallback, code, 128, 128);
1161 assert!(
1162 declared <= assumed,
1163 "code {code}: the film's peak lifted it, {declared} over {assumed}"
1164 );
1165 lower += u32::from(declared < assumed);
1166 }
1167 assert!(lower > 128, "only {lower} of 256 codes moved at all");
1168 // HLG's OOTF follows the same peak, and the black guard has to hold
1169 // above 1000 as well as below it: a system gamma over 1 makes the
1170 // `ys^(gamma - 1)` term zero rather than infinite, and a hole where
1171 // black belongs is the failure either way.
1172 let hlg = ToneMapper::new(Transfer::Hlg, Preset::Reference, Some(FILM));
1173 let (black, _, _) = mapped(&hlg, byte(16.0), 128, 128);
1174 let (near_black, _, _) = mapped(&hlg, byte(16.0 + 219.0 * 0.02), 128, 128);
1175 let (white, _, _) = mapped(&hlg, 235, 128, 128);
1176 assert!(black.abs_diff(16) <= 3, "HLG black at {FILM} -> {black}");
1177 assert!(near_black > 16, "HLG near-black at {FILM} -> {near_black}");
1178 assert!(white.abs_diff(235) <= 3, "HLG peak at {FILM} -> {white}");
1179 }
1180
1181 /// The composition rule on [`Preset`], asserted: the two fixed renditions
1182 /// are deaf to the metadata, byte for byte, and the reference one is not.
1183 /// A "read the peak" change that reached all three would make the same pick
1184 /// mean a different exposure on every file, and this is what catches it.
1185 #[test]
1186 fn only_the_reference_rendition_reads_the_declared_peak() {
1187 for transfer in [Transfer::Pq, Transfer::Hlg] {
1188 for preset in Preset::ALL {
1189 let declared = ToneMapper::new(transfer, preset, Some(1759.0));
1190 let assumed = ToneMapper::new(transfer, preset, None);
1191 let deaf = preset != Preset::Reference;
1192 assert_eq!(
1193 declared.peak() == assumed.peak(),
1194 deaf,
1195 "{preset:?} {transfer:?}: peak {} against {}",
1196 declared.peak(),
1197 assumed.peak()
1198 );
1199 assert_eq!(
1200 declared.luma == assumed.luma && declared.chroma == assumed.chroma,
1201 deaf,
1202 "{preset:?} {transfer:?}: the tables"
1203 );
1204 }
1205 }
1206 }
1207
1208 /// A declared peak is a number out of a stranger's file, so the two ways it
1209 /// can be nonsense are checked rather than divided by: a peak under SDR
1210 /// white would clip the whole picture to white, and a NaN -- which no
1211 /// comparison admits, hence no clamp catches -- would build a table of
1212 /// zeroes, i.e. a black frame. Both fall back to the rendition's own.
1213 #[test]
1214 fn a_nonsense_declared_peak_is_not_believed() {
1215 for junk in [0.0, 1.0, 99.0, 10_001.0, f32::NAN, f32::INFINITY] {
1216 let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(junk));
1217 assert_eq!(mapper.peak(), 1000.0, "declared {junk} was believed");
1218 let (white, _, _) = mapped(&mapper, byte(pq_code(1000.0)), 128, 128);
1219 assert!(
1220 white.abs_diff(235) <= 3,
1221 "declared {junk}: 1000 nits -> {white}"
1222 );
1223 }
1224 // ...and the range's own ends are believed, which is what says the
1225 // guard rejects nonsense rather than everything unusual.
1226 for good in [100.0, 4000.0, 10_000.0] {
1227 let mapper = ToneMapper::new(Transfer::Pq, Preset::Reference, Some(good));
1228 assert_eq!(mapper.peak(), good, "declared {good} was refused");
1229 }
1230 }
1231}