Skip to main content

rust_motion_cms/
builtin.rs

1//! Built-in profiles. All are generated by this crate from published colorimetric definitions
2//! (primaries, white points, transfer functions) and dedicated to the public domain (CC0-1.0),
3//! so documents that embed them carry no licence obligations. See the crate README.
4
5use std::sync::OnceLock;
6
7use crate::curve::{srgb_trc, Curve};
8use crate::math::{self, Mat3};
9use crate::pipeline::Stage;
10use crate::profile::{ColorSpace, Lut, LutKind, Pcs, Profile, ProfileClass};
11use crate::Intent;
12
13/// Copyright tag text of every built-in profile.
14pub const COPYRIGHT: &str =
15    "No copyright: CC0-1.0 public domain dedication. Generated by rust-motion-cms.";
16
17/// Identifiers of the built-in profiles.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub enum Builtin {
20    /// sRGB IEC 61966-2.1 (Rec. 709 primaries, D65, sRGB transfer function).
21    Srgb,
22    /// Display P3 (DCI-P3 primaries, D65, sRGB transfer function).
23    DisplayP3,
24    /// Adobe RGB (1998)-compatible: its published primaries, D65, gamma 563/256.
25    AdobeRgbCompat,
26    /// ProPhoto-compatible: ROMM RGB primaries, D50, gamma 1.8.
27    ProPhotoCompat,
28    /// sRGB primaries with a linear transfer function.
29    LinearSrgb,
30    /// ACEScg: AP1 primaries, the ACES white point (~D60), linear transfer. The ACES working space for CG renders.
31    AcesCg,
32    /// Rec. 2020 primaries, D65, Rec. 709 transfer function.
33    Rec2020,
34    /// Gray, gamma 2.2.
35    GrayGamma22,
36    /// Gray with the sRGB transfer function (sGray): gray `v` looks like RGB `(v, v, v)` in sRGB.
37    SGray,
38    /// Gray matching Photoshop's default working gray (Dot Gain 20 %) with our own curve: a pure
39    /// gamma of 1.732, fitted on Photoshop 27.11's RGB → Grayscale (sRGB 64 / 128 / 192 and pure red
40    /// become 46 / 105 / 177 / 107, all within 1 level). Not Adobe's profile.
41    DotGain20Compat,
42    /// CIE L*a*b* D50 identity (device Lab = PCS Lab, ICC v4 encoding).
43    LabD50,
44    /// Synthetic coated-offset CMYK (300 % total ink, medium GCR); see [`crate::synth`].
45    CoatedCmyk,
46}
47
48impl Builtin {
49    pub const ALL: [Builtin; 12] = [
50        Builtin::Srgb,
51        Builtin::DisplayP3,
52        Builtin::AdobeRgbCompat,
53        Builtin::ProPhotoCompat,
54        Builtin::LinearSrgb,
55        Builtin::AcesCg,
56        Builtin::Rec2020,
57        Builtin::GrayGamma22,
58        Builtin::SGray,
59        Builtin::DotGain20Compat,
60        Builtin::LabD50,
61        Builtin::CoatedCmyk,
62    ];
63
64    /// Stable identifier used by commands and settings.
65    pub fn id(self) -> &'static str {
66        match self {
67            Builtin::Srgb => "srgb",
68            Builtin::DisplayP3 => "display-p3",
69            Builtin::AdobeRgbCompat => "adobe-rgb-compat",
70            Builtin::ProPhotoCompat => "prophoto-compat",
71            Builtin::LinearSrgb => "linear-srgb",
72            Builtin::AcesCg => "aces-cg",
73            Builtin::Rec2020 => "rec2020",
74            Builtin::GrayGamma22 => "gray-gamma-2.2",
75            Builtin::SGray => "sgray",
76            Builtin::DotGain20Compat => "dot-gain-20-compat",
77            Builtin::LabD50 => "lab-d50",
78            Builtin::CoatedCmyk => "coated-cmyk",
79        }
80    }
81
82    /// Profile description (the `desc` tag).
83    pub fn description(self) -> &'static str {
84        match self {
85            Builtin::Srgb => "sRGB IEC61966-2.1",
86            Builtin::DisplayP3 => "Display P3",
87            Builtin::AdobeRgbCompat => "Adobe RGB (1998)-compatible (PhotoCraft)",
88            Builtin::ProPhotoCompat => "ProPhoto RGB-compatible (ROMM primaries, PhotoCraft)",
89            Builtin::LinearSrgb => "Linear sRGB (PhotoCraft)",
90            Builtin::AcesCg => "ACEScg (AP1, linear, PhotoCraft)",
91            Builtin::Rec2020 => "Rec. ITU-R BT.2020 (PhotoCraft)",
92            Builtin::GrayGamma22 => "Gray Gamma 2.2 (PhotoCraft)",
93            Builtin::SGray => "sGray (sRGB tone curve, PhotoCraft)",
94            Builtin::DotGain20Compat => "Dot Gain 20%-compatible (gamma 1.732, PhotoCraft)",
95            Builtin::LabD50 => "Lab D50 identity (PhotoCraft)",
96            Builtin::CoatedCmyk => crate::synth::DESCRIPTION,
97        }
98    }
99
100    /// Looks up an id (case-insensitive; a few aliases and the descriptions are accepted).
101    pub fn from_id(s: &str) -> Option<Builtin> {
102        let n: String = s
103            .to_ascii_lowercase()
104            .chars()
105            .filter(|c| c.is_ascii_alphanumeric())
106            .collect();
107        let alias = match n.as_str() {
108            "srgb" | "srgbiec6196621" | "srgbiec61966" => Some(Builtin::Srgb),
109            "p3" | "displayp3" => Some(Builtin::DisplayP3),
110            "adobergb" | "adobergb1998" | "adobergbcompat" | "clayrgb" => {
111                Some(Builtin::AdobeRgbCompat)
112            }
113            "prophoto" | "prophotorgb" | "prophotocompat" | "romm" | "rommrgb" => {
114                Some(Builtin::ProPhotoCompat)
115            }
116            "linearsrgb" | "srgblinear" | "linear" => Some(Builtin::LinearSrgb),
117            "rec2020" | "bt2020" => Some(Builtin::Rec2020),
118            "gray" | "graygamma22" | "gamma22" => Some(Builtin::GrayGamma22),
119            "sgray" | "graysrgb" => Some(Builtin::SGray),
120            "dotgain20" | "dotgain20compat" | "dotgain" => Some(Builtin::DotGain20Compat),
121            "aces-cg" | "acescg" => Some(Builtin::AcesCg),
122            "lab" | "labd50" | "cielab" => Some(Builtin::LabD50),
123            "cmyk" | "coatedcmyk" | "defaultcmyk" | "photocraftcoatedcmyk" => {
124                Some(Builtin::CoatedCmyk)
125            }
126            _ => None,
127        };
128        alias.or_else(|| {
129            Builtin::ALL
130                .into_iter()
131                .find(|b| b.description().eq_ignore_ascii_case(s))
132        })
133    }
134
135    /// The profile (built once per process).
136    pub fn profile(self) -> &'static Profile {
137        static CELLS: [OnceLock<Profile>; 12] = [const { OnceLock::new() }; 12];
138        // `ALL` lists the variants in declaration order (checked by `all_in_declaration_order`),
139        // so the discriminant is the cell index.
140        CELLS[self as usize].get_or_init(|| build(self))
141    }
142}
143
144/// The default profile for a colour space: sRGB, Dot Gain 20 %-compatible gray (Photoshop's default
145/// working gray), the coated CMYK profile, Lab D50.
146pub fn default_for(cs: ColorSpace) -> Option<&'static Profile> {
147    Some(match cs {
148        ColorSpace::Rgb => Builtin::Srgb.profile(),
149        ColorSpace::Gray => Builtin::DotGain20Compat.profile(),
150        ColorSpace::Cmyk => Builtin::CoatedCmyk.profile(),
151        ColorSpace::Lab => Builtin::LabD50.profile(),
152        _ => return None,
153    })
154}
155
156pub fn srgb() -> &'static Profile {
157    Builtin::Srgb.profile()
158}
159
160/// Gray with a linear tone curve: what a grayscale OpenEXR holds. Not a [`Builtin`], as it is
161/// only assigned to such files, never offered as a working space.
162pub fn linear_gray() -> &'static Profile {
163    static PROFILE: OnceLock<Profile> = OnceLock::new();
164    PROFILE.get_or_init(|| gray("Linear Gray (PhotoCraft)", Curve::Gamma(1.0)))
165}
166
167/// The ICC D65 used for the RGB spaces (chromaticity 0.3127, 0.3290).
168fn d65() -> [f64; 3] {
169    math::xy_to_xyz(math::D65_XY)
170}
171
172/// Colorant matrix adapted to D50 and quantized to s15Fixed16, with each row nudged so that
173/// RGB (1, 1, 1) maps exactly to the stored D50 white (keeps neutrals neutral).
174fn colorants(r: [f64; 2], g: [f64; 2], b: [f64; 2], white: [f64; 3]) -> (Mat3, Option<Mat3>) {
175    // Only called with the constant primaries of the built-in spaces, which are independent
176    // (every built-in profile is built in the tests).
177    #[allow(clippy::expect_used)]
178    let m = math::rgb_to_xyz_matrix(r, g, b, white).expect("built-in primaries are independent");
179    let d50 = math::d50_quantized();
180    let adapt = if (white[0] - math::D50[0]).abs() < 1e-3 && (white[2] - math::D50[2]).abs() < 1e-3
181    {
182        None
183    } else {
184        Some(math::bradford(white, math::D50))
185    };
186    let m50 = match &adapt {
187        Some(a) => math::mul(a, &m),
188        None => {
189            // White already (nearly) D50: scale rows onto the exact PCS white.
190            let s = math::apply(&m, [1.0, 1.0, 1.0]);
191            let mut o = m;
192            for (i, row) in o.iter_mut().enumerate() {
193                for v in row.iter_mut() {
194                    *v *= math::D50[i] / s[i];
195                }
196            }
197            o
198        }
199    };
200    let mut q = m50.map(|row| row.map(math::s15f16_round));
201    for (i, row) in q.iter_mut().enumerate() {
202        let err = d50[i] - row.iter().sum::<f64>();
203        let k = (0..3)
204            .max_by(|a, b| row[*a].abs().total_cmp(&row[*b].abs()))
205            .unwrap_or(0);
206        row[k] = math::s15f16_round(row[k] + err);
207    }
208    (q, adapt.map(|a| a.map(|row| row.map(math::s15f16_round))))
209}
210
211fn rgb(desc: &str, prim: [[f64; 2]; 3], white: [f64; 3], trc: Curve) -> Profile {
212    let (m, chad) = colorants(prim[0], prim[1], prim[2], white);
213    Profile {
214        version: (4, 0x30),
215        class: ProfileClass::Display,
216        color_space: ColorSpace::Rgb,
217        pcs: Pcs::Xyz,
218        rendering_intent: Intent::Perceptual,
219        description: desc.into(),
220        copyright: COPYRIGHT.into(),
221        white_point: math::d50_quantized(),
222        black_point: None,
223        chad,
224        matrix: Some(m),
225        trc: Some([trc.clone(), trc.clone(), trc]),
226        gray_trc: None,
227        a2b: [None, None, None],
228        b2a: [None, None, None],
229        bytes: None,
230        hash: Default::default(),
231    }
232    .with_encoded_bytes()
233}
234
235fn gray(desc: &str, trc: Curve) -> Profile {
236    Profile {
237        version: (4, 0x30),
238        class: ProfileClass::Display,
239        color_space: ColorSpace::Gray,
240        pcs: Pcs::Xyz,
241        rendering_intent: Intent::Perceptual,
242        description: desc.into(),
243        copyright: COPYRIGHT.into(),
244        white_point: math::d50_quantized(),
245        black_point: None,
246        chad: None,
247        matrix: None,
248        trc: None,
249        gray_trc: Some(trc),
250        a2b: [None, None, None],
251        b2a: [None, None, None],
252        bytes: None,
253        hash: Default::default(),
254    }
255    .with_encoded_bytes()
256}
257
258fn lab() -> Profile {
259    let ident = || Lut {
260        kind: LutKind::Ab,
261        inputs: 3,
262        outputs: 3,
263        stages: vec![Stage::Curves(vec![Curve::Identity; 3])],
264    };
265    Profile {
266        version: (4, 0x30),
267        class: ProfileClass::ColorSpace,
268        color_space: ColorSpace::Lab,
269        pcs: Pcs::Lab,
270        rendering_intent: Intent::Perceptual,
271        description: Builtin::LabD50.description().into(),
272        copyright: COPYRIGHT.into(),
273        white_point: math::d50_quantized(),
274        black_point: None,
275        chad: None,
276        matrix: None,
277        trc: None,
278        gray_trc: None,
279        a2b: [Some(ident()), None, None],
280        b2a: [Some(ident()), None, None],
281        bytes: None,
282        hash: Default::default(),
283    }
284    .with_encoded_bytes()
285}
286
287/// The shipped synthetic CMYK profile (generated by [`crate::synth::coated_cmyk`]; regenerate
288/// with `PHOTOCRAFT_REGEN_PROFILES=1 cargo test -p rust-motion-cms --release regen`).
289pub const COATED_CMYK_ICC: &[u8] = include_bytes!("../profiles/photocraft-coated-cmyk.icc");
290
291fn build(b: Builtin) -> Profile {
292    let (srgb_p, p3, adobe, romm, bt2020, ap1) = (
293        [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06]],
294        [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]],
295        [[0.64, 0.33], [0.21, 0.71], [0.15, 0.06]],
296        [[0.7347, 0.2653], [0.1596, 0.8404], [0.0366, 0.0001]],
297        [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]],
298        [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044]],
299    );
300    match b {
301        Builtin::Srgb => rgb(b.description(), srgb_p, d65(), srgb_trc()),
302        Builtin::DisplayP3 => rgb(b.description(), p3, d65(), srgb_trc()),
303        Builtin::AdobeRgbCompat => rgb(b.description(), adobe, d65(), Curve::Gamma(563.0 / 256.0)),
304        Builtin::ProPhotoCompat => rgb(b.description(), romm, math::D50, Curve::Gamma(1.8)),
305        Builtin::LinearSrgb => rgb(b.description(), srgb_p, d65(), Curve::Gamma(1.0)),
306        // ACEScg is scene-linear on the AP1 primaries with the ACES white point (~D60,
307        // xy 0.32168/0.33767, the ACES 2065-1 neutral).
308        Builtin::AcesCg => rgb(
309            b.description(),
310            ap1,
311            math::xy_to_xyz([0.32168, 0.33767]),
312            Curve::Gamma(1.0),
313        ),
314        Builtin::Rec2020 => {
315            // Rec. 709 OETF inverse: V = 1.099 L^0.45 − 0.099 (L ≥ 0.018), 4.5 L below.
316            let a = 1.099;
317            let trc = Curve::Parametric {
318                kind: 3,
319                p: [
320                    1.0 / 0.45,
321                    1.0 / a,
322                    (a - 1.0) / a,
323                    1.0 / 4.5,
324                    0.081,
325                    0.0,
326                    0.0,
327                ],
328            };
329            rgb(b.description(), bt2020, d65(), trc)
330        }
331        Builtin::GrayGamma22 => gray(b.description(), Curve::Gamma(2.2)),
332        Builtin::SGray => gray(b.description(), srgb_trc()),
333        Builtin::DotGain20Compat => gray(b.description(), Curve::Gamma(1.732)),
334        Builtin::LabD50 => lab(),
335        // The shipped bytes are `synth::coated_cmyk()` (checked by the `regen` test); rebuild
336        // them rather than crash if they ever fail to parse.
337        Builtin::CoatedCmyk => {
338            Profile::parse(COATED_CMYK_ICC).unwrap_or_else(|_| crate::synth::coated_cmyk())
339        }
340    }
341}