colr 0.1.0

Type-safe, zero-cost color science library with compile-time color space transforms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Signal encoding and decoding curves (transfer functions).
//!
//! Each type implements [`TransferFunction`], defining the round-trip
//! between a stored signal value and linear light:
//!
//! - `decode` (EOTF): stored signal -> linear light
//! - `encode` (OETF): linear light -> stored signal
//!
//! All methods operate on `[f32; 3]`. Alpha is never encoded and is
//! handled by the caller.
//!
//! # Specifications
//!
//! | Type           | Specification                  |
//! |----------------|-------------------------------|
//! | [`LinearTf`]   | Identity                      |
//! | [`SrgbTf`]     | IEC 61966-2-1:1999            |
//! | [`Rec709Tf`]   | ITU-R BT.709-6                |
//! | [`PqTf`]       | SMPTE ST 2084:2014            |
//! | [`HlgTf`]      | ITU-R BT.2100-2               |
//! | [`ProPhotoTf`] | ISO 22028-2:2013 (ROMM RGB)   |
//! | [`AcesCcTf`]   | Academy S-2014-003            |
//! | [`AcesCctTf`]  | Academy S-2016-001            |
//! | [`DciP3Tf`]    | SMPTE EG 432-1:2010           |

use crate::math::MathState;

/// Marks a transfer function as linear (identity encoding).
///
/// Only LinearTf implements this. Used to gate LinearLight and
/// premultiplied alpha compositing on RgbSpace<P, TF>.
pub trait IsLinearEncoding {}

/// Marks a transfer function as encoding scene-referred light.
///
/// Scene-referred signals encode physical scene radiance and require
/// a tone mapping operator before display. Linear, log, and HLG
/// transfer functions are scene-referred.
pub trait IsSceneReferred {}

/// Marks a transfer function as encoding display-referred signal.
///
/// Display-referred signals are bounded to a device output range and
/// have already passed through a tone mapping operator.
pub trait IsDisplayReferred {}

/// Signal encoding curve for a color space.
pub trait TransferFunction: 'static {
    /// Minimum valid encoded signal value per channel.
    const ENCODED_MIN: [f32; 3];
    /// Maximum valid encoded signal value per channel.
    /// `[f32::INFINITY; 3]` for unbounded scene-linear spaces.
    const ENCODED_MAX: [f32; 3];

    /// Decode stored signal to scene-linear light (inverse OETF).
    ///
    /// Note: the true HLG EOTF (ITU-R BT.2100) additionally applies an
    /// OOTF (system gamma ~1.2 dependent on display peak luminance). This
    /// implementation returns inverse-OETF scene-linear, which is correct
    /// for scene-referred pipelines that apply the OOTF separately.
    fn decode<M: MathState>(encoded: [f32; 3]) -> [f32; 3];

    /// Encode linear light to stored signal (OETF).
    fn encode<M: MathState>(linear: [f32; 3]) -> [f32; 3];
}

#[inline(always)]
fn map(v: [f32; 3], f: impl Fn(f32) -> f32) -> [f32; 3] {
    [f(v[0]), f(v[1]), f(v[2])]
}

/// Linear (identity) transfer function.
///
/// Stored values equal linear light. The only transfer function for which
/// premultiplied alpha compositing is physically correct. `ENCODED_MAX`
/// is `f32::INFINITY`. Scene-linear values are unbounded.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct LinearTf;

impl IsLinearEncoding for LinearTf {}
impl IsSceneReferred for LinearTf {}

impl TransferFunction for LinearTf {
    const ENCODED_MIN: [f32; 3] = [f32::NEG_INFINITY; 3];
    const ENCODED_MAX: [f32; 3] = [f32::INFINITY; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        v
    }
    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        v
    }
}

/// sRGB transfer function (IEC 61966-2-1:1999).
///
/// Piecewise: linear segment (slope 12.92) below threshold, power-law
/// (gamma 2.4) above. Dominant encoding for web content, PNG, JPEG,
/// and standard display output. Distinct from Rec. 709, despite identical
/// primaries, exponent and linear slope differ.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SrgbTf;

