From 95cd2c0eb79532ebcef29c6886c32f18ed0e804b Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 18 Nov 2026 12:35:09 -0800 Subject: [PATCH] Add craft-color-transform: RGB spaces, white balance, OkLab, tone curves and PQ tone mapping (#1995) * Add craft-color-transform: RGB spaces, white balance, OkLab, tone curves and PQ tone mapping craft-color-transform builds on craft-color. It holds RGB spaces from primaries and a white point with Bradford adaptation, white balance by correlated color temperature and tint, OkLab and OkLCh for any RGB space, monotone tone curves and 1D lookup tables, and the BT.2408-8 Annex 5 EETF with a maxRGB tone map. The per-pixel functions take f32 and do not allocate, and the crate builds for wasm32-unknown-unknown. Moved from StudioCraft's craft-color-transform (blamejs/StudioCraft crates/craft-color-transform). The README names the LightCraft and FilmCraft modules parts of it started from. * Color transform: compose, interpolate and invert at extreme values Lut1::compose samples the densest grid of at most MAX_LUT entries that holds both tables' points, so a short inner table, or one that crosses an outer peak between its own points, keeps the outer table's points to within one grid step. Lut1::eval weights the two entries in f64, so entries as far apart as -f32::MAX and f32::MAX no longer give NaN or infinity. MonotoneCurve::new compares the tangent pair's length with 3|d|, so a subnormal secant next to a normal one no longer gives a NaN tangent. Mat3::inverse divides the matrix by its largest entry before taking the determinant, so diag(1e110) and diag(1e-200) invert. OkLab::for_space falls back to XYZ_TO_LMS when a matrix has no inverse or an entry beyond f32. * Color transform: build the matrix arithmetic on craft_cms::math craft_cms::math gains the two hardened functions the color transforms need, and craft-color-transform calls them instead of carrying its own copies. - math::inverse divides the matrix by its largest entry before taking the determinant, so a matrix whose own determinant overflows or underflows still inverts, and it returns None for NaN, infinite or all-zero input and for an inverse beyond f64. math::invert keeps its absolute 1e-12 floor, which profile construction uses to validate ICC matrices. - math::bradford_checked returns None when a white's cone response is not finite or not above 0, or the ratios overflow. math::bradford still divides without the check. - math::BRADFORD is public. - Mat3::mul, apply, determinant and inverse, Xy::to_xyz, BRADFORD and bradford_xyz call craft_cms::math. - oklab::lms_matrices gives OkLab::for_space's matrices in f64. * Color transform: keep the EETF's black lift rising for a high target black The BT.2408 Annex 5 lift minLum * (1 - E2)^4 has a slope of 1 - 4 minLum at E2 = 0, so a target black above a quarter of the normalized range made the output fall near black, and it raised the peak well above the target peak. The lift is now minLum * (1 - E2 / r)^k with r = max(T, min(1, 2 - 4 minLum)) and k = min(4, r / minLum), where T is the top of the output (the smaller of maxLum and 1). It equals the Annex's lift up to minLum 0.25, keeps the output rising, changes continuously with the target black, and from minLum 0.5 reaches 0 at the top of the output. A target black above the source peak reads as the source peak. * Color transform: state the composition bound for the fallback grid --- Cargo.lock | 10 + Cargo.toml | 1 + crates/cms/src/math.rs | 124 +++++++- crates/color-transform/Cargo.toml | 21 ++ crates/color-transform/README.md | 74 +++++ crates/color-transform/src/cct.rs | 243 +++++++++++++++ crates/color-transform/src/curve.rs | 421 ++++++++++++++++++++++++++ crates/color-transform/src/lib.rs | 21 ++ crates/color-transform/src/oklab.rs | 246 +++++++++++++++ crates/color-transform/src/space.rs | 295 ++++++++++++++++++ crates/color-transform/src/tonemap.rs | 406 +++++++++++++++++++++++++ 11 files changed, 1859 insertions(+), 3 deletions(-) create mode 100644 crates/color-transform/Cargo.toml create mode 100644 crates/color-transform/README.md create mode 100644 crates/color-transform/src/cct.rs create mode 100644 crates/color-transform/src/curve.rs create mode 100644 crates/color-transform/src/lib.rs create mode 100644 crates/color-transform/src/oklab.rs create mode 100644 crates/color-transform/src/space.rs create mode 100644 crates/color-transform/src/tonemap.rs diff --git a/Cargo.lock b/Cargo.lock index 4c9980247..99c69c0fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1692,6 +1692,16 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-color-transform" +version = "0.1.0" +dependencies = [ + "craft-cms", + "craft-color", + "serde", + "serde_json", +] + [[package]] name = "craft-control" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 605801564..b5581ed03 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -71,6 +71,7 @@ craft-cms = { path = "crates/cms" } craft-cloud = { path = "crates/cloud" } craft-cloud-local = { path = "crates/cloud-local" } craft-color = { path = "crates/color" } +craft-color-transform = { path = "crates/color-transform" } craft-frame = { path = "crates/frame" } craft-crs = { path = "crates/crs" } craft-crw = { path = "crates/crw" } diff --git a/crates/cms/src/math.rs b/crates/cms/src/math.rs index 860126653..7e298af1a 100644 --- a/crates/cms/src/math.rs +++ b/crates/cms/src/math.rs @@ -39,7 +39,9 @@ pub const fn det(m: &Mat3) -> f64 { + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]) } -/// Inverse, or `None` when (nearly) singular. +/// Inverse, or `None` when (nearly) singular: the determinant is not finite or is below 1e-12. +/// Profile construction checks its matrices with this rule. [`inverse`] takes the determinant +/// relative to the largest entry instead. pub const fn invert(m: &Mat3) -> Option { let d = det(m); if !d.is_finite() || d.abs() < 1e-12 { @@ -53,14 +55,66 @@ pub const fn invert(m: &Mat3) -> Option { ]) } +/// Inverse of a matrix at any scale, or `None` when it holds a NaN or an infinite entry, is all +/// zeros, is singular to within rounding (the determinant is at most 1e-12 times the cube of the +/// largest entry), or has an inverse with an entry beyond the range of `f64`. +/// +/// The matrix is divided by its largest entry before the determinant is taken, so a matrix whose +/// own determinant overflows or underflows (`diag(1e-200, 1e-200, 1e-200)`) still inverts. +pub const fn inverse(m: &Mat3) -> Option { + let mut scale = 0.0f64; + let mut i = 0; + while i < 9 { + let v = m[i / 3][i % 3]; + if v.is_nan() { + return None; + } + if v.abs() > scale { + scale = v.abs(); + } + i += 1; + } + if !(scale.is_finite() && scale > 0.0) { + return None; + } + let mut s = [[0.0; 3]; 3]; + let mut i = 0; + while i < 9 { + s[i / 3][i % 3] = m[i / 3][i % 3] / scale; + i += 1; + } + let d = det(&s); + if !d.is_finite() || d.abs() <= 1e-12 { + return None; + } + // Each cofactor is divided by the determinant and then by the scale: the reciprocals can + // overflow where the quotients do not. + let c = [ + [s[1][1] * s[2][2] - s[1][2] * s[2][1], s[0][2] * s[2][1] - s[0][1] * s[2][2], s[0][1] * s[1][2] - s[0][2] * s[1][1]], + [s[1][2] * s[2][0] - s[1][0] * s[2][2], s[0][0] * s[2][2] - s[0][2] * s[2][0], s[0][2] * s[1][0] - s[0][0] * s[1][2]], + [s[1][0] * s[2][1] - s[1][1] * s[2][0], s[0][1] * s[2][0] - s[0][0] * s[2][1], s[0][0] * s[1][1] - s[0][1] * s[1][0]], + ]; + let mut inv = [[0.0; 3]; 3]; + let mut i = 0; + while i < 9 { + let v = c[i / 3][i % 3] / d / scale; + if !v.is_finite() { + return None; + } + inv[i / 3][i % 3] = v; + i += 1; + } + Some(inv) +} + /// XYZ (Y = 1) of a chromaticity `(x, y)`. pub const fn xy_to_xyz(xy: [f64; 2]) -> [f64; 3] { let [x, y] = xy; [x / y, 1.0, (1.0 - x - y) / y] } -/// Bradford cone response matrix (Lam 1985). -const BRADFORD: Mat3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]; +/// Bradford cone response matrix (Lam 1985): XYZ to sharpened cone responses. +pub const BRADFORD: Mat3 = [[0.8951, 0.2664, -0.1614], [-0.7502, 1.7135, 0.0367], [0.0389, -0.0685, 1.0296]]; /// Inverse of [`BRADFORD`] (determinant ~1.7), computed at compile time. const BRADFORD_INV: Mat3 = match invert(&BRADFORD) { @@ -77,6 +131,17 @@ pub fn bradford(src: [f64; 3], dst: [f64; 3]) -> Mat3 { mul(&inv, &mul(&scale, &BRADFORD)) } +/// [`bradford`], or `None` when a white's cone response is not finite or not above 0, or the +/// response ratios overflow. [`bradford`] divides by the source response without this check. +pub fn bradford_checked(src: [f64; 3], dst: [f64; 3]) -> Option { + let ok = |v: [f64; 3]| v.iter().all(|c| c.is_finite() && *c > 0.0); + if !(ok(apply(&BRADFORD, src)) && ok(apply(&BRADFORD, dst))) { + return None; + } + let m = bradford(src, dst); + m.iter().flatten().all(|v| v.is_finite()).then_some(m) +} + /// RGB → XYZ matrix (relative to `white`, Y = 1) for primaries given as chromaticities, or /// `None` when the primaries are not independent. pub const fn rgb_to_xyz_matrix(r: [f64; 2], g: [f64; 2], b: [f64; 2], white: [f64; 3]) -> Option { @@ -264,6 +329,59 @@ mod tests { } } + fn close(a: &Mat3, b: &Mat3, tol: f64) { + for i in 0..3 { + for j in 0..3 { + assert!((a[i][j] - b[i][j]).abs() <= tol, "[{i}][{j}] {} vs {}", a[i][j], b[i][j]); + } + } + } + + const fn diag(v: f64) -> Mat3 { + [[v, 0.0, 0.0], [0.0, v, 0.0], [0.0, 0.0, v]] + } + + #[test] + fn inverse_matches_invert_on_ordinary_matrices() { + let m = [[0.4, 0.3, 0.2], [0.2, 0.7, 0.1], [0.0, 0.1, 0.8]]; + close(&inverse(&m).unwrap(), &invert(&m).unwrap(), 1e-12); + assert_eq!(inverse(&BRADFORD).map(|_| ()), Some(())); + } + + #[test] + fn inverse_works_at_any_scale_and_rejects_what_has_no_finite_inverse() { + // The determinant, 1e-312, has no finite reciprocal; the inverse itself is finite. + close(&inverse(&diag(1e-104)).unwrap(), &diag(1e104), 1e93); + assert_eq!(invert(&diag(1e-104)), None); + // A determinant beyond f64 in either direction still leaves a finite inverse. + close(&inverse(&diag(1e-200)).unwrap(), &diag(1e200), 1e186); + close(&inverse(&diag(1e110)).unwrap(), &diag(1e-110), 1e-124); + assert_eq!(inverse(&diag(f64::MAX)).map(|m| m[0][0]), Some(1.0 / f64::MAX)); + // An inverse with entries beyond f64 is no inverse. + assert_eq!(inverse(&diag(1e-310)), None); + assert_eq!(inverse(&[[0.0; 3]; 3]), None); + assert_eq!(inverse(&[[f64::NAN; 3]; 3]), None); + assert_eq!(inverse(&diag(f64::INFINITY)), None); + let mut one_nan = IDENTITY; + one_nan[1][2] = f64::NAN; + assert_eq!(inverse(&one_nan), None); + // Singular to within rounding relative to the largest entry. + assert_eq!(inverse(&[[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [0.0, 0.0, 1e9]]), None); + } + + #[test] + fn bradford_checked_rejects_whites_with_no_cone_response() { + let d65 = xy_to_xyz(D65_XY); + close(&bradford_checked(d65, D50).unwrap(), &bradford(d65, D50), 0.0); + assert_eq!(bradford_checked([0.0; 3], D50), None); + assert_eq!(bradford_checked(d65, [f64::NAN; 3]), None); + assert_eq!(bradford_checked(d65, [-1.0, -1.0, -1.0]), None); + // Cone responses this small give scale ratios beyond f64. + assert_eq!(bradford_checked([1e-320; 3], d65), None); + // Unchecked, the zero white divides by zero. + assert!(bradford([0.0; 3], D50).iter().flatten().any(|v| !v.is_finite())); + } + #[test] fn invert_roundtrip() { let m = [[0.4, 0.3, 0.2], [0.2, 0.7, 0.1], [0.0, 0.1, 0.8]]; diff --git a/crates/color-transform/Cargo.toml b/crates/color-transform/Cargo.toml new file mode 100644 index 000000000..8b979d4c0 --- /dev/null +++ b/crates/color-transform/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "craft-color-transform" +description = "Color transforms for Craft apps: RGB spaces and Bradford adaptation, white balance by temperature and tint, OkLab and OkLCh, monotone tone curves and 1D lookup tables, and BT.2408 PQ tone mapping" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[dependencies] +# PQ (SMPTE ST 2084), the HDR reference white and the color primaries tags. +craft-color = { workspace = true } +# The 3×3 matrix arithmetic and Bradford adaptation (`craft_cms::math`). +craft-cms = { workspace = true } +serde = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/color-transform/README.md b/crates/color-transform/README.md new file mode 100644 index 000000000..967be6a52 --- /dev/null +++ b/crates/color-transform/README.md @@ -0,0 +1,74 @@ +# craft-color-transform + +Color transforms for the Craft apps: RGB spaces and chromatic adaptation, white balance by +temperature and tint, OkLab and OkLCh, monotone tone curves and 1D lookup tables, and PQ tone +mapping. It builds on [`craft-color`](../color), which holds the frame color tags, the Y'CbCr +matrices and the sRGB, PQ and HLG transfer functions. It depends on `craft-color`, `craft-cms` +and `serde`, contains no `unsafe` code, and builds for `wasm32-unknown-unknown`. The per-pixel +functions take `f32` and do not allocate. + +The matrix arithmetic comes from `craft_cms::math`. `Mat3` wraps its row-major `[[f64; 3]; 3]` +and converts to and from it with `From`. `mul`, `apply` and `determinant` call `math::mul`, +`math::apply` and `math::det`, `Mat3::inverse` calls `math::inverse`, `Xy::to_xyz` calls +`math::xy_to_xyz` after checking the chromaticity, `BRADFORD` is `math::BRADFORD`, and +`bradford_xyz` calls `math::bradford_checked`. `math::inverse` divides the matrix by its largest +entry before taking the determinant. `math::invert`, which `craft-cms` uses to validate ICC +matrices, keeps its absolute determinant floor of 1e-12. `RgbSpace::to_xyz` builds the +normalized primary matrix with `math::inverse` rather than with `math::rgb_to_xyz_matrix`, which +inverts with `math::invert`, and returns the identity when the normalized matrix has no inverse. + +Moved from StudioCraft's `craft-color-transform` +([`crates/craft-color-transform`](https://github.com/blamejs/StudioCraft/tree/2abe1824aa0d849faf8d5f91557d68ebe577f495/crates/craft-color-transform)). +Parts of it started in other Craft apps: + +- `cct`, `oklab` and `curve` came from LightCraft's `lightcraft-color` (`crates/color/src/cct.rs`, + `perceptual.rs` and `spline.rs`). `MonotoneCurve` now loads a saved curve through its + constructor, so a file cannot give it arrays of different lengths, and it bounds the points it + keeps and the size of their coordinates. `OkLab::for_space` extends the BT.2020-only OkLab + conversion to any `RgbSpace`. +- `tonemap` came from FilmCraft's `filmcraft-color` (`crates/color/src/transform.rs`, + `bt2390_eetf` and its maxRGB operator). It now follows Report ITU-R BT.2408-8 Annex 5 with + the black lift, passes values through when the target peak is at or above the source peak, + and handles a target peak below a third of the source range (see `Eetf`). + +License: MIT OR Apache-2.0. + +## Contents + +| Item | What it does | Source of the formula | +| --- | --- | --- | +| `Mat3`, `Xy`, `RgbSpace` | 3×3 matrices, CIE 1931 chromaticities, RGB spaces from primaries and a white point. `RgbSpace::to_xyz` is the normalized primary matrix. `RgbSpace::from(craft_color::Primaries)` gives the space of a frame tag. | SMPTE RP 177; primaries from ITU-R BT.709, BT.601, BT.2020 and SMPTE EG 432-1 | +| `bradford`, `bradford_xyz` | The Bradford chromatic adaptation matrix between two whites. `RgbSpace::to_space` converts between spaces with it. | The Bradford cone response matrix | +| `cct::temp_tint_to_xy`, `cct::xy_to_temp_tint` | A white at a correlated color temperature and tint, and back. Tint is Duv × 3000 along the locus normal in CIE 1960 (u, v); positive is towards green. | Kim et al., "Design of Advanced Color Temperature Control System for HDTV Applications", Journal of the Korean Physical Society 41 (2002) | +| `cct::wb_matrix`, `cct::white_balance` | The RGB matrix that makes a scene lit by one white look lit by another. | Bradford adaptation | +| `oklab` | OkLab from linear sRGB with the published matrices, from XYZ, and for any `RgbSpace` (`OkLab::for_space`, with `f32` matrices; `oklab::lms_matrices` gives the same matrices in `f64`); OkLCh. | B. Ottosson, "A perceptual color space for image processing" (2020) | +| `curve::MonotoneCurve` | A tone curve through points that does not overshoot between them. It saves as its list of points. `knots` gives each point with its tangent for evaluation in a shader. | Fritsch and Carlson, "Monotone Piecewise Cubic Interpolation", SIAM J. Numer. Anal. 17 (1980) | +| `curve::Lut1` | A 1D lookup table over 0..1 with linear interpolation. | | +| `tonemap::Eetf` | The reference EETF from a mastering display to a target display, with the black lift, on PQ values or nits. When the target peak is below a third of the source range in PQ, where the Annex's knee would be negative, the knee is 0 and the spline starts with a slope of 3 × maxLum. When minLum is above 0.25, where the Annex's lift minLum × (1 − E2)⁴ would make the output fall near black and raise the peak above the target peak, the lift is minLum × (1 − E2 / r)ᵏ with r = max(T, min(1, 2 − 4 minLum)) and k = min(4, r / minLum), where T is the smaller of maxLum and 1. This equals the Annex's lift up to minLum 0.25, keeps the output rising, changes continuously with the target black, and from minLum 0.5 reaches 0 at the top of the output. A target black above the source peak reads as the source peak. Both rules are the crate's own. | Report ITU-R BT.2408-8, Annex 5 | +| `tonemap::ToneMap` | The EETF applied to linear RGB by max(R, G, B) as a ratio, with 1.0 at the 203-nit reference white. | Report ITU-R BT.2408-8, Annex 5 (the maxRGB option) | + +## Hostile input + +- A chromaticity with `y` at or below 0, or with a coordinate that is not finite, is rejected by + `Xy::to_xyz`. `bradford` then returns the identity, and so does `RgbSpace::to_xyz` for such a + white, for collinear primaries and for a white that gives a primary no weight. `Mat3::inverse` + and `bradford_xyz` return `None` or the identity instead of a matrix with entries beyond + `f64`. +- Temperatures are clamped to 1000 K to 100 000 K, and NaN reads as 6500 K. A tint that is not + finite reads as 0. +- `MonotoneCurve` keeps at most 1024 points and drops points with a coordinate that is not + finite or is beyond ±1e6. A saved curve is read back through the same constructor, so a file + cannot give it mismatched arrays. +- `Lut1::from_fn` and `MonotoneCurve::to_lut` build at most 65 536 entries. +- Luminances are clamped to 0..10 000 nits. A target peak that is NaN or not above 0 gives an + EETF and a `ToneMap` that pass values through. + +## Tests + +`cargo test -p craft-color-transform` checks the code against published values: the sRGB matrix of +IEC 61966-2-1, the BT.709 and BT.2020 luminance weights, the BT.709 to BT.2020 matrix of +ITU-R BT.2087, the D65 to D50 Bradford matrix as Lindbloom's chromatic adaptation page prints it, +illuminant A and D65 from CIE 15:2004 (temperature, Duv, CIE 1960 coordinates), Ottosson's XYZ to +OkLab table, the OkLab value CSS Color Module Level 4 gives for `#7654CD`, the PQ levels of +BT.2408, and EETF values computed from the BT.2408 Annex 5 equations by a separate +implementation. diff --git a/crates/color-transform/src/cct.rs b/crates/color-transform/src/cct.rs new file mode 100644 index 000000000..1f81cdb19 --- /dev/null +++ b/crates/color-transform/src/cct.rs @@ -0,0 +1,243 @@ +//! Correlated color temperature, tint and white balance. +//! +//! The Planckian locus is the cubic approximation of Kim et al., "Design of Advanced Color +//! Temperature Control System for HDTV Applications", Journal of the Korean Physical Society 41 +//! (2002), over 1667 K to 25000 K. Outside that range the locus continues as a straight line in +//! mired (10⁶ / K) from the end of the approximation. Temperatures are clamped to +//! [`MIN_TEMPERATURE`] to [`MAX_TEMPERATURE`]. +//! +//! Tint is a signed distance from the locus in CIE 1960 (u, v), along the locus normal, in units +//! of 1/[`TINT_SCALE`] of Duv. A positive tint is a white above the locus (towards green), so the +//! correction that removes it adds magenta; a negative tint is a white below the locus. + +use crate::{Mat3, RgbSpace, Xy, bradford}; + +/// Tint units per unit of Duv. +pub const TINT_SCALE: f64 = 3000.0; +/// The lowest temperature the approximation covers, in kelvin. +pub const KIM_MIN: f64 = 1667.0; +/// The highest temperature the approximation covers, in kelvin. +pub const KIM_MAX: f64 = 25000.0; +/// The lowest temperature the functions here take. +pub const MIN_TEMPERATURE: f64 = 1000.0; +/// The highest temperature the functions here take. +pub const MAX_TEMPERATURE: f64 = 100_000.0; + +fn kim_xy(t: f64) -> Xy { + let t = t.clamp(KIM_MIN, KIM_MAX); + let (t2, t3) = (t * t, t * t * t); + let x = if t <= 4000.0 { + -0.2661239e9 / t3 - 0.2343589e6 / t2 + 0.8776956e3 / t + 0.179910 + } else { + -3.0258469e9 / t3 + 2.1070379e6 / t2 + 0.2226347e3 / t + 0.240390 + }; + let (x2, x3) = (x * x, x * x * x); + let y = if t <= 2222.0 { + -1.1063814 * x3 - 1.34811020 * x2 + 2.18555832 * x - 0.20219683 + } else if t <= 4000.0 { + -0.9549476 * x3 - 1.37418593 * x2 + 2.09137015 * x - 0.16748867 + } else { + 3.0817580 * x3 - 5.87338670 * x2 + 3.75112997 * x - 0.37001483 + }; + Xy::new(x, y) +} + +/// CIE 1931 xy to CIE 1960 (u, v). +pub fn xy_to_uv(p: Xy) -> (f64, f64) { + let d = -2.0 * p.x + 12.0 * p.y + 3.0; + (4.0 * p.x / d, 6.0 * p.y / d) +} + +/// CIE 1960 (u, v) to CIE 1931 xy. +pub fn uv_to_xy(u: f64, v: f64) -> Xy { + let d = 2.0 * u - 8.0 * v + 4.0; + Xy::new(3.0 * u / d, 2.0 * v / d) +} + +/// A temperature in range: NaN reads as 6500 K. +fn sane_temperature(t: f64) -> f64 { + if t.is_nan() { 6500.0 } else { t.clamp(MIN_TEMPERATURE, MAX_TEMPERATURE) } +} + +/// The locus in (u, v) at `t` kelvin. +fn locus_uv(t: f64) -> (f64, f64) { + if (KIM_MIN..=KIM_MAX).contains(&t) { + return xy_to_uv(kim_xy(t)); + } + let (a, b) = if t < KIM_MIN { (KIM_MIN, KIM_MIN + 50.0) } else { (KIM_MAX - 500.0, KIM_MAX) }; + let (ua, va) = xy_to_uv(kim_xy(a)); + let (ub, vb) = xy_to_uv(kim_xy(b)); + let (ma, mb, m) = (1e6 / a, 1e6 / b, 1e6 / t); + let s = (m - ma) / (mb - ma); + (ua + (ub - ua) * s, va + (vb - va) * s) +} + +/// The unit normal of the locus at `t`, pointing towards green (increasing v). +fn locus_normal(t: f64) -> (f64, f64) { + let m = 1e6 / t; + let (u0, v0) = locus_uv(1e6 / (m + 1.0)); + let (u1, v1) = locus_uv(1e6 / (m - 1.0).max(1.0)); + let (du, dv) = (u1 - u0, v1 - v0); + let l = du.hypot(dv).max(1e-12); + let (nx, ny) = (-dv / l, du / l); + if ny < 0.0 { (-nx, -ny) } else { (nx, ny) } +} + +/// The chromaticity of a white at temperature `t` (kelvin) and `tint`. A NaN tint reads as 0. +pub fn temp_tint_to_xy(t: f64, tint: f64) -> Xy { + let t = sane_temperature(t); + let tint = if tint.is_finite() { tint } else { 0.0 }; + let (u, v) = locus_uv(t); + let (nu, nv) = locus_normal(t); + let duv = tint / TINT_SCALE; + uv_to_xy(u + nu * duv, v + nv * duv) +} + +/// The temperature and tint of a white: the nearest point on the locus, searched in mired, and +/// the signed distance from it. The inverse of [`temp_tint_to_xy`] over its range. A +/// chromaticity with no (u, v) coordinates (NaN, or on the line where their denominator is 0) +/// reads as 6500 K with no tint. +pub fn xy_to_temp_tint(p: Xy) -> (f64, f64) { + let (u, v) = xy_to_uv(p); + if !(u.is_finite() && v.is_finite()) { + return (6500.0, 0.0); + } + let dist = |m: f64| { + let (lu, lv) = locus_uv(1e6 / m); + (u - lu).powi(2) + (v - lv).powi(2) + }; + let (lo, hi) = (1e6 / MAX_TEMPERATURE, 1e6 / MIN_TEMPERATURE); + // A scan every 5 mired, then a golden-section search around the best step. + let mut best = lo; + let mut best_d = f64::MAX; + let mut m = lo; + while m <= hi { + let d = dist(m); + if d < best_d { + best_d = d; + best = m; + } + m += 5.0; + } + let (mut a, mut b) = ((best - 5.0).max(lo), (best + 5.0).min(hi)); + let g = 0.618_033_988_75; + for _ in 0..60 { + let c = b - g * (b - a); + let d = a + g * (b - a); + if dist(c) < dist(d) { b = d } else { a = c } + } + let t = 1e6 / ((a + b) / 2.0); + let (lu, lv) = locus_uv(t); + let (nu, nv) = locus_normal(t); + (t, ((u - lu) * nu + (v - lv) * nv) * TINT_SCALE) +} + +/// The matrix (linear RGB in `space` to the same space) that makes a scene lit by a white at +/// `src` look as if it were lit by the space's own white (Bradford adaptation). +pub fn wb_matrix(space: &RgbSpace, src: Xy) -> Mat3 { + space.from_xyz().mul(&bradford(src, space.white)).mul(&space.to_xyz()) +} + +/// The matrix (linear RGB in `space` to the same space) that makes a scene lit by a white at +/// temperature and tint `from` look as if it were lit by the white at `to`. Equal settings give +/// the identity. A lower `from` temperature than `to` cools the picture. +pub fn white_balance(space: &RgbSpace, from: (f64, f64), to: (f64, f64)) -> Mat3 { + let (src, dst) = (temp_tint_to_xy(from.0, from.1), temp_tint_to_xy(to.0, to.1)); + if src == dst { + return Mat3::IDENTITY; + } + space.from_xyz().mul(&bradford(src, dst)).mul(&space.to_xyz()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{D65, REC2020, SRGB}; + + /// CIE 15:2004 gives illuminant A (a Planckian radiator at 2856 K) as x = 0.44757, + /// y = 0.40745. The cubic approximation lands within 0.001 Duv of it. + #[test] + fn illuminant_a_lies_on_the_locus() { + let (u, v) = xy_to_uv(temp_tint_to_xy(2856.0, 0.0)); + let (ua, va) = xy_to_uv(Xy::new(0.44757, 0.40745)); + assert!((u - ua).hypot(v - va) < 1e-3, "{u} {v}"); + let (t, _) = xy_to_temp_tint(Xy::new(0.44757, 0.40745)); + assert!((t - 2856.0).abs() < 15.0, "{t}"); + } + + /// CIE 15:2004 gives D65 a correlated color temperature of 6504 K; it lies above the locus + /// by a Duv of about 0.0032. + #[test] + fn d65_reads_as_6504_k_above_the_locus() { + let (t, tint) = xy_to_temp_tint(D65); + assert!((t - 6504.0).abs() < 15.0, "{t}"); + assert!((tint / TINT_SCALE - 0.0032).abs() < 3e-4, "{tint}"); + } + + /// D65 in CIE 1960 UCS is (0.1978, 0.3122). + #[test] + fn uv_matches_cie_1960_for_d65() { + let (u, v) = xy_to_uv(D65); + assert!((u - 0.1978).abs() < 1e-4 && (v - 0.3122).abs() < 1e-4, "{u} {v}"); + let back = uv_to_xy(u, v); + assert!((back.x - D65.x).abs() < 1e-12 && (back.y - D65.y).abs() < 1e-12); + } + + #[test] + fn temperature_and_tint_round_trip() { + for t in [1200.0, 2000.0, 2856.0, 4000.0, 5003.0, 6500.0, 9000.0, 15000.0, 30000.0, 50000.0] { + for tint in [-100.0, -20.0, 0.0, 35.0, 150.0] { + let (t2, tint2) = xy_to_temp_tint(temp_tint_to_xy(t, tint)); + assert!((t2 - t).abs() / t < 0.01, "{t} {tint} -> {t2}"); + assert!((tint2 - tint).abs() < 1.0, "{t} {tint} -> {tint2}"); + } + } + } + + #[test] + fn warmer_whites_are_redder_and_positive_tint_is_greener() { + assert!(temp_tint_to_xy(3000.0, 0.0).x > temp_tint_to_xy(9000.0, 0.0).x); + let (_, v0) = xy_to_uv(temp_tint_to_xy(5000.0, 0.0)); + let (_, v1) = xy_to_uv(temp_tint_to_xy(5000.0, 50.0)); + assert!(v1 > v0); + } + + #[test] + fn wb_matrix_maps_the_source_white_to_neutral() { + let src = temp_tint_to_xy(3200.0, 10.0); + let m = wb_matrix(&REC2020, src); + let out = m.apply(REC2020.from_xyz().apply(src.to_xyz().unwrap())); + assert!((out[0] - out[1]).abs() < 1e-9 && (out[1] - out[2]).abs() < 1e-9, "{out:?}"); + } + + #[test] + fn white_balance_is_the_identity_for_equal_settings_and_cools_a_warm_light() { + assert_eq!(white_balance(&SRGB, (6500.0, 0.0), (6500.0, 0.0)), Mat3::IDENTITY); + // Light at 3200 K made to look like 6500 K: a white surface lit by it turns neutral. + let m = white_balance(&SRGB, (3200.0, 0.0), (6500.0, 0.0)); + let gray = m.apply([1.0, 1.0, 1.0]); + assert!(gray[2] > gray[0], "{gray:?}"); + let lit = SRGB.from_xyz().apply(temp_tint_to_xy(3200.0, 0.0).to_xyz().unwrap()); + let lit6500 = SRGB.from_xyz().apply(temp_tint_to_xy(6500.0, 0.0).to_xyz().unwrap()); + let out = m.apply(lit); + for i in 0..3 { + assert!((out[i] - lit6500[i]).abs() < 1e-9, "{out:?} {lit6500:?}"); + } + } + + #[test] + fn hostile_temperatures_stay_finite() { + for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0, -5.0, 1e300] { + for tint in [f64::NAN, f64::INFINITY, 0.0] { + let p = temp_tint_to_xy(t, tint); + assert!(p.x.is_finite() && p.y.is_finite(), "{t} {tint} {p:?}"); + let m = white_balance(&SRGB, (t, tint), (6500.0, 0.0)); + assert!(m.0.iter().flatten().all(|v| v.is_finite()), "{t} {tint}"); + } + } + // -2x + 12y + 3 = 0 at (1.5, 0): the (u, v) denominator. + for p in [Xy::new(f64::NAN, f64::NAN), Xy::new(1.5, 0.0), Xy::new(f64::INFINITY, 0.3)] { + assert_eq!(xy_to_temp_tint(p), (6500.0, 0.0), "{p:?}"); + } + } +} diff --git a/crates/color-transform/src/curve.rs b/crates/color-transform/src/curve.rs new file mode 100644 index 000000000..cdf135cd5 --- /dev/null +++ b/crates/color-transform/src/curve.rs @@ -0,0 +1,421 @@ +//! Tone curves: monotone cubic Hermite splines and 1D lookup tables. +//! +//! [`MonotoneCurve`] interpolates its points with the tangents of F. N. Fritsch and R. E. +//! Carlson, "Monotone Piecewise Cubic Interpolation", SIAM Journal on Numerical Analysis 17 +//! (1980): between two points the curve does not overshoot, so a curve whose points rise never +//! falls. + +use std::fmt; + +use serde::de::{IgnoredAny, SeqAccess, Visitor}; +use serde::{Deserialize, Deserializer, Serialize}; + +/// The most points a [`MonotoneCurve`] keeps; points past it are ignored. +pub const MAX_POINTS: usize = 1024; +/// The largest coordinate a [`MonotoneCurve`] point may have; points farther out are dropped. +pub const MAX_COORDINATE: f64 = 1e6; + +/// A curve through points in `0..1 × 0..1` (any finite values work). It is saved as its points. +#[derive(Clone, Debug, PartialEq, Serialize)] +#[serde(into = "Vec<(f64, f64)>")] +pub struct MonotoneCurve { + xs: Vec, + ys: Vec, + ms: Vec, +} + +impl From> for MonotoneCurve { + fn from(points: Vec<(f64, f64)>) -> MonotoneCurve { + MonotoneCurve::new(&points) + } +} + +/// Reads a saved list of points, keeping the first [`MAX_POINTS`] and skipping the rest +/// without storing them. +impl<'de> Deserialize<'de> for MonotoneCurve { + fn deserialize>(d: D) -> Result { + struct Points; + impl<'de> Visitor<'de> for Points { + type Value = MonotoneCurve; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a list of [x, y] points") + } + fn visit_seq>(self, mut seq: A) -> Result { + let mut p = Vec::with_capacity(seq.size_hint().unwrap_or(0).min(MAX_POINTS)); + while p.len() < MAX_POINTS { + match seq.next_element::<(f64, f64)>()? { + Some(q) => p.push(q), + None => return Ok(MonotoneCurve::new(&p)), + } + } + while seq.next_element::()?.is_some() {} + Ok(MonotoneCurve::new(&p)) + } + } + d.deserialize_seq(Points) + } +} + +impl From for Vec<(f64, f64)> { + fn from(c: MonotoneCurve) -> Vec<(f64, f64)> { + c.points() + } +} + +impl MonotoneCurve { + /// A curve through `points`, sorted by x. Points with a coordinate that is not finite or is + /// beyond ±[`MAX_COORDINATE`] are dropped, and of points closer than 1e-9 in x the first is + /// kept. Fewer than two points give the identity. + pub fn new(points: &[(f64, f64)]) -> MonotoneCurve { + let ok = |v: f64| v.is_finite() && v.abs() <= MAX_COORDINATE; + let mut p: Vec<(f64, f64)> = points.iter().take(MAX_POINTS).copied().filter(|(x, y)| ok(*x) && ok(*y)).collect(); + p.sort_by(|a, b| a.0.total_cmp(&b.0)); + p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9); + if p.len() < 2 { + p = vec![(0.0, 0.0), (1.0, 1.0)]; + } + let n = p.len(); + let xs: Vec = p.iter().map(|q| q.0).collect(); + let ys: Vec = p.iter().map(|q| q.1).collect(); + let d: Vec = xs.windows(2).zip(ys.windows(2)).map(|(x, y)| (y[1] - y[0]) / (x[1] - x[0])).collect(); + let mut ms = vec![0.0; n]; + ms[0] = d[0]; + ms[n - 1] = d[n - 2]; + for i in 1..n - 1 { + ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 }; + } + // The Fritsch–Carlson limit: tangents inside the circle of radius 3 keep each segment + // monotone. The length of (m₀, m₁) is compared with 3·|d|, which stays finite when the + // secant d is subnormal. + for i in 0..n - 1 { + if d[i] == 0.0 { + ms[i] = 0.0; + ms[i + 1] = 0.0; + continue; + } + let r = ms[i].hypot(ms[i + 1]); + let limit = 3.0 * d[i].abs(); + if r > limit { + ms[i] = ms[i] / r * limit; + ms[i + 1] = ms[i + 1] / r * limit; + } + } + MonotoneCurve { xs, ys, ms } + } + + pub fn identity() -> MonotoneCurve { + MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)]) + } + + /// Whether the curve maps every value in `0..1` to itself. A curve whose points do not + /// reach 0 and 1 is not the identity, since it clamps outside them. + pub fn is_identity(&self) -> bool { + let covers = self.xs.first().is_some_and(|x| *x <= 0.0) && self.xs.last().is_some_and(|x| *x >= 1.0); + covers && self.xs.iter().zip(&self.ys).all(|(x, y)| x == y) && self.ms.iter().all(|m| *m == 1.0) + } + + /// The curve at `x`. Below the first point it is the first point's y, above the last the + /// last's. NaN gives NaN. + pub fn eval(&self, x: f64) -> f64 { + if x.is_nan() { + return x; + } + let n = self.xs.len(); + if x <= self.xs[0] { + return self.ys[0]; + } + if x >= self.xs[n - 1] { + return self.ys[n - 1]; + } + let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) { + Ok(i) => return self.ys[i], + Err(i) => i - 1, + }; + hermite(self.xs[i], self.ys[i], self.ms[i], self.xs[i + 1], self.ys[i + 1], self.ms[i + 1], x) + } + + /// The curve sampled at `n` evenly spaced points over `0..1` (at least 2). + pub fn to_lut(&self, n: usize) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() } + } + + /// The points, sorted by x. + pub fn points(&self) -> Vec<(f64, f64)> { + self.xs.iter().copied().zip(self.ys.iter().copied()).collect() + } + + /// Each point as `[x, y, tangent]`, for code that evaluates the same spline elsewhere (a + /// GPU pass): between points `k` and `k + 1`, with `h = x₁ − x₀` and `t = (x − x₀) / h`, + /// the curve is `(2t³ − 3t² + 1) y₀ + (t³ − 2t² + t) h m₀ + (−2t³ + 3t²) y₁ + (t³ − t²) h m₁`. + pub fn knots(&self) -> impl ExactSizeIterator + '_ { + self.xs.iter().zip(&self.ys).zip(&self.ms).map(|((x, y), m)| [*x, *y, *m]) + } +} + +fn hermite(x0: f64, y0: f64, m0: f64, x1: f64, y1: f64, m1: f64, x: f64) -> f64 { + let h = x1 - x0; + let t = (x - x0) / h; + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * y0 + (t3 - 2.0 * t2 + t) * h * m0 + (-2.0 * t3 + 3.0 * t2) * y1 + (t3 - t2) * h * m1 +} + +/// The most entries [`Lut1::from_fn`] and [`MonotoneCurve::to_lut`] build. +pub const MAX_LUT: usize = 1 << 16; + +/// A 1D lookup table over `0..1` with linear interpolation. Inputs outside `0..1` clamp. +#[derive(Clone, Debug, PartialEq)] +pub struct Lut1 { + pub v: Vec, +} + +impl Lut1 { + /// The identity with `n` entries (2 to [`MAX_LUT`]). + pub fn identity(n: usize) -> Lut1 { + Lut1::from_fn(n, |x| x) + } + + /// `f` sampled at `n` evenly spaced points over `0..1` (2 to [`MAX_LUT`]). + pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 { + let n = n.clamp(2, MAX_LUT); + Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() } + } + + /// The table at `x`. `v` is public, so a table of 1 entry reads as that constant and an + /// empty one as the identity. + #[inline] + pub fn eval(&self, x: f32) -> f32 { + let x = x.clamp(0.0, 1.0); + let n = self.v.len(); + if n < 2 { + return self.v.first().copied().unwrap_or(x); + } + let f = x * (n - 1) as f32; + let i = (f as usize).min(n - 2); + let t = f64::from(f - i as f32); + // Weighted in f64, so entries as far apart as ±f32::MAX do not overflow, and t = 0 and + // t = 1 give the entries exactly. + (f64::from(self.v[i]) * (1.0 - t) + f64::from(self.v[i + 1]) * t) as f32 + } + + /// `self ∘ inner`: `inner` applies first. An empty `inner` is the identity, so the result + /// is `self`. The result is sampled on the densest grid of at most [`MAX_LUT`] entries that + /// holds the sample points of both tables. Between two grid points it differs from + /// `self.eval(inner.eval(x))` by at most one grid step times the product of the two + /// tables' steepest slopes. When no grid of that size holds both tables' points, the result + /// uses the longer table's grid, with the same bound for that grid's step: a table whose + /// slope is near its entry count can then lose the other table's knots between two samples. + pub fn compose(&self, inner: &Lut1) -> Lut1 { + if inner.v.is_empty() { + return self.clone(); + } + let on_inner = || Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() }; + let resampled = |n: usize| Lut1::from_fn(n, |x| self.eval(inner.eval(x))); + let (a, b) = (inner.v.len() - 1, self.v.len().saturating_sub(1)); + if a == 0 || b == 0 { + return on_inner(); + } + let common = (a / gcd(a, b)).checked_mul(b).filter(|l| *l < MAX_LUT); + let steps = common.map(|l| (MAX_LUT - 1) / l * l); + match steps { + Some(s) if s == a => on_inner(), + Some(s) => resampled(s + 1), + None if inner.v.len() >= self.v.len() => on_inner(), + None => resampled(self.v.len()), + } + } + + pub fn is_identity(&self) -> bool { + let n = self.v.len(); + n >= 2 && self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6) + } +} + +fn gcd(mut a: usize, mut b: usize) -> usize { + while b != 0 { + (a, b) = (b, a % b); + } + a +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_identity_curve_maps_every_value_to_itself() { + let c = MonotoneCurve::identity(); + assert!(c.is_identity()); + for i in 0..=10 { + let x = i as f64 / 10.0; + assert!((c.eval(x) - x).abs() < 1e-12); + } + assert!(c.to_lut(256).is_identity()); + assert!(!MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]).is_identity()); + // These points lie on the diagonal, but the curve clamps below 0.2 and above 0.8. + let inner = MonotoneCurve::new(&[(0.2, 0.2), (0.8, 0.8)]); + assert_eq!(inner.eval(0.0), 0.2); + assert!(!inner.is_identity()); + assert!(MonotoneCurve::new(&[(-1.0, -1.0), (2.0, 2.0)]).is_identity()); + } + + #[test] + fn the_curve_passes_through_its_points_and_rises_with_them() { + let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)]; + let c = MonotoneCurve::new(&pts); + for (x, y) in pts { + assert!((c.eval(x) - y).abs() < 1e-12); + } + let mut prev = -1.0; + for i in 0..=1000 { + let y = c.eval(i as f64 / 1000.0); + assert!(y >= prev - 1e-12); + prev = y; + } + } + + /// Data that rise, then stay level: a natural cubic spline overshoots the level part, and + /// this curve stays on it. + #[test] + fn the_curve_does_not_overshoot_a_level_run() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]); + for i in 400..=600 { + let y = c.eval(i as f64 / 1000.0); + assert!((y - 0.5).abs() < 1e-9, "{y}"); + } + } + + /// Steep and shallow neighbors: the unlimited average tangent overshoots, the limited one + /// keeps the segment within its end values. + #[test] + fn steep_steps_stay_monotone() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.1, 0.0), (0.2, 1.0), (1.0, 1.0)]); + let mut prev = -1.0; + for i in 0..=1000 { + let y = c.eval(i as f64 / 1000.0); + assert!((0.0..=1.0).contains(&y) && y >= prev - 1e-12, "{i} {y}"); + prev = y; + } + } + + #[test] + fn the_knots_evaluate_to_the_same_curve() { + let c = MonotoneCurve::new(&[(0.0, 0.1), (0.3, 0.2), (0.7, 0.9), (1.0, 0.95)]); + let k: Vec<[f64; 3]> = c.knots().collect(); + assert_eq!(k.len(), 4); + for i in 0..=100 { + let x = i as f64 / 100.0; + let seg = k.windows(2).find(|w| x >= w[0][0] && x <= w[1][0]).unwrap(); + let y = hermite(seg[0][0], seg[0][1], seg[0][2], seg[1][0], seg[1][1], seg[1][2], x); + assert!((y - c.eval(x)).abs() < 1e-12, "{x}"); + } + } + + #[test] + fn luts_compose() { + let a = Lut1::from_fn(1024, |x| x * x); + let b = Lut1::from_fn(1024, f32::sqrt); + assert!((a.compose(&b).eval(0.3) - 0.3).abs() < 2e-3); + assert_eq!(a.compose(&Lut1 { v: vec![] }), a); + } + + /// A short `inner` does not drop the outer table's points between its own. + #[test] + fn composing_with_a_short_table_keeps_the_outer_curve() { + let peak = Lut1 { v: vec![0.0, 1.0, 0.0] }; + let c = peak.compose(&Lut1::identity(2)); + assert_eq!(c.eval(0.5), 1.0); + assert_eq!(c.eval(0.0), 0.0); + assert_eq!(c.eval(1.0), 0.0); + assert_eq!(peak.compose(&Lut1 { v: vec![0.5] }).eval(0.2), 1.0); + // Grids that do not hold each other's points, and inner tables that cross the outer + // peak between their own points. + let cases = [ + (Lut1::identity(4), peak.clone()), + (Lut1 { v: vec![0.0, 1.0, 0.0, 1.0] }, peak.clone()), + (peak.clone(), Lut1::identity(4)), + (peak.clone(), peak.clone()), + (peak.clone(), Lut1 { v: vec![0.0, 0.75] }), + (Lut1::from_fn(17, |x| (x * 9.0).sin().abs()), Lut1::from_fn(9, |x| x * x)), + ]; + for (outer, inner) in &cases { + let c = outer.compose(inner); + for i in 0..=3000 { + let x = i as f32 / 3000.0; + let want = outer.eval(inner.eval(x)); + assert!((c.eval(x) - want).abs() < 1e-3, "{outer:?} {inner:?} {x}"); + } + } + assert!((peak.compose(&Lut1 { v: vec![0.0, 0.75] }).eval(2.0 / 3.0) - 1.0).abs() < 1e-3); + // A grid beyond MAX_LUT entries falls back to the longer table's grid. + let big = Lut1::identity(MAX_LUT - 1).compose(&Lut1::identity(MAX_LUT)); + assert_eq!(big.v.len(), MAX_LUT); + } + + /// Entries this far apart overflow a difference taken between them. + #[test] + fn far_apart_entries_interpolate_without_overflow() { + let wide = Lut1 { v: vec![-f32::MAX, f32::MAX] }; + assert_eq!(wide.eval(0.0), -f32::MAX); + assert_eq!(wide.eval(1.0), f32::MAX); + assert_eq!(wide.eval(0.5), 0.0); + assert!(wide.eval(0.25).is_finite()); + let high = Lut1 { v: vec![f32::MAX, f32::MAX] }; + assert_eq!(high.eval(0.3), f32::MAX); + } + + #[test] + fn a_curve_saves_as_its_points_and_a_hostile_file_does_not_break_it() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.7), (1.0, 1.0)]); + let json = serde_json::to_string(&c).unwrap(); + assert_eq!(json, "[[0.0,0.0],[0.5,0.7],[1.0,1.0]]"); + assert_eq!(serde_json::from_str::(&json).unwrap(), c); + // A single point, unsorted points and duplicates load as a working curve. + assert!(serde_json::from_str::("[[0.5,0.5]]").unwrap().is_identity()); + let messy: MonotoneCurve = serde_json::from_str("[[1.0,1.0],[0.0,0.0],[0.0,0.3],[0.5,0.2]]").unwrap(); + assert_eq!(messy.points(), vec![(0.0, 0.0), (0.5, 0.2), (1.0, 1.0)]); + // The fields are not read from a file, so their lengths always agree. + assert!(serde_json::from_str::(r#"{"xs":[0.0],"ys":[],"ms":[]}"#).is_err()); + // A long list keeps its first MAX_POINTS points. + let long: Vec<(f64, f64)> = (0..3000).map(|i| (f64::from(i) / 3000.0, f64::from(i) / 3000.0)).collect(); + let loaded: MonotoneCurve = serde_json::from_str(&serde_json::to_string(&long).unwrap()).unwrap(); + assert_eq!(loaded.points().len(), MAX_POINTS); + assert_eq!(loaded.points()[MAX_POINTS - 1], long[MAX_POINTS - 1]); + } + + #[test] + fn nan_input_and_short_or_huge_tables_do_not_panic() { + let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]); + assert!(c.eval(f64::NAN).is_nan()); + assert!(c.eval(-f64::NAN).is_nan()); + assert_eq!(c.eval(-3.0), 0.0); + assert_eq!(c.eval(9.0), 1.0); + for n in [0, 1] { + assert_eq!(c.to_lut(n).v.len(), 2, "{n}"); + assert!(Lut1::identity(n).is_identity(), "{n}"); + } + assert_eq!(Lut1::from_fn(usize::MAX, |x| x).v.len(), MAX_LUT); + assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3); + assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0); + assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7); + assert!(!Lut1 { v: vec![0.0] }.is_identity()); + let many: Vec<(f64, f64)> = (0..5000).map(|i| (i as f64, i as f64)).collect(); + assert_eq!(MonotoneCurve::new(&many).points().len(), MAX_POINTS); + let bad = MonotoneCurve::new(&[(f64::NAN, 0.0), (0.2, f64::INFINITY), (0.5, 0.5)]); + assert!(bad.is_identity()); + // Differences between these would overflow to infinity and give NaN slopes. + let far = MonotoneCurve::new(&[(-1e308, -1e308), (0.5, 0.25), (1e308, 1e308)]); + assert!(far.is_identity()); + let wide = MonotoneCurve::new(&[(-1e6, -1e6), (1e6, 1e6), (0.0, 0.5)]); + assert!(wide.eval(3.0).is_finite()); + // A subnormal secant next to a normal one: the tangent over that secant overflows. + let flat_then_steep = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 1e-310), (1.0, 1.0)]); + assert!(flat_then_steep.knots().flatten().all(f64::is_finite)); + let mut prev = -1.0; + for i in 0..=1000 { + let y = flat_then_steep.eval(f64::from(i) / 1000.0); + assert!(y.is_finite() && y >= prev, "{i} {y}"); + prev = y; + } + } +} diff --git a/crates/color-transform/src/lib.rs b/crates/color-transform/src/lib.rs new file mode 100644 index 000000000..7708cd75e --- /dev/null +++ b/crates/color-transform/src/lib.rs @@ -0,0 +1,21 @@ +//! Color transforms for the Craft apps. +//! +//! - [`Mat3`], CIE [`Xy`] chromaticities and RGB spaces defined by primaries and a white point +//! ([`RgbSpace`]), with Bradford chromatic adaptation ([`bradford`]). +//! - White balance by correlated color temperature and tint ([`cct`]). +//! - OkLab and OkLCh ([`oklab`]). +//! - Monotone tone curves and 1D lookup tables ([`curve`]). +//! - PQ tone mapping with the reference EETF of Report ITU-R BT.2408 Annex 5 ([`tonemap`]). +//! +//! Frame color tags, Y'CbCr matrices and the transfer functions (sRGB, PQ, HLG) are in +//! `craft-color`; this crate builds on them. Every function that runs per pixel works on `f32` +//! without allocating, and builds for `wasm32-unknown-unknown`. +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod cct; +pub mod curve; +pub mod oklab; +mod space; +pub mod tonemap; + +pub use space::{BRADFORD, D50, D65, DISPLAY_P3, Mat3, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz}; diff --git a/crates/color-transform/src/oklab.rs b/crates/color-transform/src/oklab.rs new file mode 100644 index 000000000..73f5f7e4d --- /dev/null +++ b/crates/color-transform/src/oklab.rs @@ -0,0 +1,246 @@ +//! OkLab and OkLCh, as Björn Ottosson defined them in "A perceptual color space for image +//! processing" (2020). +//! +//! [`from_linear_srgb`] and [`to_linear_srgb`] use the published linear sRGB matrices. +//! [`OkLab::for_space`] builds the conversion for any [`RgbSpace`] from the published XYZ +//! matrix, adapting the space's white to D65 first (Bradford). + +use crate::{D65, Mat3, RgbSpace, bradford}; + +/// XYZ (D65) to approximate cone responses (the published M1). +pub const XYZ_TO_LMS: Mat3 = + Mat3([[0.8189330101, 0.3618667424, -0.1288597137], [0.0329845436, 0.9293118715, 0.0361456387], [0.0482003018, 0.2643662691, 0.6338517070]]); +/// Cube-rooted cone responses to Lab (the published M2). +pub const LMS_TO_LAB: Mat3 = + Mat3([[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660]]); + +/// Linear sRGB to cone responses (published with the linear sRGB conversion). +pub const SRGB_TO_LMS: Mat3 = + Mat3([[0.4122214708, 0.5363325363, 0.0514459929], [0.2119034982, 0.6806995451, 0.1073969566], [0.0883024619, 0.2817188376, 0.6299787005]]); +/// Cone responses to linear sRGB (published with the linear sRGB conversion). +pub const LMS_TO_SRGB: Mat3 = + Mat3([[4.0767416621, -3.3077115913, 0.2309699292], [-1.2684380046, 2.6097574011, -0.3413193965], [-0.0041960863, -0.7034186147, 1.7076147010]]); +/// Lab to cube-rooted cone responses (published with the linear sRGB conversion). +pub const LAB_TO_LMS: Mat3 = Mat3([[1.0, 0.3963377774, 0.2158037573], [1.0, -0.1055613458, -0.0638541728], [1.0, -0.0894841775, -1.2914855480]]); + +const fn f32s(m: &Mat3) -> [[f32; 3]; 3] { + let m = &m.0; + [ + [m[0][0] as f32, m[0][1] as f32, m[0][2] as f32], + [m[1][0] as f32, m[1][1] as f32, m[1][2] as f32], + [m[2][0] as f32, m[2][1] as f32, m[2][2] as f32], + ] +} + +const SRGB_LMS: [[f32; 3]; 3] = f32s(&SRGB_TO_LMS); +const LMS_SRGB: [[f32; 3]; 3] = f32s(&LMS_TO_SRGB); +const LAB: [[f32; 3]; 3] = f32s(&LMS_TO_LAB); +const LAB_INV: [[f32; 3]; 3] = f32s(&LAB_TO_LMS); + +#[inline] +fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] { + [ + m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2], + m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2], + m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2], + ] +} + +/// Linear sRGB (BT.709 primaries, D65) to OkLab `[L, a, b]`. +#[inline] +pub fn from_linear_srgb(rgb: [f32; 3]) -> [f32; 3] { + mul(&LAB, mul(&SRGB_LMS, rgb).map(f32::cbrt)) +} + +/// OkLab to linear sRGB. +#[inline] +pub fn to_linear_srgb(lab: [f32; 3]) -> [f32; 3] { + mul(&LMS_SRGB, mul(&LAB_INV, lab).map(|v| v * v * v)) +} + +/// XYZ (D65, white Y = 1) to OkLab. +pub fn from_xyz(xyz: [f64; 3]) -> [f64; 3] { + LMS_TO_LAB.apply(XYZ_TO_LMS.apply(xyz).map(f64::cbrt)) +} + +/// The `f64` matrices [`OkLab::for_space`] starts from: linear RGB in `space` to cone responses +/// (the white adapted to D65 by Bradford), and back. `None` when the first has no inverse. Code +/// that builds its matrices once per render in `f64` uses these with [`LMS_TO_LAB`] and +/// [`LAB_TO_LMS`]. +pub fn lms_matrices(space: &RgbSpace) -> Option<(Mat3, Mat3)> { + let to_lms = XYZ_TO_LMS.mul(&bradford(space.white, D65)).mul(&space.to_xyz()); + to_lms.inverse().map(|from_lms| (to_lms, from_lms)) +} + +/// OkLab to OkLCh `[L, C, h]`, with the hue in radians from −π to π. +#[inline] +pub fn lab_to_lch(lab: [f32; 3]) -> [f32; 3] { + [lab[0], lab[1].hypot(lab[2]), lab[2].atan2(lab[1])] +} + +/// OkLCh to OkLab. +#[inline] +pub fn lch_to_lab(lch: [f32; 3]) -> [f32; 3] { + let (s, c) = lch[2].sin_cos(); + [lch[0], lch[1] * c, lch[1] * s] +} + +/// The OkLab conversion for one RGB space, with its matrices precomputed in `f32`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OkLab { + to_lms: [[f32; 3]; 3], + from_lms: [[f32; 3]; 3], +} + +impl OkLab { + /// The conversion for linear RGB in `space`. + pub fn for_space(space: &RgbSpace) -> OkLab { + let pair = lms_matrices(space).map(|(to_lms, from_lms)| (to_lms.to_f32(), from_lms.to_f32())); + let finite = |m: &[[f32; 3]; 3]| m.iter().flatten().all(|v| v.is_finite()); + match pair { + Some((to_lms, from_lms)) if finite(&to_lms) && finite(&from_lms) => OkLab { to_lms, from_lms }, + // A matrix with no inverse or with an entry beyond f32 falls back to XYZ_TO_LMS + // alone, the matrix a space gets when its primaries and its white are both rejected. + _ => OkLab { to_lms: f32s(&XYZ_TO_LMS), from_lms: XYZ_TO_LMS.inverse().unwrap_or(Mat3::IDENTITY).to_f32() }, + } + } + + /// The `f32` matrices, row-major: linear RGB to cone responses, and back. GPU passes that + /// convert to OkLab use these with [`LMS_TO_LAB`]. + pub fn matrices(&self) -> ([[f32; 3]; 3], [[f32; 3]; 3]) { + (self.to_lms, self.from_lms) + } + + /// Linear RGB to OkLab. + #[inline] + pub fn from_rgb(&self, rgb: [f32; 3]) -> [f32; 3] { + mul(&LAB, mul(&self.to_lms, rgb).map(f32::cbrt)) + } + + /// OkLab to linear RGB. + #[inline] + pub fn to_rgb(&self, lab: [f32; 3]) -> [f32; 3] { + mul(&self.from_lms, mul(&LAB_INV, lab).map(|v| v * v * v)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{D50, REC2020, SRGB, Xy}; + + /// The table of XYZ values and their OkLab coordinates in Ottosson's definition, rounded + /// to three decimals. + #[test] + fn xyz_matches_the_published_table() { + let table = [ + ([0.950, 1.000, 1.089], [1.000, 0.000, 0.000]), + ([1.000, 0.000, 0.000], [0.450, 1.236, -0.019]), + ([0.000, 1.000, 0.000], [0.922, -0.671, 0.263]), + ([0.000, 0.000, 1.000], [0.153, -1.415, -0.449]), + ]; + for (xyz, want) in table { + let lab = from_xyz(xyz); + for i in 0..3 { + assert!((lab[i] - want[i]).abs() < 6e-4, "{xyz:?} -> {lab:?}"); + } + } + } + + /// CSS Color Module Level 4 (section 2, "These are exactly equivalent") gives #7654CD as + /// oklab(54.43237% 0.0681665 -0.1656703). + #[test] + fn an_srgb_color_matches_css_color_4() { + let rgb = [0x76, 0x54, 0xCD].map(|v: u8| craft_color::srgb_to_linear(f32::from(v) / 255.0)); + let lab = from_linear_srgb(rgb); + let want = [0.5443237, 0.0681665, -0.1656703]; + for i in 0..3 { + assert!((lab[i] - want[i]).abs() < 2e-4, "{lab:?}"); + } + } + + #[test] + fn the_srgb_matrices_and_the_space_built_from_xyz_agree() { + let srgb = OkLab::for_space(&SRGB); + for c in [[0.1, 0.5, 0.9], [1.0, 0.0, 0.0], [0.02, 0.03, 0.01], [1.0, 1.0, 1.0]] { + let a = from_linear_srgb(c); + let b = srgb.from_rgb(c); + for i in 0..3 { + assert!((a[i] - b[i]).abs() < 2e-4, "{c:?} {a:?} {b:?}"); + } + } + } + + #[test] + fn white_is_l1_and_grays_have_no_chroma_in_every_space() { + let d50 = crate::RgbSpace { white: D50, ..SRGB }; + for space in [SRGB, REC2020, d50] { + let ok = OkLab::for_space(&space); + let w = ok.from_rgb([1.0, 1.0, 1.0]); + assert!((w[0] - 1.0).abs() < 2e-4 && w[1].abs() < 2e-4 && w[2].abs() < 2e-4, "{space:?} {w:?}"); + let g = ok.from_rgb([0.18, 0.18, 0.18]); + assert!(g[1].abs() < 2e-4 && g[2].abs() < 2e-4, "{space:?} {g:?}"); + } + } + + #[test] + fn conversions_round_trip() { + let ok = OkLab::for_space(&REC2020); + for c in [[0.1, 0.5, 0.9], [1.0, 0.0, 0.0], [0.02, 0.03, 0.01], [2.0, 1.5, 0.3], [-0.1, 0.4, 0.2]] { + let a = to_linear_srgb(from_linear_srgb(c)); + let b = ok.to_rgb(ok.from_rgb(c)); + for i in 0..3 { + assert!((a[i] - c[i]).abs() < 1e-4 * c[i].abs().max(1.0), "{c:?} {a:?}"); + assert!((b[i] - c[i]).abs() < 1e-4 * c[i].abs().max(1.0), "{c:?} {b:?}"); + } + } + let lab = lch_to_lab(lab_to_lch([0.5, 0.1, -0.05])); + assert!((lab[1] - 0.1).abs() < 1e-6 && (lab[2] + 0.05).abs() < 1e-6); + } + + #[test] + fn a_space_that_does_not_exist_does_not_produce_nan() { + let bad = crate::RgbSpace { r: Xy::new(0.3, 0.0), ..SRGB }; + let ok = OkLab::for_space(&bad); + assert!(ok.from_rgb([0.5, 0.5, 0.5]).iter().all(|v| v.is_finite())); + } + + #[test] + fn the_f64_matrices_match_the_published_xyz_conversion() { + let (to, from) = lms_matrices(&SRGB).unwrap(); + let p = to.mul(&from); + for i in 0..3 { + for j in 0..3 { + assert!((p.0[i][j] - if i == j { 1.0 } else { 0.0 }).abs() < 1e-12, "{p:?}"); + } + } + // The published linear sRGB matrix and the one built from XYZ differ by at most 3.1e-4. + for i in 0..3 { + for j in 0..3 { + assert!((to.0[i][j] - SRGB_TO_LMS.0[i][j]).abs() < 5e-4, "{to:?}"); + } + } + for c in [[0.1, 0.5, 0.9], [1.0, 1.0, 1.0]] { + let lab = LMS_TO_LAB.apply(to.apply(c).map(f64::cbrt)); + let f = OkLab::for_space(&SRGB).from_rgb(c.map(|v| v as f32)); + for i in 0..3 { + assert!((lab[i] - f64::from(f[i])).abs() < 1e-5, "{c:?} {lab:?} {f:?}"); + } + } + let bad = crate::RgbSpace { r: Xy::new(0.3, 0.0), ..SRGB }; + assert!(lms_matrices(&bad).is_some_and(|(t, _)| t.0.iter().flatten().all(|v| v.is_finite()))); + } + + /// A white this close to y = 0 gives `f64` matrices with entries beyond `f32`. + #[test] + fn a_space_whose_matrices_overflow_f32_does_not_produce_nan() { + let far = crate::RgbSpace { white: Xy::new(0.5, 1e-40), ..SRGB }; + let ok = OkLab::for_space(&far); + let (to, from) = ok.matrices(); + assert!(to.iter().chain(from.iter()).flatten().all(|v| v.is_finite()), "{to:?} {from:?}"); + for c in [[0.0; 3], [0.5, 0.5, 0.5], [1.0, 0.0, 0.0]] { + assert!(ok.from_rgb(c).iter().all(|v| v.is_finite()), "{c:?}"); + assert!(ok.to_rgb(ok.from_rgb(c)).iter().all(|v| v.is_finite()), "{c:?}"); + } + } +} diff --git a/crates/color-transform/src/space.rs b/crates/color-transform/src/space.rs new file mode 100644 index 000000000..c0c1da382 --- /dev/null +++ b/crates/color-transform/src/space.rs @@ -0,0 +1,295 @@ +//! 3×3 matrices, chromaticities, RGB spaces and Bradford chromatic adaptation. + +use craft_cms::math; +use craft_color::Primaries; +use serde::{Deserialize, Serialize}; + +/// A row-major 3×3 matrix. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Mat3(pub [[f64; 3]; 3]); + +impl Mat3 { + pub const IDENTITY: Mat3 = Mat3([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]); + + pub const fn diag(a: f64, b: f64, c: f64) -> Mat3 { + Mat3([[a, 0.0, 0.0], [0.0, b, 0.0], [0.0, 0.0, c]]) + } + + /// `self × o`: applying the product applies `o` first ([`math::mul`]). + pub fn mul(&self, o: &Mat3) -> Mat3 { + Mat3(math::mul(&self.0, &o.0)) + } + + /// [`math::apply`]. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + math::apply(&self.0, v) + } + + /// [`math::det`]. + pub fn determinant(&self) -> f64 { + math::det(&self.0) + } + + /// The inverse, or `None` when the matrix holds a non-finite value, is singular to within + /// rounding (the determinant is at most 1e-12 times the cube of the largest entry), or has an + /// inverse with an entry beyond the range of `f64` ([`math::inverse`]). + pub fn inverse(&self) -> Option { + math::inverse(&self.0).map(Mat3) + } + + pub fn transpose(&self) -> Mat3 { + let m = &self.0; + Mat3([[m[0][0], m[1][0], m[2][0]], [m[0][1], m[1][1], m[2][1]], [m[0][2], m[1][2], m[2][2]]]) + } + + /// The matrix as `f32`, row-major, for per-pixel code and GPU uniforms. + pub fn to_f32(&self) -> [[f32; 3]; 3] { + self.0.map(|r| r.map(|v| v as f32)) + } +} + +/// A row-major array, the form `craft_cms::math::Mat3` takes. +impl From<[[f64; 3]; 3]> for Mat3 { + fn from(m: [[f64; 3]; 3]) -> Mat3 { + Mat3(m) + } +} + +impl From for [[f64; 3]; 3] { + fn from(m: Mat3) -> [[f64; 3]; 3] { + m.0 + } +} + +/// A CIE 1931 xy chromaticity. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct Xy { + pub x: f64, + pub y: f64, +} + +impl Xy { + pub const fn new(x: f64, y: f64) -> Xy { + Xy { x, y } + } + + /// XYZ with Y = 1, or `None` when `y` is not above 0, a coordinate is not finite, or `y` is + /// so small that X or Z overflows. + pub fn to_xyz(self) -> Option<[f64; 3]> { + if !(self.x.is_finite() && self.y.is_finite() && self.y > 0.0) { + return None; + } + let xyz = math::xy_to_xyz([self.x, self.y]); + xyz.iter().all(|v| v.is_finite()).then_some(xyz) + } + + /// The chromaticity of an XYZ triple, or `None` when X + Y + Z is not above 0. + pub fn from_xyz(v: [f64; 3]) -> Option { + let s = v[0] + v[1] + v[2]; + if !(s.is_finite() && s > 0.0) { + return None; + } + Some(Xy::new(v[0] / s, v[1] / s)) + } +} + +/// CIE standard illuminant D65, as ITU-R BT.709 and BT.2020 give it. +pub const D65: Xy = Xy::new(0.3127, 0.3290); +/// CIE illuminant D50, the ICC profile connection space white. +pub const D50: Xy = Xy::new(0.3457, 0.3585); + +/// An RGB color space: three primaries and a white point. A space read at run time (from a +/// file's primaries or a stream's mastering metadata) is built with a struct literal. +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +pub struct RgbSpace { + pub r: Xy, + pub g: Xy, + pub b: Xy, + pub white: Xy, +} + +/// The ITU-R BT.709 primaries, which sRGB (IEC 61966-2-1) shares. +pub const SRGB: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.30, 0.60), b: Xy::new(0.15, 0.06), white: D65 }; +/// ITU-R BT.601, 625-line systems. +pub const REC601_625: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.29, 0.60), b: Xy::new(0.15, 0.06), white: D65 }; +/// ITU-R BT.601, 525-line systems. +pub const REC601_525: RgbSpace = RgbSpace { r: Xy::new(0.630, 0.340), g: Xy::new(0.310, 0.595), b: Xy::new(0.155, 0.070), white: D65 }; +/// ITU-R BT.2020 (and BT.2100). +pub const REC2020: RgbSpace = RgbSpace { r: Xy::new(0.708, 0.292), g: Xy::new(0.170, 0.797), b: Xy::new(0.131, 0.046), white: D65 }; +/// The DCI-P3 primaries with a D65 white (SMPTE EG 432-1). +pub const DISPLAY_P3: RgbSpace = RgbSpace { r: Xy::new(0.680, 0.320), g: Xy::new(0.265, 0.690), b: Xy::new(0.150, 0.060), white: D65 }; + +impl From for RgbSpace { + fn from(p: Primaries) -> RgbSpace { + match p { + Primaries::Bt709 => SRGB, + Primaries::Bt601_625 => REC601_625, + Primaries::Bt601_525 => REC601_525, + Primaries::Bt2020 => REC2020, + Primaries::P3D65 => DISPLAY_P3, + } + } +} + +impl RgbSpace { + /// Linear RGB in this space to XYZ, with the space's white at Y = 1 (the normalized primary + /// matrix of SMPTE RP 177). Primaries or a white that do not define a space (collinear + /// primaries, a `y` of 0, a white on a primary or on the line between two) give the identity. + pub fn to_xyz(&self) -> Mat3 { + let (Some(r), Some(g), Some(b), Some(w)) = (self.r.to_xyz(), self.g.to_xyz(), self.b.to_xyz(), self.white.to_xyz()) else { + return Mat3::IDENTITY; + }; + let m = Mat3([[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]]); + let Some(inv) = m.inverse() else { return Mat3::IDENTITY }; + let s = inv.apply(w); + let npm = m.mul(&Mat3::diag(s[0], s[1], s[2])); + // A white that gives a primary no weight leaves a matrix with no inverse. + if npm.inverse().is_none() { Mat3::IDENTITY } else { npm } + } + + /// XYZ to linear RGB in this space: the inverse of [`to_xyz`](Self::to_xyz). + pub fn from_xyz(&self) -> Mat3 { + self.to_xyz().inverse().unwrap_or(Mat3::IDENTITY) + } + + /// The luminance weights of R, G and B (the Y row of [`to_xyz`](Self::to_xyz)). + pub fn luma(&self) -> [f64; 3] { + self.to_xyz().0[1] + } + + /// Linear RGB in `self` to linear RGB in `dst`, Bradford-adapting between the white points. + pub fn to_space(&self, dst: &RgbSpace) -> Mat3 { + dst.from_xyz().mul(&bradford(self.white, dst.white)).mul(&self.to_xyz()) + } +} + +/// The Bradford cone response matrix (XYZ to sharpened cone responses). +pub const BRADFORD: Mat3 = Mat3(math::BRADFORD); + +/// The Bradford chromatic adaptation matrix (XYZ to XYZ) from white `src` to white `dst`. A +/// white that [`Xy::to_xyz`] rejects gives the identity. +pub fn bradford(src: Xy, dst: Xy) -> Mat3 { + if src == dst { + return Mat3::IDENTITY; + } + match (src.to_xyz(), dst.to_xyz()) { + (Some(s), Some(d)) => bradford_xyz(s, d), + _ => Mat3::IDENTITY, + } +} + +/// [`bradford`] for whites given as XYZ. A white with a cone response that is not above 0 or +/// not finite, or a pair whose response ratios overflow, gives the identity. +pub fn bradford_xyz(src: [f64; 3], dst: [f64; 3]) -> Mat3 { + math::bradford_checked(src, dst).map_or(Mat3::IDENTITY, Mat3) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn close(a: &Mat3, b: &[[f64; 3]; 3], tol: f64) { + for i in 0..3 { + for j in 0..3 { + assert!((a.0[i][j] - b[i][j]).abs() < tol, "[{i}][{j}] {} vs {}", a.0[i][j], b[i][j]); + } + } + } + + /// IEC 61966-2-1 gives the sRGB RGB to XYZ matrix to four decimals. + #[test] + fn srgb_matrix_matches_iec_61966_2_1() { + close(&SRGB.to_xyz(), &[[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]], 1e-4); + } + + /// ITU-R BT.2020 and BT.709 give the luminance coefficients. + #[test] + fn luminance_weights_match_bt709_and_bt2020() { + for (space, want) in [(SRGB, [0.2126, 0.7152, 0.0722]), (REC2020, [0.2627, 0.6780, 0.0593])] { + let l = space.luma(); + for i in 0..3 { + assert!((l[i] - want[i]).abs() < 1e-4, "{space:?} {l:?}"); + } + } + } + + /// The Bradford matrix from D65 to D50 as Lindbloom's chromatic adaptation tables print it, + /// with his reference whites. + #[test] + fn bradford_d65_to_d50_matches_the_published_matrix() { + let m = bradford_xyz([0.95047, 1.0, 1.08883], [0.96422, 1.0, 0.82521]); + let want = [[1.0478112, 0.0228866, -0.0501270], [0.0295424, 0.9904844, -0.0170491], [-0.0092345, 0.0150436, 0.7521316]]; + close(&m, &want, 1e-6); + } + + #[test] + fn adaptation_maps_white_to_white_and_round_trips() { + let m = bradford(D65, D50); + let w = m.apply(D65.to_xyz().unwrap()); + let d50 = D50.to_xyz().unwrap(); + for i in 0..3 { + assert!((w[i] - d50[i]).abs() < 1e-12); + } + let back = bradford(D50, D65).mul(&m); + close(&back, &Mat3::IDENTITY.0, 1e-12); + let v = SRGB.to_space(&REC2020).apply([1.0, 1.0, 1.0]); + assert!(v.iter().all(|c| (c - 1.0).abs() < 1e-9), "{v:?}"); + } + + /// The BT.709 to BT.2020 conversion matrix of Report ITU-R BT.2087 (equation 2). + #[test] + fn bt709_to_bt2020_matches_bt2087() { + let want = [[0.6274, 0.3293, 0.0433], [0.0691, 0.9195, 0.0114], [0.0164, 0.0880, 0.8956]]; + close(&SRGB.to_space(&REC2020), &want, 1e-4); + } + + #[test] + fn primaries_tags_map_to_spaces() { + assert_eq!(RgbSpace::from(Primaries::Bt2020), REC2020); + assert_eq!(RgbSpace::from(Primaries::default()), SRGB); + } + + #[test] + fn hostile_whites_and_primaries_do_not_produce_nan() { + assert_eq!(Xy::new(0.3, 0.0).to_xyz(), None); + assert_eq!(Xy::new(f64::NAN, 0.3).to_xyz(), None); + assert_eq!(Xy::new(0.3, 1e-320).to_xyz(), None); + assert_eq!(bradford(Xy::new(0.3, 1e-320), D65), Mat3::IDENTITY); + assert_eq!(Xy::from_xyz([0.0, 0.0, 0.0]), None); + assert_eq!(bradford(Xy::new(0.3, 0.0), D65), Mat3::IDENTITY); + assert_eq!(bradford(D65, Xy::new(f64::INFINITY, 0.3)), Mat3::IDENTITY); + assert_eq!(bradford_xyz([-1.0, 1.0, 1.0], [0.95, 1.0, 1.09]), Mat3::IDENTITY); + let flat = RgbSpace { r: Xy::new(0.2, 0.2), g: Xy::new(0.3, 0.3), b: Xy::new(0.4, 0.4), white: D65 }; + assert_eq!(flat.to_xyz(), Mat3::IDENTITY); + assert_eq!(Mat3([[f64::NAN; 3]; 3]).inverse(), None); + // The determinant, 1e-312, has no finite reciprocal; the inverse itself is finite. + let tiny = Mat3::diag(1e-104, 1e-104, 1e-104).inverse().unwrap(); + close(&tiny, &[[1e104, 0.0, 0.0], [0.0, 1e104, 0.0], [0.0, 0.0, 1e104]], 1e93); + // A determinant beyond f64 in either direction still leaves a finite inverse. + let small = Mat3::diag(1e-200, 1e-200, 1e-200).inverse().unwrap(); + close(&small, &Mat3::diag(1e200, 1e200, 1e200).0, 1e186); + let large = Mat3::diag(1e110, 1e110, 1e110).inverse().unwrap(); + close(&large, &Mat3::diag(1e-110, 1e-110, 1e-110).0, 1e-124); + // An inverse with entries beyond f64 is no inverse. + assert_eq!(Mat3::diag(1e-310, 1e-310, 1e-310).inverse(), None); + assert_eq!(Mat3([[0.0; 3]; 3]).inverse(), None); + assert_eq!(Mat3::diag(f64::MAX, f64::MAX, f64::MAX).inverse().map(|m| m.0[0][0]), Some(1.0 / f64::MAX)); + // A white on a primary leaves two primaries with no weight: no space. + let on_red = RgbSpace { white: SRGB.r, ..SRGB }; + assert_eq!(on_red.to_xyz(), Mat3::IDENTITY); + assert_eq!(on_red.from_xyz(), Mat3::IDENTITY); + // Cone responses this small give scale ratios beyond f64. + assert_eq!(bradford_xyz([1e-320; 3], D65.to_xyz().unwrap()), Mat3::IDENTITY); + } + + /// A space built from primaries read at run time saves and loads, and its matrix converts + /// to and from a plain array. + #[test] + fn spaces_save_and_load() { + let read = RgbSpace { r: Xy::new(0.7, 0.29), g: Xy::new(0.16, 0.8), b: Xy::new(0.13, 0.05), white: D50 }; + let json = serde_json::to_string(&read).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), read); + let m: [[f64; 3]; 3] = read.to_xyz().into(); + assert_eq!(Mat3::from(m), read.to_xyz()); + } +} diff --git a/crates/color-transform/src/tonemap.rs b/crates/color-transform/src/tonemap.rs new file mode 100644 index 000000000..45bafd2cd --- /dev/null +++ b/crates/color-transform/src/tonemap.rs @@ -0,0 +1,406 @@ +//! PQ tone mapping with the reference EETF of Report ITU-R BT.2408-8, Annex 5 ("Displaying +//! PQ: calculating the EETF"), which Report ITU-R BT.2390 described before it. +//! +//! The EETF works on PQ (SMPTE ST 2084) values: it keeps the range below a knee 1:1, rolls off +//! the range above it with a Hermite spline so the source peak lands on the target peak, and +//! lifts the target black with a tapered offset. [`ToneMap`] applies it to RGB by max(R, G, B), +//! the "maxRGB" option of the Annex, as a ratio, so hue and saturation are kept. + +use craft_color::{REFERENCE_WHITE_NITS, pq_eotf, pq_inverse_eotf}; + +/// PQ code value (0..1) of `nits`. +fn pq(nits: f64) -> f64 { + f64::from(pq_inverse_eotf((nits / 10_000.0).clamp(0.0, 1.0) as f32)) +} + +/// Luminance in nits of the PQ value `e`. +fn nits(e: f64) -> f64 { + f64::from(pq_eotf(e.clamp(0.0, 1.0) as f32)) * 10_000.0 +} + +/// A luminance in nits: NaN, negative values and infinity read as 0, 0 and 10 000. +fn sane(n: f64) -> f64 { + if n.is_nan() { 0.0 } else { n.clamp(0.0, 10_000.0) } +} + +/// The reference EETF from a mastering display (black `src_black`, peak `src_peak`) to a +/// target display (black `dst_black`, peak `dst_peak`), all in nits. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Eetf { + pb: f64, + span: f64, + min_lum: f64, + max_lum: f64, + ks: f64, + /// The spline's slope at the knee: 1 within the Annex's range. + slope: f64, + /// The black lift's exponent: 4 within the Annex's range. + lift: f64, + /// The E2 at which the black lift reaches 0: 1 within the Annex's range. + reach: f64, +} + +impl Eetf { + /// Luminances are clamped to 0..10 000 nits. A target black below the source black adds no + /// lift. When the source range is empty the EETF passes values through. + /// + /// When the target peak sits below a third of the source range in PQ, the Annex's knee + /// (KS = 1.5 maxLum − 0.5) is negative. The knee is then 0 and the spline starts with a + /// slope of 3 maxLum, the steepest that keeps it rising. + /// + /// The Annex's black lift, minLum × (1 − E2)⁴, makes the output fall near black when minLum + /// is above 0.25, and lifts the peak well above the target peak. The lift here is + /// minLum × (1 − E2 / r)ᵏ with r = max(T, min(1, 2 − 4 minLum)) and k = min(4, r / minLum), + /// where T, the top of the output, is the smaller of maxLum and 1. Up to minLum 0.25 this is + /// the Annex's lift. Above it, k is the largest exponent that keeps the output rising, r moves + /// continuously from 1 down to T, and from minLum 0.5 the lift reaches 0 at the top of the + /// output. A target black above the source peak reads as the source peak. + /// + /// A target peak at or below the source black would put every output at the source black + /// or above it; the source black then reads as 0. A target black above the target peak + /// reads as the target peak. A target peak that is NaN or not above 0 names no display, and + /// the EETF then passes values through. + pub fn new(src_black: f64, src_peak: f64, dst_black: f64, dst_peak: f64) -> Eetf { + let pb = pq(sane(src_black)); + let pass = Eetf { pb, span: 0.0, min_lum: 0.0, max_lum: 1.0, ks: 1.0, slope: 1.0, lift: 4.0, reach: 1.0 }; + if dst_peak.is_nan() || dst_peak <= 0.0 { + return pass; + } + let (dst_peak, pw) = (sane(dst_peak), pq(sane(src_peak))); + let dst_black = sane(dst_black).min(dst_peak); + if pw <= pb { + return pass; + } + let pb = if pq(dst_peak) <= pb { 0.0 } else { pb }; + let span = pw - pb; + // Step 2. + let min_lum = ((pq(dst_black) - pb) / span).max(0.0); + let max_lum = ((pq(dst_peak) - pb) / span).max(0.0); + let ks = 1.5 * max_lum - 0.5; + let (ks, slope) = if ks >= 0.0 { (ks, 1.0) } else { (0.0, 3.0 * max_lum) }; + // E2 ends at `top`. The output's slope at E2 = 0 is 1 − lift × minLum / reach, so the + // exponent is at most reach / minLum. Up to minLum 0.25 this gives the Annex's (1, 4); both + // change continuously above it, and reach is `top` from minLum 0.5. A target black above + // the source peak (minLum above `top`) reads as the source peak. + let top = max_lum.min(1.0); + let min_lum = min_lum.min(top); + let reach = top.max((2.0 - 4.0 * min_lum).min(1.0)); + let lift = if min_lum > 0.0 { (reach / min_lum).min(4.0) } else { 4.0 }; + Eetf { pb, span, min_lum, max_lum, ks, slope, lift, reach } + } + + /// Whether the EETF passes every value through unchanged. + pub fn is_identity(&self) -> bool { + self.span <= 0.0 || (self.max_lum >= 1.0 && self.min_lum <= 0.0) + } + + /// The EETF on a PQ value (0..1): steps 1 to 5 of the Annex. Unless the EETF is the + /// identity, values above the source peak map as the peak does. + pub fn apply_pq(&self, e: f64) -> f64 { + if self.is_identity() || e.is_nan() { + return e; + } + // Step 1. + let e1 = ((e - self.pb) / self.span).clamp(0.0, 1.0); + // Steps 3 and 4: 1:1 below the knee, the Hermite spline above it. + let e2 = if e1 < self.ks || self.max_lum >= 1.0 { + e1 + } else { + let t = (e1 - self.ks) / (1.0 - self.ks); + let (t2, t3) = (t * t, t * t * t); + (2.0 * t3 - 3.0 * t2 + 1.0) * self.ks + (t3 - 2.0 * t2 + t) * (1.0 - self.ks) * self.slope + (-2.0 * t3 + 3.0 * t2) * self.max_lum + }; + let e3 = if self.reach == 1.0 && self.lift == 4.0 { + e2 + self.min_lum * (1.0 - e2).powi(4) + } else { + e2 + self.min_lum * (1.0 - e2 / self.reach).max(0.0).powf(self.lift) + }; + // Step 5. + e3 * self.span + self.pb + } + + /// The EETF on a luminance in nits. + pub fn apply_nits(&self, n: f64) -> f64 { + nits(self.apply_pq(pq(sane(n)))) + } +} + +/// The BT.2408 EETF from a display of peak `src_peak` to one of peak `dst_peak` (nits), with +/// black at 0. +pub fn eetf(n: f64, src_peak: f64, dst_peak: f64) -> f64 { + Eetf::new(0.0, src_peak, 0.0, dst_peak).apply_nits(n) +} + +/// Entries in [`ToneMap`]'s table. +const TABLE: usize = 4096; + +/// Tone mapping of linear RGB, where 1.0 is reference white, from a source peak to a target +/// peak. It applies the EETF (black at 0) to max(R, G, B) and scales the three channels by the +/// same ratio. The ratios are tabulated on a PQ axis once, so [`apply`](Self::apply) does not +/// allocate. +#[derive(Clone, Debug, PartialEq)] +pub struct ToneMap { + src_peak: f32, + dst_peak: f32, + white: f32, + identity: bool, + /// Output nits over input nits, at PQ values `i / (TABLE − 1)`. + ratio: Vec, +} + +impl ToneMap { + /// Tone mapping with reference white at `craft_color::REFERENCE_WHITE_NITS` (203 nits, + /// Report ITU-R BT.2408). + pub fn new(src_peak_nits: f64, dst_peak_nits: f64) -> ToneMap { + ToneMap::with_reference_white(src_peak_nits, dst_peak_nits, REFERENCE_WHITE_NITS) + } + + /// Tone mapping where 1.0 is `white_nits`. A white that is not above 0 or not finite reads + /// as 203 nits, and one above 10 000 nits as 10 000. + pub fn with_reference_white(src_peak_nits: f64, dst_peak_nits: f64, white_nits: f64) -> ToneMap { + let (s, d) = (sane(src_peak_nits), sane(dst_peak_nits)); + let white = if white_nits.is_finite() && white_nits > 0.0 { white_nits.min(10_000.0) } else { REFERENCE_WHITE_NITS }; + let curve = Eetf::new(0.0, s, 0.0, d); + let identity = curve.is_identity(); + let ratio = if identity { + Vec::new() + } else { + (0..TABLE) + .map(|i| { + let e = i as f64 / (TABLE - 1) as f64; + let n = nits(e); + if n <= 1e-6 { 1.0 } else { (curve.apply_nits(n) / n) as f32 } + }) + .collect() + }; + ToneMap { src_peak: s as f32, dst_peak: d as f32, white: white as f32, identity, ratio } + } + + /// Whether [`apply`](Self::apply) returns its input (the target peak is at or above the + /// source peak). + pub fn is_identity(&self) -> bool { + self.identity + } + + /// One pixel of linear RGB, 1.0 = reference white. + #[inline] + pub fn apply(&self, c: [f32; 3]) -> [f32; 3] { + if self.identity { + return c; + } + let m = c[0].max(c[1]).max(c[2]); + // NaN (all three channels NaN) and values at or below 0 pass through. + if m.is_nan() || m <= 0.0 { + return c; + } + let n = m * self.white; + if n >= self.src_peak { + // The brightest channel lands on the target peak. Dividing by m first keeps an + // infinite channel (or an n that overflows) from giving infinity times 0. + let peak = self.dst_peak / self.white; + return c.map(|v| if v >= m { peak } else { v / m * peak }); + } + let k = self.lookup(pq_inverse_eotf(n / 10_000.0)); + c.map(|v| v * k) + } + + #[inline] + fn lookup(&self, e: f32) -> f32 { + let last = self.ratio.len().saturating_sub(1); + let p = e.clamp(0.0, 1.0) * last as f32; + let i = (p as usize).min(last.saturating_sub(1)); + let (Some(a), Some(b)) = (self.ratio.get(i), self.ratio.get(i + 1)) else { return 1.0 }; + a + (b - a) * (p - i as f32) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Report ITU-R BT.2408 lists 203 nits (HDR reference white) at 58 % PQ and 1000 nits at + /// 75 %; these check the PQ functions the EETF stands on. + #[test] + fn pq_reference_levels() { + assert!((pq(203.0) - 0.58).abs() < 0.005, "{}", pq(203.0)); + assert!((pq(1000.0) - 0.75).abs() < 0.005, "{}", pq(1000.0)); + assert!((nits(pq(100.0)) - 100.0).abs() < 0.05); + } + + /// Values computed from the Annex 5 equations and the ST 2084 constants by a separate + /// implementation, 1000 nits to 100 nits. + #[test] + fn matches_an_independent_evaluation_of_the_annex() { + let curve = Eetf::new(0.0, 1000.0, 0.0, 100.0); + for (input, want) in ORACLE_1000_TO_100 { + let got = curve.apply_nits(input); + assert!((got - want).abs() <= want * 2e-4 + 1e-4, "{input} nits: {got} vs {want}"); + } + let lifted = Eetf::new(0.0, 1000.0, 0.1, 100.0); + for (input, want) in ORACLE_1000_TO_100_BLACK_01 { + let got = lifted.apply_nits(input); + assert!((got - want).abs() <= want * 2e-4 + 1e-4, "{input} nits: {got} vs {want}"); + } + } + + const ORACLE_1000_TO_100: [(f64, f64); 9] = [ + (0.0, 0.000000), + (1.0, 1.000000), + (10.0, 10.000000), + (50.0, 46.142955), + (100.0, 69.454403), + (203.0, 88.243641), + (400.0, 97.598409), + (700.0, 99.854805), + (1000.0, 100.000000), + ]; + const ORACLE_1000_TO_100_BLACK_01: [(f64, f64); 9] = [ + (0.0, 0.100000), + (1.0, 1.608558), + (10.0, 11.080978), + (50.0, 47.142334), + (100.0, 70.309850), + (203.0, 88.992667), + (400.0, 98.298831), + (700.0, 100.543945), + (1000.0, 100.688420), + ]; + + #[test] + fn the_knee_keeps_low_values_and_lands_the_peak_on_the_target() { + let curve = Eetf::new(0.0, 1000.0, 0.0, 100.0); + assert!((curve.apply_nits(1000.0) - 100.0).abs() < 0.05); + assert!((curve.apply_nits(5000.0) - 100.0).abs() < 0.05, "above the source peak"); + // Below the knee (KS = 1.5 maxLum − 0.5) the EETF is 1:1. + let below = nits(curve.ks * pq(1000.0) * 0.99); + assert!((curve.apply_nits(below) - below).abs() < below * 1e-4, "{below}"); + let mut prev = 0.0; + for i in 0..=1000 { + let out = curve.apply_pq(f64::from(i) / 1000.0 * pq(1000.0)); + assert!(out >= prev - 1e-12, "monotone"); + prev = out; + } + assert!(Eetf::new(0.0, 100.0, 0.0, 1000.0).is_identity()); + assert_eq!(eetf(400.0, 100.0, 1000.0) as f32, nits(pq(400.0)) as f32); + } + + /// 10 000 nits to 1 nit puts the target peak below a third of the source range: the curve + /// still rises from 0 to the target peak and keeps shadows apart. + #[test] + fn a_deep_reduction_keeps_rising_without_crushing_shadows() { + let curve = Eetf::new(0.0, 10_000.0, 0.0, 1.0); + let mut prev = -1.0; + for i in 0..=2000 { + let out = curve.apply_pq(f64::from(i) / 2000.0); + assert!(out > prev || i == 0, "{i}: {out} after {prev}"); + assert!(out >= 0.0); + prev = out; + } + assert!((curve.apply_nits(10_000.0) - 1.0).abs() < 1e-3); + assert!(curve.apply_nits(0.01) > 0.0 && curve.apply_nits(0.01) < curve.apply_nits(0.1)); + } + + #[test] + fn the_black_lift_raises_black_to_the_target_black() { + let curve = Eetf::new(0.0, 1000.0, 0.1, 100.0); + assert!((curve.apply_nits(0.0) - 0.1).abs() < 1e-3, "{}", curve.apply_nits(0.0)); + // The taper (1 − E2)⁴ is small but not 0 at the target peak, so the peak rises a little. + let peak = curve.apply_nits(1000.0); + assert!(peak > 100.0 && peak < 101.0, "{peak}"); + } + + #[test] + fn a_high_target_black_keeps_the_output_rising_and_lands_the_peak() { + let cases = [(100.0, 100.0), (50.0, 100.0), (10.0, 100.0), (1.0, 100.0), (0.1, 1000.0), (40.0, 4000.0), (2000.0, 4000.0)]; + for (black, peak) in cases { + let curve = Eetf::new(0.0, 1000.0, black, peak); + // A target black above the 1000-nit source peak reads as the source peak. + let want = f64::min(black, 1000.0); + assert!((curve.apply_nits(0.0) - want).abs() < 1e-2 * want.max(1.0), "{black} {peak}: {}", curve.apply_nits(0.0)); + // From minLum 0.5 the lift reaches 0 at the top of the output. + let top = curve.apply_nits(1000.0); + if curve.min_lum >= 0.5 { + assert!((top - f64::min(peak, 1000.0)).abs() < 1e-2 * peak, "{black} {peak}: {top}"); + } + let mut last = curve.apply_pq(0.0); + for i in 1..=1000 { + let out = curve.apply_pq(f64::from(i) / 1000.0); + assert!(out >= last - 1e-12, "{black} {peak} at {i}: {out} < {last}"); + last = out; + } + } + } + + #[test] + fn the_output_changes_continuously_with_the_target_black() { + for peak in [100.0, 300.0, 4000.0] { + let at = |black: f64, n: f64| Eetf::new(0.0, 1000.0, black, peak).apply_pq(pq(n)); + // Target blacks 1/20 000 of the target peak's PQ value apart. + let black = |i: u32| nits(f64::from(i) / 20_000.0 * pq(peak)); + for n in [0.0, 1.0, 100.0, 1000.0] { + let mut last = at(0.0, n); + for i in 1..=20_000 { + let out = at(black(i), n); + assert!((out - last).abs() < 1e-3, "peak {peak}, input {n}, black {}: {last} to {out}", black(i)); + last = out; + } + } + } + } + + #[test] + fn tone_map_keeps_hue_and_maps_the_peak() { + let tm = ToneMap::new(1000.0, 203.0); + let peak = 1000.0 / 203.0; + let out = tm.apply([peak, peak * 0.5, peak * 0.25]); + assert!((out[0] - 1.0).abs() < 1e-3, "{out:?}"); + assert!((out[1] / out[0] - 0.5).abs() < 1e-6 && (out[2] / out[0] - 0.25).abs() < 1e-6); + let low = tm.apply([0.02, 0.01, 0.0]); + assert!((low[0] - 0.02).abs() < 1e-4, "{low:?}"); + assert_eq!(tm.apply([0.0, 0.0, 0.0]), [0.0, 0.0, 0.0]); + assert_eq!(tm.apply([-1.0, -2.0, -0.5]), [-1.0, -2.0, -0.5]); + } + + /// With a target peak above the source peak nothing changes, highlights above the source + /// peak included (they are not raised to the target peak). + #[test] + fn a_brighter_target_leaves_colors_alone() { + let tm = ToneMap::new(1000.0, 4000.0); + assert!(tm.is_identity()); + let hot = [1200.0 / 203.0, 0.5, 0.1]; + assert_eq!(tm.apply(hot), hot); + } + + #[test] + fn hostile_values_do_not_panic_or_spread() { + let tm = ToneMap::new(f64::NAN, f64::INFINITY); + assert!(tm.is_identity()); + let huge = ToneMap::with_reference_white(1000.0, 100.0, 1e100); + assert!((huge.apply([1.0, 1.0, 1.0])[0] - 100.0 / 10_000.0).abs() < 1e-4, "{:?}", huge.apply([1.0, 1.0, 1.0])); + let tm = ToneMap::with_reference_white(1000.0, 100.0, -3.0); + // max() skips NaN, so the other channels are mapped by their own maximum. + assert!(tm.apply([f32::NAN, 0.5, 0.5]).iter().skip(1).all(|v| v.is_finite())); + assert_eq!(tm.apply([f32::INFINITY, 0.5, 0.0]), [100.0 / 203.0, 0.0, 0.0]); + assert_eq!(tm.apply([f32::MAX, f32::MAX, 0.0]), [100.0 / 203.0, 100.0 / 203.0, 0.0]); + // A target peak below the source black: the peak still lands on the target peak. + let dim = Eetf::new(100.0, 1000.0, 0.0, 50.0); + assert!((dim.apply_nits(1000.0) - 50.0).abs() < 0.05, "{}", dim.apply_nits(1000.0)); + assert!(Eetf::new(0.0, 1000.0, 500.0, 100.0).apply_nits(0.0) <= 100.0 + 0.05); + let e = Eetf::new(500.0, 100.0, 0.0, 50.0); + assert!(e.is_identity()); + assert_eq!(e.apply_pq(0.3), 0.3); + assert!(Eetf::new(0.0, 1000.0, 0.0, 100.0).apply_pq(f64::NAN).is_nan()); + } + + /// A target peak that is NaN, 0 or negative passes the picture through instead of turning it + /// black. + #[test] + fn a_missing_target_peak_passes_values_through() { + for peak in [f64::NAN, 0.0, -100.0, f64::NEG_INFINITY] { + let tm = ToneMap::new(1000.0, peak); + assert!(tm.is_identity(), "{peak}"); + assert_eq!(tm.apply([0.8, 0.5, 0.1]), [0.8, 0.5, 0.1], "{peak}"); + assert!(Eetf::new(0.0, 1000.0, 0.0, peak).is_identity(), "{peak}"); + } + } +}