Skip to main content

rust_motion_cms/
synth.rs

1//! Synthetic CMYK output profiles.
2//!
3//! Adobe's CMYK profiles (U.S. Web Coated SWOP, Coated FOGRA39 …) are proprietary, and the
4//! freely downloadable characterisation-based profiles come with redistribution conditions, so
5//! Photocraft ships a CMYK profile it generates itself from a documented printer model:
6//!
7//! * **Forward model** (CMYK → XYZ): Yule–Nielsen modified Neugebauer (n = 2) over the 16
8//!   ink overprints, with Demichel coverage weights and a parabolic tone value increase (dot
9//!   gain) per ink. The eight K-free primaries use the published ISO 12647-2 coated-paper Lab
10//!   aim values (paper, C, M, Y, the three two-colour overprints) and an estimated three-colour
11//!   black; overprints with black are derived multiplicatively with a first-surface reflection
12//!   floor.
13//! * **AToB** (all intents): 11⁴ `lut16` table of the forward model, relative colorimetric
14//!   (paper → L* 100).
15//! * **BToA1** (colorimetric): for every Lab node, black generation (GCR) from the gray
16//!   component of the K-free solution, then a bounded least-squares solve for C, M, Y with the
17//!   total ink limit; out-of-gamut colours land on the closest reachable colour (clipping).
18//! * **BToA0/BToA2** (perceptual/saturation): the target is first compressed into the gamut —
19//!   L* is scaled onto the device black, chroma is softly compressed against a gamut boundary
20//!   descriptor sampled from the forward model — then solved as above.
21//!
22//! The model is plausible for coated offset, not a measured characterisation: use a real
23//! profile from your print provider for production print.
24
25use crate::clut::Clut;
26use crate::curve::Curve;
27use crate::math;
28use crate::pipeline::Stage;
29use crate::profile::{ColorSpace, Lut, LutKind, Pcs, Profile, ProfileClass};
30use crate::Intent;
31
32pub const DESCRIPTION: &str = "PhotoCraft Coated CMYK (synthetic, 300% TAC, medium GCR)";
33
34/// Parameters of the synthetic profile.
35#[derive(Clone, Debug)]
36pub struct CmykParams {
37    pub description: String,
38    /// Total area coverage limit (3.0 = 300 %).
39    pub tac: f64,
40    /// Gray component (min of C, M, Y of the K-free solution) where black generation starts.
41    pub gcr_start: f64,
42    /// Maximum black.
43    pub k_max: f64,
44    /// Exponent of the black generation curve above `gcr_start`.
45    pub gcr_gamma: f64,
46    /// Tone value increase at 50 % for C, M, Y, K.
47    pub tvi: [f64; 4],
48    /// Grid points of the AToB (4D) and BToA (3D) tables.
49    pub grid_a2b: usize,
50    pub grid_b2a: usize,
51}
52
53impl Default for CmykParams {
54    fn default() -> Self {
55        CmykParams {
56            description: DESCRIPTION.into(),
57            tac: 3.0,
58            gcr_start: 0.2,
59            k_max: 0.95,
60            gcr_gamma: 1.1,
61            tvi: [0.14, 0.14, 0.14, 0.17],
62            grid_a2b: 11,
63            grid_b2a: 21,
64        }
65    }
66}
67
68/// The printer model.
69#[derive(Clone, Debug)]
70pub struct CmykModel {
71    /// Absolute XYZ (D50) of the 16 overprints, indexed by ink bit mask (C=1, M=2, Y=4, K=8),
72    /// stored as `X^(1/n)` for the Yule–Nielsen sum.
73    prim_n: [[f64; 3]; 16],
74    /// Absolute XYZ of the paper.
75    pub paper: [f64; 3],
76    tvi: [f64; 4],
77}
78
79const YN: f64 = 2.0;
80
81impl CmykModel {
82    pub fn coated(tvi: [f64; 4]) -> Self {
83        let lab = |l: f64, a: f64, b: f64| math::lab_to_xyz([l, a, b], math::D50);
84        // ISO 12647-2 (coated, paper type 1/2) Lab aims, D50/2°; CMY overprint estimated.
85        let w = lab(95.0, 0.0, -2.0);
86        let base: [[f64; 3]; 8] = [
87            w,                       // paper
88            lab(55.0, -37.0, -50.0), // C
89            lab(48.0, 74.0, -3.0),   // M
90            lab(24.0, 22.0, -46.0),  // C+M (blue)
91            lab(89.0, -5.0, 93.0),   // Y
92            lab(50.0, -65.0, 27.0),  // C+Y (green)
93            lab(47.0, 68.0, 48.0),   // M+Y (red)
94            lab(23.0, 0.0, 0.0),     // C+M+Y
95        ];
96        let k = lab(16.0, 0.0, 0.0);
97        // Overprints with black: multiplicative in reflectance above a first-surface floor.
98        let floor = 0.006;
99        let mut prim = [[0.0; 3]; 16];
100        for m in 0..16 {
101            let p = base[m & 7];
102            prim[m] = if m & 8 == 0 {
103                p
104            } else {
105                std::array::from_fn(|i| {
106                    let s = floor * w[i];
107                    s + (p[i] - s) * (k[i] - s) / (w[i] - s)
108                })
109            };
110        }
111        let prim_n = prim.map(|p| p.map(|v| v.max(0.0).powf(1.0 / YN)));
112        CmykModel {
113            prim_n,
114            paper: w,
115            tvi,
116        }
117    }
118
119    /// Absolute XYZ of an ink combination (each coverage in `[0, 1]`).
120    pub fn xyz(&self, cmyk: [f64; 4]) -> [f64; 3] {
121        let a: [f64; 4] = std::array::from_fn(|i| {
122            let v = cmyk[i].clamp(0.0, 1.0);
123            (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0)
124        });
125        let mut s = [0.0; 3];
126        for m in 0..16 {
127            let mut w = 1.0;
128            for (i, ai) in a.iter().enumerate() {
129                w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai };
130            }
131            if w == 0.0 {
132                continue;
133            }
134            for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) {
135                *acc += w * p;
136            }
137        }
138        s.map(|v| v.powf(YN))
139    }
140
141    /// ICC-relative Lab (paper = L* 100).
142    pub fn lab(&self, cmyk: [f64; 4]) -> [f64; 3] {
143        let x = self.xyz(cmyk);
144        let rel = [
145            x[0] * math::D50[0] / self.paper[0],
146            x[1] * math::D50[1] / self.paper[1],
147            x[2] * math::D50[2] / self.paper[2],
148        ];
149        math::xyz_to_lab(rel, math::D50)
150    }
151}
152
153/// Bounded least-squares solve for C, M, Y given K, minimising ΔE76 to `target`, subject to
154/// `C + M + Y ≤ limit` (projected Levenberg–Marquardt with a numerical Jacobian).
155fn solve_cmy(
156    model: &CmykModel,
157    target: [f64; 3],
158    k: f64,
159    limit: f64,
160    seeds: &[[f64; 3]],
161) -> ([f64; 3], f64) {
162    let project = |mut x: [f64; 3]| {
163        for _ in 0..4 {
164            for v in &mut x {
165                *v = v.clamp(0.0, 1.0);
166            }
167            let s: f64 = x.iter().sum();
168            if s <= limit + 1e-12 {
169                break;
170            }
171            let active = x.iter().filter(|v| **v > 0.0).count().max(1) as f64;
172            let d = (s - limit) / active;
173            for v in &mut x {
174                if *v > 0.0 {
175                    *v -= d;
176                }
177            }
178        }
179        x
180    };
181    let err = |x: [f64; 3]| {
182        let l = model.lab([x[0], x[1], x[2], k]);
183        [l[0] - target[0], l[1] - target[1], l[2] - target[2]]
184    };
185    let norm2 = |e: [f64; 3]| e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
186    let mut best = ([0.0; 3], f64::INFINITY);
187    for seed in seeds {
188        let mut x = project(*seed);
189        let mut e = err(x);
190        let mut f = norm2(e);
191        let mut lambda = 1e-3;
192        for _ in 0..60 {
193            // Jacobian (3×3) by forward differences.
194            let h = 1e-5;
195            let mut j = [[0.0; 3]; 3];
196            for c in 0..3 {
197                let mut xp = x;
198                xp[c] += h;
199                let ep = err(xp);
200                for r in 0..3 {
201                    j[r][c] = (ep[r] - e[r]) / h;
202                }
203            }
204            // (JᵀJ + λ diag) δ = −Jᵀe
205            let mut a = [[0.0; 3]; 3];
206            let mut g = [0.0; 3];
207            for r in 0..3 {
208                for c in 0..3 {
209                    a[r][c] = (0..3).map(|k| j[k][r] * j[k][c]).sum();
210                }
211                g[r] = -(0..3).map(|k| j[k][r] * e[k]).sum::<f64>();
212            }
213            let mut improved = false;
214            for _ in 0..8 {
215                let mut al = a;
216                for (d, row) in al.iter_mut().enumerate() {
217                    row[d] += lambda * (1.0 + a[d][d]);
218                }
219                let Some(inv) = math::invert(&al) else {
220                    lambda *= 10.0;
221                    continue;
222                };
223                let step = math::apply(&inv, g);
224                let xn = project([x[0] + step[0], x[1] + step[1], x[2] + step[2]]);
225                let en = err(xn);
226                let fnew = norm2(en);
227                if fnew < f {
228                    let moved = (0..3).map(|i| (xn[i] - x[i]).abs()).fold(0.0, f64::max);
229                    x = xn;
230                    e = en;
231                    f = fnew;
232                    lambda = (lambda * 0.3).max(1e-9);
233                    improved = moved > 1e-9;
234                    break;
235                }
236                lambda *= 10.0;
237            }
238            if !improved || f < 1e-10 {
239                break;
240            }
241        }
242        if f < best.1 {
243            best = (x, f);
244        }
245        if best.1 < 1e-6 {
246            break;
247        }
248    }
249    (best.0, best.1.sqrt())
250}
251
252const SEEDS: [[f64; 3]; 5] = [
253    [0.3, 0.3, 0.3],
254    [0.05, 0.05, 0.05],
255    [0.8, 0.8, 0.8],
256    [0.9, 0.2, 0.2],
257    [0.2, 0.9, 0.9],
258];
259
260/// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve.
261pub fn separate(
262    model: &CmykModel,
263    p: &CmykParams,
264    target: [f64; 3],
265    warm: Option<[f64; 4]>,
266) -> ([f64; 4], f64) {
267    let mut seeds: Vec<[f64; 3]> = warm.map(|w| vec![[w[0], w[1], w[2]]]).unwrap_or_default();
268    seeds.extend_from_slice(&SEEDS);
269    let (cmy0, _) = solve_cmy(model, target, 0.0, 3.0, &seeds);
270    let g = cmy0[0].min(cmy0[1]).min(cmy0[2]);
271    let k = if g <= p.gcr_start {
272        0.0
273    } else {
274        p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma)
275    };
276    let mut seeds2 = vec![
277        [
278            (cmy0[0] - k).max(0.0),
279            (cmy0[1] - k).max(0.0),
280            (cmy0[2] - k).max(0.0),
281        ],
282        cmy0,
283    ];
284    seeds2.extend_from_slice(&seeds);
285    let (cmy, de) = solve_cmy(model, target, k, (p.tac - k).max(0.0), &seeds2);
286    ([cmy[0], cmy[1], cmy[2], k], de)
287}
288
289/// Gamut boundary descriptor: maximum chroma per (L*, hue) bin, sampled from the model.
290struct Gbd {
291    l_bins: usize,
292    h_bins: usize,
293    cmax: Vec<f64>,
294    black_l: f64,
295}
296
297impl Gbd {
298    fn new(model: &CmykModel, p: &CmykParams) -> Self {
299        let (l_bins, h_bins) = (41usize, 72usize);
300        let mut cmax = vec![0.0f64; l_bins * h_bins];
301        let n = 21;
302        let mut black_l = 100.0f64;
303        for ci in 0..n {
304            for mi in 0..n {
305                for yi in 0..n {
306                    for ki in 0..11 {
307                        let v = [
308                            ci as f64 / (n - 1) as f64,
309                            mi as f64 / (n - 1) as f64,
310                            yi as f64 / (n - 1) as f64,
311                            ki as f64 / 10.0,
312                        ];
313                        if v.iter().sum::<f64>() > p.tac + 1e-9 {
314                            continue;
315                        }
316                        let lab = model.lab(v);
317                        black_l = black_l.min(lab[0]);
318                        let c = lab[1].hypot(lab[2]);
319                        let h = lab[2].atan2(lab[1]).rem_euclid(std::f64::consts::TAU);
320                        let li = ((lab[0] / 100.0) * (l_bins - 1) as f64)
321                            .round()
322                            .clamp(0.0, (l_bins - 1) as f64)
323                            as usize;
324                        let hi =
325                            ((h / std::f64::consts::TAU) * h_bins as f64).round() as usize % h_bins;
326                        let e = &mut cmax[li * h_bins + hi];
327                        *e = e.max(c);
328                    }
329                }
330            }
331        }
332        // Fill holes and smooth: max over a 3×3 neighbourhood, then a box blur.
333        let get = |v: &Vec<f64>, l: isize, h: isize| {
334            let l = l.clamp(0, l_bins as isize - 1) as usize;
335            let h = h.rem_euclid(h_bins as isize) as usize;
336            v[l * h_bins + h]
337        };
338        let mut filled = cmax.clone();
339        for l in 0..l_bins as isize {
340            for h in 0..h_bins as isize {
341                let mut m = 0.0f64;
342                for dl in -1..=1 {
343                    for dh in -1..=1 {
344                        m = m.max(get(&cmax, l + dl, h + dh));
345                    }
346                }
347                filled[l as usize * h_bins + h as usize] = m;
348            }
349        }
350        let mut smooth = filled.clone();
351        for l in 0..l_bins as isize {
352            for h in 0..h_bins as isize {
353                let mut s = 0.0;
354                for dl in -1..=1 {
355                    for dh in -1..=1 {
356                        s += get(&filled, l + dl, h + dh);
357                    }
358                }
359                smooth[l as usize * h_bins + h as usize] = s / 9.0;
360            }
361        }
362        Gbd {
363            l_bins,
364            h_bins,
365            cmax: smooth,
366            black_l,
367        }
368    }
369
370    fn max_chroma(&self, l: f64, h: f64) -> f64 {
371        let lp = (l / 100.0).clamp(0.0, 1.0) * (self.l_bins - 1) as f64;
372        let hp = (h.rem_euclid(std::f64::consts::TAU) / std::f64::consts::TAU) * self.h_bins as f64;
373        let (l0, h0) = (lp.floor() as usize, hp.floor() as usize);
374        let (fl, fh) = (lp - l0 as f64, hp - h0 as f64);
375        let l1 = (l0 + 1).min(self.l_bins - 1);
376        let (h0m, h1m) = (h0 % self.h_bins, (h0 + 1) % self.h_bins);
377        let v = |l: usize, h: usize| self.cmax[l * self.h_bins + h];
378        let a = v(l0, h0m) + (v(l0, h1m) - v(l0, h0m)) * fh;
379        let b = v(l1, h0m) + (v(l1, h1m) - v(l1, h0m)) * fh;
380        a + (b - a) * fl
381    }
382
383    /// Perceptual gamut compression of a relative Lab colour.
384    fn compress(&self, lab: [f64; 3]) -> [f64; 3] {
385        let l = self.black_l + lab[0].clamp(0.0, 100.0) * (100.0 - self.black_l) / 100.0;
386        let c = lab[1].hypot(lab[2]);
387        if c < 1e-9 {
388            return [l, 0.0, 0.0];
389        }
390        let h = lab[2].atan2(lab[1]);
391        let cm = self.max_chroma(l, h).max(1e-3);
392        let knee = 0.8 * cm;
393        let c2 = if c <= knee {
394            c
395        } else {
396            knee + (cm - knee) * ((c - knee) / (cm - knee)).tanh()
397        };
398        [l, c2 * h.cos(), c2 * h.sin()]
399    }
400}
401
402fn lab_node_legacy(i: usize, n: usize) -> f64 {
403    i as f64 / (n - 1) as f64
404}
405
406/// Decodes a legacy (lut16) Lab node coordinate triple.
407fn decode_v2(v: [f64; 3]) -> [f64; 3] {
408    [
409        v[0] * 100.0 * 65535.0 / 65280.0,
410        v[1] * 65535.0 / 256.0 - 128.0,
411        v[2] * 65535.0 / 256.0 - 128.0,
412    ]
413}
414
415fn encode_v2(lab: [f64; 3]) -> [f32; 3] {
416    [
417        (lab[0] / (100.0 * 65535.0 / 65280.0)).clamp(0.0, 1.0) as f32,
418        ((lab[1] + 128.0) * 256.0 / 65535.0).clamp(0.0, 1.0) as f32,
419        ((lab[2] + 128.0) * 256.0 / 65535.0).clamp(0.0, 1.0) as f32,
420    ]
421}
422
423#[cfg(not(target_arch = "wasm32"))]
424fn par_map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
425    use rayon::prelude::*;
426    (0..n).into_par_iter().map(f).collect()
427}
428
429#[cfg(target_arch = "wasm32")]
430fn par_map<T: Send>(n: usize, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {
431    (0..n).map(f).collect()
432}
433
434fn b2a_table(model: &CmykModel, p: &CmykParams, gbd: Option<&Gbd>) -> Clut {
435    let n = p.grid_b2a;
436    let nodes = n * n * n;
437    let vals = par_map(n * n, |row| {
438        // One (L, a) row along b, warm-starting each solve from its neighbour.
439        let (li, ai) = (row / n, row % n);
440        let mut warm = None;
441        let mut out = Vec::with_capacity(n * 4);
442        for bi in 0..n {
443            let lab = decode_v2([
444                lab_node_legacy(li, n),
445                lab_node_legacy(ai, n),
446                lab_node_legacy(bi, n),
447            ]);
448            let target = match gbd {
449                Some(g) => g.compress(lab),
450                None => lab,
451            };
452            let (cmyk, _) = separate(model, p, target, warm);
453            warm = Some(cmyk);
454            out.extend(cmyk.map(|v| v as f32));
455        }
456        out
457    });
458    let data: Vec<f32> = vals.into_iter().flatten().collect();
459    debug_assert_eq!(data.len(), nodes * 4);
460    Clut::new(vec![n; 3], 4, data)
461}
462
463fn lut16(clut: Clut) -> Lut {
464    let (i, o) = (clut.inputs, clut.outputs);
465    Lut {
466        kind: LutKind::Lut16,
467        inputs: i,
468        outputs: o,
469        stages: vec![
470            Stage::Curves(vec![Curve::Table(vec![0.0, 1.0]); i]),
471            Stage::Clut(clut),
472            Stage::Curves(vec![Curve::Table(vec![0.0, 1.0]); o]),
473        ],
474    }
475}
476
477/// Generates a synthetic CMYK profile.
478pub fn cmyk_profile(p: &CmykParams) -> Profile {
479    let model = CmykModel::coated(p.tvi);
480    let g = p.grid_a2b;
481    let a2b = Clut::sample(vec![g; 4], 3, |inp, out| {
482        let lab = model.lab([inp[0] as f64, inp[1] as f64, inp[2] as f64, inp[3] as f64]);
483        out.copy_from_slice(&encode_v2(lab));
484    });
485    let gbd = Gbd::new(&model, p);
486    let colorimetric = b2a_table(&model, p, None);
487    let perceptual = b2a_table(&model, p, Some(&gbd));
488    let a2b = lut16(a2b);
489    let (b0, b1) = (lut16(perceptual), lut16(colorimetric));
490    Profile {
491        version: (4, 0x30),
492        class: ProfileClass::Output,
493        color_space: ColorSpace::Cmyk,
494        pcs: Pcs::Lab,
495        rendering_intent: Intent::Perceptual,
496        description: p.description.clone(),
497        copyright: crate::builtin::COPYRIGHT.into(),
498        white_point: model.paper.map(math::s15f16_round),
499        black_point: None,
500        chad: None,
501        matrix: None,
502        trc: None,
503        gray_trc: None,
504        a2b: [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)],
505        b2a: [Some(b0.clone()), Some(b1), Some(b0)],
506        bytes: None,
507        hash: Default::default(),
508    }
509    .with_encoded_bytes()
510}
511
512/// The default coated profile (what `profiles/photocraft-coated-cmyk.icc` contains).
513pub fn coated_cmyk() -> Profile {
514    cmyk_profile(&CmykParams::default())
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520
521    #[test]
522    fn model_anchors() {
523        let m = CmykModel::coated(CmykParams::default().tvi);
524        let w = m.lab([0.0; 4]);
525        assert!(
526            (w[0] - 100.0).abs() < 1e-9 && w[1].abs() < 1e-9 && w[2].abs() < 1e-9,
527            "{w:?}"
528        );
529        let k = m.lab([0.0, 0.0, 0.0, 1.0]);
530        assert!(k[0] > 12.0 && k[0] < 22.0, "{k:?}");
531        let rich = m.lab([0.75, 0.65, 0.6, 0.9]);
532        assert!(rich[0] < k[0], "{rich:?}");
533        // Monotonic in each ink.
534        for ink in 0..4 {
535            let mut prev = 101.0;
536            for i in 0..=20 {
537                let mut v = [0.2, 0.2, 0.2, 0.2];
538                v[ink] = i as f64 / 20.0;
539                let l = m.lab(v)[0];
540                assert!(l < prev + 1e-9, "ink {ink} step {i}: {l} >= {prev}");
541                prev = l;
542            }
543        }
544    }
545
546    #[test]
547    fn separation_hits_in_gamut_targets() {
548        let m = CmykModel::coated(CmykParams::default().tvi);
549        let p = CmykParams::default();
550        let reachable = [
551            [0.3, 0.4, 0.1, 0.1],
552            [0.6, 0.1, 0.5, 0.0],
553            [0.05, 0.1, 0.7, 0.0],
554            [0.5, 0.45, 0.45, 0.4],
555        ]
556        .map(|v| m.lab(v));
557        for target in [[50.0, 0.0, 0.0]].into_iter().chain(reachable) {
558            let (cmyk, de) = separate(&m, &p, target, None);
559            assert!(de < 1.5, "{target:?} -> {cmyk:?} ΔE {de}");
560            assert!(cmyk.iter().sum::<f64>() <= p.tac + 1e-6);
561        }
562    }
563}