const SRGB_ALPHA: f32 = 1.055;
const SRGB_GAMMA: f32 = 2.4;
const SRGB_LINEAR_SLOPE: f32 = 12.92;
const SRGB_LINEAR_THRESHOLD: f32 = 0.0031308;
const SRGB_ENCODED_THRESHOLD: f32 = 0.04045;

impl TransferFunction for SrgbTf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x <= SRGB_ENCODED_THRESHOLD {
                x / SRGB_LINEAR_SLOPE
            } else {
                M::powf((x + (SRGB_ALPHA - 1.0)) / SRGB_ALPHA, SRGB_GAMMA)
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            let abs = x.abs();
            sign * if abs <= SRGB_LINEAR_THRESHOLD {
                abs * SRGB_LINEAR_SLOPE
            } else {
                SRGB_ALPHA * M::powf(abs, 1.0 / SRGB_GAMMA) - (SRGB_ALPHA - 1.0)
            }
        })
    }
}

/// Rec. ITU-R BT.709-6 transfer function.
///
/// Same primaries as sRGB, different curve: slope 4.5, effective
/// gamma ~2.222. Used for HD broadcast. Visually close to sRGB but
/// not interchangeable in precision workflows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Rec709Tf;

// These constants are the intersection-preserving values from ITU-R BT.709-6.
// They have more digits than f32 can represent but are kept verbatim from the
// spec to document intent. f32 rounds them at compile time.
#[allow(clippy::excessive_precision)]
const REC709_ALPHA: f32 = 1.09929682680944;
const REC709_POWER: f32 = 0.45;
const REC709_LINEAR_SLOPE: f32 = 4.5;
#[allow(clippy::excessive_precision)]
const REC709_LINEAR_THRESHOLD: f32 = 0.018053968510807;
#[allow(clippy::excessive_precision)]
const REC709_ENCODED_THRESHOLD: f32 = 0.081242858298635;

impl TransferFunction for Rec709Tf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x <= REC709_ENCODED_THRESHOLD {
                x / REC709_LINEAR_SLOPE
            } else {
                M::powf((x + (REC709_ALPHA - 1.0)) / REC709_ALPHA, 1.0 / REC709_POWER)
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            let abs = x.abs();
            sign * if abs <= REC709_LINEAR_THRESHOLD {
                abs * REC709_LINEAR_SLOPE
            } else {
                REC709_ALPHA * M::powf(abs, REC709_POWER) - (REC709_ALPHA - 1.0)
            }
        })
    }
}

/// SMPTE ST 2084 Perceptual Quantizer (PQ) transfer function.
///
/// Display-referred HDR. Encoded 1.0 represents 10,000 cd/m2. Typical
/// HDR10 display peaks are 1,000-4,000 nits (decoded ~0.1-0.4).
/// Used in HDR10 and as the base layer in Dolby Vision.
///
/// Decode denominator `c2 - c3 * V^(1/m2)` is bounded in
/// `[c2-c3, c2] = [0.164, 18.85]` for `V` in `[0, 1]`. No guard needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PqTf;

// PQ constants are exact rational numbers from SMPTE ST 2084 - 2610/16384
// etc. They are precisely representable as binary fractions in f32.
#[allow(clippy::excessive_precision)]
const PQ_M1: f32 = 0.1593017578125; // 2610/16384
const PQ_M2: f32 = 78.84375; // 2523/32
const PQ_C1: f32 = 0.8359375; // 3424/4096
#[allow(clippy::excessive_precision)]
const PQ_C2: f32 = 18.8515625; // 2413/128
const PQ_C3: f32 = 18.6875; // 2392/128

impl TransferFunction for PqTf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let v_m2 = M::powf(x.max(0.0), 1.0 / PQ_M2);
            let num = (v_m2 - PQ_C1).max(0.0);
            let den = PQ_C2 - PQ_C3 * v_m2;
            M::powf(num / den, 1.0 / PQ_M1)
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let y_m1 = M::powf(x.max(0.0), PQ_M1);
            M::powf((PQ_C1 + PQ_C2 * y_m1) / (1.0 + PQ_C3 * y_m1), PQ_M2)
        })
    }
}

