Skip to main content

zenpixels_convert/
oklab.rs

1#![allow(clippy::excessive_precision)]
2//! Oklab relative to any supported RGB primaries.
3//!
4//! [`OklabSpace`] holds the two matrices that planar Oklab kernels need and does
5//! scalar conversions. The constants are CSS Color 4's, for Björn Ottosson's Oklab.
6
7use crate::gamut::GamutMatrix;
8use magemath::cbrtf::{Cbrtf, CbrtfDomain, CbrtfOptions};
9use zenpixels::Primaries;
10
11const OKLAB_MATH_PORTABILITY: magemath::Portability = if cfg!(all(
12    target_arch = "wasm32",
13    not(feature = "precise-portable")
14)) {
15    magemath::Portability::BackendDependent
16} else {
17    magemath::Portability::BitExact
18};
19
20/// Division-free `magemath` cube root for untrusted / arbitrary `f32` inputs
21/// (`<= 1.47 ULP`, exact on `±0.0`, subnormals, `±inf`, and `NaN`, bit-identical
22/// between scalar and all SIMD tiers).
23pub(crate) const OKLAB_CBRT_ALL: u128 = CbrtfOptions::new()
24    .domain(CbrtfDomain::AllFloats)
25    .midp()
26    .portability(OKLAB_MATH_PORTABILITY)
27    .caller()
28    .bits();
29
30/// Division-free `magemath` cube root for verified finite bounded LMS inputs
31/// (`|x| < f32::MAX / 3`, admitting signed zeros and subnormals because
32/// `m1[r][c] * f32::MIN_POSITIVE` can be subnormal even when RGB has
33/// `FloatClaims::NO_SUBNORMALS | POSITIVE`). Bit-identical to [`OKLAB_CBRT_ALL`]
34/// across the full finite bounded domain.
35pub(crate) const OKLAB_CBRT_FINITE: u128 = CbrtfOptions::new()
36    .domain(CbrtfDomain::Bounded)
37    .midp()
38    .admit_subnormals()
39    .portability(OKLAB_MATH_PORTABILITY)
40    .assume_in_bounds()
41    .caller()
42    .bits();
43
44/// Division-free `magemath` cube root for strictly positive normal inputs
45/// (`[f32::MIN_POSITIVE, f32::MAX / 3)`). Bit-identical to [`OKLAB_CBRT_ALL`].
46const OKLAB_CBRT_POS_NORMAL: u128 = CbrtfOptions::new()
47    .domain(CbrtfDomain::PositiveNormals)
48    .midp()
49    .reject_subnormals()
50    .portability(OKLAB_MATH_PORTABILITY)
51    .assume_in_bounds()
52    .caller()
53    .bits();
54
55// ---------------------------------------------------------------------------
56// Oklab matrices: CSS Color 4's conversions.js, which recomputes Björn Ottosson's
57// so that D65 white gives L = 1 with no chroma.
58// ---------------------------------------------------------------------------
59
60/// M1 step 1: CIE XYZ (D65) → LMS.
61pub const LMS_FROM_XYZ: GamutMatrix = GamutMatrix::from_rows([
62    [0.8190224379967030, 0.3619062600528904, -0.1288737815209879],
63    [0.0329836539323885, 0.9292868615863434, 0.0361446663506424],
64    [0.0481771893596242, 0.2642395317527308, 0.6335478284694309],
65]);
66
67/// Inverse of M1: LMS → CIE XYZ (D65).
68pub const XYZ_FROM_LMS: GamutMatrix = GamutMatrix::from_rows([
69    [1.2268798758459243, -0.5578149944602171, 0.2813910456659647],
70    [-0.0405757452148008, 1.1122868032803170, -0.0717110580655164],
71    [-0.0763729366746601, -0.4214933324022432, 1.5869240198367816],
72]);
73
74/// M2: LMS^(1/3) → Oklab [L, a, b]. Universal, primaries-independent.
75pub const OKLAB_FROM_LMS_CBRT: GamutMatrix = GamutMatrix::from_rows([
76    [0.2104542683093140, 0.7936177747023054, -0.0040720430116193],
77    [1.9779985324311684, -2.4285922420485799, 0.4505937096174110],
78    [0.0259040424655478, 0.7827717124575296, -0.8086757549230774],
79]);
80
81/// Inverse of M2: Oklab [L, a, b] → LMS^(1/3).
82pub const LMS_CBRT_FROM_OKLAB: GamutMatrix = GamutMatrix::from_rows([
83    [1.0, 0.3963377773761749, 0.2158037573099136],
84    [1.0, -0.1055613458156586, -0.0638541728258133],
85    [1.0, -0.0894841775298119, -1.2914855480194092],
86]);
87
88// ---------------------------------------------------------------------------
89// Combined matrices
90// ---------------------------------------------------------------------------
91
92/// Oklab relative to one set of RGB primaries.
93///
94/// Holds both directions so the two can't be swapped: a [`GamutMatrix`] alone
95/// doesn't say which way it goes. Kernels take [`rgb_to_lms`](Self::rgb_to_lms)
96/// or [`lms_to_rgb`](Self::lms_to_rgb) directly.
97///
98/// ```
99/// use zenpixels_convert::{Primaries, oklab::OklabSpace};
100///
101/// let space = OklabSpace::for_primaries(Primaries::Bt709).unwrap();
102/// let [l, a, b] = space.from_rgb([1.0, 1.0, 1.0]);
103/// assert!((l - 1.0).abs() < 1e-3 && a.abs() < 1e-3 && b.abs() < 1e-3);
104/// ```
105#[derive(Clone, Copy, Debug, PartialEq)]
106pub struct OklabSpace {
107    primaries: Primaries,
108    rgb_to_lms: GamutMatrix,
109    lms_to_rgb: GamutMatrix,
110}
111
112impl OklabSpace {
113    /// The space for `primaries`, or `None` when they have no XYZ matrix here.
114    #[must_use]
115    pub fn for_primaries(primaries: Primaries) -> Option<Self> {
116        Some(Self {
117            primaries,
118            rgb_to_lms: rgb_to_lms_matrix(primaries)?,
119            lms_to_rgb: lms_to_rgb_matrix(primaries)?,
120        })
121    }
122
123    /// The space for validated [`zenpixels::CustomPrimaries`] (Bradford-adapted to D65).
124    #[must_use]
125    pub fn for_custom_primaries(primaries: zenpixels::CustomPrimaries) -> Option<Self> {
126        let to_xyz = GamutMatrix::from_rows(primaries.rgb_to_xyz_f32(zenpixels::WhitePoint::D65)?);
127        let from_xyz =
128            GamutMatrix::from_rows(primaries.xyz_to_rgb_f32(zenpixels::WhitePoint::D65)?);
129        Some(Self {
130            primaries: Primaries::Unknown,
131            rgb_to_lms: to_xyz.then(&LMS_FROM_XYZ),
132            lms_to_rgb: XYZ_FROM_LMS.then(&from_xyz),
133        })
134    }
135
136    /// The primaries this space is relative to.
137    #[inline]
138    #[must_use]
139    pub const fn primaries(&self) -> Primaries {
140        self.primaries
141    }
142
143    /// Linear RGB to LMS, skipping an intermediate XYZ buffer.
144    #[inline]
145    #[must_use]
146    pub const fn rgb_to_lms(&self) -> &GamutMatrix {
147        &self.rgb_to_lms
148    }
149
150    /// LMS to linear RGB, skipping an intermediate XYZ buffer.
151    #[inline]
152    #[must_use]
153    pub const fn lms_to_rgb(&self) -> &GamutMatrix {
154        &self.lms_to_rgb
155    }
156
157    /// Linear RGB to `[L, a, b]`.
158    #[inline]
159    #[must_use]
160    #[allow(clippy::wrong_self_convention)]
161    pub fn from_rgb(&self, [r, g, b]: [f32; 3]) -> [f32; 3] {
162        rgb_to_oklab(r, g, b, self.rgb_to_lms.rows())
163    }
164
165    /// `[L, a, b]` to linear RGB, unclipped.
166    #[inline]
167    #[must_use]
168    pub fn to_rgb(&self, [l, a, b]: [f32; 3]) -> [f32; 3] {
169        oklab_to_rgb(l, a, b, self.lms_to_rgb.rows())
170    }
171}
172
173/// `LMS_FROM_XYZ × RGB_TO_XYZ`.
174pub(crate) fn rgb_to_lms_matrix(primaries: Primaries) -> Option<GamutMatrix> {
175    Some(GamutMatrix::to_xyz(primaries)?.then(&LMS_FROM_XYZ))
176}
177
178/// `XYZ_TO_RGB × XYZ_FROM_LMS`.
179pub(crate) fn lms_to_rgb_matrix(primaries: Primaries) -> Option<GamutMatrix> {
180    Some(XYZ_FROM_LMS.then(GamutMatrix::from_xyz(primaries)?))
181}
182
183// ---------------------------------------------------------------------------
184// Fast cube root
185// ---------------------------------------------------------------------------
186
187/// Division-free cube root (`<= 1.47 ULP`) via const-configured `magemath::Cbrtf<Midp>`.
188///
189/// Exact on signed zeros, subnormals, negatives, infinities, and `NaN`, and
190/// bit-identical between scalar and all SIMD tiers.
191#[inline]
192pub(crate) fn fast_cbrt(x: f32) -> f32 {
193    Cbrtf::<OKLAB_CBRT_ALL>::scalar_infallible(x)
194}
195
196/// Const-specialized [`fast_cbrt`] matching [`fast_cbrt`] bit-for-bit on its promised domain.
197#[inline(always)]
198#[allow(dead_code)]
199pub(crate) fn fast_cbrt_spec<
200    const NO_SPECIAL: bool,
201    const NO_SUBNORMALS: bool,
202    const NON_NEGATIVE: bool,
203    const POSITIVE: bool,
204>(
205    x: f32,
206) -> f32 {
207    if !NO_SPECIAL {
208        return Cbrtf::<OKLAB_CBRT_ALL>::scalar_infallible(x);
209    }
210    if POSITIVE && NO_SUBNORMALS {
211        return Cbrtf::<OKLAB_CBRT_POS_NORMAL>::scalar_infallible(x);
212    }
213    Cbrtf::<OKLAB_CBRT_FINITE>::scalar_infallible(x)
214}
215
216/// Const-specialized linear RGB → Oklab `[L, a, b]`, bit-identical to [`rgb_to_oklab`]
217/// whenever the `LMS` cone intermediates satisfy the enabled flags.
218#[inline(always)]
219#[allow(dead_code)]
220pub(crate) fn rgb_to_oklab_spec<
221    const NO_SPECIAL: bool,
222    const LMS_NO_SUBNORMALS: bool,
223    const LMS_NON_NEGATIVE: bool,
224    const LMS_POSITIVE: bool,
225>(
226    r: f32,
227    g: f32,
228    b: f32,
229    m1: &[[f32; 3]; 3],
230) -> [f32; 3] {
231    let l = m1[0][0] * r + m1[0][1] * g + m1[0][2] * b;
232    let m = m1[1][0] * r + m1[1][1] * g + m1[1][2] * b;
233    let s = m1[2][0] * r + m1[2][1] * g + m1[2][2] * b;
234
235    let l_ = fast_cbrt_spec::<NO_SPECIAL, LMS_NO_SUBNORMALS, LMS_NON_NEGATIVE, LMS_POSITIVE>(l);
236    let m_ = fast_cbrt_spec::<NO_SPECIAL, LMS_NO_SUBNORMALS, LMS_NON_NEGATIVE, LMS_POSITIVE>(m);
237    let s_ = fast_cbrt_spec::<NO_SPECIAL, LMS_NO_SUBNORMALS, LMS_NON_NEGATIVE, LMS_POSITIVE>(s);
238
239    let ok_l = OKLAB_FROM_LMS_CBRT.0[0][0] * l_
240        + OKLAB_FROM_LMS_CBRT.0[0][1] * m_
241        + OKLAB_FROM_LMS_CBRT.0[0][2] * s_;
242    let ok_a = OKLAB_FROM_LMS_CBRT.0[1][0] * l_
243        + OKLAB_FROM_LMS_CBRT.0[1][1] * m_
244        + OKLAB_FROM_LMS_CBRT.0[1][2] * s_;
245    let ok_b = OKLAB_FROM_LMS_CBRT.0[2][0] * l_
246        + OKLAB_FROM_LMS_CBRT.0[2][1] * m_
247        + OKLAB_FROM_LMS_CBRT.0[2][2] * s_;
248
249    [ok_l, ok_a, ok_b]
250}
251
252// ---------------------------------------------------------------------------
253// Scalar reference conversions
254// ---------------------------------------------------------------------------
255
256/// Scalar reference: linear RGB → Oklab \[L, a, b\].
257///
258/// `m1` is the combined RGB→LMS matrix from [`rgb_to_lms_matrix`].
259/// All inputs should be in linear light (apply EOTF first).
260#[inline]
261pub(crate) fn rgb_to_oklab(r: f32, g: f32, b: f32, m1: &[[f32; 3]; 3]) -> [f32; 3] {
262    // Step 1: linear RGB → LMS
263    let l = m1[0][0] * r + m1[0][1] * g + m1[0][2] * b;
264    let m = m1[1][0] * r + m1[1][1] * g + m1[1][2] * b;
265    let s = m1[2][0] * r + m1[2][1] * g + m1[2][2] * b;
266
267    // Step 2: cube root (non-linearity)
268    let l_ = fast_cbrt(l);
269    let m_ = fast_cbrt(m);
270    let s_ = fast_cbrt(s);
271
272    // Step 3: LMS^(1/3) → Oklab via M2
273    let ok_l = OKLAB_FROM_LMS_CBRT.0[0][0] * l_
274        + OKLAB_FROM_LMS_CBRT.0[0][1] * m_
275        + OKLAB_FROM_LMS_CBRT.0[0][2] * s_;
276    let ok_a = OKLAB_FROM_LMS_CBRT.0[1][0] * l_
277        + OKLAB_FROM_LMS_CBRT.0[1][1] * m_
278        + OKLAB_FROM_LMS_CBRT.0[1][2] * s_;
279    let ok_b = OKLAB_FROM_LMS_CBRT.0[2][0] * l_
280        + OKLAB_FROM_LMS_CBRT.0[2][1] * m_
281        + OKLAB_FROM_LMS_CBRT.0[2][2] * s_;
282
283    [ok_l, ok_a, ok_b]
284}
285
286/// Scalar reference: Oklab \[L, a, b\] → linear RGB.
287///
288/// `m1_inv` is the combined LMS→RGB matrix from [`lms_to_rgb_matrix`].
289#[inline]
290pub(crate) fn oklab_to_rgb(l: f32, a: f32, b: f32, m1_inv: &[[f32; 3]; 3]) -> [f32; 3] {
291    // Step 1: Oklab → LMS^(1/3) via inverse M2
292    let l_ = LMS_CBRT_FROM_OKLAB.0[0][0] * l
293        + LMS_CBRT_FROM_OKLAB.0[0][1] * a
294        + LMS_CBRT_FROM_OKLAB.0[0][2] * b;
295    let m_ = LMS_CBRT_FROM_OKLAB.0[1][0] * l
296        + LMS_CBRT_FROM_OKLAB.0[1][1] * a
297        + LMS_CBRT_FROM_OKLAB.0[1][2] * b;
298    let s_ = LMS_CBRT_FROM_OKLAB.0[2][0] * l
299        + LMS_CBRT_FROM_OKLAB.0[2][1] * a
300        + LMS_CBRT_FROM_OKLAB.0[2][2] * b;
301
302    // Step 2: cube (inverse of cube root)
303    let lms_l = l_ * l_ * l_;
304    let lms_m = m_ * m_ * m_;
305    let lms_s = s_ * s_ * s_;
306
307    // Step 3: LMS → linear RGB via inverse M1
308    let r = m1_inv[0][0] * lms_l + m1_inv[0][1] * lms_m + m1_inv[0][2] * lms_s;
309    let g = m1_inv[1][0] * lms_l + m1_inv[1][1] * lms_m + m1_inv[1][2] * lms_s;
310    let b = m1_inv[2][0] * lms_l + m1_inv[2][1] * lms_m + m1_inv[2][2] * lms_s;
311
312    [r, g, b]
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use zenpixels::Primaries as ColorPrimaries;
319
320    #[test]
321    fn fast_cbrt_accuracy() {
322        let test_values: [f32; 10] = [0.0, 0.001, 0.01, 0.1, 0.5, 1.0, 2.0, 8.0, 27.0, 100.0];
323        for &x in &test_values {
324            // Keep the oracle independent of the target libc's cbrtf.
325            let expected = libm::cbrtf(x);
326            let got = fast_cbrt(x);
327            let err = (got - expected).abs();
328            assert!(
329                err < 1e-5 || err / expected.max(1e-10) < 1e-5,
330                "fast_cbrt({x}) = {got}, expected {expected}, err = {err}"
331            );
332        }
333    }
334
335    #[test]
336    fn fast_cbrt_negative() {
337        let got = fast_cbrt(-8.0);
338        assert!((got - (-2.0)).abs() < 1e-5, "fast_cbrt(-8) = {got}");
339    }
340
341    #[test]
342    fn oklab_roundtrip_bt709() {
343        let m1 = rgb_to_lms_matrix(ColorPrimaries::Bt709).unwrap();
344        let m1_inv = lms_to_rgb_matrix(ColorPrimaries::Bt709).unwrap();
345
346        let test_colors = [
347            [0.5, 0.3, 0.8],
348            [1.0, 0.0, 0.0],
349            [0.0, 1.0, 0.0],
350            [0.0, 0.0, 1.0],
351            [0.18, 0.18, 0.18], // 18% gray
352        ];
353
354        for rgb in &test_colors {
355            let [l, a, b] = rgb_to_oklab(rgb[0], rgb[1], rgb[2], m1.rows());
356            let [r2, g2, b2] = oklab_to_rgb(l, a, b, m1_inv.rows());
357            for c in 0..3 {
358                let err = (rgb[c] - [r2, g2, b2][c]).abs();
359                assert!(err < 1e-4, "roundtrip error for {rgb:?} channel {c}: {err}");
360            }
361        }
362    }
363
364    /// Neutrals have no chroma and L is the cube root of the gray, in every space with a matrix.
365    #[test]
366    fn oklab_neutrals_have_no_chroma() {
367        for p in [
368            ColorPrimaries::Bt709,
369            ColorPrimaries::DisplayP3,
370            ColorPrimaries::Bt2020,
371        ] {
372            let m1 = rgb_to_lms_matrix(p).unwrap();
373            for i in 1..=4096 {
374                let g = i as f32 / 4096.0;
375                let [l, a, b] = rgb_to_oklab(g, g, g, m1.rows());
376                assert!(a.hypot(b) < 1e-6, "{p:?} gray {g}: a {a}, b {b}");
377                assert!((l - libm::cbrtf(g)).abs() < 2e-6, "{p:?} gray {g}: L {l}");
378            }
379        }
380    }
381
382    /// CSS Color 4's results for sRGB's primaries, from its conversions.js in f64.
383    #[test]
384    fn oklab_matches_css() {
385        let m1 = rgb_to_lms_matrix(ColorPrimaries::Bt709).unwrap();
386        for (rgb, css) in [
387            ([1.0, 0.0, 0.0], [0.627955, 0.224863, 0.125846]),
388            ([0.0, 1.0, 0.0], [0.866440, -0.233888, 0.179498]),
389            ([0.0, 0.0, 1.0], [0.452014, -0.032457, -0.311528]),
390        ] {
391            let lab = rgb_to_oklab(rgb[0], rgb[1], rgb[2], m1.rows());
392            for (got, want) in lab.iter().zip(css) {
393                assert!((got - want).abs() < 2e-6, "{rgb:?}: {lab:?} vs {css:?}");
394            }
395        }
396    }
397
398    #[test]
399    fn oklab_black_point() {
400        let m1 = rgb_to_lms_matrix(ColorPrimaries::Bt709).unwrap();
401        let [l, a, b] = rgb_to_oklab(0.0, 0.0, 0.0, m1.rows());
402        assert!(l.abs() < 1e-6, "black L should be ~0.0, got {l}");
403        assert!(a.abs() < 1e-6, "black a should be ~0.0, got {a}");
404        assert!(b.abs() < 1e-6, "black b should be ~0.0, got {b}");
405    }
406
407    #[test]
408    fn oklab_roundtrip_bt2020() {
409        let m1 = rgb_to_lms_matrix(ColorPrimaries::Bt2020).unwrap();
410        let m1_inv = lms_to_rgb_matrix(ColorPrimaries::Bt2020).unwrap();
411
412        let rgb = [0.4, 0.6, 0.2];
413        let [l, a, b] = rgb_to_oklab(rgb[0], rgb[1], rgb[2], m1.rows());
414        let [r2, g2, b2] = oklab_to_rgb(l, a, b, m1_inv.rows());
415        for c in 0..3 {
416            let err = (rgb[c] - [r2, g2, b2][c]).abs();
417            assert!(err < 1e-4, "BT.2020 roundtrip error channel {c}: {err}");
418        }
419    }
420
421    #[test]
422    fn combined_matrices_available() {
423        assert!(rgb_to_lms_matrix(ColorPrimaries::Bt709).is_some());
424        assert!(rgb_to_lms_matrix(ColorPrimaries::DisplayP3).is_some());
425        assert!(rgb_to_lms_matrix(ColorPrimaries::Bt2020).is_some());
426        assert!(rgb_to_lms_matrix(ColorPrimaries::Unknown).is_none());
427
428        assert!(lms_to_rgb_matrix(ColorPrimaries::Bt709).is_some());
429        assert!(lms_to_rgb_matrix(ColorPrimaries::Unknown).is_none());
430    }
431
432    #[test]
433    fn fast_cbrt_spec_is_bit_identical_to_fast_cbrt_across_domains() {
434        let mut samples = alloc::vec![
435            0.0_f32,
436            -0.0_f32,
437            f32::from_bits(1),
438            -f32::from_bits(1),
439            f32::from_bits(0x007f_ffff),
440            -f32::from_bits(0x007f_ffff),
441            f32::MIN_POSITIVE,
442            -f32::MIN_POSITIVE,
443            1e-20,
444            -1e-20,
445            0.0031308,
446            0.5,
447            -0.5,
448            1.0,
449            -1.0,
450            100.0,
451            -100.0,
452            f32::MAX,
453            f32::MIN,
454        ];
455        // Sweep across subnormal and normal bit patterns.
456        let mut b = 1u32;
457        while b < 0x0080_0000 {
458            samples.push(f32::from_bits(b));
459            samples.push(-f32::from_bits(b));
460            b = b.saturating_add(65_521);
461        }
462        let mut b = 0x0080_0000u32;
463        while b < 0x7f80_0000 {
464            samples.push(f32::from_bits(b));
465            samples.push(-f32::from_bits(b));
466            b = b.saturating_add(524_287);
467        }
468
469        for x in samples {
470            let want = fast_cbrt(x).to_bits();
471            // All finite values satisfy NO_SPECIAL:
472            assert_eq!(
473                fast_cbrt_spec::<true, false, false, false>(x).to_bits(),
474                want,
475                "finite spec mismatch at {x:?} ({:#010x})",
476                x.to_bits()
477            );
478            if !x.is_sign_negative() {
479                assert_eq!(
480                    fast_cbrt_spec::<true, false, true, false>(x).to_bits(),
481                    want,
482                    "nonneg spec mismatch at {x:?}"
483                );
484            }
485            if !x.is_subnormal() {
486                assert_eq!(
487                    fast_cbrt_spec::<true, true, false, false>(x).to_bits(),
488                    want,
489                    "nosub spec mismatch at {x:?}"
490                );
491            }
492            if !x.is_sign_negative() && !x.is_subnormal() {
493                assert_eq!(
494                    fast_cbrt_spec::<true, true, true, false>(x).to_bits(),
495                    want,
496                    "nonneg+nosub spec mismatch at {x:?}"
497                );
498            }
499            if x > 0.0 && !x.is_subnormal() {
500                assert_eq!(
501                    fast_cbrt_spec::<true, true, true, true>(x).to_bits(),
502                    want,
503                    "pos+nosub spec mismatch at {x:?}"
504                );
505            }
506        }
507    }
508}