Skip to main content

zenpixels_convert/tonemap/
bt2446a.rs

1//! BT.2446 Method A tone mapper — the ITU's reference for graded
2//! HDR↔SDR conversion with psychophysically verified round-trip fidelity.
3//!
4//! ITU-R BT.2446-1 §4. TMO: 1000 cd/m² HDR → 100 cd/m² SDR.
5//!
6//! Psychophysical evaluation (Annex 1): 12 participants, 115 images,
7//! 2AFC on Sony BVM-X300 — imperceptible degradation after full
8//! round-trip (p = 0.167 HDR, p = 0.196 SDR).
9//!
10//! The method operates in a perceptually linearized log-luminance domain
11//! with a piecewise polynomial knee, Hunt-effect color correction in
12//! Y'Cb'Cr', and BT.2020 luma weights.
13//!
14//! Reference: ITU-R BT.2446-1 (03/2021) §4 + Annex 1.
15//!
16//! # Provenance
17//!
18//! Extracted from `zentone::Bt2446A` (zentone commit `2a7c86b1`). The
19//! algorithm is byte-identical; the only difference is that this
20//! crate's copy is the canonical home, and the `ToneMap` trait integration
21//! is dropped (the trait lives in `zentone` and is not used here — the
22//! `HdrToSdr` wrapper drives the curve directly through its inherent
23//! methods).
24//!
25//! The kernel is a magetypes-defined `f32x16` strip that resolves to
26//! AVX-512 on V4, 2× AVX2 on V3, NEON on aarch64, WASM-SIMD on wasm32, and
27//! the polyfill scalar on everything else.
28//! [`Bt2446A::map_rgb_bt2020_peak_normalized`] and the last 1–15 pixels of
29//! a row run the same lanes, padded.
30
31use libm::powf;
32use magemath::SimdMath;
33use magemath::expf::ExpfOptions;
34use magemath::logf::{LogfDomain, LogfOptions};
35use magemath::powf::{PowfDomain, PowfOptions};
36
37// BT.2020 luma weights (BT.2446 uses BT.2020, not BT.709) — shared with
38// `measure` via the parent module's `BT2020_L*` constants.
39use super::{BT2020_LB as LB, BT2020_LG as LG, BT2020_LR as LR};
40
41const MATH_PORTABILITY: magemath::Portability = if cfg!(all(
42    target_arch = "wasm32",
43    not(feature = "precise-portable")
44)) {
45    magemath::Portability::BackendDependent
46} else {
47    magemath::Portability::BitExact
48};
49
50/// `v^(1/2.4)` on `[f32::MIN_POSITIVE, 1.0]`: `|-126 / 2.4| = 52.5 <= 125`, eliding all range checks.
51const BT2446_INV24: u128 = PowfOptions::new()
52    .domain(PowfDomain::PositiveUnit)
53    .const_exponent(1.0 / 2.4)
54    .reject_subnormals()
55    .portability(MATH_PORTABILITY)
56    .assume_in_bounds()
57    .caller()
58    .bits();
59
60/// `log2(arg)` on finite positive normals `[f32::MIN_POSITIVE, f32::MAX]`.
61const BT2446_LOG2: u128 = LogfOptions::new()
62    .domain(LogfDomain::PositiveNormals)
63    .reject_subnormals()
64    .portability(MATH_PORTABILITY)
65    .assume_in_bounds()
66    .caller()
67    .bits();
68
69/// `exp2(x)` on clamped `[-126.0, 127.0]`, eliding overflow/underflow checks.
70const BT2446_EXP2: u128 = ExpfOptions::new()
71    .unclamped_exp2_range()
72    .portability(MATH_PORTABILITY)
73    .assume_in_bounds()
74    .caller()
75    .bits();
76
77/// BT.1886 `v^2.4` fast path on `[1e-15, 1.0]`: `|log2(1e-15) * 2.4| = 119.6 <= 125`,
78/// eliding output saturation on all normal display-visible pixels.
79const BT2446_EOTF24_LO: f32 = 1.0e-15;
80const BT2446_EOTF24_ELIDE: u128 = PowfOptions::new()
81    .domain(PowfDomain::PositiveUnit)
82    .base_range(BT2446_EOTF24_LO, 1.0)
83    .const_exponent(2.4)
84    .reject_subnormals()
85    .portability(MATH_PORTABILITY)
86    .assume_in_bounds()
87    .caller()
88    .bits();
89
90/// BT.1886 `v^2.4` saturating path for chunks containing near-zero / zero channels in `[0.0, 1.0]`.
91const BT2446_EOTF24_SAT: u128 = PowfOptions::new()
92    .domain(PowfDomain::PositiveUnit)
93    .const_exponent(2.4)
94    .reject_subnormals()
95    .saturate_output()
96    .portability(MATH_PORTABILITY)
97    .assume_in_bounds()
98    .caller()
99    .bits();
100
101/// BT.2446 Method A tonemapper with explicit baked HDR/SDR peak luminances.
102///
103/// Construct with [`with_peaks`](Self::with_peaks), then apply directly via
104/// [`map_rgb_bt2020_peak_normalized`](Self::map_rgb_bt2020_peak_normalized) or
105/// [`map_strip_bt2020_peak_normalized`](Self::map_strip_bt2020_peak_normalized),
106/// or pass into [`ConvertPolicy::with_tone_mapper`](crate::ConvertPolicy::with_tone_mapper).
107/// For pipeline-managed peak resolution (measuring or reading declared metadata
108/// at [`ToneMapper::prepare`](crate::tonemap::ToneMapper::prepare) time), use
109/// [`Bt2446APipelineManaged`] (or [`Bt2446A::pipeline_managed`]).
110///
111/// Input is linear-light BT.2020 RGB normalized so `1.0 = hdr_peak_nits`. Output
112/// is linear-light BT.2020 RGB normalized so `1.0 = sdr_peak_nits` — the
113/// BT.2446-1 §4 pipeline natively emits gamma-encoded `R'_TMO` `G'_TMO` `B'_TMO`
114/// (BT.1886 1/2.4); we apply the BT.1886 EOTF (`^2.4`) at the output to deliver
115/// a linear-light contract (matching libplacebo's own `bt2446a` which ends with
116/// `bt1886_eotf`).
117///
118/// # When to pick this
119///
120/// The most rigorously validated HDR → SDR curve published — the only one
121/// with a peer-reviewed psychophysical study showing imperceptible
122/// degradation after a full HDR → SDR → HDR round-trip on graded content.
123/// Pick when broadcast-grade fidelity matters.
124///
125/// Reference: ITU-R BT.2446-1 (03/2021) §4 + Annex 1 (12 participants,
126/// 115 images, Sony BVM-X300, 2AFC, p ≈ 0.17 indistinguishability).
127///
128/// # Examples
129///
130/// ```
131/// # #[cfg(feature = "bt2446a")]
132/// # {
133/// use zenpixels_convert::{Nits, tonemap::Bt2446A};
134///
135/// let curve = Bt2446A::with_peaks(
136///     Nits::new_positive_or_panic(1000.0),
137///     Nits::new_positive_or_panic(100.0),
138/// );
139/// let sdr = curve.map_rgb_bt2020_peak_normalized([0.6, 0.4, 0.2]);
140/// assert!(sdr.iter().all(|&c| (0.0..=1.0).contains(&c)));
141/// # }
142/// ```
143#[derive(Debug, Clone, Copy)]
144pub struct Bt2446A {
145    source_peak: zenpixels::Nits,
146    target_peak: zenpixels::Nits,
147    pub(crate) rho_hdr: f32,
148    pub(crate) inv_log_rho_hdr: f32,
149    pub(crate) rho_sdr: f32,
150    pub(crate) inv_rho_sdr_minus_1: f32,
151}
152
153/// Pipeline-managed BT.2446 Method A [`ToneMapper`](crate::tonemap::ToneMapper)
154/// descriptor whose HDR/SDR peak luminances are supplied by [`ImagePlan`](crate::ImagePlan)
155/// or [`RowPlan`](crate::RowPlan) at
156/// [`ToneMapper::prepare`](crate::tonemap::ToneMapper::prepare) time.
157///
158/// Unlike [`Bt2446A`] (which always holds baked peaks and exposes direct pixel/strip
159/// mapping methods), `Bt2446APipelineManaged` cannot be called directly without
160/// resolving peaks through [`ToneMapper::prepare`](crate::tonemap::ToneMapper::prepare).
161#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
162pub struct Bt2446APipelineManaged;
163
164impl Bt2446A {
165    /// Create a new BT.2446 Method A tonemapper with explicit typed peak luminances baked in.
166    ///
167    /// - `hdr_peak`: peak luminance of HDR content (e.g. `Nits::new_positive_or_panic(1000.0)`).
168    /// - `sdr_peak`: peak luminance of SDR target (e.g. `Nits::new_positive_or_panic(100.0)`).
169    ///
170    /// Use this when the source peak is already known at construction time.
171    /// For pipeline-orchestrated peak resolution via
172    /// [`PeakSource`](zenpixels::PeakSource) (`Measured`, `Declared`, or `Fixed`)
173    /// at `prepare()` time, use [`pipeline_managed`](Self::pipeline_managed) /
174    /// [`Bt2446APipelineManaged`] instead.
175    #[must_use]
176    pub fn with_peaks(hdr_peak: zenpixels::Nits, sdr_peak: zenpixels::Nits) -> Self {
177        let compiled = Bt2446AExecutor::compile(hdr_peak.nits(), sdr_peak.nits());
178        Self {
179            source_peak: hdr_peak,
180            target_peak: sdr_peak,
181            rho_hdr: compiled.rho_hdr,
182            inv_log_rho_hdr: compiled.inv_log_rho_hdr,
183            rho_sdr: compiled.rho_sdr,
184            inv_rho_sdr_minus_1: compiled.inv_rho_sdr_minus_1,
185        }
186    }
187
188    /// Construct a pipeline-managed BT.2446-A descriptor ([`Bt2446APipelineManaged`])
189    /// whose peaks are supplied by the pipeline at
190    /// [`ToneMapper::prepare`](crate::tonemap::ToneMapper::prepare) time.
191    ///
192    /// Use this when you don't know the source peak nits at the
193    /// builder-construction site and want [`ImagePlan`](crate::ImagePlan) to
194    /// resolve peaks via [`PeakSource`](zenpixels::PeakSource) or
195    /// [`measure_content_light_level`](crate::measure_content_light_level).
196    #[must_use]
197    pub const fn pipeline_managed() -> Bt2446APipelineManaged {
198        Bt2446APipelineManaged
199    }
200
201    /// Baked HDR source peak luminance in cd/m².
202    #[inline]
203    #[must_use]
204    pub const fn source_peak(&self) -> zenpixels::Nits {
205        self.source_peak
206    }
207
208    /// Baked SDR target peak luminance in cd/m².
209    #[inline]
210    #[must_use]
211    pub const fn target_peak(&self) -> zenpixels::Nits {
212        self.target_peak
213    }
214
215    /// Map a single HDR pixel (linear-light **BT.2020** RGB normalized so
216    /// `1.0 = source_peak()`) to an SDR pixel (linear-light **BT.2020** RGB
217    /// normalized so `1.0 = target_peak()`).
218    ///
219    /// Input must be finite; `NaN`/negative channels are not scrubbed here
220    /// (see [`Self::map_strip_bt2020_peak_normalized`]).
221    ///
222    /// Implemented as a 1-element strip through
223    /// [`Self::map_strip_bt2020_peak_normalized`]. A single pixel runs the
224    /// same lanes as a row, padded.
225    #[doc(alias = "map_rgb")]
226    #[must_use]
227    pub fn map_rgb_bt2020_peak_normalized(&self, rgb: [f32; 3]) -> [f32; 3] {
228        let mut buf = [rgb];
229        self.map_strip_bt2020_peak_normalized(&mut buf);
230        buf[0]
231    }
232
233    /// Apply the curve to a strip of linear-light **BT.2020** RGB pixels
234    /// (normalized so `1.0 = source_peak()` on input and `1.0 = target_peak()`
235    /// on output) in place, dispatching to the widest available SIMD tier.
236    ///
237    /// # Input contract
238    ///
239    /// Expects **finite** linear-light BT.2020 RGB. Non-finite input is
240    /// not scrubbed, and `NaN`/`inf` can reach the output. The conversion pipeline
241    /// scrubs non-finite values *before* calling this; direct callers own that themselves.
242    #[doc(alias = "map_strip_simd")]
243    pub fn map_strip_bt2020_peak_normalized(&self, strip: &mut [[f32; 3]]) {
244        archmage::attuned!(
245            bt2446a_tier(
246                strip,
247                self.rho_hdr,
248                self.inv_log_rho_hdr,
249                self.rho_sdr,
250                self.inv_rho_sdr_minus_1,
251            ),
252            [_v4x(cfg(avx512)), _v3, _neon, _wasm128, _scalar]
253        );
254    }
255}
256
257// ----------------------------------------------------------------------------
258// Two-phase ToneMapper integration
259// ----------------------------------------------------------------------------
260
261/// Compiled-for-this-image BT.2446-A strip executor.
262///
263/// Holds the `(rho_hdr, inv_log_rho_hdr, rho_sdr, inv_rho_sdr_minus_1)`
264/// quadruple precomputed from a resolved
265/// [`ToneMapContext`](crate::hdr::ToneMapContext). Produced by
266/// [`<Bt2446A as ToneMapper>::prepare`](crate::hdr::ToneMapper::prepare)
267/// and stashed in the plan's
268/// [`OnceCell<Arc<dyn StripMapper>>`](once_cell::sync::OnceCell) so
269/// subsequent strip dispatches reuse the same compiled kernel.
270#[derive(Debug, Clone, Copy)]
271pub(crate) struct Bt2446AExecutor {
272    pub(crate) rho_hdr: f32,
273    pub(crate) inv_log_rho_hdr: f32,
274    pub(crate) rho_sdr: f32,
275    pub(crate) inv_rho_sdr_minus_1: f32,
276}
277
278impl Bt2446AExecutor {
279    /// Compile from a resolved `(source_peak_nits, target_peak_nits)`
280    /// pair. Mirrors the math in [`Bt2446A::with_peaks`].
281    #[must_use]
282    pub(crate) fn compile(source_peak_nits: f32, target_peak_nits: f32) -> Self {
283        let inv_gamma = 1.0_f32 / 2.4;
284        let rho_hdr = 1.0 + 32.0 * powf(source_peak_nits / 10000.0, inv_gamma);
285        let log_rho_hdr = libm::logf(rho_hdr);
286        let rho_sdr = 1.0 + 32.0 * powf(target_peak_nits / 10000.0, inv_gamma);
287        Self {
288            rho_hdr,
289            inv_log_rho_hdr: 1.0 / log_rho_hdr,
290            rho_sdr,
291            inv_rho_sdr_minus_1: 1.0 / (rho_sdr - 1.0),
292        }
293    }
294
295    /// Apply the compiled curve to an interleaved RGB strip in place
296    /// (BT.2020 working space).
297    fn apply_strip(&self, strip: &mut [[f32; 3]]) {
298        archmage::attuned!(
299            bt2446a_tier(
300                strip,
301                self.rho_hdr,
302                self.inv_log_rho_hdr,
303                self.rho_sdr,
304                self.inv_rho_sdr_minus_1,
305            ),
306            [_v4x(cfg(avx512)), _v3, _neon, _wasm128, _scalar]
307        );
308    }
309}
310
311impl crate::tonemap::StripMapper for Bt2446AExecutor {
312    fn map_strip(&self, input: &[f32], output: &mut [f32]) {
313        debug_assert_eq!(
314            input.len(),
315            output.len(),
316            "StripMapper::map_strip: slice length mismatch"
317        );
318        debug_assert!(
319            input.len().is_multiple_of(3),
320            "StripMapper::map_strip: input not RGB-triple-aligned"
321        );
322        if !core::ptr::eq(input.as_ptr(), output.as_ptr()) {
323            output.copy_from_slice(input);
324        }
325        let triples = output.len() / 3;
326        let strip: &mut [[f32; 3]] = bytemuck::cast_slice_mut(&mut output[..triples * 3]);
327        self.apply_strip(strip);
328    }
329}
330
331fn prepare_bt2446a_peaks(
332    src: f32,
333    dst: f32,
334) -> Result<crate::tonemap::PreparedMapper, whereat::At<crate::ConvertError>> {
335    if !src.is_finite() || !dst.is_finite() || src < 1e-3 || dst < 1e-3 {
336        return Err(crate::error::err_at(crate::ConvertError::ToneMapperFailed));
337    }
338    let exec = Bt2446AExecutor::compile(src, dst);
339    if !exec.rho_hdr.is_finite()
340        || !exec.inv_log_rho_hdr.is_finite()
341        || !exec.rho_sdr.is_finite()
342        || !exec.inv_rho_sdr_minus_1.is_finite()
343    {
344        return Err(crate::error::err_at(crate::ConvertError::ToneMapperFailed));
345    }
346    Ok(crate::tonemap::PreparedMapper::Streaming(
347        alloc::boxed::Box::new(exec),
348    ))
349}
350
351impl crate::tonemap::ToneMapper for Bt2446A {
352    fn requirements(&self) -> crate::tonemap::Requirements {
353        crate::tonemap::Requirements::NONE
354    }
355
356    fn prepare(
357        &self,
358        _ctx: &crate::tonemap::ToneMapContext,
359        pulse: Option<&dyn how_far::Pulse>,
360    ) -> Result<crate::tonemap::PreparedMapper, whereat::At<crate::ConvertError>> {
361        crate::pulse::check_pulse(pulse)?;
362        prepare_bt2446a_peaks(self.source_peak.nits(), self.target_peak.nits())
363    }
364
365    fn name(&self) -> &'static str {
366        "bt2446a"
367    }
368
369    fn working_primaries_for(&self, _target: zenpixels::Primaries) -> zenpixels::Primaries {
370        zenpixels::Primaries::Bt2020
371    }
372
373    fn baked_peaks(&self) -> Option<(f32, f32)> {
374        Some((self.source_peak.nits(), self.target_peak.nits()))
375    }
376}
377
378impl crate::tonemap::ToneMapper for Bt2446APipelineManaged {
379    fn requirements(&self) -> crate::tonemap::Requirements {
380        crate::tonemap::Requirements::SOURCE_PEAK_ONLY
381    }
382
383    fn prepare(
384        &self,
385        ctx: &crate::tonemap::ToneMapContext,
386        pulse: Option<&dyn how_far::Pulse>,
387    ) -> Result<crate::tonemap::PreparedMapper, whereat::At<crate::ConvertError>> {
388        crate::pulse::check_pulse(pulse)?;
389        prepare_bt2446a_peaks(ctx.source_peak_nits, ctx.target_peak_nits)
390    }
391
392    fn name(&self) -> &'static str {
393        "bt2446a"
394    }
395
396    fn working_primaries_for(&self, _target: zenpixels::Primaries) -> zenpixels::Primaries {
397        zenpixels::Primaries::Bt2020
398    }
399
400    fn baked_peaks(&self) -> Option<(f32, f32)> {
401        None
402    }
403}
404
405macro_rules! bt2446a_body {
406    ($vec:ident, $lanes:literal, $token:ident, $row:ident, $rho_hdr:ident, $inv_log_rho_hdr:ident, $rho_sdr:ident, $inv_rho_sdr_minus_1:ident) => {{
407        let zero = $vec::zero_t($token);
408        let one = $vec::splat_t($token, 1.0);
409        let lr = $vec::splat_t($token, LR);
410        let lg = $vec::splat_t($token, LG);
411        let lb = $vec::splat_t($token, LB);
412        let rho_hdr_minus_1 = $vec::splat_t($token, $rho_hdr - 1.0);
413        let inv_log_rho_hdr_v = $vec::splat_t($token, $inv_log_rho_hdr);
414        let inv_rho_sdr_m1_v = $vec::splat_t($token, $inv_rho_sdr_minus_1);
415        let log2_rho_sdr = $vec::splat_t($token, libm::log2f($rho_sdr));
416        let pos_eps = $vec::splat_t($token, f32::MIN_POSITIVE);
417        let eotf_lo = $vec::splat_t($token, BT2446_EOTF24_LO);
418        let exp_lo = $vec::splat_t($token, -126.0);
419        let exp_hi = $vec::splat_t($token, 127.0);
420        let ln2 = $vec::splat_t($token, core::f32::consts::LN_2);
421
422        let t1 = $vec::splat_t($token, 0.7399);
423        let t2 = $vec::splat_t($token, 0.9909);
424        let a1 = $vec::splat_t($token, 1.0770);
425        let a2_a = $vec::splat_t($token, -1.1510);
426        let a2_b = $vec::splat_t($token, 2.7811);
427        let a2_c = $vec::splat_t($token, -0.6302);
428        let a3_a = $vec::splat_t($token, 0.5);
429        let a3_b = $vec::splat_t($token, 0.5);
430        let one_p_one = $vec::splat_t($token, 1.1);
431        let inv_1_8814 = $vec::splat_t($token, 1.0 / 1.8814);
432        let inv_1_4746 = $vec::splat_t($token, 1.0 / 1.4746);
433        // 0.16455 = 2·Kb·(1-Kb)/Kg, 0.57135 = 2·Kr·(1-Kr)/Kg for BT.2020 (already
434        // divided by Kg; do NOT divide again — that was the pre-fix bug).
435        let mat_g_b = $vec::splat_t($token, 0.16455);
436        let mat_g_r = $vec::splat_t($token, 0.57135);
437        let mat_r_cr = $vec::splat_t($token, 1.4746);
438        let mat_b_cb = $vec::splat_t($token, 1.8814);
439        let zero_one = $vec::splat_t($token, 0.1);
440
441        let (chunks, remainder) = $row.as_chunks_mut::<$lanes>();
442        macro_rules! run_chunk {
443            ($chunk:expr) => {{
444                let chunk: &mut [[f32; 3]; $lanes] = $chunk;
445                let mut ra = [0.0_f32; $lanes];
446                let mut ga = [0.0_f32; $lanes];
447                let mut ba = [0.0_f32; $lanes];
448                for (i, px) in chunk.iter().enumerate() {
449                    ra[i] = px[0];
450                    ga[i] = px[1];
451                    ba[i] = px[2];
452                }
453                // ITU-R BT.2446-1 §4.1 Table 2 specifies normalized [0, 1] HDR RGB inputs.
454                // Record `valid` from the raw positive mask before clamping to `[pos_eps, 1.0]`
455                // so every downstream `assume_in_bounds` transcendental sees finite positive normals
456                // while originally zero/non-positive pixels still snap to exact 0.0 on store.
457                let raw_r = $vec::load_t($token, &ra);
458                let raw_g = $vec::load_t($token, &ga);
459                let raw_b = $vec::load_t($token, &ba);
460                let valid = raw_r.simd_gt(zero) | raw_g.simd_gt(zero) | raw_b.simd_gt(zero);
461                let r = raw_r.min(one).max(pos_eps);
462                let g = raw_g.min(one).max(pos_eps);
463                let b = raw_b.min(one).max(pos_eps);
464
465                let r_p = r.powf_const::<BT2446_INV24>();
466                let g_p = g.powf_const::<BT2446_INV24>();
467                let b_p = b.powf_const::<BT2446_INV24>();
468
469                let y_p = lr * r_p + lg * g_p + lb * b_p;
470
471                let arg = (one + rho_hdr_minus_1 * y_p).max(pos_eps);
472                let ln_arg = arg.log2::<BT2446_LOG2>() * ln2;
473                let y_p_lin = ln_arg * inv_log_rho_hdr_v;
474
475                let lo_branch = a1 * y_p_lin;
476                let mid_branch = a2_a * y_p_lin * y_p_lin + a2_b * y_p_lin + a2_c;
477                let hi_branch = a3_a * y_p_lin + a3_b;
478                let in_lo = y_p_lin.simd_le(t1);
479                let in_hi = y_p_lin.simd_ge(t2);
480                let mid_or_hi = $vec::blend(in_hi, hi_branch, mid_branch);
481                let y_c = $vec::blend(in_lo, lo_branch, mid_or_hi);
482
483                let exp_arg = (y_c * log2_rho_sdr).max_fast(exp_lo).min_fast(exp_hi);
484                let y_sdr = (exp_arg.exp2::<BT2446_EXP2>() - one) * inv_rho_sdr_m1_v;
485
486                let f = y_sdr / (one_p_one * y_p);
487                let cb = f * (b_p - y_p) * inv_1_8814;
488                let cr = f * (r_p - y_p) * inv_1_4746;
489                let cr_pos = cr.max(zero);
490                let y_tmo = y_sdr - zero_one * cr_pos;
491
492                // Clamp into `[0, 1]`, the domain of the BT.1886 EOTF.
493                let r_prime_out = (y_tmo + mat_r_cr * cr).max(zero).min(one);
494                let g_prime_out = (y_tmo - mat_g_b * cb - mat_g_r * cr).max(zero).min(one);
495                let b_prime_out = (y_tmo + mat_b_cb * cb).max(zero).min(one);
496
497                // BT.1886 EOTF (`^2.4`): fast elided path when all lanes >= 1e-15,
498                // saturating SIMD path otherwise (with 0 staying exact 0.0).
499                let eotf = |v: $vec| {
500                    if v.simd_ge(eotf_lo).bitcast_to_i32().all_true() {
501                        v.powf_const::<BT2446_EOTF24_ELIDE>()
502                    } else {
503                        $vec::blend(
504                            v.simd_gt(zero),
505                            v.max(pos_eps).powf_const::<BT2446_EOTF24_SAT>(),
506                            zero,
507                        )
508                    }
509                };
510                let r_out = eotf(r_prime_out);
511                let g_out = eotf(g_prime_out);
512                let b_out = eotf(b_prime_out);
513
514                // Pre-clamp turns originally-zero pixels into `pos_eps`; the
515                // `valid` mask computed from the raw inputs snaps them back to true black on store.
516                let or_arr = $vec::blend(valid, r_out, zero).to_array();
517                let og_arr = $vec::blend(valid, g_out, zero).to_array();
518                let ob_arr = $vec::blend(valid, b_out, zero).to_array();
519                for (i, px) in chunk.iter_mut().enumerate() {
520                    px[0] = or_arr[i];
521                    px[1] = og_arr[i];
522                    px[2] = ob_arr[i];
523                }
524            }};
525        }
526        for chunk in chunks {
527            run_chunk!(chunk);
528        }
529
530        // The same lanes for the tail, padded, so that where a row ends or splits can't show in its
531        // output. A second implementation here once did, by up to 5.88e-5 of polynomial error.
532        if !remainder.is_empty() {
533            let mut tail = [[0.0_f32; 3]; $lanes];
534            tail[..remainder.len()].copy_from_slice(remainder);
535            run_chunk!(&mut tail);
536            remainder.copy_from_slice(&tail[..remainder.len()]);
537        }
538    }};
539}
540
541/// Const-configured `magemath` BT.2446-A SIMD kernel: 8-wide on V3/NEON/WASM128/scalar
542/// and 16-wide native AVX-512 when compiled with `--features avx512`.
543#[archmage::attune(_*_t, define(f32x8))]
544pub(crate) fn bt2446a_tier(
545    token: Token,
546    row: &mut [[f32; 3]],
547    rho_hdr: f32,
548    inv_log_rho_hdr: f32,
549    rho_sdr: f32,
550    inv_rho_sdr_minus_1: f32,
551) {
552    bt2446a_body!(
553        f32x8,
554        8,
555        token,
556        row,
557        rho_hdr,
558        inv_log_rho_hdr,
559        rho_sdr,
560        inv_rho_sdr_minus_1
561    );
562}
563
564#[cfg(all(target_arch = "x86_64", feature = "avx512"))]
565#[archmage::arcane]
566pub(crate) fn bt2446a_tier_v4x_t(
567    token: archmage::X64V4xToken,
568    row: &mut [[f32; 3]],
569    rho_hdr: f32,
570    inv_log_rho_hdr: f32,
571    rho_sdr: f32,
572    inv_rho_sdr_minus_1: f32,
573) {
574    use magetypes::simd::generic::f32x16;
575    type Vec16 = f32x16<archmage::X64V4xToken>;
576    bt2446a_body!(
577        Vec16,
578        16,
579        token,
580        row,
581        rho_hdr,
582        inv_log_rho_hdr,
583        rho_sdr,
584        inv_rho_sdr_minus_1
585    );
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591
592    #[test]
593    fn rho_hdr_matches_itu_reference_values() {
594        // ITU-R BT.2446-1 §4 cites ρ_H ≈ 13.2 at 1000 nits and 33 at
595        // 10 000 nits. The pre-fix code used `(L/10000)^2.4` which gave
596        // ρ_H ≈ 1.127 — essentially identity — breaking the entire
597        // compression curve. Pin ρ to the spec values so the bug can't
598        // return.
599        let tm1k = Bt2446A::with_peaks(
600            zenpixels::Nits::new_positive_or_panic(1000.0),
601            zenpixels::Nits::new_positive_or_panic(100.0),
602        );
603        assert!(
604            (tm1k.rho_hdr - 13.260).abs() < 0.02,
605            "ρ_H at 1000 nits ≈ 13.26, got {}",
606            tm1k.rho_hdr
607        );
608        let tm10k = Bt2446A::with_peaks(
609            zenpixels::Nits::new_positive_or_panic(10_000.0),
610            zenpixels::Nits::new_positive_or_panic(100.0),
611        );
612        assert!(
613            (tm10k.rho_hdr - 33.0).abs() < 0.05,
614            "ρ_H at 10 000 nits = 33.0, got {}",
615            tm10k.rho_hdr
616        );
617        // Bound far enough below the correct value that any regression to
618        // the pre-fix `^2.4` formula is immediately visible.
619        assert!(
620            tm1k.rho_hdr > 5.0,
621            "ρ_H regressed toward the pre-fix value (~1.13); got {}",
622            tm1k.rho_hdr
623        );
624    }
625
626    #[test]
627    fn libplacebo_parity_end_to_end_on_gray_ramp() {
628        // End-to-end parity check against the published libplacebo
629        // BT.2446-A formula (haasn/libplacebo, src/tone_mapping.c). Drives
630        // the curve through `map_rgb` on a gray ramp (R=G=B=x): the Hunt
631        // correction term (Cb, Cr) is zero for neutral input, so the
632        // channel value reduces to the per-channel EETF + BT.1886 EOTF
633        // chain. Must be bit-close (<1e-4) to libplacebo's numerics.
634        fn libplacebo_eetf_then_eotf(x: f32, hdr_peak: f32, sdr_peak: f32) -> f32 {
635            let x = x.clamp(0.0, 1.0);
636            let p_hdr = 1.0 + 32.0 * powf(hdr_peak / 10000.0, 1.0 / 2.4);
637            let p_sdr = 1.0 + 32.0 * powf(sdr_peak / 10000.0, 1.0 / 2.4);
638            let x_p = powf(x, 1.0 / 2.4);
639            let mut y = libm::logf(1.0 + (p_hdr - 1.0) * x_p) / libm::logf(p_hdr);
640            y = if y <= 0.7399 {
641                1.0770 * y
642            } else if y < 0.9909 {
643                -1.1510 * y * y + 2.7811 * y - 0.6302
644            } else {
645                0.5 * y + 0.5
646            };
647            let y_sdr_prime = (powf(p_sdr, y) - 1.0) / (p_sdr - 1.0);
648            powf(y_sdr_prime, 2.4)
649        }
650
651        for &(hdr, sdr) in &[(1000.0_f32, 100.0_f32), (4000.0, 100.0), (10_000.0, 100.0)] {
652            let tm = Bt2446A::with_peaks(
653                zenpixels::Nits::new_positive_or_panic(hdr),
654                zenpixels::Nits::new_positive_or_panic(sdr),
655            );
656            for &x in &[0.05_f32, 0.18, 0.3, 0.5, 0.7, 0.85, 0.95, 1.0] {
657                let got = tm.map_rgb_bt2020_peak_normalized([x, x, x])[0];
658                let want = libplacebo_eetf_then_eotf(x, hdr, sdr);
659                assert!(
660                    (got - want).abs() < 1e-4,
661                    "libplacebo parity at (hdr={hdr}, sdr={sdr}, x={x}): got {got}, want {want}"
662                );
663            }
664        }
665    }
666
667    #[test]
668    fn output_is_linear_light_not_gamma_encoded() {
669        // The contract is "linear-light HDR in, linear-light SDR out". The
670        // BT.2446-1 spec's pipeline emits gamma-encoded SDR; we MUST apply
671        // the BT.1886 EOTF (`^2.4`) at the output (matching libplacebo's
672        // `bt1886_eotf` close). Pre-fix returned gamma-encoded values,
673        // which the consumer then double-gamma-encoded — every pixel came
674        // out far too bright (median ΔE2000 ≈ 23 on the shootout corpus).
675        let tm = Bt2446A::with_peaks(
676            zenpixels::Nits::new_positive_or_panic(1000.0),
677            zenpixels::Nits::new_positive_or_panic(100.0),
678        );
679
680        let black = tm.map_rgb_bt2020_peak_normalized([0.0, 0.0, 0.0]);
681        assert_eq!(black, [0.0, 0.0, 0.0]);
682
683        let peak = tm.map_rgb_bt2020_peak_normalized([1.0, 1.0, 1.0]);
684        for c in peak {
685            assert!(
686                (c - 1.0).abs() < 1e-4,
687                "HDR peak should round-trip to SDR peak: {c}"
688            );
689        }
690
691        // Mid-grey trace: 0.18 HDR → 0.660 gamma → 0.370 linear via ^2.4.
692        // Pre-fix returned ≈0.660 (gamma-encoded); post-fix returns ≈0.370.
693        let mid = tm.map_rgb_bt2020_peak_normalized([0.18, 0.18, 0.18]);
694        for c in mid {
695            assert!(
696                (c - 0.370).abs() < 0.02,
697                "mid-grey HDR 0.18 should map to linear-light SDR ≈ 0.37, got {c}"
698            );
699        }
700        assert!(
701            mid[0] < 0.55,
702            "mid-grey output regressed toward the pre-fix gamma-encoded value (~0.66); got {}",
703            mid[0]
704        );
705    }
706
707    #[test]
708    fn bt2446a_prepare_honors_pulse_cancellation() {
709        use crate::tonemap::{ToneMapContext, ToneMapper};
710
711        struct TimedOutStop;
712        impl how_far::Stop for TimedOutStop {
713            fn check(&self) -> Result<(), how_far::StopReason> {
714                Err(how_far::StopReason::TimedOut)
715            }
716        }
717
718        let ctx = ToneMapContext {
719            source_peak_nits: 1000.0,
720            target_peak_nits: 100.0,
721            working_primaries: zenpixels::Primaries::Bt2020,
722        };
723        let pulse = how_far::StopOnly::borrowed(&TimedOutStop);
724
725        let baked = Bt2446A::with_peaks(
726            zenpixels::Nits::new_positive_or_panic(1000.0),
727            zenpixels::Nits::new_positive_or_panic(100.0),
728        );
729        assert_eq!(
730            *baked.prepare(&ctx, Some(&pulse)).unwrap_err().error(),
731            crate::ConvertError::Cancelled(how_far::StopReason::TimedOut)
732        );
733        assert!(baked.prepare(&ctx, None).is_ok());
734
735        let managed = Bt2446A::pipeline_managed();
736        assert_eq!(
737            *managed.prepare(&ctx, Some(&pulse)).unwrap_err().error(),
738            crate::ConvertError::Cancelled(how_far::StopReason::TimedOut)
739        );
740        assert!(managed.prepare(&ctx, None).is_ok());
741    }
742}