FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
M8.8: colour science in filmcraft-color — camera log curves, gamuts, BT.2390 tone mapping, gamut mapping; .cube/.3dl LUTs with tetrahedral interpolation
Brandon Thomas6f61d3e7507b
diff --git a/crates/color/README.md b/crates/color/README.mdnew file mode 100644index 000000000..041db40b9--- /dev/null+++ b/crates/color/README.md@@ -0,0 +1,119 @@+# filmcraft-color++Colour science for FilmCraft (layer L0, no workspace dependencies): Y'CbCr matrices, transfer+functions, camera log curves, RGB gamuts, colour-managed input/output transforms with tone and+gamut mapping, and LUT files.++| Module | Contents |+|---|---|+| `lib.rs` | `Matrix`/`Transfer`/`Primaries`/`Range`/`ColorInfo` (stream metadata), Y'CbCr↔R'G'B', sRGB, PQ (ST 2084), HLG (ARIB STD-B67), HSL, hex colours |+| `log` | camera log curves (encode/decode), their signal domains |+| `spaces` | gamuts and 3×3 matrices (SMPTE RP 177), `ColorSpace` (Interpret Footage choices), `WorkingSpace`, `ColorPipeline` |+| `transform` | `InputTransform` (source → working), `OutputTransform` (working → monitor / export), BT.2390 tone mapping, gamut compression |+| `lut` | `.cube` (1D, 3D, shaper + 3D) and `.3dl` parse/write, tetrahedral interpolation |++## Working units++The compositor works in linear light with **1.0 = reference white**: SDR white for SDR media, and+**203 cd/m²** for HDR (ITU-R BT.2408, "HDR Reference White"). SDR media keeps its values in an HDR+sequence (the BT.2408 SDR-in-HDR mapping), HDR highlights are values above 1.0, and log media+decodes to scene-linear reflectance (18 % grey = 0.18). Working primaries are BT.709 for a Rec. 709+sequence and BT.2020 for Rec. 2100 PQ/HLG sequences or when "wide gamut" is on.++## Camera log curves++Each curve is implemented from the manufacturer's published document. "Domain" is the normalisation+the document uses: **CV** = 10-bit code value / 1023 (full scale), **IRE** = video-range normalised+(code 64 → 0, code 940 → 1). `log::signal_from_normalized` converts the decoder's normalised value+(which already accounts for the file's range flag) into the curve domain, so the same formulas work+for limited- and full-range files.++| Curve | Gamut | Source | Domain | Decode (signal y → linear x) |+|---|---|---|---|---|+| Sony S-Log3 | S-Gamut3.Cine / S-Gamut3 | Sony, *Technical Summary for S-Gamut3.Cine/S-Log3 and S-Gamut3/S-Log3* (2014) | CV | y ≥ 171.2102946929/1023: x = 10^((1023y − 420)/261.5)·0.19 − 0.01; else x = (1023y − 95)·0.01125/(171.2102946929 − 95) |+| Panasonic V-Log | V-Gamut | Panasonic, *V-Log/V-Gamut Reference Manual* (2014) | CV | y < 0.181: x = (y − 0.125)/5.6; else x = 10^((y − d)/c) − b, b = 0.00873, c = 0.241514, d = 0.598206 |+| Canon Log 2 | Cinema Gamut | Canon, *Canon Log Gamma Curves* white paper (2018) | IRE | x' = ±(10^(±(y − 0.092864125)/0.24136077) − 1)/87.09937546 (sign by y vs 0.092864125); x = 0.9·x' (Canon's x is reflectance / 0.9) |+| Canon Log 3 | Cinema Gamut | same | IRE | y < 0.097465473: x' = −(10^((0.12783901 − y)/0.36726845) − 1)/14.98325; y ≤ 0.15277891: x' = (y − 0.12512219)/1.9754798; else x' = (10^((y − 0.12240537)/0.36726845) − 1)/14.98325; x = 0.9·x' |+| ARRI LogC3 (EI 800) | ARRI Wide Gamut 3 | ARRI, *ALEXA Log C Curve — Usage in VFX* (2017), EI 800 row | CV | y > e·cut + f: x = (10^((y − d)/c) − b)/a; else x = (y − f)/e; cut 0.010591, a 5.555556, b 0.052272, c 0.247190, d 0.385537, e 5.367655, f 0.092809 |+| ARRI LogC4 | ARRI Wide Gamut 4 | ARRI, *ARRI LogC4 Logarithmic Color Space — Specification* (2022) | CV | a = (2¹⁸ − 16)/117.45, b = 928/1023, c = 95/1023, s = 7·ln2·2^(7 − 14c/b)/(a·b), t = (2^(6 − 14c/b) − 64)/a; y ≥ 0: x = (2^(14(y − c)/b + 6) − 64)/a; else x = y·s + t |+| Apple Log | BT.2020 | Apple, *Apple Log Profile* white paper (2023) | IRE | R0 = −0.05641088, Rt = 0.01, c = 47.28711236, β = 0.00964052, γ = 0.08550479, δ = 0.69336945; P ≥ c(Rt − R0)²: x = 2^((P − δ)/γ) − β; else x = √(P/c) + R0 |+| DJI D-Log | D-Gamut | DJI, *White Paper on D-Log and D-Gamut of DJI Cinema Color System* (2017) | CV | y ≤ 0.14: x = (y − 0.0929)/6.025; else x = (10^(3.89616y − 2.27752) − 0.0108)/0.9892 |++The encoders are the exact inverses given in the same documents. DJI **D-Log M** is not+implemented: DJI has not published its formula (only conversion LUTs), and we do not derive curves+from third-party LUTs.++Gamut primaries (all D65 white, x/y):++| Gamut | R | G | B | Source |+|---|---|---|---|---|+| BT.709 | 0.640, 0.330 | 0.300, 0.600 | 0.150, 0.060 | ITU-R BT.709-6 |+| BT.2020 | 0.708, 0.292 | 0.170, 0.797 | 0.131, 0.046 | ITU-R BT.2020-2 |+| P3 D65 | 0.680, 0.320 | 0.265, 0.690 | 0.150, 0.060 | SMPTE EG 432-1 |+| S-Gamut3.Cine | 0.766, 0.275 | 0.225, 0.800 | 0.089, −0.087 | Sony technical summary |+| S-Gamut3 | 0.730, 0.280 | 0.140, 0.855 | 0.100, −0.050 | Sony technical summary |+| V-Gamut | 0.730, 0.280 | 0.165, 0.840 | 0.100, −0.030 | Panasonic reference manual |+| Cinema Gamut | 0.740, 0.270 | 0.170, 1.140 | 0.080, −0.100 | Canon white paper |+| ARRI Wide Gamut 3 | 0.6840, 0.3130 | 0.2210, 0.8480 | 0.0861, −0.1020 | ARRI Log C document |+| ARRI Wide Gamut 4 | 0.7347, 0.2653 | 0.1424, 0.8576 | 0.0991, −0.0308 | ARRI LogC4 specification |+| D-Gamut | 0.71, 0.31 | 0.21, 0.88 | 0.09, −0.08 | DJI white paper |++Matrices are derived from the chromaticities (SMPTE RP 177 normalised primary matrix); tests check+the result against the published BT.709 RGB→XYZ and BT.2087 BT.709→BT.2020 matrices.++## HDR transfer functions++* **PQ** (SMPTE ST 2084 / BT.2100): decoded to absolute cd/m², then divided by 203.+* **HLG** (ARIB STD-B67 / BT.2100): inverse OETF to scene light, then the BT.2100 OOTF+ `Fd = Lw·Ys^(γ−1)·E` with Lw = 1000 cd/m², γ = 1.2 and Ys from BT.2020 luma, then ÷ 203. A 75 %+ HLG signal lands at reference white (BT.2408). HLG export applies the inverse OOTF and the OETF.++## Tone mapping (HDR/log → SDR)++When an HDR or log source enters a Rec. 709 working space with **Auto Tone Map Media** on (the+default), and on the monitors of an HDR sequence, FilmCraft applies the **ITU-R BT.2390 EETF**:++1. m = max(R, G, B) in working units, converted to cd/m² (×203) and PQ-encoded, normalised by the+ PQ value of the source peak;+2. below the knee KS = 1.5·maxLum − 0.5 (maxLum = PQ(target peak)/PQ(source peak)) the value is+ unchanged; above it a Hermite spline maps the rest of the range onto [KS, maxLum];+3. RGB is scaled by m'/m, which keeps hue and saturation.++Source peak: the content's mastering peak for PQ when known (default 1000 cd/m²), 1000 cd/m² for+HLG, and for log media the curve's own peak capped at 4000 cd/m² (so the knee starts above mid+grey). Target peak: 203 cd/m² = SDR white. HDR reference white then lands at ≈ 0.79 linear (≈ 90 %+on the sRGB curve).++## Gamut mapping++* **Input** (camera gamuts wider than the working gamut): per-channel distance compression towards+ the achromatic axis, after the ACES Reference Gamut Compression: for each channel+ d = (max − c)/max; distances below 0.8 are unchanged, distances from 0.8 to 1.25 are compressed+ into 0.8–1.0 with a power-1.2 curve. Colours within 80 % of the boundary are untouched.+* **Output** (BT.2020 working → BT.709 monitor/export): colours with a negative component are+ desaturated towards their BT.709 luminance just enough to fit (`desaturate_into_gamut`); in-gamut+ colours, such as BT.709 media in a wide-gamut sequence, come back exactly.++## LUTs++* `.cube`: the published Cube LUT 1.0 text format — `TITLE`, `LUT_1D_SIZE` (2–65536), `LUT_3D_SIZE`+ (2–256), `DOMAIN_MIN`/`DOMAIN_MAX`, legacy `LUT_1D_INPUT_RANGE`/`LUT_3D_INPUT_RANGE`, comments,+ CRLF. A file with both sizes is a 1D shaper followed by a cube. Red changes fastest.+* `.3dl`: optional `3DMESH` / `Mesh <in> <out>` header, the input mesh line (non-uniform meshes+ become a 1D shaper), `n³` integer rows with blue fastest; output depth from the header or the+ largest value. We write 33-point, 10-bit-mesh, 12-bit-output files.+* 3D interpolation is **tetrahedral**. Tests compare it with a brute-force reference (barycentric+ coordinates in each of the six Kuhn tetrahedra, solved with a 3×3 inverse) on random points for+ sizes 2–33, check exactness on affine LUTs and at grid nodes, and round-trip both formats.++FilmCraft ships no LUT files. Its built-in looks and camera conversions are generated from code+(`filmcraft-render`), and are written to disk only when the user exports them.++## Tests++`cargo test -p filmcraft-color`: encode∘decode round trips for every curve (−1 % to 8× and over+the full signal range in both file ranges), published reference points (S-Log3 95/420/598, V-Log+128/433/602, LogC3 18 % → 0.391, LogC4 18 % → 0.2784, Canon Log 2/3 18 % → 39.2 %/34.3 % IRE, Apple+Log 18 % → 0.488, D-Log 0 → 0.0929), PQ/HLG reference white, EETF continuity/monotonicity and peak,+hue preservation, gamut compression, BT.709/BT.2087 matrices, LUT interpolation and file round+trips.diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rsindex 0ba386d25..e67ce908a 100644--- a/crates/color/src/lib.rs+++ b/crates/color/src/lib.rs@@ -1,4 +1,6 @@-//! Colour science for FilmCraft: YUV matrices, transfer functions, colour metadata and LUTs.+//! Colour science for FilmCraft: YUV matrices, transfer functions, camera log curves, gamuts,+//! colour-managed input/output transforms (tone and gamut mapping), colour metadata and LUTs.+//! See the crate README for the formulas and their sources.//!//! The compositor works in **linear-light, premultiplied RGBA f32** in the sequence working space//! (Rec.709 primaries by default). Decoded frames carry [`ColorInfo`] so conversions are explicit.@@ -6,6 +8,16 @@use serde::{Deserialize, Serialize};use std::sync::OnceLock;+pub mod log;+pub mod lut;+pub mod spaces;+pub mod transform;++pub use log::LogCurve;+pub use lut::{Lut, Lut1d, Lut3d, LutFormat};+pub use spaces::{ColorPipeline, ColorSpace, Curve, Gamut, WorkingSpace};+pub use transform::{DecodeTable, InputTransform, OutputTransform, REFERENCE_WHITE_NITS, ToneMap};+/// YUV ↔ RGB matrix coefficients.#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]pub enum Matrix {@@ -251,107 +263,6 @@ pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] {[f(h + 1.0 / 3.0), f(h), f(h - 1.0 / 3.0)]}-/// A 3D LUT (from a `.cube` file), applied to encoded RGB in 0..1.-#[derive(Clone, Debug, PartialEq)]-pub struct Lut3d {- pub title: String,- pub size: usize,- pub domain_min: [f32; 3],- pub domain_max: [f32; 3],- /// `size³` entries, red fastest.- pub data: Vec<[f32; 3]>,-}--impl Lut3d {- pub fn identity(size: usize) -> Self {- let n = (size - 1) as f32;- let mut data = Vec::with_capacity(size * size * size);- for b in 0..size {- for g in 0..size {- for r in 0..size {- data.push([r as f32 / n, g as f32 / n, b as f32 / n]);- }- }- }- Lut3d { title: "identity".into(), size, domain_min: [0.0; 3], domain_max: [1.0; 3], data }- }-- /// Parse the Adobe/Resolve `.cube` text format (3D LUTs).- pub fn parse_cube(text: &str) -> Result<Lut3d, String> {- let mut size = 0usize;- let mut title = String::new();- let mut dmin = [0.0f32; 3];- let mut dmax = [1.0f32; 3];- let mut data = Vec::new();- for line in text.lines() {- let line = line.trim();- if line.is_empty() || line.starts_with('#') {- continue;- }- let mut it = line.split_whitespace();- let key = it.next().unwrap_or("");- match key {- "TITLE" => title = line[5..].trim().trim_matches('"').to_string(),- "LUT_3D_SIZE" => size = it.next().and_then(|v| v.parse().ok()).ok_or("bad LUT_3D_SIZE")?,- "LUT_1D_SIZE" => return Err("1D .cube LUTs are not supported yet".into()),- "DOMAIN_MIN" | "DOMAIN_MAX" => {- let v: Vec<f32> = it.filter_map(|x| x.parse().ok()).collect();- if v.len() != 3 {- return Err(format!("bad {key}"));- }- let t = if key == "DOMAIN_MIN" { &mut dmin } else { &mut dmax };- t.copy_from_slice(&v);- }- _ => {- let v: Vec<f32> = line.split_whitespace().filter_map(|x| x.parse().ok()).collect();- if v.len() == 3 {- data.push([v[0], v[1], v[2]]);- }- }- }- }- if size < 2 || data.len() != size * size * size {- return Err(format!("expected {}³ entries, found {}", size, data.len()));- }- Ok(Lut3d { title, size, domain_min: dmin, domain_max: dmax, data })- }-- pub fn to_cube(&self) -> String {- let mut s = format!("TITLE \"{}\"\nLUT_3D_SIZE {}\n", self.title, self.size);- for d in &self.data {- s += &format!("{:.6} {:.6} {:.6}\n", d[0], d[1], d[2]);- }- s- }-- /// Trilinear lookup.- pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {- let n = self.size;- let m = (n - 1) as f32;- let mut idx = [0usize; 3];- let mut frac = [0f32; 3];- for c in 0..3 {- let t = ((rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c])).clamp(0.0, 1.0) * m;- let i = (t.floor() as usize).min(n - 2);- idx[c] = i;- frac[c] = t - i as f32;- }- let at = |r: usize, g: usize, b: usize| self.data[r + g * n + b * n * n];- let mut out = [0f32; 3];- for (k, o) in out.iter_mut().enumerate() {- let c = |dr, dg, db| at(idx[0] + dr, idx[1] + dg, idx[2] + db)[k];- let x00 = c(0, 0, 0) + (c(1, 0, 0) - c(0, 0, 0)) * frac[0];- let x10 = c(0, 1, 0) + (c(1, 1, 0) - c(0, 1, 0)) * frac[0];- let x01 = c(0, 0, 1) + (c(1, 0, 1) - c(0, 0, 1)) * frac[0];- let x11 = c(0, 1, 1) + (c(1, 1, 1) - c(0, 1, 1)) * frac[0];- let y0 = x00 + (x10 - x00) * frac[1];- let y1 = x01 + (x11 - x01) * frac[1];- *o = y0 + (y1 - y0) * frac[2];- }- out- }-}-/// Parse `#rrggbb` / `#rrggbbaa` into 0..1 floats.pub fn parse_hex(s: &str) -> Option<[f32; 4]> {let s = s.trim().trim_start_matches('#');@@ -419,15 +330,6 @@ mod tests {}}- #[test]- fn cube_identity() {- let lut = Lut3d::identity(17);- let parsed = Lut3d::parse_cube(&lut.to_cube()).unwrap();- let v = parsed.apply([0.3, 0.55, 0.91]);- assert!((v[0] - 0.3).abs() < 1e-4 && (v[1] - 0.55).abs() < 1e-4 && (v[2] - 0.91).abs() < 1e-4);- assert!(Lut3d::parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());- }-#[test]fn hex() {assert_eq!(parse_hex("#ff8000"), Some([1.0, 128.0 / 255.0, 0.0, 1.0]));diff --git a/crates/color/src/log.rs b/crates/color/src/log.rsnew file mode 100644index 000000000..7fd23afa8--- /dev/null+++ b/crates/color/src/log.rs@@ -0,0 +1,336 @@+//! Camera log curves, implemented from the manufacturers' published specifications.+//!+//! Every curve is a pair `encode(linear) → signal` / `decode(signal) → linear`, where *linear* is+//! scene-linear reflectance (18 % grey = 0.18) and *signal* is the curve's own normalised domain:+//!+//! * [`Domain::CodeValue`]: the specification is written in 10-bit code values / 1023 (full+//! scale). Sony, Panasonic, ARRI and DJI publish their curves this way (S-Log3 black = 95/1023).+//! * [`Domain::Ire`]: the specification is written in "IRE" (video-range normalised: 0 = code 64,+//! 1 = code 940). Canon publishes Canon Log 2/3 this way; Apple Log is treated the same.+//!+//! [`signal_from_normalized`] / [`normalized_from_signal`] convert between the decoder's+//! normalised value (which already accounts for the file's range flag) and the curve domain.+//! Formulas and sources are listed in the crate README (§ Camera log curves).++use crate::Range;++/// The normalisation a curve's published formula uses.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Domain {+ /// 10-bit code value / 1023.+ CodeValue,+ /// Video-range normalised (code 64 → 0, code 940 → 1).+ Ire,+}++/// A camera log encoding.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum LogCurve {+ /// Sony S-Log3.+ SLog3,+ /// Panasonic V-Log.+ VLog,+ /// Canon Log 2.+ CLog2,+ /// Canon Log 3.+ CLog3,+ /// ARRI LogC3 (ALEXA classic/Mini/LF, EI 800).+ LogC3,+ /// ARRI LogC4 (ALEXA 35).+ LogC4,+ /// Apple Log (iPhone 15 Pro and later).+ AppleLog,+ /// DJI D-Log.+ DLog,+}++impl LogCurve {+ pub const ALL: [LogCurve; 8] =+ [LogCurve::SLog3, LogCurve::VLog, LogCurve::CLog2, LogCurve::CLog3, LogCurve::LogC3, LogCurve::LogC4, LogCurve::AppleLog, LogCurve::DLog];++ pub fn domain(self) -> Domain {+ match self {+ LogCurve::CLog2 | LogCurve::CLog3 | LogCurve::AppleLog => Domain::Ire,+ _ => Domain::CodeValue,+ }+ }++ pub fn label(self) -> &'static str {+ match self {+ LogCurve::SLog3 => "S-Log3",+ LogCurve::VLog => "V-Log",+ LogCurve::CLog2 => "Canon Log 2",+ LogCurve::CLog3 => "Canon Log 3",+ LogCurve::LogC3 => "ARRI LogC3",+ LogCurve::LogC4 => "ARRI LogC4",+ LogCurve::AppleLog => "Apple Log",+ LogCurve::DLog => "DJI D-Log",+ }+ }++ /// Scene-linear → signal (curve domain).+ pub fn encode(self, x: f64) -> f64 {+ match self {+ LogCurve::SLog3 => slog3_encode(x),+ LogCurve::VLog => vlog_encode(x),+ LogCurve::CLog2 => clog2_encode(x),+ LogCurve::CLog3 => clog3_encode(x),+ LogCurve::LogC3 => logc3_encode(x),+ LogCurve::LogC4 => logc4_encode(x),+ LogCurve::AppleLog => apple_log_encode(x),+ LogCurve::DLog => dlog_encode(x),+ }+ }++ /// Signal (curve domain) → scene-linear.+ pub fn decode(self, y: f64) -> f64 {+ match self {+ LogCurve::SLog3 => slog3_decode(y),+ LogCurve::VLog => vlog_decode(y),+ LogCurve::CLog2 => clog2_decode(y),+ LogCurve::CLog3 => clog3_decode(y),+ LogCurve::LogC3 => logc3_decode(y),+ LogCurve::LogC4 => logc4_decode(y),+ LogCurve::AppleLog => apple_log_decode(y),+ LogCurve::DLog => dlog_decode(y),+ }+ }++ /// Scene-linear value of the maximum signal (code 1023), used as the source peak for tone+ /// mapping.+ pub fn peak_linear(self) -> f64 {+ let top = match self.domain() {+ Domain::CodeValue => 1.0,+ Domain::Ire => (1023.0 - 64.0) / 876.0,+ };+ self.decode(top)+ }+}++/// Decoder-normalised value (0..1 in the file's range) → curve-domain signal.+pub fn signal_from_normalized(v: f64, range: Range, d: Domain) -> f64 {+ match (range, d) {+ (Range::Limited, Domain::CodeValue) => (64.0 + 876.0 * v) / 1023.0,+ (Range::Full, Domain::Ire) => (1023.0 * v - 64.0) / 876.0,+ _ => v,+ }+}++/// Curve-domain signal → decoder-normalised value (0..1 in the file's range).+pub fn normalized_from_signal(s: f64, range: Range, d: Domain) -> f64 {+ match (range, d) {+ (Range::Limited, Domain::CodeValue) => (1023.0 * s - 64.0) / 876.0,+ (Range::Full, Domain::Ire) => (64.0 + 876.0 * s) / 1023.0,+ _ => s,+ }+}++// ---------------------------------------------------------------- Sony S-Log3+// Sony, "Technical Summary for S-Gamut3.Cine/S-Log3 and S-Gamut3/S-Log3" (2014).++pub fn slog3_encode(x: f64) -> f64 {+ if x >= 0.011_25 { (420.0 + ((x + 0.01) / (0.18 + 0.01)).log10() * 261.5) / 1023.0 } else { (x * (171.210_294_692_9 - 95.0) / 0.011_25 + 95.0) / 1023.0 }+}+pub fn slog3_decode(y: f64) -> f64 {+ if y >= 171.210_294_692_9 / 1023.0 {+ 10f64.powf((y * 1023.0 - 420.0) / 261.5) * (0.18 + 0.01) - 0.01+ } else {+ (y * 1023.0 - 95.0) * 0.011_25 / (171.210_294_692_9 - 95.0)+ }+}++// ---------------------------------------------------------------- Panasonic V-Log+// Panasonic, "V-Log/V-Gamut Reference Manual" (rev. 1.0, 2014).++const VLOG_B: f64 = 0.008_73;+const VLOG_C: f64 = 0.241_514;+const VLOG_D: f64 = 0.598_206;++pub fn vlog_encode(x: f64) -> f64 {+ if x < 0.01 { 5.6 * x + 0.125 } else { VLOG_C * (x + VLOG_B).log10() + VLOG_D }+}+pub fn vlog_decode(y: f64) -> f64 {+ if y < 0.181 { (y - 0.125) / 5.6 } else { 10f64.powf((y - VLOG_D) / VLOG_C) - VLOG_B }+}++// ---------------------------------------------------------------- Canon Log 2 / 3+// Canon, "Canon Log Gamma Curves — Description of the Canon Log, Canon Log 2 and Canon Log 3"+// (white paper, 2018). The formulas take x = reflectance / 0.9 and give IRE.++pub fn clog2_encode(r: f64) -> f64 {+ let x = r / 0.9;+ if x < 0.0 { -0.241_360_77 * (-x * 87.099_375_46 + 1.0).log10() + 0.092_864_125 } else { 0.241_360_77 * (x * 87.099_375_46 + 1.0).log10() + 0.092_864_125 }+}+pub fn clog2_decode(y: f64) -> f64 {+ let x = if y < 0.092_864_125 {+ -(10f64.powf((0.092_864_125 - y) / 0.241_360_77) - 1.0) / 87.099_375_46+ } else {+ (10f64.powf((y - 0.092_864_125) / 0.241_360_77) - 1.0) / 87.099_375_46+ };+ x * 0.9+}++pub fn clog3_encode(r: f64) -> f64 {+ let x = r / 0.9;+ if x < -0.014 {+ -0.367_268_45 * (-x * 14.983_25 + 1.0).log10() + 0.127_839_01+ } else if x <= 0.014 {+ 1.975_479_8 * x + 0.125_122_19+ } else {+ 0.367_268_45 * (x * 14.983_25 + 1.0).log10() + 0.122_405_37+ }+}+pub fn clog3_decode(y: f64) -> f64 {+ let x = if y < 0.097_465_473 {+ -(10f64.powf((0.127_839_01 - y) / 0.367_268_45) - 1.0) / 14.983_25+ } else if y <= 0.152_778_91 {+ (y - 0.125_122_19) / 1.975_479_8+ } else {+ (10f64.powf((y - 0.122_405_37) / 0.367_268_45) - 1.0) / 14.983_25+ };+ x * 0.9+}++// ---------------------------------------------------------------- ARRI LogC3 (EI 800)+// ARRI, "ALEXA Log C Curve — Usage in VFX" (2017), table for EI 800, scene-linear variant.++const LOGC3: (f64, f64, f64, f64, f64, f64, f64) = (0.010_591, 5.555_556, 0.052_272, 0.247_190, 0.385_537, 5.367_655, 0.092_809);++pub fn logc3_encode(x: f64) -> f64 {+ let (cut, a, b, c, d, e, f) = LOGC3;+ if x > cut { c * (a * x + b).log10() + d } else { e * x + f }+}+pub fn logc3_decode(t: f64) -> f64 {+ let (cut, a, b, c, d, e, f) = LOGC3;+ if t > e * cut + f { (10f64.powf((t - d) / c) - b) / a } else { (t - f) / e }+}++// ---------------------------------------------------------------- ARRI LogC4+// ARRI, "ARRI LogC4 Logarithmic Color Space — Specification" (2022).++fn logc4_consts() -> (f64, f64, f64, f64, f64) {+ let a = (2f64.powi(18) - 16.0) / 117.45;+ let b = (1023.0 - 95.0) / 1023.0;+ let c = 95.0 / 1023.0;+ let s = (7.0 * std::f64::consts::LN_2 * 2f64.powf(7.0 - 14.0 * c / b)) / (a * b);+ let t = (2f64.powf(14.0 * (-c / b) + 6.0) - 64.0) / a;+ (a, b, c, s, t)+}+pub fn logc4_encode(x: f64) -> f64 {+ let (a, b, c, s, t) = logc4_consts();+ if x >= t { ((a * x + 64.0).log2() - 6.0) / 14.0 * b + c } else { (x - t) / s }+}+pub fn logc4_decode(y: f64) -> f64 {+ let (a, b, c, s, t) = logc4_consts();+ if y >= 0.0 { (2f64.powf(14.0 * (y - c) / b + 6.0) - 64.0) / a } else { y * s + t }+}++// ---------------------------------------------------------------- Apple Log+// Apple, "Apple Log Profile" white paper (2023).++const APPLE: (f64, f64, f64, f64, f64, f64) = (-0.056_410_88, 0.01, 47.287_112_36, 0.009_640_52, 0.085_504_79, 0.693_369_45);++pub fn apple_log_encode(r: f64) -> f64 {+ let (r0, rt, c, beta, gamma, delta) = APPLE;+ if r >= rt {+ gamma * (r + beta).log2() + delta+ } else if r >= r0 {+ c * (r - r0) * (r - r0)+ } else {+ 0.0+ }+}+pub fn apple_log_decode(p: f64) -> f64 {+ let (r0, rt, c, beta, gamma, delta) = APPLE;+ let pt = c * (rt - r0) * (rt - r0);+ if p >= pt {+ 2f64.powf((p - delta) / gamma) - beta+ } else if p >= 0.0 {+ (p / c).sqrt() + r0+ } else {+ r0+ }+}++// ---------------------------------------------------------------- DJI D-Log+// DJI, "White Paper on D-Log and D-Gamut of DJI Cinema Color System" (2017).++pub fn dlog_encode(x: f64) -> f64 {+ if x <= 0.0078 { 6.025 * x + 0.0929 } else { (x * 0.9892 + 0.0108).log10() * 0.256_663 + 0.584_555 }+}+pub fn dlog_decode(y: f64) -> f64 {+ if y <= 0.14 { (y - 0.0929) / 6.025 } else { (10f64.powf(3.896_16 * y - 2.277_52) - 0.0108) / 0.9892 }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn roundtrip_every_curve() {+ for c in LogCurve::ALL {+ for i in 0..=400 {+ // −1 % … 40× mid grey+ let x = -0.01 + (i as f64 / 400.0).powi(3) * 8.0;+ let y = c.encode(x);+ let back = c.decode(y);+ assert!((back - x).abs() <= 1e-6 * x.abs().max(1.0) + 1e-9, "{c:?}: {x} → {y} → {back}");+ }+ // monotone signal+ let mut prev = f64::NEG_INFINITY;+ for i in 0..=1000 {+ let y = c.encode(i as f64 / 100.0);+ assert!(y > prev, "{c:?} not increasing at {i}");+ prev = y;+ }+ }+ }++ /// Reference points from the published specifications (code values are 10-bit).+ #[test]+ fn published_reference_values() {+ let cv = |c: LogCurve, x: f64| match c.domain() {+ Domain::CodeValue => c.encode(x) * 1023.0,+ Domain::Ire => 64.0 + c.encode(x) * 876.0,+ };+ let close = |a: f64, b: f64, tol: f64, what: &str| assert!((a - b).abs() <= tol, "{what}: {a} vs {b}");+ // Sony: 0 % → 95, 18 % → 420, 90 % → 598 (Technical Summary, table 1).+ close(cv(LogCurve::SLog3, 0.0), 95.0, 0.01, "S-Log3 0%");+ close(cv(LogCurve::SLog3, 0.18), 420.0, 0.01, "S-Log3 18%");+ close(cv(LogCurve::SLog3, 0.9), 598.0, 0.5, "S-Log3 90%");+ // Panasonic: 0 % → 128, 18 % → 433, 90 % → 602 (V-Log manual, table).+ close(cv(LogCurve::VLog, 0.0), 128.0, 0.5, "V-Log 0%");+ close(cv(LogCurve::VLog, 0.18), 433.0, 0.5, "V-Log 18%");+ close(cv(LogCurve::VLog, 0.9), 602.0, 0.5, "V-Log 90%");+ // ARRI LogC3 EI 800: 18 % → 0.391 (= code 400).+ close(LogCurve::LogC3.encode(0.18), 0.391, 0.0006, "LogC3 18%");+ close(cv(LogCurve::LogC3, 0.18), 400.0, 0.5, "LogC3 18% code");+ // ARRI LogC4: 18 % → 0.2784 (spec example), 0 → 95/1023.+ close(LogCurve::LogC4.encode(0.18), 0.278_4, 0.0005, "LogC4 18%");+ close(LogCurve::LogC4.encode(0.0), 95.0 / 1023.0, 1e-9, "LogC4 0");+ // Canon: 18 % grey → 39.2 % IRE (Log 2, ±0.7) and 34.3 % IRE (Log 3).+ close(LogCurve::CLog2.encode(0.18) * 100.0, 39.2, 0.7, "C-Log2 18%");+ close(LogCurve::CLog3.encode(0.18) * 100.0, 34.3, 0.2, "C-Log3 18%");+ // Apple Log: 18 % grey → 0.488 (white paper figure), black 0 → R0 floor.+ close(LogCurve::AppleLog.encode(0.18), 0.488, 0.001, "Apple Log 18%");+ close(LogCurve::AppleLog.encode(-0.056_410_88), 0.0, 1e-12, "Apple Log R0");+ // DJI D-Log: 0 → 0.0929, 18 % → 0.398 (white paper).+ close(LogCurve::DLog.encode(0.0), 0.0929, 1e-9, "D-Log 0");+ close(LogCurve::DLog.encode(0.18), 0.398, 0.002, "D-Log 18%");+ }++ #[test]+ fn domain_conversion_roundtrip() {+ for r in [Range::Limited, Range::Full] {+ for d in [Domain::CodeValue, Domain::Ire] {+ for v in [0.0, 0.25, 0.8, 1.0] {+ assert!((normalized_from_signal(signal_from_normalized(v, r, d), r, d) - v).abs() < 1e-12);+ }+ }+ }+ // limited-range code 420 is S-Log3 mid grey+ let norm = (420.0 - 64.0) / 876.0;+ let s = signal_from_normalized(norm, Range::Limited, Domain::CodeValue);+ assert!((LogCurve::SLog3.decode(s) - 0.18).abs() < 1e-6);+ }+}diff --git a/crates/color/src/lut.rs b/crates/color/src/lut.rsnew file mode 100644index 000000000..92e919738--- /dev/null+++ b/crates/color/src/lut.rs@@ -0,0 +1,628 @@+//! Colour lookup tables: `.cube` (1D, 3D, or a 1D shaper followed by a 3D cube) and Autodesk+//! `.3dl`, parse and write, with tetrahedral 3D interpolation.+//!+//! * `.cube` follows the published "Cube LUT Specification 1.0" text format: `TITLE`,+//! `LUT_1D_SIZE` (2–65536), `LUT_3D_SIZE` (2–256), `DOMAIN_MIN`/`DOMAIN_MAX`, the legacy+//! `LUT_1D_INPUT_RANGE`/`LUT_3D_INPUT_RANGE`, `#` comments; data rows have red changing fastest.+//! A file with both sizes holds the 1D table first (a shaper), then the cube.+//! * `.3dl` (Lustre/Flame): optional `3DMESH`/`Mesh <in> <out>` header, one line of input mesh+//! points (e.g. `0 64 … 1023`, which sets the input bit depth and need not be uniform), then+//! `n³` integer rows with **blue changing fastest**. The output bit depth comes from the header+//! or the largest value (10/12/14/16-bit).+//!+//! Interpolation: 1D tables linear per channel, 3D cubes tetrahedral (the cell is split into six+//! tetrahedra along its main diagonal; exact for any affine LUT and continuous across cells).++use std::fmt::Write as _;++/// A per-channel 1D table.+#[derive(Clone, Debug, PartialEq)]+pub struct Lut1d {+ pub domain_min: [f32; 3],+ pub domain_max: [f32; 3],+ pub data: Vec<[f32; 3]>,+}++impl Lut1d {+ pub fn identity(size: usize) -> Self {+ let n = (size - 1) as f32;+ Lut1d { domain_min: [0.0; 3], domain_max: [1.0; 3], data: (0..size).map(|i| [i as f32 / n; 3]).collect() }+ }+ pub fn size(&self) -> usize {+ self.data.len()+ }+ #[inline]+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {+ let n = self.data.len() - 1;+ let mut o = [0.0; 3];+ for c in 0..3 {+ let t = ((rgb[c] - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c])).clamp(0.0, 1.0) * n as f32;+ let i = (t as usize).min(n.saturating_sub(1));+ let f = t - i as f32;+ o[c] = self.data[i][c] + (self.data[(i + 1).min(n)][c] - self.data[i][c]) * f;+ }+ o+ }+}++/// A 3D cube, `size³` entries, red fastest.+#[derive(Clone, Debug, PartialEq)]+pub struct Lut3d {+ pub title: String,+ pub size: usize,+ pub domain_min: [f32; 3],+ pub domain_max: [f32; 3],+ pub data: Vec<[f32; 3]>,+}++impl Lut3d {+ pub fn identity(size: usize) -> Self {+ Self::from_fn(size, |c| c)+ }++ /// Sample a colour transform on a `size³` grid over 0..1.+ pub fn from_fn(size: usize, f: impl Fn([f32; 3]) -> [f32; 3]) -> Self {+ let n = (size - 1) as f32;+ let mut data = Vec::with_capacity(size * size * size);+ for b in 0..size {+ for g in 0..size {+ for r in 0..size {+ data.push(f([r as f32 / n, g as f32 / n, b as f32 / n]));+ }+ }+ }+ Lut3d { title: String::new(), size, domain_min: [0.0; 3], domain_max: [1.0; 3], data }+ }++ #[inline]+ pub fn at(&self, r: usize, g: usize, b: usize) -> [f32; 3] {+ self.data[r + g * self.size + b * self.size * self.size]+ }++ /// Parse a `.cube` file that contains a 3D table (a shaper, if present, is rejected; use+ /// [`Lut::parse_cube`] for those).+ pub fn parse_cube(text: &str) -> Result<Lut3d, String> {+ let l = Lut::parse_cube(text)?;+ match (l.shaper, l.cube) {+ (None, Some(c)) => Ok(c),+ (Some(_), _) => Err("the file has a 1D shaper; load it as a Lut".into()),+ (None, None) => Err("no 3D table".into()),+ }+ }++ pub fn to_cube(&self) -> String {+ Lut { title: self.title.clone(), shaper: None, cube: Some(self.clone()) }.to_cube()+ }++ /// Normalised grid coordinate (0..size-1) of an input value.+ #[inline]+ fn coord(&self, v: f32, c: usize) -> f32 {+ ((v - self.domain_min[c]) / (self.domain_max[c] - self.domain_min[c])).clamp(0.0, 1.0) * (self.size - 1) as f32+ }++ /// Tetrahedral interpolation.+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {+ let n = self.size;+ let (x, y, z) = (self.coord(rgb[0], 0), self.coord(rgb[1], 1), self.coord(rgb[2], 2));+ let (r0, g0, b0) = ((x as usize).min(n - 2), (y as usize).min(n - 2), (z as usize).min(n - 2));+ let (fr, fg, fb) = (x - r0 as f32, y - g0 as f32, z - b0 as f32);+ let c = |dr: usize, dg: usize, db: usize| self.at(r0 + dr, g0 + dg, b0 + db);+ let c000 = c(0, 0, 0);+ let c111 = c(1, 1, 1);+ // weights (w0 on c000, then the two intermediate corners, w3 on c111)+ let (ca, cb, w) = if fr > fg {+ if fg > fb {+ (c(1, 0, 0), c(1, 1, 0), [1.0 - fr, fr - fg, fg - fb, fb])+ } else if fr > fb {+ (c(1, 0, 0), c(1, 0, 1), [1.0 - fr, fr - fb, fb - fg, fg])+ } else {+ (c(0, 0, 1), c(1, 0, 1), [1.0 - fb, fb - fr, fr - fg, fg])+ }+ } else if fb > fg {+ (c(0, 0, 1), c(0, 1, 1), [1.0 - fb, fb - fg, fg - fr, fr])+ } else if fb > fr {+ (c(0, 1, 0), c(0, 1, 1), [1.0 - fg, fg - fb, fb - fr, fr])+ } else {+ (c(0, 1, 0), c(1, 1, 0), [1.0 - fg, fg - fr, fr - fb, fb])+ };+ let mut o = [0.0; 3];+ for k in 0..3 {+ o[k] = w[0] * c000[k] + w[1] * ca[k] + w[2] * cb[k] + w[3] * c111[k];+ }+ o+ }++ /// Trilinear interpolation (kept for comparison; LUTs render tetrahedrally).+ pub fn apply_trilinear(&self, rgb: [f32; 3]) -> [f32; 3] {+ let n = self.size;+ let (x, y, z) = (self.coord(rgb[0], 0), self.coord(rgb[1], 1), self.coord(rgb[2], 2));+ let (r0, g0, b0) = ((x as usize).min(n - 2), (y as usize).min(n - 2), (z as usize).min(n - 2));+ let (fr, fg, fb) = (x - r0 as f32, y - g0 as f32, z - b0 as f32);+ let mut out = [0f32; 3];+ for (k, o) in out.iter_mut().enumerate() {+ let c = |dr, dg, db| self.at(r0 + dr, g0 + dg, b0 + db)[k];+ let x00 = c(0, 0, 0) + (c(1, 0, 0) - c(0, 0, 0)) * fr;+ let x10 = c(0, 1, 0) + (c(1, 1, 0) - c(0, 1, 0)) * fr;+ let x01 = c(0, 0, 1) + (c(1, 0, 1) - c(0, 0, 1)) * fr;+ let x11 = c(0, 1, 1) + (c(1, 1, 1) - c(0, 1, 1)) * fr;+ let y0 = x00 + (x10 - x00) * fg;+ let y1 = x01 + (x11 - x01) * fg;+ *o = y0 + (y1 - y0) * fb;+ }+ out+ }+}++/// A LUT file: an optional 1D table (alone, or as a shaper) and an optional 3D cube.+#[derive(Clone, Debug, PartialEq)]+pub struct Lut {+ pub title: String,+ pub shaper: Option<Lut1d>,+ pub cube: Option<Lut3d>,+}++/// File formats [`Lut::parse`] understands.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LutFormat {+ Cube,+ ThreeDl,+}++impl LutFormat {+ pub fn from_path(path: &str) -> Option<LutFormat> {+ let ext = path.rsplit('.').next()?.to_ascii_lowercase();+ match ext.as_str() {+ "cube" => Some(LutFormat::Cube),+ "3dl" => Some(LutFormat::ThreeDl),+ _ => None,+ }+ }+ pub fn extension(self) -> &'static str {+ match self {+ LutFormat::Cube => "cube",+ LutFormat::ThreeDl => "3dl",+ }+ }+}++fn floats(line: &str) -> Result<Vec<f32>, String> {+ line.split_whitespace().map(|x| x.parse::<f32>().map_err(|_| format!("not a number: {x:?}"))).collect()+}++impl Lut {+ pub fn from_cube(cube: Lut3d) -> Self {+ Lut { title: cube.title.clone(), shaper: None, cube: Some(cube) }+ }++ /// Parse by format (sniffs `LUT_*_SIZE` for `.cube` when the format is unknown).+ pub fn parse(text: &str, format: Option<LutFormat>) -> Result<Lut, String> {+ match format {+ Some(LutFormat::Cube) => Lut::parse_cube(text),+ Some(LutFormat::ThreeDl) => Lut::parse_3dl(text),+ None if text.contains("LUT_3D_SIZE") || text.contains("LUT_1D_SIZE") => Lut::parse_cube(text),+ None => Lut::parse_3dl(text),+ }+ }++ pub fn parse_cube(text: &str) -> Result<Lut, String> {+ let mut size1 = 0usize;+ let mut size3 = 0usize;+ let mut title = String::new();+ let mut dmin = [0.0f32; 3];+ let mut dmax = [1.0f32; 3];+ let mut range1: Option<[f32; 2]> = None;+ let mut range3: Option<[f32; 2]> = None;+ let mut rows: Vec<[f32; 3]> = Vec::new();+ for (ln, raw) in text.lines().enumerate() {+ let line = raw.split('#').next().unwrap_or("").trim();+ if line.is_empty() {+ continue;+ }+ let mut it = line.split_whitespace();+ let key = it.next().unwrap_or("");+ let err = |m: &str| format!("line {}: {m}", ln + 1);+ if key.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) {+ if !rows.is_empty() {+ return Err(err("keyword after table data"));+ }+ match key {+ "TITLE" => title = line[5..].trim().trim_matches('"').to_string(),+ "LUT_1D_SIZE" => {+ size1 = it.next().and_then(|v| v.parse().ok()).ok_or_else(|| err("bad LUT_1D_SIZE"))?;+ if !(2..=65536).contains(&size1) {+ return Err(err("LUT_1D_SIZE must be 2–65536"));+ }+ }+ "LUT_3D_SIZE" => {+ size3 = it.next().and_then(|v| v.parse().ok()).ok_or_else(|| err("bad LUT_3D_SIZE"))?;+ if !(2..=256).contains(&size3) {+ return Err(err("LUT_3D_SIZE must be 2–256"));+ }+ }+ "DOMAIN_MIN" | "DOMAIN_MAX" => {+ let v = floats(&line[key.len()..]).map_err(|e| err(&e))?;+ if v.len() != 3 {+ return Err(err(&format!("{key} needs 3 values")));+ }+ let t = if key == "DOMAIN_MIN" { &mut dmin } else { &mut dmax };+ t.copy_from_slice(&v);+ }+ "LUT_1D_INPUT_RANGE" | "LUT_3D_INPUT_RANGE" => {+ let v = floats(&line[key.len()..]).map_err(|e| err(&e))?;+ if v.len() != 2 {+ return Err(err(&format!("{key} needs 2 values")));+ }+ let r = Some([v[0], v[1]]);+ if key == "LUT_1D_INPUT_RANGE" { range1 = r } else { range3 = r }+ }+ // unknown keywords (vendor extensions) are ignored, as the spec allows+ _ => {}+ }+ continue;+ }+ let v = floats(line).map_err(|e| err(&e))?;+ if v.len() != 3 {+ return Err(err("data rows need 3 values"));+ }+ rows.push([v[0], v[1], v[2]]);+ }+ if size1 == 0 && size3 == 0 {+ return Err("no LUT_1D_SIZE or LUT_3D_SIZE".into());+ }+ let want = size1 + size3 * size3 * size3;+ if rows.len() != want {+ return Err(format!("expected {want} table rows, found {}", rows.len()));+ }+ for d in 0..3 {+ if dmax[d] <= dmin[d] {+ return Err("DOMAIN_MAX must exceed DOMAIN_MIN".into());+ }+ }+ let both = size1 > 0 && size3 > 0;+ let dom = |r: Option<[f32; 2]>, own: bool| match r {+ Some(r) => ([r[0]; 3], [r[1]; 3]),+ None if own => (dmin, dmax),+ None => ([0.0; 3], [1.0; 3]),+ };+ let shaper = (size1 > 0).then(|| {+ let (lo, hi) = dom(range1, true);+ Lut1d { domain_min: lo, domain_max: hi, data: rows[..size1].to_vec() }+ });+ let cube = (size3 > 0).then(|| {+ // with a shaper in front, the cube sees the shaper's output (0..1 unless stated)+ let (lo, hi) = dom(range3, !both);+ Lut3d { title: title.clone(), size: size3, domain_min: lo, domain_max: hi, data: rows[size1..].to_vec() }+ });+ Ok(Lut { title, shaper, cube })+ }++ pub fn to_cube(&self) -> String {+ let mut s = String::new();+ if !self.title.is_empty() {+ let _ = writeln!(s, "TITLE \"{}\"", self.title.replace('"', "'"));+ }+ let both = self.shaper.is_some() && self.cube.is_some();+ if let Some(sh) = &self.shaper {+ let _ = writeln!(s, "LUT_1D_SIZE {}", sh.size());+ if both {+ if sh.domain_min != [0.0; 3] || sh.domain_max != [1.0; 3] {+ let _ = writeln!(s, "LUT_1D_INPUT_RANGE {} {}", sh.domain_min[0], sh.domain_max[0]);+ }+ } else {+ write_domain(&mut s, sh.domain_min, sh.domain_max);+ }+ }+ if let Some(c) = &self.cube {+ let _ = writeln!(s, "LUT_3D_SIZE {}", c.size);+ if both {+ if c.domain_min != [0.0; 3] || c.domain_max != [1.0; 3] {+ let _ = writeln!(s, "LUT_3D_INPUT_RANGE {} {}", c.domain_min[0], c.domain_max[0]);+ }+ } else {+ write_domain(&mut s, c.domain_min, c.domain_max);+ }+ }+ for d in self.shaper.iter().flat_map(|l| &l.data).chain(self.cube.iter().flat_map(|l| &l.data)) {+ let _ = writeln!(s, "{} {} {}", fmt6(d[0]), fmt6(d[1]), fmt6(d[2]));+ }+ s+ }++ /// Parse an Autodesk `.3dl`.+ pub fn parse_3dl(text: &str) -> Result<Lut, String> {+ let mut mesh: Option<Vec<f32>> = None;+ let mut out_bits: Option<u32> = None;+ let mut rows: Vec<[f32; 3]> = Vec::new();+ for (ln, raw) in text.lines().enumerate() {+ let line = raw.split('#').next().unwrap_or("").trim();+ if line.is_empty() {+ continue;+ }+ let err = |m: &str| format!("line {}: {m}", ln + 1);+ let first = line.split_whitespace().next().unwrap_or("");+ if first.eq_ignore_ascii_case("3DMESH") || first.eq_ignore_ascii_case("LUT8") || first.eq_ignore_ascii_case("GAMMA") {+ continue;+ }+ if first.eq_ignore_ascii_case("Mesh") {+ let v: Vec<u32> = line.split_whitespace().skip(1).filter_map(|x| x.parse().ok()).collect();+ if v.len() == 2 {+ out_bits = Some(v[1]);+ }+ continue;+ }+ let v = floats(line).map_err(|e| err(&e))?;+ if mesh.is_none() {+ if v.len() < 2 {+ return Err(err("expected the input mesh line"));+ }+ mesh = Some(v);+ continue;+ }+ if v.len() != 3 {+ return Err(err("data rows need 3 values"));+ }+ rows.push([v[0], v[1], v[2]]);+ }+ let mesh = mesh.ok_or("empty .3dl")?;+ let n = mesh.len();+ if rows.len() != n * n * n {+ return Err(format!("expected {}³ = {} rows, found {}", n, n * n * n, rows.len()));+ }+ if mesh.windows(2).any(|w| w[1] <= w[0]) {+ return Err("input mesh must increase".into());+ }+ let in_max = bit_max(mesh[n - 1]);+ let peak = rows.iter().flat_map(|r| r.iter()).fold(0f32, |a, b| a.max(*b));+ let out_max = match out_bits {+ Some(b) if (8..=16).contains(&b) => ((1u32 << b) - 1) as f32,+ _ => bit_max(peak),+ };+ // blue fastest in the file → red fastest in memory+ let mut data = vec![[0f32; 3]; n * n * n];+ for (i, r) in rows.iter().enumerate() {+ let (ri, gi, bi) = (i / (n * n), (i / n) % n, i % n);+ data[ri + gi * n + bi * n * n] = [r[0] / out_max, r[1] / out_max, r[2] / out_max];+ }+ let lo = mesh[0] / in_max;+ let hi = mesh[n - 1] / in_max;+ let uniform = mesh.iter().enumerate().all(|(i, m)| (m - (mesh[0] + (mesh[n - 1] - mesh[0]) * i as f32 / (n - 1) as f32)).abs() <= 1.0);+ let shaper = (!uniform).then(|| {+ // piecewise-linear map from input value to the mesh index, as a 1D shaper+ let size = 4096;+ let data = (0..size)+ .map(|k| {+ let x = k as f32 / (size - 1) as f32 * in_max;+ let j = mesh.iter().position(|m| *m > x).unwrap_or(n).clamp(1, n - 1);+ let t = ((x - mesh[j - 1]) / (mesh[j] - mesh[j - 1])).clamp(0.0, 1.0);+ [((j - 1) as f32 + t) / (n - 1) as f32; 3]+ })+ .collect();+ Lut1d { domain_min: [0.0; 3], domain_max: [1.0; 3], data }+ });+ let (dmin, dmax) = if uniform { ([lo; 3], [hi; 3]) } else { ([0.0; 3], [1.0; 3]) };+ Ok(Lut { title: String::new(), shaper, cube: Some(Lut3d { title: String::new(), size: n, domain_min: dmin, domain_max: dmax, data }) })+ }++ /// Write a `.3dl` (10-bit input mesh, 12-bit output). Shapers are baked into the cube.+ pub fn to_3dl(&self) -> Result<String, String> {+ let cube = self.baked_cube(33)?;+ let n = cube.size;+ let mut s = String::from("# written by FilmCraft\n");+ if !self.title.is_empty() {+ let _ = writeln!(s, "# {}", self.title);+ }+ let mesh: Vec<String> = (0..n).map(|i| ((i as f64 * 1023.0 / (n - 1) as f64).round() as u32).to_string()).collect();+ let _ = writeln!(s, "{}", mesh.join(" "));+ let q = |v: f32| (v.clamp(0.0, 1.0) * 4095.0).round() as u32;+ for r in 0..n {+ for g in 0..n {+ for b in 0..n {+ let v = cube.at(r, g, b);+ let _ = writeln!(s, "{} {} {}", q(v[0]), q(v[1]), q(v[2]));+ }+ }+ }+ Ok(s)+ }++ /// The LUT as a single cube over 0..1 (resampled when there is a shaper or a non-unit domain).+ pub fn baked_cube(&self, size: usize) -> Result<Lut3d, String> {+ match (&self.shaper, &self.cube) {+ (None, Some(c)) if c.domain_min == [0.0; 3] && c.domain_max == [1.0; 3] => Ok(c.clone()),+ (None, None) => Err("empty LUT".into()),+ _ => Ok(Lut3d { title: self.title.clone(), ..Lut3d::from_fn(size, |c| self.apply(c)) }),+ }+ }++ #[inline]+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {+ let mut c = rgb;+ if let Some(s) = &self.shaper {+ c = s.apply(c);+ }+ if let Some(l) = &self.cube {+ c = l.apply(c);+ }+ c+ }+}++fn write_domain(s: &mut String, lo: [f32; 3], hi: [f32; 3]) {+ if lo != [0.0; 3] || hi != [1.0; 3] {+ let _ = writeln!(s, "DOMAIN_MIN {} {} {}", lo[0], lo[1], lo[2]);+ let _ = writeln!(s, "DOMAIN_MAX {} {} {}", hi[0], hi[1], hi[2]);+ }+}++fn fmt6(v: f32) -> String {+ let s = format!("{v:.6}");+ if s == "-0.000000" { "0.000000".into() } else { s }+}++/// Full-scale value of the smallest common integer depth that holds `v`.+fn bit_max(v: f32) -> f32 {+ [255.0, 1023.0, 4095.0, 16383.0, 65535.0].into_iter().find(|m| v <= *m).unwrap_or(65535.0)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Brute-force tetrahedral reference: find the Kuhn simplex (one of the 6 tetrahedra along the+ /// cell diagonal) whose barycentric coordinates are all ≥ 0, by solving a 3×3 system for each.+ fn brute_tetra(l: &Lut3d, rgb: [f32; 3]) -> [f32; 3] {+ let n = l.size;+ let g: Vec<f64> = (0..3).map(|c| ((rgb[c] - l.domain_min[c]) / (l.domain_max[c] - l.domain_min[c])).clamp(0.0, 1.0) as f64 * (n - 1) as f64).collect();+ let base: Vec<usize> = g.iter().map(|v| (*v as usize).min(n - 2)).collect();+ let f = [g[0] - base[0] as f64, g[1] - base[1] as f64, g[2] - base[2] as f64];+ let perms = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]];+ for p in perms {+ // vertices: 0, e_p0, e_p0+e_p1, 1+ let mut v = [[0usize; 3]; 4];+ v[1][p[0]] = 1;+ v[2] = v[1];+ v[2][p[1]] = 1;+ v[3] = [1, 1, 1];+ // solve f = a1 v1 + a2 v2 + a3 v3 (v0 = 0)+ let m = [+ [v[1][0] as f64, v[2][0] as f64, v[3][0] as f64],+ [v[1][1] as f64, v[2][1] as f64, v[3][1] as f64],+ [v[1][2] as f64, v[2][2] as f64, v[3][2] as f64],+ ];+ let a = crate::spaces::mul_vec(&crate::spaces::inverse(&m), f);+ let a0 = 1.0 - a[0] - a[1] - a[2];+ if [a0, a[0], a[1], a[2]].iter().all(|w| *w >= -1e-9) {+ let ws = [a0, a[0], a[1], a[2]];+ let mut o = [0f64; 3];+ for (k, vert) in v.iter().enumerate() {+ let c = l.at(base[0] + vert[0], base[1] + vert[1], base[2] + vert[2]);+ for ch in 0..3 {+ o[ch] += ws[k] * c[ch] as f64;+ }+ }+ return o.map(|x| x as f32);+ }+ }+ unreachable!("point in no tetrahedron")+ }++ fn wild(size: usize) -> Lut3d {+ // a non-linear, non-separable LUT+ Lut3d::from_fn(size, |c| [(c[0] * c[1] + c[2].powi(2)).sin(), c[1].powf(0.45) * (1.0 - 0.3 * c[0]), (c[0] - c[2]).abs() + 0.1 * c[1]])+ }++ #[test]+ fn tetrahedral_matches_brute_force() {+ let mut s = 12345u64;+ let mut rnd = || {+ s ^= s << 13;+ s ^= s >> 7;+ s ^= s << 17;+ (s % 1_000_001) as f32 / 1_000_000.0+ };+ for size in [2, 5, 17, 33] {+ let l = wild(size);+ for _ in 0..2000 {+ let c = [rnd() * 1.1 - 0.05, rnd(), rnd()];+ let a = l.apply(c);+ let b = brute_tetra(&l, c);+ for k in 0..3 {+ assert!((a[k] - b[k]).abs() < 1e-5, "size {size} {c:?}: {a:?} vs {b:?}");+ }+ }+ }+ }++ #[test]+ fn tetrahedral_exact_on_affine_and_nodes() {+ let aff = |c: [f32; 3]| [0.2 + 0.5 * c[0] - 0.1 * c[2], 0.3 * c[1] + 0.4 * c[0], 0.9 * c[2] - 0.05];+ let l = Lut3d::from_fn(9, aff);+ for c in [[0.13, 0.77, 0.5], [0.99, 0.01, 0.42], [0.5, 0.5, 0.5]] {+ let (a, b) = (l.apply(c), aff(c));+ assert!((0..3).all(|k| (a[k] - b[k]).abs() < 1e-5));+ }+ let w = wild(7);+ for (r, g, b) in [(0, 0, 0), (3, 5, 1), (6, 6, 6)] {+ let c = [r as f32 / 6.0, g as f32 / 6.0, b as f32 / 6.0];+ let (a, t, want) = (w.apply(c), w.apply_trilinear(c), w.at(r, g, b));+ assert!((0..3).all(|k| (a[k] - want[k]).abs() < 1e-6 && (t[k] - want[k]).abs() < 1e-6));+ }+ }++ #[test]+ fn cube_roundtrip_3d_1d_and_shaper() {+ let mut c = wild(17);+ c.title = "wild".into();+ c.domain_min = [-0.1, 0.0, 0.0];+ c.domain_max = [1.5, 1.0, 2.0];+ let lut = Lut::from_cube(c);+ let text = lut.to_cube();+ assert!(text.contains("DOMAIN_MIN -0.1 0 0") && text.contains("LUT_3D_SIZE 17"));+ let back = Lut::parse_cube(&text).unwrap();+ assert_eq!(back.title, "wild");+ let (a, b) = (lut.cube.as_ref().unwrap(), back.cube.as_ref().unwrap());+ assert_eq!((a.size, a.domain_min, a.domain_max), (b.size, b.domain_min, b.domain_max));+ assert!(a.data.iter().zip(&b.data).all(|(x, y)| (0..3).all(|k| (x[k] - y[k]).abs() < 1e-6)));+ // 1D only+ let one = Lut {+ title: String::new(),+ shaper: Some(Lut1d { domain_min: [0.0; 3], domain_max: [1.0; 3], data: (0..1024).map(|i| [(i as f32 / 1023.0).powf(2.2); 3]).collect() }),+ cube: None,+ };+ let back = Lut::parse_cube(&one.to_cube()).unwrap();+ assert_eq!(back.shaper.as_ref().unwrap().size(), 1024);+ assert!((back.apply([0.5; 3])[0] - 0.5f32.powf(2.2)).abs() < 1e-4);+ // shaper + cube+ let both = Lut { title: "s".into(), shaper: one.shaper.clone(), cube: Some(Lut3d::identity(9)) };+ let back = Lut::parse_cube(&both.to_cube()).unwrap();+ assert!(back.shaper.is_some() && back.cube.is_some());+ assert!((back.apply([0.5; 3])[1] - 0.5f32.powf(2.2)).abs() < 1e-3);+ }++ #[test]+ fn cube_sizes_up_to_65_and_errors() {+ let l = Lut3d::identity(65);+ let back = Lut3d::parse_cube(&l.to_cube()).unwrap();+ assert_eq!(back.size, 65);+ let v = back.apply([0.3, 0.55, 0.91]);+ assert!((v[0] - 0.3).abs() < 1e-5 && (v[1] - 0.55).abs() < 1e-5 && (v[2] - 0.91).abs() < 1e-5);+ assert!(Lut3d::parse_cube("LUT_3D_SIZE 2\n0 0 0\n").is_err());+ assert!(Lut::parse_cube("LUT_3D_SIZE 1\n0 0 0\n").is_err());+ assert!(Lut::parse_cube("TITLE \"x\"\n").is_err());+ assert!(Lut::parse_cube("LUT_3D_SIZE 2\n0 0 0\nLUT_1D_SIZE 2\n").is_err());+ assert!(Lut::parse_cube("LUT_3D_SIZE 2\nDOMAIN_MIN 1 1 1\nDOMAIN_MAX 0 0 0\n0 0 0\n0 0 0\n0 0 0\n0 0 0\n0 0 0\n0 0 0\n0 0 0\n0 0 0\n").is_err());+ // comments, blank lines, Windows newlines, inline comments+ let txt = "# hi\r\nTITLE \"t\"\r\n\r\nLUT_3D_SIZE 2 # two\r\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";+ let l = Lut3d::parse_cube(txt).unwrap();+ assert_eq!(l.apply([0.25, 0.5, 0.75]), [0.25, 0.5, 0.75]);+ }++ #[test]+ fn threedl_roundtrip_and_orientation() {+ // a LUT that swaps red and blue, so orientation errors show+ let swap = Lut::from_cube(Lut3d::from_fn(17, |c| [c[2], c[1] * 0.5, c[0]]));+ let text = swap.to_3dl().unwrap();+ assert!(text.lines().nth(1).unwrap().starts_with("0 64 128"));+ let back = Lut::parse_3dl(&text).unwrap();+ for c in [[0.1, 0.2, 0.9], [0.8, 0.5, 0.3]] {+ let (a, b) = (swap.apply(c), back.apply(c));+ assert!((0..3).all(|k| (a[k] - b[k]).abs() < 1.0 / 4095.0 + 1e-4), "{a:?} vs {b:?}");+ }+ // hand-written 2-point Lustre file, blue fastest, 12-bit output+ let lustre = "3DMESH\nMesh 1 12\n0 1023\n0 0 0\n0 0 4095\n0 4095 0\n0 4095 4095\n4095 0 0\n4095 0 4095\n4095 4095 0\n4095 4095 4095\n";+ let l = Lut::parse_3dl(lustre).unwrap();+ let v = l.apply([0.2, 0.4, 0.6]);+ assert!((v[0] - 0.2).abs() < 1e-4 && (v[1] - 0.4).abs() < 1e-4 && (v[2] - 0.6).abs() < 1e-4, "{v:?}");+ // non-uniform mesh → shaper+ let nu = "0 100 1023\n".to_string() + &(0..27).map(|i| format!("{} {} {}\n", (i / 9) * 2047, ((i / 3) % 3) * 2047, (i % 3) * 2047)).collect::<String>();+ let l = Lut::parse_3dl(&nu).unwrap();+ assert!(l.shaper.is_some());+ let v = l.apply([100.0 / 1023.0, 0.0, 1.0]);+ assert!((v[0] - 2047.0 / 4095.0).abs() < 2e-3, "{v:?}");+ assert!(Lut::parse_3dl("0 512 1023\n1 2 3\n").is_err());+ // format sniffing+ assert!(Lut::parse(&swap.to_cube(), None).is_ok());+ assert!(Lut::parse(&text, None).is_ok());+ assert_eq!(LutFormat::from_path("a/b/Look.CUBE"), Some(LutFormat::Cube));+ }+}diff --git a/crates/color/src/spaces.rs b/crates/color/src/spaces.rsnew file mode 100644index 000000000..0dd93f271--- /dev/null+++ b/crates/color/src/spaces.rs@@ -0,0 +1,419 @@+//! Colour spaces: RGB primaries (and the 3×3 matrices between them), named source colour spaces+//! for "Interpret Footage ▸ Color Management", and the sequence working space.+//!+//! Every gamut here has a D65 white point, so conversions are a plain RGB→XYZ→RGB product with no+//! chromatic adaptation. Matrices follow SMPTE RP 177 (derivation of the normalised primary+//! matrix from chromaticities).++use serde::{Deserialize, Serialize};++use crate::log::LogCurve;+use crate::{ColorInfo, Primaries, Transfer};++pub type Mat3 = [[f64; 3]; 3];++pub const D65: [f64; 2] = [0.3127, 0.3290];++/// A set of RGB primaries (all D65).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum Gamut {+ Bt709,+ Bt2020,+ P3D65,+ /// Sony S-Gamut3.Cine.+ SGamut3Cine,+ /// Sony S-Gamut3.+ SGamut3,+ /// Panasonic V-Gamut.+ VGamut,+ /// Canon Cinema Gamut.+ CinemaGamut,+ /// ARRI Wide Gamut 3.+ Awg3,+ /// ARRI Wide Gamut 4.+ Awg4,+ /// DJI D-Gamut.+ DGamut,+}++impl Gamut {+ /// (x, y) of R, G, B. Sources: ITU-R BT.709-6, BT.2020-2, SMPTE EG 432-1 (P3), and the camera+ /// vendors' documents listed in the crate README.+ pub fn primaries(self) -> [[f64; 2]; 3] {+ match self {+ Gamut::Bt709 => [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]],+ Gamut::Bt2020 => [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]],+ Gamut::P3D65 => [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]],+ Gamut::SGamut3Cine => [[0.766, 0.275], [0.225, 0.800], [0.089, -0.087]],+ Gamut::SGamut3 => [[0.730, 0.280], [0.140, 0.855], [0.100, -0.050]],+ Gamut::VGamut => [[0.730, 0.280], [0.165, 0.840], [0.100, -0.030]],+ Gamut::CinemaGamut => [[0.740, 0.270], [0.170, 1.140], [0.080, -0.100]],+ Gamut::Awg3 => [[0.6840, 0.3130], [0.2210, 0.8480], [0.0861, -0.1020]],+ Gamut::Awg4 => [[0.7347, 0.2653], [0.1424, 0.8576], [0.0991, -0.0308]],+ Gamut::DGamut => [[0.71, 0.31], [0.21, 0.88], [0.09, -0.08]],+ }+ }++ pub fn from_primaries(p: Primaries) -> Gamut {+ match p {+ Primaries::Bt2020 => Gamut::Bt2020,+ Primaries::P3D65 => Gamut::P3D65,+ // BT.601 primaries are close enough to BT.709 that NLEs treat them as such.+ _ => Gamut::Bt709,+ }+ }++ /// RGB → CIE XYZ (normalised so white Y = 1).+ pub fn to_xyz(self) -> Mat3 {+ npm(self.primaries(), D65)+ }++ /// Luminance weights (the Y row of [`Gamut::to_xyz`]).+ pub fn luma(self) -> [f64; 3] {+ self.to_xyz()[1]+ }+}++/// Normalised primary matrix (SMPTE RP 177).+pub fn npm(p: [[f64; 2]; 3], w: [f64; 2]) -> Mat3 {+ let xyz = |c: [f64; 2]| [c[0] / c[1], 1.0, (1.0 - c[0] - c[1]) / c[1]];+ let (r, g, b) = (xyz(p[0]), xyz(p[1]), xyz(p[2]));+ let m = [[r[0], g[0], b[0]], [r[1], g[1], b[1]], [r[2], g[2], b[2]]];+ let s = mul_vec(&inverse(&m), xyz(w));+ [[m[0][0] * s[0], m[0][1] * s[1], m[0][2] * s[2]], [m[1][0] * s[0], m[1][1] * s[1], m[1][2] * s[2]], [m[2][0] * s[0], m[2][1] * s[1], m[2][2] * s[2]]]+}++pub fn mul(a: &Mat3, b: &Mat3) -> Mat3 {+ let mut o = [[0.0; 3]; 3];+ for i in 0..3 {+ for j in 0..3 {+ o[i][j] = (0..3).map(|k| a[i][k] * b[k][j]).sum();+ }+ }+ o+}++pub fn mul_vec(m: &Mat3, v: [f64; 3]) -> [f64; 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]]+}++pub fn inverse(m: &Mat3) -> Mat3 {+ let [[a, b, c], [d, e, f], [g, h, i]] = *m;+ let det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);+ let k = 1.0 / det;+ [+ [(e * i - f * h) * k, (c * h - b * i) * k, (b * f - c * e) * k],+ [(f * g - d * i) * k, (a * i - c * g) * k, (c * d - a * f) * k],+ [(d * h - e * g) * k, (b * g - a * h) * k, (a * e - b * d) * k],+ ]+}++pub const IDENTITY: Mat3 = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];++/// Linear RGB in `src` → linear RGB in `dst`.+pub fn gamut_matrix(src: Gamut, dst: Gamut) -> Mat3 {+ if src == dst {+ return IDENTITY;+ }+ mul(&inverse(&dst.to_xyz()), &src.to_xyz())+}++pub fn to_f32(m: &Mat3) -> [[f32; 3]; 3] {+ m.map(|r| r.map(|v| v as f32))+}++#[inline]+pub fn apply3(m: &[[f32; 3]; 3], c: [f32; 3]) -> [f32; 3] {+ [m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2], m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2], m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2]]+}++/// How a colour space's signal becomes light.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum Curve {+ /// Display-referred SDR (BT.709 / BT.1886 / sRGB) — decoded with the sRGB curve like the rest+ /// of the pipeline; 1.0 = SDR white.+ Sdr,+ Srgb,+ Linear,+ /// SMPTE ST 2084, absolute.+ Pq,+ /// ARIB STD-B67 / BT.2100 HLG (scene light; the OOTF is applied separately).+ Hlg,+ Log(LogCurve),+}++/// Source colour spaces offered by Interpret Footage ▸ Color Management.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum ColorSpace {+ Rec709,+ Srgb,+ /// Rec. 2020 SDR (BT.2020 primaries, BT.709-style transfer).+ Rec2020,+ /// Display P3 (D65) SDR.+ P3D65,+ /// Rec. 2100 PQ (BT.2020 primaries, ST 2084).+ Rec2100Pq,+ /// Rec. 2100 HLG.+ Rec2100Hlg,+ SLog3SGamut3Cine,+ SLog3SGamut3,+ VLogVGamut,+ CLog2CinemaGamut,+ CLog3CinemaGamut,+ LogC3Awg3,+ LogC4Awg4,+ /// Apple Log (BT.2020 primaries).+ AppleLog,+ DLogDGamut,+ /// Linear light with BT.709 primaries (EXR-style float sources).+ Linear709,+}++impl ColorSpace {+ pub const ALL: [ColorSpace; 16] = [+ ColorSpace::Rec709,+ ColorSpace::Srgb,+ ColorSpace::Rec2020,+ ColorSpace::P3D65,+ ColorSpace::Rec2100Pq,+ ColorSpace::Rec2100Hlg,+ ColorSpace::SLog3SGamut3Cine,+ ColorSpace::SLog3SGamut3,+ ColorSpace::VLogVGamut,+ ColorSpace::CLog2CinemaGamut,+ ColorSpace::CLog3CinemaGamut,+ ColorSpace::LogC3Awg3,+ ColorSpace::LogC4Awg4,+ ColorSpace::AppleLog,+ ColorSpace::DLogDGamut,+ ColorSpace::Linear709,+ ];++ /// Stable id used in commands and project files.+ pub fn id(self) -> &'static str {+ match self {+ ColorSpace::Rec709 => "rec709",+ ColorSpace::Srgb => "srgb",+ ColorSpace::Rec2020 => "rec2020",+ ColorSpace::P3D65 => "p3d65",+ ColorSpace::Rec2100Pq => "rec2100-pq",+ ColorSpace::Rec2100Hlg => "rec2100-hlg",+ ColorSpace::SLog3SGamut3Cine => "slog3-sgamut3cine",+ ColorSpace::SLog3SGamut3 => "slog3-sgamut3",+ ColorSpace::VLogVGamut => "vlog-vgamut",+ ColorSpace::CLog2CinemaGamut => "clog2-cinemagamut",+ ColorSpace::CLog3CinemaGamut => "clog3-cinemagamut",+ ColorSpace::LogC3Awg3 => "logc3-awg3",+ ColorSpace::LogC4Awg4 => "logc4-awg4",+ ColorSpace::AppleLog => "applelog",+ ColorSpace::DLogDGamut => "dlog-dgamut",+ ColorSpace::Linear709 => "linear709",+ }+ }++ pub fn label(self) -> &'static str {+ match self {+ ColorSpace::Rec709 => "Rec. 709",+ ColorSpace::Srgb => "sRGB",+ ColorSpace::Rec2020 => "Rec. 2020",+ ColorSpace::P3D65 => "P3 D65",+ ColorSpace::Rec2100Pq => "Rec. 2100 PQ",+ ColorSpace::Rec2100Hlg => "Rec. 2100 HLG",+ ColorSpace::SLog3SGamut3Cine => "Sony S-Log3 / S-Gamut3.Cine",+ ColorSpace::SLog3SGamut3 => "Sony S-Log3 / S-Gamut3",+ ColorSpace::VLogVGamut => "Panasonic V-Log / V-Gamut",+ ColorSpace::CLog2CinemaGamut => "Canon Log 2 / Cinema Gamut",+ ColorSpace::CLog3CinemaGamut => "Canon Log 3 / Cinema Gamut",+ ColorSpace::LogC3Awg3 => "ARRI LogC3 / ARRI Wide Gamut 3",+ ColorSpace::LogC4Awg4 => "ARRI LogC4 / ARRI Wide Gamut 4",+ ColorSpace::AppleLog => "Apple Log / Rec. 2020",+ ColorSpace::DLogDGamut => "DJI D-Log / D-Gamut",+ ColorSpace::Linear709 => "Linear (Rec. 709 primaries)",+ }+ }++ /// Parse an id or a label (case-insensitive, punctuation ignored).+ pub fn parse(s: &str) -> Option<ColorSpace> {+ let norm = |x: &str| x.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();+ let n = norm(s);+ ColorSpace::ALL.into_iter().find(|c| norm(c.id()) == n || norm(c.label()) == n)+ }++ pub fn gamut(self) -> Gamut {+ match self {+ ColorSpace::Rec709 | ColorSpace::Srgb | ColorSpace::Linear709 => Gamut::Bt709,+ ColorSpace::Rec2020 | ColorSpace::Rec2100Pq | ColorSpace::Rec2100Hlg | ColorSpace::AppleLog => Gamut::Bt2020,+ ColorSpace::P3D65 => Gamut::P3D65,+ ColorSpace::SLog3SGamut3Cine => Gamut::SGamut3Cine,+ ColorSpace::SLog3SGamut3 => Gamut::SGamut3,+ ColorSpace::VLogVGamut => Gamut::VGamut,+ ColorSpace::CLog2CinemaGamut | ColorSpace::CLog3CinemaGamut => Gamut::CinemaGamut,+ ColorSpace::LogC3Awg3 => Gamut::Awg3,+ ColorSpace::LogC4Awg4 => Gamut::Awg4,+ ColorSpace::DLogDGamut => Gamut::DGamut,+ }+ }++ pub fn curve(self) -> Curve {+ match self {+ ColorSpace::Rec709 | ColorSpace::Rec2020 | ColorSpace::P3D65 => Curve::Sdr,+ ColorSpace::Srgb => Curve::Srgb,+ ColorSpace::Linear709 => Curve::Linear,+ ColorSpace::Rec2100Pq => Curve::Pq,+ ColorSpace::Rec2100Hlg => Curve::Hlg,+ ColorSpace::SLog3SGamut3Cine | ColorSpace::SLog3SGamut3 => Curve::Log(LogCurve::SLog3),+ ColorSpace::VLogVGamut => Curve::Log(LogCurve::VLog),+ ColorSpace::CLog2CinemaGamut => Curve::Log(LogCurve::CLog2),+ ColorSpace::CLog3CinemaGamut => Curve::Log(LogCurve::CLog3),+ ColorSpace::LogC3Awg3 => Curve::Log(LogCurve::LogC3),+ ColorSpace::LogC4Awg4 => Curve::Log(LogCurve::LogC4),+ ColorSpace::AppleLog => Curve::Log(LogCurve::AppleLog),+ ColorSpace::DLogDGamut => Curve::Log(LogCurve::DLog),+ }+ }++ /// Carries more than SDR range (needs tone mapping into an SDR working space).+ pub fn is_hdr(self) -> bool {+ matches!(self.curve(), Curve::Pq | Curve::Hlg | Curve::Log(_))+ }+ pub fn is_log(self) -> bool {+ matches!(self.curve(), Curve::Log(_))+ }++ /// The colour space signalled by stream metadata (VUI / `colr` / MKV Colour).+ pub fn from_info(c: &ColorInfo) -> ColorSpace {+ match (c.transfer, c.primaries) {+ (Transfer::Pq, _) => ColorSpace::Rec2100Pq,+ (Transfer::Hlg, _) => ColorSpace::Rec2100Hlg,+ (Transfer::Linear, _) => ColorSpace::Linear709,+ (Transfer::Srgb, Primaries::P3D65) => ColorSpace::P3D65,+ (Transfer::Srgb, _) => ColorSpace::Srgb,+ (_, Primaries::Bt2020) => ColorSpace::Rec2020,+ (_, Primaries::P3D65) => ColorSpace::P3D65,+ _ => ColorSpace::Rec709,+ }+ }+}++/// Sequence working colour space (Sequence Settings ▸ Color).+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub enum WorkingSpace {+ #[default]+ Rec709,+ Rec2100Pq,+ Rec2100Hlg,+}++impl WorkingSpace {+ pub const ALL: [WorkingSpace; 3] = [WorkingSpace::Rec709, WorkingSpace::Rec2100Pq, WorkingSpace::Rec2100Hlg];++ pub fn id(self) -> &'static str {+ match self {+ WorkingSpace::Rec709 => "rec709",+ WorkingSpace::Rec2100Pq => "rec2100-pq",+ WorkingSpace::Rec2100Hlg => "rec2100-hlg",+ }+ }+ pub fn label(self) -> &'static str {+ match self {+ WorkingSpace::Rec709 => "Rec. 709",+ WorkingSpace::Rec2100Pq => "Rec. 2100 PQ",+ WorkingSpace::Rec2100Hlg => "Rec. 2100 HLG",+ }+ }+ pub fn parse(s: &str) -> Option<WorkingSpace> {+ let norm = |x: &str| x.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();+ let n = norm(s);+ WorkingSpace::ALL.into_iter().find(|w| norm(w.id()) == n || norm(w.label()) == n)+ }+ pub fn is_hdr(self) -> bool {+ self != WorkingSpace::Rec709+ }+ /// The colour space exports of this sequence are encoded in.+ pub fn output_space(self) -> ColorSpace {+ match self {+ WorkingSpace::Rec709 => ColorSpace::Rec709,+ WorkingSpace::Rec2100Pq => ColorSpace::Rec2100Pq,+ WorkingSpace::Rec2100Hlg => ColorSpace::Rec2100Hlg,+ }+ }+}++/// Everything the renderer needs to know about a sequence's colour pipeline.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+pub struct ColorPipeline {+ pub working: WorkingSpace,+ /// Composite in linear BT.2020 primaries even for a Rec. 709 sequence.+ pub wide_gamut: bool,+ /// Tone map HDR and log media into an SDR working space (Auto Tone Map Media).+ pub auto_tone_map: bool,+}++impl ColorPipeline {+ pub const REC709: ColorPipeline = ColorPipeline { working: WorkingSpace::Rec709, wide_gamut: false, auto_tone_map: true };++ /// Linear primaries of the compositing space.+ pub fn working_gamut(&self) -> Gamut {+ if self.working.is_hdr() || self.wide_gamut { Gamut::Bt2020 } else { Gamut::Bt709 }+ }+ /// The classic pipeline: linear BT.709, display-referred SDR.+ pub fn is_plain(&self) -> bool {+ !self.working.is_hdr() && !self.wide_gamut+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn bt709_npm_matches_published_matrix() {+ // ITU-R BT.709 / sRGB RGB→XYZ (IEC 61966-2-1 rounds to 4 places).+ let m = Gamut::Bt709.to_xyz();+ let want = [[0.4124, 0.3576, 0.1805], [0.2126, 0.7152, 0.0722], [0.0193, 0.1192, 0.9505]];+ for i in 0..3 {+ for j in 0..3 {+ assert!((m[i][j] - want[i][j]).abs() < 1e-4, "{i}{j}: {}", m[i][j]);+ }+ }+ // BT.2020 luma coefficients (BT.2020-2 table 4).+ let l = Gamut::Bt2020.luma();+ assert!((l[0] - 0.2627).abs() < 1e-4 && (l[1] - 0.6780).abs() < 1e-4 && (l[2] - 0.0593).abs() < 1e-4);+ }++ #[test]+ fn bt2020_to_709_matches_bt2087() {+ // ITU-R BT.2087-0, linear BT.2020 → BT.709 (inverse of the published 709→2020 matrix).+ let m = gamut_matrix(Gamut::Bt709, Gamut::Bt2020);+ let want = [[0.6274, 0.3293, 0.0433], [0.0691, 0.9195, 0.0114], [0.0164, 0.0880, 0.8956]];+ for i in 0..3 {+ for j in 0..3 {+ assert!((m[i][j] - want[i][j]).abs() < 1e-4, "{i}{j}: {}", m[i][j]);+ }+ }+ // white maps to white for every gamut pair+ for a in [Gamut::SGamut3Cine, Gamut::Awg4, Gamut::CinemaGamut, Gamut::DGamut, Gamut::VGamut] {+ let w = mul_vec(&gamut_matrix(a, Gamut::Bt709), [1.0, 1.0, 1.0]);+ assert!(w.iter().all(|v| (v - 1.0).abs() < 1e-9), "{a:?}: {w:?}");+ let back = mul(&gamut_matrix(Gamut::Bt709, a), &gamut_matrix(a, Gamut::Bt709));+ for i in 0..3 {+ for j in 0..3 {+ assert!((back[i][j] - IDENTITY[i][j]).abs() < 1e-9);+ }+ }+ }+ }++ #[test]+ fn ids_parse() {+ for c in ColorSpace::ALL {+ assert_eq!(ColorSpace::parse(c.id()), Some(c));+ assert_eq!(ColorSpace::parse(c.label()), Some(c));+ }+ assert_eq!(WorkingSpace::parse("Rec. 2100 PQ"), Some(WorkingSpace::Rec2100Pq));+ assert_eq!(WorkingSpace::parse("rec709"), Some(WorkingSpace::Rec709));+ let hdr = ColorInfo { transfer: Transfer::Hlg, primaries: Primaries::Bt2020, ..ColorInfo::REC709 };+ assert_eq!(ColorSpace::from_info(&hdr), ColorSpace::Rec2100Hlg);+ assert_eq!(ColorSpace::from_info(&ColorInfo::REC709), ColorSpace::Rec709);+ }+}diff --git a/crates/color/src/transform.rs b/crates/color/src/transform.rsnew file mode 100644index 000000000..77cbbcb01--- /dev/null+++ b/crates/color/src/transform.rs@@ -0,0 +1,475 @@+//! Colour-managed conversions between sources, the working space and outputs.+//!+//! **Working units.** The compositor works in linear light where 1.0 is *reference white*: SDR+//! white for SDR media, and 203 cd/m² for HDR (ITU-R BT.2408 "HDR Reference White"). SDR media+//! therefore keeps its values when it is placed in an HDR sequence, and HDR highlights are+//! simply values above 1.0. Log media decodes to scene-linear reflectance (18 % grey = 0.18).+//!+//! **Input** ([`InputTransform`]): signal → per-channel decode table (curve) → HLG OOTF (BT.2100,+//! 1000 cd/m² nominal peak, γ = 1.2) → 3×3 gamut matrix into the working primaries → tone mapping+//! (only when an HDR or log source enters an SDR working space and Auto Tone Map is on) → gamut+//! compression (only when the source gamut is wider than the working gamut).+//!+//! **Output** ([`OutputTransform`]): working linear → display-referred SDR BT.709 for monitors+//! (tone mapping from HDR working spaces, gamut mapping from wide gamut), or → encoded PQ/HLG+//! signal for HDR exports. Out-of-gamut colours there are desaturated towards their luminance+//! just enough to fit ([`desaturate_into_gamut`]), so in-gamut colours (e.g. BT.709 content in a+//! BT.2020 working space) come back exactly.+//!+//! **Tone mapping** is the ITU-R BT.2390 EETF (Hermite knee in the PQ domain) applied to+//! max(R,G,B) and used as a ratio on RGB, so hue and saturation are preserved. **Gamut+//! compression** pulls out-of-gamut colours (negative components after the matrix) towards the+//! achromatic axis with a per-channel distance compression after the ACES Reference Gamut+//! Compression (threshold 0.8, limit 1.25, power 1.2); colours inside 80 % of the gamut boundary+//! are unchanged.++use crate::log::{Domain, normalized_from_signal, signal_from_normalized};+use crate::spaces::{ColorPipeline, ColorSpace, Curve, Gamut, gamut_matrix, to_f32};+use crate::{Range, hlg_inverse_oetf, hlg_oetf, linear_to_srgb, pq_eotf, pq_inverse_eotf, srgb_to_linear};++/// BT.2408 HDR reference white.+pub const REFERENCE_WHITE_NITS: f64 = 203.0;+/// Nominal peak of an HLG display (BT.2100 Note 5c) and the default mastering peak of PQ media+/// without metadata.+pub const HDR_PEAK_NITS: f64 = 1000.0;+const HLG_GAMMA: f64 = 1.2;+/// Source peak assumed when tone mapping log media: the curve's own peak, capped here so the+/// BT.2390 knee starts above mid grey (≈ 45 cd/m², i.e. 0.22 in working units).+pub const LOG_PEAK_NITS: f64 = 4000.0;++/// Decode one channel: decoder-normalised signal → working-linear (no OOTF, no matrix).+pub fn decode_channel(v: f64, curve: Curve, range: Range) -> f64 {+ match curve {+ Curve::Sdr | Curve::Srgb => {+ if v < 0.0 {+ -(srgb_to_linear((-v) as f32) as f64)+ } else {+ srgb_to_linear(v as f32) as f64+ }+ }+ Curve::Linear => v,+ Curve::Pq => pq_eotf(v as f32) as f64 * 10_000.0 / REFERENCE_WHITE_NITS,+ // scene light 0..1; the OOTF (which needs all three channels) runs in the pixel stage+ Curve::Hlg => hlg_inverse_oetf(v.clamp(0.0, 1.0) as f32) as f64,+ Curve::Log(c) => c.decode(signal_from_normalized(v, range, c.domain())),+ }+}++/// Encode one channel: working-linear → decoder-normalised signal (inverse of [`decode_channel`]).+pub fn encode_channel(l: f64, curve: Curve, range: Range) -> f64 {+ match curve {+ Curve::Sdr | Curve::Srgb => {+ if l < 0.0 {+ -(linear_to_srgb((-l) as f32) as f64)+ } else {+ linear_to_srgb(l as f32) as f64+ }+ }+ Curve::Linear => l,+ Curve::Pq => pq_inverse_eotf((l.max(0.0) * REFERENCE_WHITE_NITS / 10_000.0) as f32) as f64,+ Curve::Hlg => hlg_oetf(l.clamp(0.0, 1.0) as f32) as f64,+ Curve::Log(c) => normalized_from_signal(c.encode(l), range, c.domain()),+ }+}++/// A sampled signal → linear lookup with linear interpolation over `[lo, hi]` (values outside+/// clamp), so log footage keeps its super-whites.+#[derive(Clone, Debug)]+pub struct DecodeTable {+ pub lo: f32,+ pub hi: f32,+ pub values: Vec<f32>,+}++impl DecodeTable {+ pub fn new(lo: f32, hi: f32, n: usize, f: impl Fn(f64) -> f64) -> Self {+ let values = (0..n).map(|i| f(lo as f64 + (hi - lo) as f64 * i as f64 / (n - 1) as f64) as f32).collect();+ DecodeTable { lo, hi, values }+ }+ /// The decode table for a colour space's curve.+ pub fn for_curve(curve: Curve, range: Range) -> Self {+ match curve {+ Curve::Log(_) => DecodeTable::new(-0.1, 1.1, 8192, |v| decode_channel(v, curve, range)),+ _ => DecodeTable::new(0.0, 1.0, 4096, |v| decode_channel(v, curve, range)),+ }+ }+ #[inline]+ pub fn lookup(&self, v: f32) -> f32 {+ let n = self.values.len() - 1;+ let p = ((v - self.lo) / (self.hi - self.lo)).clamp(0.0, 1.0) * n as f32;+ let i = (p as usize).min(n - 1);+ let f = p - i as f32;+ self.values[i] + (self.values[i + 1] - self.values[i]) * f+ }+}++/// ITU-R BT.2390 EETF: maps `nits` from a display with peak `src_peak` to one with peak+/// `dst_peak` (black level 0). Identity when `dst_peak ≥ src_peak`.+pub fn bt2390_eetf(nits: f64, src_peak: f64, dst_peak: f64) -> f64 {+ if dst_peak >= src_peak || nits <= 0.0 {+ return nits.max(0.0).min(src_peak.max(dst_peak));+ }+ let pq = |n: f64| pq_inverse_eotf((n / 10_000.0).clamp(0.0, 1.0) as f32) as f64;+ let smax = pq(src_peak);+ let e1 = (pq(nits) / smax).min(1.0);+ let max_lum = pq(dst_peak) / smax;+ let ks = 1.5 * max_lum - 0.5;+ let e2 = if e1 < ks {+ e1+ } else {+ let t = (e1 - ks) / (1.0 - ks);+ let (t2, t3) = (t * t, t * t * t);+ (2.0 * t3 - 3.0 * t2 + 1.0) * ks + (t3 - 2.0 * t2 + t) * (1.0 - ks) + (-2.0 * t3 + 3.0 * t2) * max_lum+ };+ pq_eotf((e2 * smax) as f32) as f64 * 10_000.0+}++/// Tone-mapping operator in working units: BT.2390 on max(R,G,B), applied as a ratio.+#[derive(Clone, Debug)]+pub struct ToneMap {+ pub src_peak_nits: f64,+ pub dst_peak_nits: f64,+ /// max(R,G,B) (working units) → scale factor, sampled in the PQ domain.+ table: DecodeTable,+}++impl ToneMap {+ pub fn new(src_peak_nits: f64, dst_peak_nits: f64) -> Self {+ let (s, d) = (src_peak_nits, dst_peak_nits);+ // sample on a PQ-encoded axis so the shadows get enough resolution+ let table = DecodeTable::new(0.0, 1.0, 4096, |e| {+ let nits = pq_eotf(e as f32) as f64 * 10_000.0;+ if nits <= 1e-6 { 1.0 } else { bt2390_eetf(nits, s, d) / nits }+ });+ ToneMap { src_peak_nits, dst_peak_nits, table }+ }+ #[inline]+ pub fn apply(&self, c: [f32; 3]) -> [f32; 3] {+ let m = c[0].max(c[1]).max(c[2]);+ if m <= 0.0 {+ return c;+ }+ let nits = m * REFERENCE_WHITE_NITS as f32;+ let k = if nits >= self.src_peak_nits as f32 {+ // above the source peak: clip to the target peak+ (self.dst_peak_nits / REFERENCE_WHITE_NITS) as f32 / m+ } else {+ self.table.lookup(pq_inverse_eotf(nits / 10_000.0))+ };+ [c[0] * k, c[1] * k, c[2] * k]+ }+}++/// Compress out-of-gamut colours towards the achromatic axis (see module docs). Used on input,+/// where camera gamuts extend well beyond the working gamut.+#[inline]+pub fn gamut_compress(c: [f32; 3]) -> [f32; 3] {+ const TH: f32 = 0.8;+ const LIM: f32 = 1.25;+ const P: f32 = 1.2;+ let ach = c[0].max(c[1]).max(c[2]);+ if ach <= 1e-9 {+ return c.map(|v| v.max(0.0));+ }+ // scale so that LIM maps to exactly 1.0+ let s = (LIM - TH) / (((LIM - TH) / (1.0 - TH)).powf(P) - 1.0).powf(1.0 / P);+ c.map(|v| {+ let d = (ach - v) / ach;+ if d < TH {+ return v;+ }+ let x = (d - TH) / s;+ let dc = TH + s * x / (1.0 + x.powf(P)).powf(1.0 / P);+ ach - dc * ach+ })+}++/// Source → working-space conversion for one colour space.+#[derive(Clone, Debug)]+pub struct InputTransform {+ pub source: ColorSpace,+ pub table: DecodeTable,+ matrix: [[f32; 3]; 3],+ identity_matrix: bool,+ /// HLG OOTF luma weights (BT.2020) and the scale to working units.+ hlg: Option<([f32; 3], f32)>,+ tone: Option<ToneMap>,+ compress: bool,+}++impl InputTransform {+ /// `src_peak_nits` is the mastering/content peak of PQ media when the file signals it.+ pub fn new(src: ColorSpace, range: Range, pipe: &ColorPipeline, src_peak_nits: Option<f64>) -> Self {+ let curve = src.curve();+ let wg = pipe.working_gamut();+ let m = gamut_matrix(src.gamut(), wg);+ let identity_matrix = src.gamut() == wg;+ let hlg = (curve == Curve::Hlg).then(|| {+ let l = Gamut::Bt2020.luma();+ ([l[0] as f32, l[1] as f32, l[2] as f32], (HDR_PEAK_NITS / REFERENCE_WHITE_NITS) as f32)+ });+ let peak = match curve {+ Curve::Pq => src_peak_nits.unwrap_or(HDR_PEAK_NITS).clamp(REFERENCE_WHITE_NITS, 10_000.0),+ Curve::Hlg => HDR_PEAK_NITS,+ Curve::Log(c) => (c.peak_linear() * REFERENCE_WHITE_NITS).clamp(REFERENCE_WHITE_NITS, LOG_PEAK_NITS),+ _ => REFERENCE_WHITE_NITS,+ };+ let tone = (src.is_hdr() && !pipe.working.is_hdr() && pipe.auto_tone_map).then(|| ToneMap::new(peak, REFERENCE_WHITE_NITS));+ let compress = !identity_matrix && !gamut_within(src.gamut(), wg);+ InputTransform { source: src, table: DecodeTable::for_curve(curve, range), matrix: to_f32(&m), identity_matrix, hlg, tone, compress }+ }++ /// Whether anything happens after the per-channel table.+ pub fn has_pixel_stage(&self) -> bool {+ !self.identity_matrix || self.hlg.is_some() || self.tone.is_some() || self.compress+ }++ /// The per-pixel stage (input: the table's output).+ #[inline]+ pub fn apply(&self, mut c: [f32; 3]) -> [f32; 3] {+ if let Some((l, k)) = self.hlg {+ let ys = (l[0] * c[0] + l[1] * c[1] + l[2] * c[2]).max(0.0);+ let g = k * ys.powf((HLG_GAMMA - 1.0) as f32);+ c = c.map(|v| v * g);+ }+ if !self.identity_matrix {+ c = crate::spaces::apply3(&self.matrix, c);+ }+ if let Some(t) = &self.tone {+ c = t.apply(c);+ }+ if self.compress {+ c = gamut_compress(c);+ }+ c+ }++ /// Signal → working linear for one RGB triple (table + pixel stage).+ pub fn convert(&self, rgb: [f32; 3]) -> [f32; 3] {+ self.apply(rgb.map(|v| self.table.lookup(v)))+ }+}++/// Whether gamut `a` lies inside gamut `b` (so no compression is needed going a → b).+fn gamut_within(a: Gamut, b: Gamut) -> bool {+ a == b || matches!((a, b), (Gamut::Bt709, _) | (Gamut::P3D65, Gamut::Bt2020))+}++/// Bring a colour with negative components into gamut by desaturating towards its luminance+/// (`luma` = the target gamut's Y weights) just enough that the smallest component is 0. In-gamut+/// colours are unchanged; hue and luminance are preserved.+#[inline]+pub fn desaturate_into_gamut(c: [f32; 3], luma: [f32; 3]) -> [f32; 3] {+ let mn = c[0].min(c[1]).min(c[2]);+ if mn >= 0.0 {+ return c;+ }+ let y = luma[0] * c[0] + luma[1] * c[1] + luma[2] * c[2];+ if y <= 0.0 {+ return [0.0; 3];+ }+ let t = y / (y - mn);+ c.map(|v| (y + (v - y) * t).max(0.0))+}++/// Working space → monitor (display-referred SDR BT.709) or → encoded export signal.+#[derive(Clone, Debug)]+pub struct OutputTransform {+ pub target: ColorSpace,+ matrix: [[f32; 3]; 3],+ identity_matrix: bool,+ tone: Option<ToneMap>,+ /// Target luma weights when the working gamut is wider than the target's.+ compress: Option<[f32; 3]>,+}++impl OutputTransform {+ /// For the monitors: SDR BT.709 linear (encode with the sRGB curve as usual).+ pub fn display(pipe: &ColorPipeline) -> Self {+ Self::new(pipe, ColorSpace::Rec709)+ }+ /// For export/encode into `target` (Rec709, Rec2100Pq or Rec2100Hlg).+ pub fn new(pipe: &ColorPipeline, target: ColorSpace) -> Self {+ let wg = pipe.working_gamut();+ let tg = target.gamut();+ let tone = (pipe.working.is_hdr() && !target.is_hdr()).then(|| ToneMap::new(HDR_PEAK_NITS, REFERENCE_WHITE_NITS));+ let l = tg.luma();+ let compress = (!gamut_within(wg, tg)).then(|| [l[0] as f32, l[1] as f32, l[2] as f32]);+ OutputTransform { target, matrix: to_f32(&gamut_matrix(wg, tg)), identity_matrix: wg == tg, tone, compress }+ }+ pub fn is_identity(&self) -> bool {+ self.identity_matrix && self.tone.is_none()+ }+ /// Working linear → target linear (SDR: 1.0 = white; HDR: working units).+ #[inline]+ pub fn apply(&self, mut c: [f32; 3]) -> [f32; 3] {+ if let Some(t) = &self.tone {+ c = t.apply(c);+ }+ if !self.identity_matrix {+ c = crate::spaces::apply3(&self.matrix, c);+ }+ if let Some(l) = self.compress {+ c = desaturate_into_gamut(c, l);+ }+ c+ }+ /// Working linear → encoded signal (0..1, full scale) of the target colour space.+ pub fn encode(&self, c: [f32; 3]) -> [f32; 3] {+ let l = self.apply(c);+ match self.target.curve() {+ Curve::Hlg => {+ // inverse OOTF (BT.2100): display light (normalised to the 1000 cd/m² peak) → scene+ let k = (REFERENCE_WHITE_NITS / HDR_PEAK_NITS) as f32;+ let fd = l.map(|v| (v * k).clamp(0.0, 1.0));+ let lm = Gamut::Bt2020.luma();+ let yd = (lm[0] as f32 * fd[0] + lm[1] as f32 * fd[1] + lm[2] as f32 * fd[2]).max(1e-9);+ let g = yd.powf(((1.0 - HLG_GAMMA) / HLG_GAMMA) as f32);+ fd.map(|v| hlg_oetf((v * g).clamp(0.0, 1.0)))+ }+ curve => l.map(|v| encode_channel(v as f64, curve, Range::Full).clamp(0.0, 1.0) as f32),+ }+ }+}++/// Convenience: a log colour space → display Rec. 709 (tone mapped), used for the built-in+/// camera conversion LUTs.+pub fn log_to_rec709(src: ColorSpace, rgb_signal: [f32; 3], range: Range) -> [f32; 3] {+ let t = InputTransform::new(src, range, &ColorPipeline::REC709, None);+ let l = t.convert(rgb_signal);+ l.map(|v| linear_to_srgb(v.clamp(0.0, 1.0)))+}++/// Decoder-normalised value of a curve-domain value — re-exported for callers that build their+/// own tables.+pub fn domain_value(v: f64, range: Range, d: Domain) -> f64 {+ signal_from_normalized(v, range, d)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::spaces::WorkingSpace;++ fn hdr(w: WorkingSpace) -> ColorPipeline {+ ColorPipeline { working: w, wide_gamut: false, auto_tone_map: true }+ }++ #[test]+ fn channel_roundtrips_every_curve() {+ for cs in ColorSpace::ALL {+ for range in [Range::Limited, Range::Full] {+ for i in 1..100 {+ let v = i as f64 / 100.0;+ if cs == ColorSpace::AppleLog && domain_value(v, range, Domain::Ire) < 0.0 {+ continue; // Apple Log has no code values below its black floor+ }+ let l = decode_channel(v, cs.curve(), range);+ let back = encode_channel(l, cs.curve(), range);+ assert!((back - v).abs() < 2e-4, "{cs:?} {range:?}: {v} → {l} → {back}");+ }+ }+ }+ }++ #[test]+ fn pq_and_hlg_reference_white() {+ // PQ 58 % ≈ 203 cd/m² (BT.2408 table 1) → 1.0+ let pq203 = pq_inverse_eotf(203.0 / 10_000.0) as f64;+ assert!((pq203 - 0.58).abs() < 0.002, "{pq203}");+ assert!((decode_channel(pq203, Curve::Pq, Range::Full) - 1.0).abs() < 1e-3);+ // HLG 75 % on a 1000 cd/m² display ≈ 203 cd/m² (BT.2408) → ≈ 1.0 working+ let t = InputTransform::new(ColorSpace::Rec2100Hlg, Range::Full, &hdr(WorkingSpace::Rec2100Hlg), None);+ let w = t.convert([0.75, 0.75, 0.75]);+ assert!((w[0] - 1.0).abs() < 0.01, "{w:?}");+ // and back through the HLG output+ let o = OutputTransform::new(&hdr(WorkingSpace::Rec2100Hlg), ColorSpace::Rec2100Hlg);+ let e = o.encode(w);+ assert!((e[0] - 0.75).abs() < 1e-3, "{e:?}");+ let o = OutputTransform::new(&hdr(WorkingSpace::Rec2100Pq), ColorSpace::Rec2100Pq);+ assert!((o.encode([1.0; 3])[1] as f64 - pq203).abs() < 1e-4);+ }++ #[test]+ fn eetf_properties() {+ // identity below the knee, continuous, monotone, hits the target peak+ let (s, d) = (1000.0, 203.0);+ assert!((bt2390_eetf(1.0, s, d) - 1.0).abs() < 1e-3);+ assert!((bt2390_eetf(s, s, d) - d).abs() < 0.5);+ let mut prev = 0.0;+ for i in 1..=1000 {+ let y = bt2390_eetf(i as f64, s, d);+ assert!(y >= prev - 1e-3 && y <= d + 0.05, "{i}: {y}");+ prev = y;+ }+ // reference white ends up at ≈ 0.8 of SDR white (≈ 90 % on the sRGB curve)+ let rw = bt2390_eetf(203.0, s, d) / 203.0;+ assert!((0.7..0.9).contains(&rw), "{rw}");+ assert_eq!(bt2390_eetf(500.0, 203.0, 1000.0), 500.0f64.min(1000.0));+ }++ #[test]+ fn tone_map_preserves_hue_and_maps_peak() {+ let tm = ToneMap::new(1000.0, 203.0);+ let c = [4.0f32, 2.0, 1.0];+ let o = tm.apply(c);+ assert!((o[0] / o[1] - 2.0).abs() < 1e-4 && (o[1] / o[2] - 2.0).abs() < 1e-4);+ let peak = tm.apply([1000.0 / 203.0; 3]);+ assert!((peak[0] - 1.0).abs() < 0.01, "{peak:?}");+ let dark = tm.apply([0.05; 3]);+ assert!((dark[0] - 0.05).abs() < 1e-3);+ }++ #[test]+ fn gamut_compression() {+ // in-gamut colours are untouched+ for c in [[0.5f32, 0.4, 0.3], [1.0, 0.25, 0.25], [0.2, 0.2, 0.2]] {+ assert_eq!(gamut_compress(c), c);+ }+ // anything up to the limit comes back inside, hue order kept+ let o = gamut_compress([1.0, -0.2, 0.3]);+ assert!(o.iter().all(|v| *v >= 0.0), "{o:?}");+ assert!(o[0] > o[2] && o[2] > o[1]);+ // continuity at the threshold+ let a = gamut_compress([1.0, 0.2001, 0.5]);+ assert!((a[1] - 0.2001).abs() < 1e-3);+ }++ #[test]+ fn log_sources_land_sensibly_in_rec709() {+ // mid grey stays mid grey; the S-Gamut3.Cine primaries map out of 709 and get compressed+ for cs in ColorSpace::ALL.into_iter().filter(|c| c.is_log()) {+ let Curve::Log(curve) = cs.curve() else { unreachable!() };+ let grey = normalized_from_signal(curve.encode(0.18), Range::Limited, curve.domain()) as f32;+ let t = InputTransform::new(cs, Range::Limited, &ColorPipeline::REC709, None);+ let g = t.convert([grey; 3]);+ assert!(g.iter().all(|v| (v - 0.18).abs() < 0.01), "{cs:?}: {g:?}");+ let red = t.convert([0.9, grey, grey]);+ assert!(red.iter().all(|v| *v >= -1e-6) && red.iter().all(|v| *v <= 1.0 + 1e-4), "{cs:?}: {red:?}");+ let disp = log_to_rec709(cs, [grey; 3], Range::Limited);+ assert!((disp[0] - linear_to_srgb(0.18)).abs() < 0.02);+ }+ }++ #[test]+ fn sdr_in_hdr_keeps_values_and_display_tone_maps() {+ let pipe = hdr(WorkingSpace::Rec2100Pq);+ let t = InputTransform::new(ColorSpace::Rec709, Range::Limited, &pipe, None);+ let w = t.convert([1.0, 1.0, 1.0]);+ assert!(w.iter().all(|v| (v - 1.0).abs() < 1e-4), "709 white = reference white: {w:?}");+ let red = t.convert([1.0, 0.0, 0.0]);+ // 709 red in 2020 (BT.2087)+ assert!((red[0] - 0.6274).abs() < 1e-3 && (red[1] - 0.0691).abs() < 1e-3 && (red[2] - 0.0164).abs() < 1e-3);+ let d = OutputTransform::display(&pipe);+ let back = d.apply(red);+ assert!((back[0] - 0.8).abs() < 0.2 && back[1].abs() < 1e-4 && back[2].abs() < 1e-4, "{back:?}");+ // a BT.2020-only green is desaturated into 709 keeping its luminance+ let g = d.apply([0.0, 0.5, 0.0]);+ assert!(g.iter().all(|v| *v >= 0.0) && g[1] > g[0] && g[1] > g[2], "{g:?}");+ // a 1000-nit highlight comes back at SDR peak+ let hi = d.apply([1000.0 / 203.0; 3]);+ assert!((hi[0] - 1.0).abs() < 0.01);+ // plain pipeline is an identity+ assert!(OutputTransform::display(&ColorPipeline::REC709).is_identity());+ }+}