/// ITU-R BT.2100-2 Hybrid Log-Gamma (HLG) transfer function.
///
/// Scene-referred HDR. Backward-compatible with SDR displays. An HLG
/// signal on a standard monitor produces a usable image without tone
/// mapping. Reference white sits at ~0.75 on the signal scale.
/// Used in UHD broadcast (BBC, NHK, UHD-2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct HlgTf;

const HLG_A: f32 = 0.17883277;
const HLG_B: f32 = 0.28466892;
const HLG_C: f32 = 0.559_910_7;
const HLG_LINEAR_THRESHOLD: f32 = 1.0 / 12.0;
const HLG_ENCODED_THRESHOLD: f32 = 0.5;

impl TransferFunction for HlgTf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x.abs() <= HLG_ENCODED_THRESHOLD {
                // Use x * |x| to preserve sign and maintain monotonicity
                // into the negative domain.
                x * x.abs() / 3.0
            } else {
                let sign = if x < 0.0 { -1.0 } else { 1.0 };
                sign * (M::exp((x.abs() - HLG_C) / HLG_A) + HLG_B) / 12.0
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let abs = x.abs();
            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            if abs <= HLG_LINEAR_THRESHOLD {
                sign * M::sqrt(3.0 * abs)
            } else {
                sign * (HLG_A * M::ln((12.0 * abs - HLG_B).max(f32::MIN_POSITIVE)) + HLG_C)
            }
        })
    }
}

/// ProPhoto (ROMM RGB) transfer function (ISO 22028-2:2013).
///
/// Power-law gamma 1.8 with a small linear segment near black.
/// Shallower gamma than sRGB reduces shadow quantization across
/// ProPhoto's wide gamut. Used in camera raw and professional photo
/// workflows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ProPhotoTf;

const PRO_PHOTO_GAMMA: f32 = 1.8;
const PRO_PHOTO_LINEAR_SLOPE: f32 = 16.0;
const PRO_PHOTO_LINEAR_THRESHOLD: f32 = 1.0 / 512.0;
const PRO_PHOTO_ENCODED_THRESHOLD: f32 = 1.0 / 32.0; // slope * linear threshold

impl TransferFunction for ProPhotoTf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            let abs = x.abs();
            sign * if abs <= PRO_PHOTO_ENCODED_THRESHOLD {
                abs / PRO_PHOTO_LINEAR_SLOPE
            } else {
                M::powf(abs, PRO_PHOTO_GAMMA)
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let sign = if x < 0.0 { -1.0 } else { 1.0 };
            let abs = x.abs();
            sign * if abs <= PRO_PHOTO_LINEAR_THRESHOLD {
                abs * PRO_PHOTO_LINEAR_SLOPE
            } else {
                M::powf(abs, 1.0 / PRO_PHOTO_GAMMA)
            }
        })
    }
}

/// ACEScc logarithmic transfer function (Academy S-2014-003).
///
/// Logarithmic encoding of ACES linear data for color grading.
/// Can encode values below zero and above one in scene-linear.
/// `ENCODED_MIN` and `ENCODED_MAX` represent the encoding of
/// scene-linear `[0, 65504]` (ACES HALF_MAX).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AcesCcTf;

const ACESCC_CUT1: f32 = -0.30136986; // (9.72 - 15) / 17.52
const ACESCC_LOG_SCALE: f32 = 17.52;
const ACESCC_LOG_OFFSET: f32 = 9.72;
const LOG2_RECIP: f32 = 1.0 / core::f32::consts::LN_2;

