Skip to main content

zenpixels_convert/tonemap/
gamut_compress.rs

1//! Soft gamut compression in OKLch: reduces chroma near and past the boundary of
2//! a set of primaries, keeping hue and lightness.
3//!
4//! Scaling OKLab chroma by `s` at constant L and hue is a straight blend in
5//! cube-root LMS, `x'(s) = L + s (x' - L)`, because the a and b rows of that
6//! matrix sum to zero and the L row sums to one. Each RGB channel is therefore a
7//! cubic in `s`, and the gamut boundary is its first crossing of 0 or 1. That needs
8//! no hue, `atan2`, square root or lookup table, so it vectorizes directly:
9//!
10//! 1. A gate in linear RGB passes interior pixels through bit-identical. Only those
11//!    it rejects reach the solve, packed into full SIMD batches.
12//! 2. A chord from gray to the input starts each lane before its first crossing.
13//! 3. Three Newton steps find the crossing, and a rational knee sets the new chroma.
14//!
15//! Measurements and comparisons are in `docs/gamut-mapping-survey.md`, and the
16//! harness is `benchmarks/gamut-compress`.
17
18use archmage::prelude::*;
19use magemath::SimdMath;
20use magemath::cbrtf::{Cbrtf, CbrtfDomain, CbrtfOptions};
21use zenpixels::Primaries;
22
23use crate::oklab::{LMS_CBRT_FROM_OKLAB, OKLAB_FROM_LMS_CBRT, OklabSpace};
24
25const MATH_PORTABILITY: magemath::Portability = if cfg!(all(
26    target_arch = "wasm32",
27    not(feature = "precise-portable")
28)) {
29    magemath::Portability::BackendDependent
30} else {
31    magemath::Portability::BitExact
32};
33
34/// Division-free `magemath` cube root for soft gamut compression (`<= 1.47 ULP`,
35/// exact on signed zeros, subnormals, infinities, and NaN, bit-identical between
36/// SIMD and scalar callers).
37const SOFT_COMPRESS_CBRT: u128 = CbrtfOptions::new()
38    .domain(CbrtfDomain::AllFloats)
39    .midp()
40    .portability(MATH_PORTABILITY)
41    .caller()
42    .bits();
43
44/// Newton steps on the boundary. At 3, the largest difference from bisection on a
45/// BT.2020 grid was 0.000002 in OKLab, and 2 left 0.00098.
46const SOLVE_STEPS: u32 = 3;
47
48/// The gate's upper limit: a pixel with its largest channel at or above this is
49/// close enough to the top of the cube that it always gets solved.
50const GATE_TOP: f32 = 0.95;
51
52/// Smallest `min / max` among colors past the knee, rounded up, from 399 lightness
53/// by 1,440 hue boundary points per target (`gamut-compress gate-all`). A pixel with
54/// a larger ratio and `max < GATE_TOP` can't be past the knee. Infinity disables it.
55fn gate_ratio(primaries: Primaries, knee: f32) -> f32 {
56    #[allow(unreachable_patterns)]
57    match (primaries, knee) {
58        (Primaries::Bt709, k) if k >= 0.96 => 0.0875,
59        (Primaries::DisplayP3, k) if k >= 0.96 => 0.0865,
60        (Primaries::Bt2020, k) if k >= 0.96 => 0.1115,
61        (Primaries::Bt709, k) if k >= 0.90 => 0.5435,
62        (Primaries::DisplayP3, k) if k >= 0.90 => 0.539,
63        (Primaries::Bt2020, k) if k >= 0.90 => 0.55,
64        _ => f32::INFINITY,
65    }
66}
67
68/// Soft chroma compression for one set of primaries.
69///
70/// Below `knee` times the largest in-gamut chroma at a pixel's lightness and hue,
71/// colors pass through unchanged. Above it, chroma rolls off along a rational curve
72/// that's continuous in value and slope at the knee and approaches the boundary.
73/// Hue and lightness are kept. Results stay within about 0.001 of the cube, so a
74/// final clamp is still needed.
75///
76/// Cheap to construct, with no table and no allocation.
77///
78/// # Examples
79///
80/// ```
81/// # #[cfg(feature = "oklab")] {
82/// use zenpixels_convert::tonemap::SoftCompress;
83/// use zenpixels_convert::oklab::OklabSpace;
84/// use zenpixels_convert::Primaries;
85///
86/// let space = OklabSpace::for_primaries(Primaries::Bt709).unwrap();
87/// let compress = SoftCompress::new(&space, SoftCompress::DEFAULT_KNEE);
88///
89/// let mut pixels = [[1.2_f32, 0.05, 0.05]]; // out-of-gamut red
90/// compress.apply_strip(&mut pixels);
91/// assert!(pixels[0].iter().all(|&c| (-1e-3..=1.0 + 1e-3).contains(&c)));
92/// # }
93/// ```
94#[derive(Debug, Clone, PartialEq)]
95pub struct SoftCompress {
96    space: OklabSpace,
97    knee: f32,
98    gate_ratio: f32,
99    /// Past `1 / knee` nothing changes, so the solve needn't look further.
100    scale_cap: f32,
101}
102
103impl SoftCompress {
104    /// Production default knee: the fraction of the largest in-gamut chroma where
105    /// the rolloff begins. From a sweep of 76 imazen-26 gain-mapped HDR images on
106    /// 2026-06-23, the largest value whose corpus-p90 share of pre-clamp
107    /// out-of-gamut pixels stayed under 0.1 %.
108    pub const DEFAULT_KNEE: f32 = 0.96;
109
110    /// A compressor for `space`. `knee` is in `0.0..=1.0`, and 1.0 maps to the
111    /// boundary with no rolloff.
112    ///
113    /// Knees under about 0.5 reach far beyond the boundary, where the solve hasn't
114    /// been qualified.
115    #[must_use]
116    pub fn new(space: &OklabSpace, knee: f32) -> Self {
117        Self {
118            space: *space,
119            knee,
120            gate_ratio: gate_ratio(space.primaries(), knee),
121            scale_cap: (1.0 / knee).clamp(1.25, 16.0),
122        }
123    }
124
125    /// Compress a row of linear RGB pixels in place.
126    ///
127    /// Interior pixels stay bit-identical. Non-finite channels, and magnitudes above
128    /// about 1e38, pass through unchanged.
129    pub fn apply_strip(&self, rgb: &mut [[f32; 3]]) {
130        reattune!(apply_strip_impl(self, rgb), [_v3, _neon, _wasm128, _scalar])
131    }
132
133    /// Pure scalar counterpart of [`Self::apply_strip`] (0-bit identical; keeps
134    /// SIMD dead-stripped in [`Accelerators::SCALAR`](crate::Accelerators::SCALAR)).
135    pub(crate) fn apply_strip_scalar(&self, rgb: &mut [[f32; 3]]) {
136        apply_strip_impl_scalar_t(archmage::ScalarToken, self, rgb);
137    }
138
139    /// Compress OKLab planes in place, leaving `l` as is. For pipelines that already
140    /// hold planar OKLab. Equivalent to converting to RGB and using
141    /// [`apply_strip`](Self::apply_strip), up to rounding.
142    ///
143    /// # Errors
144    ///
145    /// [`DimensionMismatch`](crate::ConvertError::DimensionMismatch) when `a` or `b` differs in
146    /// length from `l`, leaving both untouched.
147    pub fn compress_oklab_planes(
148        &self,
149        l: &[f32],
150        a: &mut [f32],
151        b: &mut [f32],
152    ) -> Result<(), whereat::At<crate::ConvertError>> {
153        let n = l.len();
154        if a.len() != n || b.len() != n {
155            return Err(whereat::at!(crate::ConvertError::DimensionMismatch));
156        }
157        reattune!(
158            compress_planes_impl(self, l, a, b),
159            [_v3, _neon, _wasm128, _scalar]
160        );
161        Ok(())
162    }
163
164    /// Knee: the fraction of the largest in-gamut chroma where compression starts.
165    #[inline]
166    #[must_use]
167    pub fn knee(&self) -> f32 {
168        self.knee
169    }
170}
171
172/// The chroma scale for each lane, and which lanes it applies to, from lightness,
173/// the offset of each cube-root LMS channel from it, and the input's RGB.
174///
175/// Uses plain multiply and add, with no fused operations, so that every SIMD tier
176/// gives identical bits.
177macro_rules! chroma_scale {
178    ($splat:ident, $dot:ident, $sc:expr, $ll:ident, $dl:ident, $dm:ident, $ds:ident, $r0:ident, $g0:ident, $b0:ident) => {{
179        let inv = $sc.space.lms_to_rgb().rows();
180        let (zero, one, three) = ($splat(0.0), $splat(1.0), $splat(3.0));
181        let cap = $splat($sc.scale_cap);
182        let tiny = $splat(1e-12);
183
184        // Start on the chord from gray (s = 0, every channel L^3) to the input
185        // (s = 1). Starting at s = 1 on a far-out color lands on a later crossing.
186        let gray = $ll * $ll * $ll;
187        let chord = |v: f32x8| -> f32x8 {
188            let over = (one - gray) / (v - gray);
189            let under = gray / (gray - v);
190            f32x8::blend(
191                v.simd_lt(zero),
192                under,
193                f32x8::blend(v.simd_gt(one), over, cap),
194            )
195        };
196        let mut s = chord($r0)
197            .min(chord($g0))
198            .min(chord($b0))
199            .max(zero)
200            .min(one);
201
202        for _ in 0..SOLVE_STEPS {
203            let (xl, xm, xs) = ($ll + s * $dl, $ll + s * $dm, $ll + s * $ds);
204            let (l2, m2, s2) = (xl * xl, xm * xm, xs * xs);
205            let (l3, m3, s3) = (l2 * xl, m2 * xm, s2 * xs);
206            let (gl, gm, gs) = (l2 * $dl, m2 * $dm, s2 * $ds);
207            // Each channel's next estimate of its crossing; the nearest one binds.
208            let toward = |row: &[f32; 3]| -> f32x8 {
209                let v = $dot(row, l3, m3, s3);
210                let grad = three * $dot(row, gl, gm, gs);
211                let face = f32x8::blend(grad.simd_gt(zero), one, zero);
212                f32x8::blend(grad.abs().simd_lt(tiny), cap, s + (face - v) / grad)
213            };
214            s = toward(&inv[0])
215                .min(toward(&inv[1]))
216                .min(toward(&inv[2]))
217                .max(zero)
218                .min(cap);
219        }
220
221        // Rational knee in units of the input's chroma, which sits at s = 1:
222        // continuous in value and slope at the knee, approaching the boundary.
223        let knee_s = $splat($sc.knee) * s;
224        let excess = one - knee_s;
225        let range = s - knee_s;
226        let scaled = knee_s + range * excess / (excess + range);
227        // No representable chroma at L <= 0 or L >= 1.
228        let dead = $ll.simd_le(zero) | $ll.simd_ge(one);
229        // Multiplying by zero gives NaN for exactly the non-finite values.
230        let finite =
231            ($r0 * zero).simd_eq(zero) & ($g0 * zero).simd_eq(zero) & ($b0 * zero).simd_eq(zero);
232        (
233            f32x8::blend(dead, zero, scaled),
234            (excess.simd_gt(zero) | dead) & finite,
235        )
236    }};
237}
238
239#[inline(always)]
240fn simd_min_f32(a: f32, b: f32) -> f32 {
241    if a < b { a } else { b }
242}
243
244#[inline(always)]
245fn simd_max_f32(a: f32, b: f32) -> f32 {
246    if a > b { a } else { b }
247}
248
249#[inline(always)]
250fn dot_scalar(row: &[f32; 3], a: f32, b: f32, c: f32) -> f32 {
251    row[0] * a + row[1] * b + row[2] * c
252}
253
254/// Scalar 1-pixel mirror of `chroma_scale!` — avoids 8-wide unrolled `f32x8<ScalarToken>`
255/// codegen while matching the SIMD tiers bit-for-bit.
256#[inline(always)]
257#[allow(clippy::too_many_arguments)]
258fn chroma_scale_scalar(
259    sc: &SoftCompress,
260    ll: f32,
261    dl: f32,
262    dm: f32,
263    ds: f32,
264    r0: f32,
265    g0: f32,
266    b0: f32,
267) -> (f32, bool) {
268    let inv = sc.space.lms_to_rgb().rows();
269    let cap = sc.scale_cap;
270    let gray = ll * ll * ll;
271    let chord = |v: f32| -> f32 {
272        let over = (1.0 - gray) / (v - gray);
273        let under = gray / (gray - v);
274        if v < 0.0 {
275            under
276        } else if v > 1.0 {
277            over
278        } else {
279            cap
280        }
281    };
282    let mut s = simd_min_f32(
283        simd_max_f32(
284            simd_min_f32(simd_min_f32(chord(r0), chord(g0)), chord(b0)),
285            0.0,
286        ),
287        1.0,
288    );
289
290    for _ in 0..SOLVE_STEPS {
291        let (xl, xm, xs) = (ll + s * dl, ll + s * dm, ll + s * ds);
292        let (l2, m2, s2) = (xl * xl, xm * xm, xs * xs);
293        let (l3, m3, s3) = (l2 * xl, m2 * xm, s2 * xs);
294        let (gl, gm, gs) = (l2 * dl, m2 * dm, s2 * ds);
295        let toward = |row: &[f32; 3]| -> f32 {
296            let v = dot_scalar(row, l3, m3, s3);
297            let grad = 3.0 * dot_scalar(row, gl, gm, gs);
298            let face = if grad > 0.0 { 1.0 } else { 0.0 };
299            if grad.abs() < 1e-12 {
300                cap
301            } else {
302                s + (face - v) / grad
303            }
304        };
305        s = simd_min_f32(
306            simd_max_f32(
307                simd_min_f32(
308                    simd_min_f32(toward(&inv[0]), toward(&inv[1])),
309                    toward(&inv[2]),
310                ),
311                0.0,
312            ),
313            cap,
314        );
315    }
316
317    let knee_s = sc.knee * s;
318    let excess = 1.0 - knee_s;
319    let range = s - knee_s;
320    let scaled = knee_s + range * excess / (excess + range);
321    let dead = ll <= 0.0 || ll >= 1.0;
322    let finite = (r0 * 0.0 == 0.0) && (g0 * 0.0 == 0.0) && (b0 * 0.0 == 0.0);
323    (
324        if dead { 0.0 } else { scaled },
325        (excess > 0.0 || dead) && finite,
326    )
327}
328
329#[cold]
330#[inline(never)]
331fn apply_strip_impl_scalar_t(
332    _token: archmage::ScalarToken,
333    sc: &SoftCompress,
334    rgb: &mut [[f32; 3]],
335) {
336    let (m1, inv) = (sc.space.rgb_to_lms().rows(), sc.space.lms_to_rgb().rows());
337    let ok = OKLAB_FROM_LMS_CBRT.rows()[0];
338    let ratio = sc.gate_ratio;
339
340    for px in rgb.iter_mut() {
341        let [r0, g0, b0] = *px;
342        let mx = simd_max_f32(simd_max_f32(r0, g0), b0);
343        let mn = simd_min_f32(simd_min_f32(r0, g0), b0);
344        if mn > mx * ratio && mx < GATE_TOP {
345            continue;
346        }
347        let lc = Cbrtf::<SOFT_COMPRESS_CBRT>::scalar_infallible(dot_scalar(&m1[0], r0, g0, b0));
348        let mc = Cbrtf::<SOFT_COMPRESS_CBRT>::scalar_infallible(dot_scalar(&m1[1], r0, g0, b0));
349        let sc2 = Cbrtf::<SOFT_COMPRESS_CBRT>::scalar_infallible(dot_scalar(&m1[2], r0, g0, b0));
350        let ll = dot_scalar(&ok, lc, mc, sc2);
351        let (dl, dm, ds) = (lc - ll, mc - ll, sc2 - ll);
352        let (scaled, active) = chroma_scale_scalar(sc, ll, dl, dm, ds, r0, g0, b0);
353        if active {
354            let (xl, xm, xs) = (ll + scaled * dl, ll + scaled * dm, ll + scaled * ds);
355            let (l3, m3, s3) = (xl * xl * xl, xm * xm * xm, xs * xs * xs);
356            *px = [
357                dot_scalar(&inv[0], l3, m3, s3),
358                dot_scalar(&inv[1], l3, m3, s3),
359                dot_scalar(&inv[2], l3, m3, s3),
360            ];
361        }
362    }
363}
364
365#[cold]
366#[inline(never)]
367fn compress_planes_impl_scalar_t(
368    _token: archmage::ScalarToken,
369    sc: &SoftCompress,
370    l: &[f32],
371    a: &mut [f32],
372    b: &mut [f32],
373) {
374    let inv = sc.space.lms_to_rgb().rows();
375    let [row_l, row_m, row_s] = *LMS_CBRT_FROM_OKLAB.rows();
376    for ((&ll, av), bv) in l.iter().zip(a.iter_mut()).zip(b.iter_mut()) {
377        let (a0, b0_in) = (*av, *bv);
378        let dl = dot_scalar(&row_l, 0.0, a0, b0_in);
379        let dm = dot_scalar(&row_m, 0.0, a0, b0_in);
380        let ds = dot_scalar(&row_s, 0.0, a0, b0_in);
381        let (xl, xm, xs) = (ll + dl, ll + dm, ll + ds);
382        let (l3, m3, s3) = (xl * xl * xl, xm * xm * xm, xs * xs * xs);
383        let r0 = dot_scalar(&inv[0], l3, m3, s3);
384        let g0 = dot_scalar(&inv[1], l3, m3, s3);
385        let b0 = dot_scalar(&inv[2], l3, m3, s3);
386        let mx = simd_max_f32(simd_max_f32(r0, g0), b0);
387        let mn = simd_min_f32(simd_min_f32(r0, g0), b0);
388        if mn > mx * sc.gate_ratio && mx < GATE_TOP {
389            continue;
390        }
391        let (scaled, active) = chroma_scale_scalar(sc, ll, dl, dm, ds, r0, g0, b0);
392        if active {
393            *av = a0 * scaled;
394            *bv = b0_in * scaled;
395        }
396    }
397}
398
399#[attune(_*_t, -_scalar_t, define(f32x8))]
400fn apply_strip_impl(token: Token, sc: &SoftCompress, rgb: &mut [[f32; 3]]) {
401    let splat = |v: f32| f32x8::splat_t(token, v);
402    let dot = |row: &[f32; 3], a: f32x8, b: f32x8, c: f32x8| -> f32x8 {
403        splat(row[0]) * a + splat(row[1]) * b + splat(row[2]) * c
404    };
405    let (m1, inv) = (sc.space.rgb_to_lms().rows(), sc.space.lms_to_rgb().rows());
406    let ok = OKLAB_FROM_LMS_CBRT.rows()[0];
407    let (ratio, top) = (splat(sc.gate_ratio), splat(GATE_TOP));
408
409    let solve = |px: &mut [[f32; 3]; 8]| {
410        let r0 = f32x8::from_array_t(token, core::array::from_fn(|i| px[i][0]));
411        let g0 = f32x8::from_array_t(token, core::array::from_fn(|i| px[i][1]));
412        let b0 = f32x8::from_array_t(token, core::array::from_fn(|i| px[i][2]));
413        let lc = dot(&m1[0], r0, g0, b0).cbrt::<SOFT_COMPRESS_CBRT>();
414        let mc = dot(&m1[1], r0, g0, b0).cbrt::<SOFT_COMPRESS_CBRT>();
415        let sc2 = dot(&m1[2], r0, g0, b0).cbrt::<SOFT_COMPRESS_CBRT>();
416        let ll = dot(&ok, lc, mc, sc2);
417        let (dl, dm, ds) = (lc - ll, mc - ll, sc2 - ll);
418        let (scaled, active) = chroma_scale!(splat, dot, sc, ll, dl, dm, ds, r0, g0, b0);
419        let (xl, xm, xs) = (ll + scaled * dl, ll + scaled * dm, ll + scaled * ds);
420        let (l3, m3, s3) = (xl * xl * xl, xm * xm * xm, xs * xs * xs);
421        let rr = f32x8::blend(active, dot(&inv[0], l3, m3, s3), r0).to_array();
422        let gg = f32x8::blend(active, dot(&inv[1], l3, m3, s3), g0).to_array();
423        let bb = f32x8::blend(active, dot(&inv[2], l3, m3, s3), b0).to_array();
424        for (i, out) in px.iter_mut().enumerate() {
425            *out = [rr[i], gg[i], bb[i]];
426        }
427    };
428
429    // Rejected pixels wait here with their position, then go through as a batch,
430    // so one edge pixel doesn't cost a whole mixed group of 8.
431    let mut batch = [[0.5f32; 3]; 8];
432    let mut slots = [0usize; 8];
433    let mut used = 0;
434    let n = rgb.len();
435    let mut start = 0;
436    while start < n {
437        let end = (start + 8).min(n);
438        // Padding lanes of a short tail are 1.0, which the gate rejects, so they
439        // can't produce a false all-interior result; they're never read back.
440        let mut lanes = [[1.0f32; 8]; 3];
441        for (i, px) in rgb[start..end].iter().enumerate() {
442            lanes[0][i] = px[0];
443            lanes[1][i] = px[1];
444            lanes[2][i] = px[2];
445        }
446        let r = f32x8::from_array_t(token, lanes[0]);
447        let g = f32x8::from_array_t(token, lanes[1]);
448        let b = f32x8::from_array_t(token, lanes[2]);
449        let mx = r.max(g).max(b);
450        let mn = r.min(g).min(b);
451        let interior = mn.simd_gt(mx * ratio) & mx.simd_lt(top);
452        if end - start == 8 && interior.bitcast_to_i32().all_true() {
453            start = end;
454            continue;
455        }
456        let keep = interior.to_array();
457        for i in 0..end - start {
458            if keep[i].to_bits() == 0 {
459                batch[used] = rgb[start + i];
460                slots[used] = start + i;
461                used += 1;
462                if used == 8 {
463                    solve(&mut batch);
464                    for k in 0..8 {
465                        rgb[slots[k]] = batch[k];
466                    }
467                    used = 0;
468                }
469            }
470        }
471        start = end;
472    }
473    if used > 0 {
474        batch[used..].fill([0.5; 3]);
475        solve(&mut batch);
476        for k in 0..used {
477            rgb[slots[k]] = batch[k];
478        }
479    }
480}
481
482#[attune(_*_t, -_scalar_t, define(f32x8))]
483fn compress_planes_impl(token: Token, sc: &SoftCompress, l: &[f32], a: &mut [f32], b: &mut [f32]) {
484    let splat = |v: f32| f32x8::splat_t(token, v);
485    let dot = |row: &[f32; 3], x: f32x8, y: f32x8, z: f32x8| -> f32x8 {
486        splat(row[0]) * x + splat(row[1]) * y + splat(row[2]) * z
487    };
488    let inv = sc.space.lms_to_rgb().rows();
489    let [row_l, row_m, row_s] = *LMS_CBRT_FROM_OKLAB.rows();
490    let n = l.len();
491    let mut start = 0;
492    while start < n {
493        let end = (start + 8).min(n);
494        let count = end - start;
495        // Padding has L = 0, which is dead, and is never written back.
496        let (mut ll_a, mut a_a, mut b_a) = ([0f32; 8], [0f32; 8], [0f32; 8]);
497        ll_a[..count].copy_from_slice(&l[start..end]);
498        a_a[..count].copy_from_slice(&a[start..end]);
499        b_a[..count].copy_from_slice(&b[start..end]);
500        let ll = f32x8::from_array_t(token, ll_a);
501        let av = f32x8::from_array_t(token, a_a);
502        let bv = f32x8::from_array_t(token, b_a);
503        let zero = splat(0.0);
504        let dl = dot(&row_l, zero, av, bv);
505        let dm = dot(&row_m, zero, av, bv);
506        let ds = dot(&row_s, zero, av, bv);
507        let (xl, xm, xs) = (ll + dl, ll + dm, ll + ds);
508        let (l3, m3, s3) = (xl * xl * xl, xm * xm * xm, xs * xs * xs);
509        let r0 = dot(&inv[0], l3, m3, s3);
510        let g0 = dot(&inv[1], l3, m3, s3);
511        let b0 = dot(&inv[2], l3, m3, s3);
512        // The same gate as for RGB: most colors in most images end here.
513        let mx = r0.max(g0).max(b0);
514        let mn = r0.min(g0).min(b0);
515        let interior = mn.simd_gt(mx * splat(sc.gate_ratio)) & mx.simd_lt(splat(GATE_TOP));
516        if count == 8 && interior.bitcast_to_i32().all_true() {
517            start = end;
518            continue;
519        }
520        let (scaled, active) = chroma_scale!(splat, dot, sc, ll, dl, dm, ds, r0, g0, b0);
521        let out_a = f32x8::blend(active, av * scaled, av).to_array();
522        let out_b = f32x8::blend(active, bv * scaled, bv).to_array();
523        a[start..end].copy_from_slice(&out_a[..count]);
524        b[start..end].copy_from_slice(&out_b[..count]);
525        start = end;
526    }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532    use crate::oklab::rgb_to_lms_matrix;
533    use zenpixels::Primaries as ColorPrimaries;
534
535    const ALL: [ColorPrimaries; 3] = [
536        ColorPrimaries::Bt709,
537        ColorPrimaries::DisplayP3,
538        ColorPrimaries::Bt2020,
539    ];
540
541    fn space(p: ColorPrimaries) -> OklabSpace {
542        OklabSpace::for_primaries(p).unwrap()
543    }
544
545    /// Largest in-gamut chroma at (L, hue), by bisection.
546    fn exact_boundary(space: &OklabSpace, l: f32, ca: f32, sa: f32) -> f32 {
547        let (mut lo, mut hi) = (0.0f32, 2.0f32);
548        for _ in 0..40 {
549            let mid = (lo + hi) / 2.0;
550            let in_gamut = space
551                .to_rgb([l, mid * ca, mid * sa])
552                .iter()
553                .all(|&v| (0.0..=1.0).contains(&v));
554            if in_gamut { lo = mid } else { hi = mid }
555        }
556        lo
557    }
558
559    fn cube(n: u32) -> alloc::vec::Vec<[f32; 3]> {
560        let d = (n - 1) as f32;
561        let mut v = alloc::vec::Vec::new();
562        for r in 0..n {
563            for g in 0..n {
564                for b in 0..n {
565                    v.push([r as f32 / d, g as f32 / d, b as f32 / d]);
566                }
567            }
568        }
569        v
570    }
571
572    /// The gate must never pass a color the map would change, at each table entry.
573    #[test]
574    fn gated_pixels_are_past_no_knee() {
575        for p in ALL {
576            for knee in [0.90, 0.96] {
577                let sc = SoftCompress::new(&space(p), knee);
578                let mut solved_only = sc.clone();
579                solved_only.gate_ratio = f32::INFINITY;
580                let input = cube(65);
581                let (mut gated, mut full) = (input.clone(), input.clone());
582                sc.apply_strip(&mut gated);
583                solved_only.apply_strip(&mut full);
584                assert_eq!(gated, full, "{p:?} knee {knee}");
585            }
586        }
587    }
588
589    #[test]
590    fn interior_colors_stay_bit_identical() {
591        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
592        let input = [[0.5f32, 0.4, 0.3], [0.2, 0.2, 0.2], [0.8, 0.7, 0.75]];
593        let mut out = input;
594        sc.apply_strip(&mut out);
595        assert_eq!(out, input);
596    }
597
598    #[test]
599    fn out_of_gamut_lands_in_the_cube() {
600        let m = crate::gamut::GamutMatrix::between(ColorPrimaries::Bt2020, ColorPrimaries::Bt709)
601            .unwrap();
602        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
603        let mut v: alloc::vec::Vec<[f32; 3]> = cube(33).into_iter().map(|c| m.apply(c)).collect();
604        sc.apply_strip(&mut v);
605        for px in v {
606            for c in px {
607                assert!((-1e-3..=1.0 + 1e-3).contains(&c), "{px:?}");
608            }
609        }
610    }
611
612    #[test]
613    fn hue_and_lightness_are_kept() {
614        let sp = space(ColorPrimaries::Bt709);
615        let m = crate::gamut::GamutMatrix::between(ColorPrimaries::Bt2020, ColorPrimaries::Bt709)
616            .unwrap();
617        let sc = SoftCompress::new(&sp, 0.96);
618        for c in cube(17) {
619            let x = m.apply(c);
620            let [l0, a0, b0] = sp.from_rgb(x);
621            if !(0.02..0.98).contains(&l0) || a0.hypot(b0) < 0.01 {
622                continue;
623            }
624            let mut out = [x];
625            sc.apply_strip(&mut out);
626            let [l1, a1, b1] = sp.from_rgb(out[0]);
627            assert!((l1 - l0).abs() < 1e-3, "{c:?}: L {l0} to {l1}");
628            if a1.hypot(b1) > 1e-3 {
629                let cross = (a0 * b1 - b0 * a1) / (a0.hypot(b0) * a1.hypot(b1));
630                assert!(cross.abs() < 2e-3, "{c:?}: hue moved, sin {cross}");
631            }
632        }
633    }
634
635    /// Solve and bisection agree where the boundary is crossed once.
636    #[test]
637    fn scale_matches_bisection() {
638        let sp = space(ColorPrimaries::Bt709);
639        for knee in [0.5f32, 0.75, 0.96, 1.0] {
640            let sc = SoftCompress::new(&sp, knee);
641            for li in 2..=8 {
642                let l = li as f32 / 10.0;
643                for h in (0..360).step_by(15) {
644                    // Dark blues re-enter the gamut, so bisection isn't a reference there.
645                    if (240..=285).contains(&h) {
646                        continue;
647                    }
648                    let (sa, ca) = (h as f32).to_radians().sin_cos();
649                    let cmax = exact_boundary(&sp, l, ca, sa);
650                    let c = cmax * 1.1;
651                    let (mut a, mut b) = ([c * ca], [c * sa]);
652                    sc.compress_oklab_planes(&[l], &mut a, &mut b).unwrap();
653                    let k = knee * cmax;
654                    let (range, excess) = (cmax - k, c - k);
655                    let want = if range <= 0.0 {
656                        cmax
657                    } else {
658                        k + range * excess / (excess + range)
659                    };
660                    let got = a[0].hypot(b[0]);
661                    assert!(
662                        (got - want).abs() < 2e-3,
663                        "knee {knee} L {l} hue {h}: {got} vs {want}"
664                    );
665                }
666            }
667        }
668    }
669
670    #[test]
671    fn hue_zero_has_no_seam() {
672        let sp = space(ColorPrimaries::Bt709);
673        let sc = SoftCompress::new(&sp, 0.96);
674        for h in [-1e-5f32, -1e-7, -1e-9, 0.0, 1e-9, 1e-7] {
675            let (mut a, mut b) = ([0.4 * h.cos()], [0.4 * h.sin()]);
676            sc.compress_oklab_planes(&[0.5], &mut a, &mut b).unwrap();
677            assert!((a[0] - 0.2027).abs() < 3e-3, "hue {h:e}: a {}", a[0]);
678        }
679    }
680
681    #[test]
682    fn planes_match_the_rgb_path() {
683        let sp = space(ColorPrimaries::Bt709);
684        let m =
685            crate::gamut::GamutMatrix::between(ColorPrimaries::DisplayP3, ColorPrimaries::Bt709)
686                .unwrap();
687        let sc = SoftCompress::new(&sp, 0.96);
688        let input: alloc::vec::Vec<[f32; 3]> = cube(17).into_iter().map(|c| m.apply(c)).collect();
689        let mut rgb = input.clone();
690        sc.apply_strip(&mut rgb);
691        let lab: alloc::vec::Vec<[f32; 3]> = input.iter().map(|&c| sp.from_rgb(c)).collect();
692        let l: alloc::vec::Vec<f32> = lab.iter().map(|v| v[0]).collect();
693        let mut a: alloc::vec::Vec<f32> = lab.iter().map(|v| v[1]).collect();
694        let mut b: alloc::vec::Vec<f32> = lab.iter().map(|v| v[2]).collect();
695        sc.compress_oklab_planes(&l, &mut a, &mut b).unwrap();
696        for i in 0..input.len() {
697            let want = sp.from_rgb(rgb[i]);
698            assert!(
699                (a[i] - want[1]).abs() < 1e-3 && (b[i] - want[2]).abs() < 1e-3,
700                "{:?}: {} {} vs {want:?}",
701                input[i],
702                a[i],
703                b[i]
704            );
705        }
706    }
707
708    /// Any row split gives the same bits as one call.
709    #[test]
710    fn row_length_does_not_change_results() {
711        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
712        let m = crate::gamut::GamutMatrix::between(ColorPrimaries::Bt2020, ColorPrimaries::Bt709)
713            .unwrap();
714        let input: alloc::vec::Vec<[f32; 3]> = cube(9).into_iter().map(|c| m.apply(c)).collect();
715        let mut whole = input.clone();
716        sc.apply_strip(&mut whole);
717        for width in [1usize, 2, 3, 7, 8, 9, 15, 16, 17] {
718            let mut parts = input.clone();
719            for chunk in parts.chunks_mut(width) {
720                sc.apply_strip(chunk);
721            }
722            assert_eq!(parts, whole, "width {width}");
723        }
724    }
725
726    #[test]
727    fn non_finite_and_empty_inputs() {
728        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
729        sc.apply_strip(&mut []);
730        let mut px = [[f32::NAN, 0.5, 0.5], [f32::INFINITY, 0.5, 0.5]];
731        sc.apply_strip(&mut px);
732        assert!(px[0][0].is_nan());
733        assert!(px[1][0].is_infinite());
734    }
735
736    #[test]
737    fn plane_length_mismatch_is_an_error() {
738        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
739        let (mut a, mut b) = ([0.0f32; 2], [0.0f32; 3]);
740        assert!(sc.compress_oklab_planes(&[0.5; 3], &mut a, &mut b).is_err());
741    }
742
743    #[test]
744    fn extremes_become_achromatic() {
745        let sc = SoftCompress::new(&space(ColorPrimaries::Bt709), 0.96);
746        let (mut a, mut b) = ([0.1f32, 0.1], [0.1f32, 0.1]);
747        sc.compress_oklab_planes(&[0.0, 1.0], &mut a, &mut b)
748            .unwrap();
749        assert_eq!((a, b), ([0.0, 0.0], [0.0, 0.0]));
750    }
751
752    #[test]
753    fn gate_table_covers_every_primaries_with_an_lms_matrix() {
754        for p in ALL {
755            assert!(rgb_to_lms_matrix(p).is_some());
756            assert!(gate_ratio(p, 0.96).is_finite());
757            assert!(gate_ratio(p, 0.5).is_infinite());
758        }
759    }
760}