impl TransferFunction for AcesCcTf {
    const ENCODED_MIN: [f32; 3] = [-0.3584; 3]; // encoding of scene-linear 0
    const ENCODED_MAX: [f32; 3] = [1.4679; 3]; // encoding of ACES HALF_MAX 65504

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            let linear = x * ACESCC_LOG_SCALE - ACESCC_LOG_OFFSET;
            if x < ACESCC_CUT1 {
                (M::exp(linear * core::f32::consts::LN_2) - 2.0_f32.powi(-16)) * 2.0
            } else {
                M::exp(linear * core::f32::consts::LN_2)
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x < 0.0 {
                (M::ln(2.0_f32.powi(-16)) * LOG2_RECIP + ACESCC_LOG_OFFSET) / ACESCC_LOG_SCALE
            } else if x < 2.0_f32.powi(-15) {
                (M::ln(2.0_f32.powi(-16) + x * 0.5) * LOG2_RECIP + ACESCC_LOG_OFFSET) / ACESCC_LOG_SCALE
            } else {
                (M::ln(x) * LOG2_RECIP + ACESCC_LOG_OFFSET) / ACESCC_LOG_SCALE
            }
        })
    }
}

/// ACEScct quasi-logarithmic transfer function (Academy S-2016-001).
///
/// Like ACEScc but with a linear toe segment, behaving more like
/// traditional log encodings near black. Preferred for grading tools
/// that expect a toe.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct AcesCctTf;

const ACESCCT_X_BRK: f32 = 0.0078125; // scene-linear breakpoint
const ACESCCT_Y_BRK: f32 = 0.155_251_15; // encoded breakpoint
const ACESCCT_A: f32 = 10.540_237; // linear segment slope
const ACESCCT_B: f32 = 0.072_905_53; // linear segment offset
const ACESCCT_LOG_SCALE: f32 = 17.52;
const ACESCCT_LOG_OFFSET: f32 = 9.72;

impl TransferFunction for AcesCctTf {
    const ENCODED_MIN: [f32; 3] = [ACESCCT_B; 3]; // encoding of scene-linear 0
    const ENCODED_MAX: [f32; 3] = [1.4679; 3]; // same upper bound as ACEScc

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x <= ACESCCT_Y_BRK {
                (x - ACESCCT_B) / ACESCCT_A
            } else {
                M::exp((x * ACESCCT_LOG_SCALE - ACESCCT_LOG_OFFSET) * core::f32::consts::LN_2)
            }
        })
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| {
            if x <= ACESCCT_X_BRK {
                ACESCCT_A * x.max(0.0) + ACESCCT_B
            } else {
                (M::ln(x) * LOG2_RECIP + ACESCCT_LOG_OFFSET) / ACESCCT_LOG_SCALE
            }
        })
    }
}

/// DCI-P3 transfer function (SMPTE EG 432-1:2010).
///
/// Pure power law, gamma 2.6. No linear segment. Used for digital
/// cinema projection. Consumer Display P3 uses [`SrgbTf`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct DciP3Tf;

const DCI_P3_GAMMA: f32 = 2.6;

impl TransferFunction for DciP3Tf {
    const ENCODED_MIN: [f32; 3] = [0.0; 3];
    const ENCODED_MAX: [f32; 3] = [1.0; 3];

    #[inline(always)]
    fn decode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| M::powf(x.max(0.0), DCI_P3_GAMMA))
    }

    #[inline(always)]
    fn encode<M: MathState>(v: [f32; 3]) -> [f32; 3] {
        map(v, |x| M::powf(x.max(0.0), 1.0 / DCI_P3_GAMMA))
    }
}

// Scene-referred transfer functions encode physical scene radiance.
// Linear, log (ACEScc/ACEScct), and HLG are all scene-referred.
impl IsSceneReferred for HlgTf {}
impl IsSceneReferred for AcesCcTf {}
impl IsSceneReferred for AcesCctTf {}

// Display-referred transfer functions encode device output range.
impl IsDisplayReferred for SrgbTf {}
impl IsDisplayReferred for Rec709Tf {}
impl IsDisplayReferred for PqTf {}
impl IsDisplayReferred for ProPhotoTf {}
impl IsDisplayReferred for DciP3Tf {}