Skip to main content

rust_motion_cms/
transform.rs

1//! Colour transforms between profiles through the PCS, with rendering intents, black point
2//! compensation, soft-proofing chains, and fast lookup-table evaluation of pixel buffers.
3
4use std::collections::HashMap;
5use std::sync::{Arc, Mutex, OnceLock};
6
7use crate::clut::{Clut, MAX_CHANNELS};
8use crate::curve::Curve;
9use crate::math;
10use crate::pipeline::{Pipeline, Stage};
11use crate::profile::{ColorSpace, Pcs, Profile, ProfileClass};
12use crate::{CmsError, Intent};
13
14/// Sample storage of a byte buffer for [`Transform::convert_bytes_many`].
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum SampleKind {
17    U8,
18    U16,
19    F32,
20}
21
22/// Options for building a [`Transform`].
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
24pub struct TransformOptions {
25    pub intent: Intent,
26    /// Adobe-style black point compensation (ignored for absolute colorimetric).
27    pub bpc: bool,
28    /// `true`: float buffers go through the exact pipeline (default). `false`: float buffers use
29    /// the same lookup tables as integer buffers (faster, for previews).
30    pub precise_float: bool,
31}
32
33impl Default for TransformOptions {
34    fn default() -> Self {
35        Self {
36            intent: Intent::RelativeColorimetric,
37            bpc: true,
38            precise_float: true,
39        }
40    }
41}
42
43/// Grid sizes of the device-link tables built for integer (and fast float) evaluation.
44pub const GRID_3D: usize = 33;
45pub const GRID_4D: usize = 17;
46const TABLE_1D: usize = 4096;
47/// Resolution of output shaper tables (indexed by `x^(1/4)`).
48const OUT_TABLE: usize = 4096;
49
50/// ICC v4 perceptual reference medium black (ICC.1:2010 §6.3.4.4), XYZ.
51const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287];
52
53/// Accelerated representation of a transform.
54#[derive(Debug)]
55enum Core {
56    /// Input curves (sampled per input channel over `[0, 1]`, 4096+1 entries; 256 exact
57    /// entries for 8-bit input) followed by an optional matrix.
58    Shaper {
59        curves8: Vec<[f32; 256]>,
60        curves: Vec<Vec<f32>>,
61        matrix: Option<(usize, usize, Vec<f32>, Vec<f32>)>,
62    },
63    /// Device link table over the input space.
64    Grid(Clut),
65    /// No acceleration possible: use the exact pipeline.
66    Exact,
67}
68
69/// Output inverse-curve tables indexed by `x^(1/4)` (accurate near black even for pure gamma
70/// curves, whose slope is infinite at zero).
71#[derive(Debug)]
72struct Post {
73    tables: Vec<Vec<f32>>,
74}
75
76impl Post {
77    #[inline]
78    fn eval(&self, c: usize, x: f32) -> f32 {
79        let t = &self.tables[c];
80        let u = x.clamp(0.0, 1.0).sqrt().sqrt() * (OUT_TABLE - 1) as f32;
81        let i = (u as usize).min(OUT_TABLE - 2);
82        let f = u - i as f32;
83        t[i] + (t[i + 1] - t[i]) * f
84    }
85}
86
87/// A colour transform from one profile's device space to another's.
88///
89/// Build once (it precomputes lookup tables) and apply to any number of buffers from any
90/// thread. Buffers are interleaved; colour channels come first in each pixel and any further
91/// channels (alpha, spot) are copied or left alone.
92#[derive(Debug)]
93pub struct Transform {
94    inputs: usize,
95    outputs: usize,
96    opts: TransformOptions,
97    pipeline: Pipeline,
98    core: Core,
99    post: Option<Post>,
100    /// Pre-located grid coordinates per 8-bit code: (offset contribution, fraction) per input.
101    grid8: Vec<[(u32, f32); 256]>,
102}
103
104impl Transform {
105    /// Transform from `src` to `dst` with `intent`, optionally with black point compensation.
106    pub fn new(
107        src: &Profile,
108        dst: &Profile,
109        intent: Intent,
110        bpc: bool,
111    ) -> Result<Transform, CmsError> {
112        Self::with_options(
113            src,
114            dst,
115            TransformOptions {
116                intent,
117                bpc,
118                ..Default::default()
119            },
120        )
121    }
122
123    pub fn with_options(
124        src: &Profile,
125        dst: &Profile,
126        opts: TransformOptions,
127    ) -> Result<Transform, CmsError> {
128        let stages = link_stages(src, dst, opts.intent, opts.bpc)?;
129        let mut t = Self::from_pipeline(Pipeline::new(src.channels(), stages), opts);
130        if opts.intent != Intent::AbsoluteColorimetric {
131            t.fix_white(src.color_space, dst.color_space);
132        }
133        Ok(t)
134    }
135
136    /// Soft-proof transform `src → proof → dst` (Photoshop View › Proof Setup): `intent`/`bpc`
137    /// apply to the document → proof step; the proof → display step is relative colorimetric
138    /// with BPC, or absolute colorimetric without BPC when `simulate_paper` is set (paper
139    /// colour and black ink simulated).
140    pub fn proof(
141        src: &Profile,
142        proof: &Profile,
143        dst: &Profile,
144        intent: Intent,
145        bpc: bool,
146        simulate_paper: bool,
147    ) -> Result<Transform, CmsError> {
148        let mut stages = link_stages(src, proof, intent, bpc)?;
149        stages.push(Stage::Clamp01);
150        let (i2, b2) = if simulate_paper {
151            (Intent::AbsoluteColorimetric, false)
152        } else {
153            (Intent::RelativeColorimetric, true)
154        };
155        stages.extend(link_stages(proof, dst, i2, b2)?);
156        Ok(Self::from_pipeline(
157            Pipeline::new(src.channels(), stages),
158            TransformOptions {
159                intent,
160                bpc,
161                precise_float: true,
162            },
163        ))
164    }
165
166    /// Builds a transform from an arbitrary pipeline over normalised values.
167    pub fn from_pipeline(mut pipeline: Pipeline, opts: TransformOptions) -> Transform {
168        pipeline.optimize();
169        let (inputs, outputs) = (pipeline.inputs, pipeline.outputs);
170        // Split trailing inverse curves into accurate output tables.
171        let mut head = pipeline.stages.clone();
172        let mut post = None;
173        if let Some(Stage::InvCurves(cs)) = head.last() {
174            if cs.len() == outputs {
175                let tables = cs
176                    .iter()
177                    .map(|c| {
178                        (0..OUT_TABLE)
179                            .map(|i| {
180                                let u = i as f64 / (OUT_TABLE - 1) as f64;
181                                c.eval_inverse64(u * u * u * u).clamp(0.0, 1.0) as f32
182                            })
183                            .collect()
184                    })
185                    .collect();
186                post = Some(Post { tables });
187                head.pop();
188                if matches!(head.last(), Some(Stage::Clamp01)) {
189                    head.pop();
190                }
191            }
192        }
193        let head_pipe = Pipeline::new(inputs, head.clone());
194        let mid = head_pipe.outputs;
195        let core = match head.as_slice() {
196            [] => Core::Shaper {
197                curves8: Vec::new(),
198                curves: Vec::new(),
199                matrix: None,
200            },
201            [Stage::Curves(cs)] if cs.len() == inputs => shaper(cs, None),
202            [Stage::Matrix {
203                rows,
204                cols,
205                m,
206                offset,
207            }] => shaper(&[], Some((*rows, *cols, m, offset))),
208            [Stage::Curves(cs), Stage::Matrix {
209                rows,
210                cols,
211                m,
212                offset,
213            }] if cs.len() == inputs => shaper(cs, Some((*rows, *cols, m, offset))),
214            // Purely analytic heads (Lab/XYZ maths, matrices, curves) are evaluated exactly:
215            // a grid would amplify interpolation error through steep output curves.
216            _ if !head.iter().any(|s| matches!(s, Stage::Clut(_))) => Core::Exact,
217            _ => match inputs {
218                1 => Core::Grid(Clut::sample(vec![TABLE_1D], mid, |i, o| {
219                    head_pipe.eval(i, o)
220                })),
221                3 => Core::Grid(Clut::sample(vec![GRID_3D; 3], mid, |i, o| {
222                    head_pipe.eval(i, o)
223                })),
224                4 => Core::Grid(Clut::sample(vec![GRID_4D; 4], mid, |i, o| {
225                    head_pipe.eval(i, o)
226                })),
227                2 => Core::Grid(Clut::sample(vec![GRID_3D; 2], mid, |i, o| {
228                    head_pipe.eval(i, o)
229                })),
230                _ => Core::Exact,
231            },
232        };
233        let grid8 = match &core {
234            Core::Grid(c) if c.inputs >= 2 => (0..c.inputs)
235                .map(|d| {
236                    let n = c.grid[d];
237                    let stride = c.data.len() / c.outputs / c.grid[..=d].iter().product::<usize>()
238                        * c.outputs;
239                    std::array::from_fn(|v| {
240                        let p = v as f32 / 255.0 * (n - 1) as f32;
241                        let i = (p as usize).min(n - 2);
242                        ((i * stride) as u32, p - i as f32)
243                    })
244                })
245                .collect(),
246            _ => Vec::new(),
247        };
248        Transform {
249            inputs,
250            outputs,
251            opts,
252            pipeline,
253            core,
254            post,
255            grid8,
256        }
257    }
258
259    /// White preservation: the device-link node at the source's device white gets exactly the
260    /// destination's device white, so paper/white survive table quantization (e.g. the PCS
261    /// white is not a node of a legacy-encoded Lab grid).
262    fn fix_white(&mut self, src: ColorSpace, dst: ColorSpace) {
263        let (Some(sw), Some(mut dw)) = (device_white(src), device_white(dst)) else {
264            return;
265        };
266        if self.post.is_some() {
267            // Output curves map 1 → 1 for additive spaces; the grid holds pre-curve values.
268            if !matches!(dst, ColorSpace::Rgb | ColorSpace::Gray) {
269                return;
270            }
271            dw.iter_mut().for_each(|v| *v = 1.0);
272        }
273        let Core::Grid(c) = &mut self.core else {
274            return;
275        };
276        if c.inputs != sw.len() || c.outputs != dw.len() {
277            return;
278        }
279        let mut off = 0usize;
280        let mut stride = c.outputs;
281        for d in (0..c.inputs).rev() {
282            let n = c.grid[d];
283            let pos = sw[d] * (n - 1) as f32;
284            if (pos - pos.round()).abs() > 1e-6 {
285                return;
286            }
287            off += pos.round() as usize * stride;
288            stride *= n;
289        }
290        c.data[off..off + c.outputs].copy_from_slice(&dw);
291    }
292
293    pub fn inputs(&self) -> usize {
294        self.inputs
295    }
296    pub fn outputs(&self) -> usize {
297        self.outputs
298    }
299    pub fn options(&self) -> TransformOptions {
300        self.opts
301    }
302    /// The exact evaluation pipeline.
303    pub fn pipeline(&self) -> &Pipeline {
304        &self.pipeline
305    }
306
307    /// Exact evaluation of one colour (`inputs` → `outputs` normalised values).
308    #[inline]
309    pub fn eval(&self, input: &[f32], out: &mut [f32]) {
310        self.pipeline.eval(input, out);
311    }
312
313    /// Lookup-table evaluation of one colour (what integer buffers use).
314    #[inline]
315    pub fn eval_fast(&self, input: &[f32], out: &mut [f32]) {
316        let mut mid = [0.0f32; 16];
317        match &self.core {
318            Core::Exact => return self.pipeline.eval(input, out),
319            Core::Grid(c) => {
320                let mut inp = [0.0f32; 16];
321                for (d, s) in inp.iter_mut().zip(&input[..self.inputs]) {
322                    *d = s.clamp(0.0, 1.0);
323                }
324                c.eval(&inp[..self.inputs], &mut mid[..c.outputs]);
325            }
326            Core::Shaper { curves, matrix, .. } => {
327                let mut v = [0.0f32; 16];
328                for k in 0..self.inputs {
329                    v[k] = if curves.is_empty() {
330                        input[k]
331                    } else {
332                        table(&curves[k], input[k])
333                    };
334                }
335                apply_matrix(matrix, &v, &mut mid, self.inputs);
336            }
337        }
338        self.finish(&mid, out);
339    }
340
341    #[inline]
342    fn finish(&self, mid: &[f32], out: &mut [f32]) {
343        match &self.post {
344            Some(p) => {
345                for k in 0..self.outputs {
346                    out[k] = p.eval(k, mid[k]);
347                }
348            }
349            None => out[..self.outputs].copy_from_slice(&mid[..self.outputs]),
350        }
351    }
352
353    /// Converts float pixels. `src`/`dst` hold whole pixels of `src_stride`/`dst_stride`
354    /// values; colour channels come first. Trailing channels are copied when `copy_extra`.
355    pub fn convert_f32(
356        &self,
357        src: &[f32],
358        src_stride: usize,
359        dst: &mut [f32],
360        dst_stride: usize,
361        copy_extra: bool,
362    ) {
363        self.check(src_stride, dst_stride);
364        let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
365        par_rows(src, src_stride, dst, dst_stride, |s, d| {
366            self.run_f32(s, src_stride, d, dst_stride, extra)
367        });
368    }
369
370    fn run_f32(&self, s: &[f32], ss: usize, d: &mut [f32], ds: usize, extra: usize) {
371        let precise = self.opts.precise_float || matches!(self.core, Core::Exact);
372        for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
373            if precise {
374                self.pipeline.eval(sp, dp);
375            } else {
376                self.eval_fast(sp, dp);
377            }
378            for e in 0..extra {
379                dp[self.outputs + e] = sp[self.inputs + e];
380            }
381        }
382    }
383
384    /// In-place float conversion; `stride ≥ max(inputs, outputs)`.
385    pub fn apply(&self, buf: &mut [f32], stride: usize) {
386        assert!(stride >= self.inputs.max(self.outputs), "stride too small");
387        let precise = self.opts.precise_float || matches!(self.core, Core::Exact);
388        let body = |chunk: &mut [f32]| {
389            let mut out = [0.0f32; 16];
390            for p in chunk.chunks_exact_mut(stride) {
391                if precise {
392                    self.pipeline.eval(p, &mut out);
393                } else {
394                    self.eval_fast(p, &mut out);
395                }
396                p[..self.outputs].copy_from_slice(&out[..self.outputs]);
397            }
398        };
399        par_inplace(buf, stride, body);
400    }
401
402    /// Converts 8-bit pixels (see [`Transform::convert_f32`] for the layout).
403    pub fn convert_u8(
404        &self,
405        src: &[u8],
406        src_stride: usize,
407        dst: &mut [u8],
408        dst_stride: usize,
409        copy_extra: bool,
410    ) {
411        self.check(src_stride, dst_stride);
412        let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
413        par_rows(src, src_stride, dst, dst_stride, |s, d| {
414            self.run_u8(s, src_stride, d, dst_stride, extra)
415        });
416    }
417
418    fn run_u8(&self, s: &[u8], ss: usize, d: &mut [u8], ds: usize, extra: usize) {
419        let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
420        let mut mid = [0.0f32; 16];
421        let mut out = [0.0f32; 16];
422        match &self.core {
423            Core::Grid(c) if c.inputs == 3 => {
424                let (g0, g1, g2) = (&self.grid8[0], &self.grid8[1], &self.grid8[2]);
425                let s1 = c.outputs * c.grid[2];
426                let s0 = s1 * c.grid[1];
427                for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
428                    let (a, b, cc) = (g0[sp[0] as usize], g1[sp[1] as usize], g2[sp[2] as usize]);
429                    c.tetra_pub(
430                        (a.0 + b.0 + cc.0) as usize,
431                        [s0, s1, c.outputs],
432                        [a.1, b.1, cc.1],
433                        &mut mid,
434                    );
435                    self.finish(&mid, &mut out);
436                    for k in 0..self.outputs {
437                        dp[k] = q(out[k]);
438                    }
439                    for e in 0..extra {
440                        dp[self.outputs + e] = sp[self.inputs + e];
441                    }
442                }
443            }
444            Core::Grid(c) if c.inputs == 4 => {
445                let g = &self.grid8;
446                let s3 = c.outputs;
447                let s2 = s3 * c.grid[3];
448                let s1 = s2 * c.grid[2];
449                let s0 = s1 * c.grid[1];
450                let mut hi = [0.0f32; 16];
451                for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
452                    let (a, b, cc, k4) = (
453                        g[0][sp[0] as usize],
454                        g[1][sp[1] as usize],
455                        g[2][sp[2] as usize],
456                        g[3][sp[3] as usize],
457                    );
458                    let base = (a.0 + b.0 + cc.0 + k4.0) as usize;
459                    c.tetra_pub(base, [s1, s2, s3], [b.1, cc.1, k4.1], &mut mid);
460                    if a.1 > 0.0 {
461                        c.tetra_pub(base + s0, [s1, s2, s3], [b.1, cc.1, k4.1], &mut hi);
462                        for k in 0..c.outputs {
463                            mid[k] += (hi[k] - mid[k]) * a.1;
464                        }
465                    }
466                    self.finish(&mid, &mut out);
467                    for k in 0..self.outputs {
468                        dp[k] = q(out[k]);
469                    }
470                    for e in 0..extra {
471                        dp[self.outputs + e] = sp[self.inputs + e];
472                    }
473                }
474            }
475            Core::Shaper {
476                curves8, matrix, ..
477            } => {
478                let mut v = [0.0f32; 16];
479                for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
480                    for k in 0..self.inputs {
481                        v[k] = if curves8.is_empty() {
482                            sp[k] as f32 / 255.0
483                        } else {
484                            curves8[k][sp[k] as usize]
485                        };
486                    }
487                    apply_matrix(matrix, &v, &mut mid, self.inputs);
488                    self.finish(&mid, &mut out);
489                    for k in 0..self.outputs {
490                        dp[k] = q(out[k]);
491                    }
492                    for e in 0..extra {
493                        dp[self.outputs + e] = sp[self.inputs + e];
494                    }
495                }
496            }
497            _ => {
498                let mut inp = [0.0f32; 16];
499                for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
500                    for k in 0..self.inputs {
501                        inp[k] = sp[k] as f32 / 255.0;
502                    }
503                    self.eval_fast(&inp, &mut out);
504                    for k in 0..self.outputs {
505                        dp[k] = q(out[k]);
506                    }
507                    for e in 0..extra {
508                        dp[self.outputs + e] = sp[self.inputs + e];
509                    }
510                }
511            }
512        }
513    }
514
515    /// Converts 16-bit pixels (see [`Transform::convert_f32`] for the layout).
516    pub fn convert_u16(
517        &self,
518        src: &[u16],
519        src_stride: usize,
520        dst: &mut [u16],
521        dst_stride: usize,
522        copy_extra: bool,
523    ) {
524        self.check(src_stride, dst_stride);
525        let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
526        par_rows(src, src_stride, dst, dst_stride, |s, d| {
527            self.run_u16(s, src_stride, d, dst_stride, extra)
528        });
529    }
530
531    fn run_u16(&self, s: &[u16], ss: usize, d: &mut [u16], ds: usize, extra: usize) {
532        let mut inp = [0.0f32; 16];
533        let mut out = [0.0f32; 16];
534        for (sp, dp) in s.chunks_exact(ss).zip(d.chunks_exact_mut(ds)) {
535            for k in 0..self.inputs {
536                inp[k] = sp[k] as f32 / 65535.0;
537            }
538            self.eval_fast(&inp, &mut out);
539            for k in 0..self.outputs {
540                dp[k] = (out[k].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16;
541            }
542            for e in 0..extra {
543                dp[self.outputs + e] = sp[self.inputs + e];
544            }
545        }
546    }
547
548    /// Converts many independent buffers of native-endian samples in one parallel pass (e.g.
549    /// all tiles of a surface): far cheaper than one parallel call per small buffer. Each job
550    /// is `(src bytes, dst bytes)` holding whole pixels of `src_stride`/`dst_stride` samples.
551    pub fn convert_bytes_many(
552        &self,
553        sample: SampleKind,
554        jobs: Vec<(&[u8], &mut [u8])>,
555        src_stride: usize,
556        dst_stride: usize,
557        copy_extra: bool,
558    ) {
559        self.check(src_stride, dst_stride);
560        let extra = extra_channels(self, src_stride, dst_stride, copy_extra);
561        let run = |(s, d): (&[u8], &mut [u8])| match sample {
562            SampleKind::U8 => self.run_u8(s, src_stride, d, dst_stride, extra),
563            SampleKind::U16 => {
564                let a: Vec<u16> = s
565                    .as_chunks::<2>()
566                    .0
567                    .iter()
568                    .map(|b| u16::from_ne_bytes([b[0], b[1]]))
569                    .collect();
570                let mut o: Vec<u16> = d
571                    .as_chunks::<2>()
572                    .0
573                    .iter()
574                    .map(|b| u16::from_ne_bytes([b[0], b[1]]))
575                    .collect();
576                self.run_u16(&a, src_stride, &mut o, dst_stride, extra);
577                for (b, v) in d.as_chunks_mut::<2>().0.iter_mut().zip(o) {
578                    b.copy_from_slice(&v.to_ne_bytes());
579                }
580            }
581            SampleKind::F32 => {
582                let a: Vec<f32> = s
583                    .as_chunks::<4>()
584                    .0
585                    .iter()
586                    .map(|b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]]))
587                    .collect();
588                let mut o: Vec<f32> = d
589                    .as_chunks::<4>()
590                    .0
591                    .iter()
592                    .map(|b| f32::from_ne_bytes([b[0], b[1], b[2], b[3]]))
593                    .collect();
594                self.run_f32(&a, src_stride, &mut o, dst_stride, extra);
595                for (b, v) in d.as_chunks_mut::<4>().0.iter_mut().zip(o) {
596                    b.copy_from_slice(&v.to_ne_bytes());
597                }
598            }
599        };
600        #[cfg(not(target_arch = "wasm32"))]
601        {
602            use rayon::prelude::*;
603            jobs.into_par_iter().for_each(run);
604        }
605        #[cfg(target_arch = "wasm32")]
606        jobs.into_iter().for_each(run);
607    }
608
609    fn check(&self, ss: usize, ds: usize) {
610        assert!(
611            ss >= self.inputs && ds >= self.outputs,
612            "pixel stride smaller than the channel count"
613        );
614    }
615}
616
617fn device_white(cs: ColorSpace) -> Option<Vec<f32>> {
618    Some(match cs {
619        ColorSpace::Rgb => vec![1.0; 3],
620        ColorSpace::Gray => vec![1.0],
621        ColorSpace::Cmyk => vec![0.0; 4],
622        ColorSpace::Cmy => vec![0.0; 3],
623        ColorSpace::Lab => vec![1.0, 0.5, 0.5],
624        _ => return None,
625    })
626}
627
628fn extra_channels(t: &Transform, ss: usize, ds: usize, copy: bool) -> usize {
629    if copy {
630        (ss - t.inputs).min(ds - t.outputs)
631    } else {
632        0
633    }
634}
635
636fn shaper(cs: &[Curve], matrix: Option<(usize, usize, &Vec<f64>, &Vec<f64>)>) -> Core {
637    let curves8 = cs
638        .iter()
639        .map(|c| std::array::from_fn(|i| c.eval64(i as f64 / 255.0) as f32))
640        .collect();
641    let curves = cs
642        .iter()
643        .map(|c| {
644            (0..=TABLE_1D)
645                .map(|i| c.eval64(i as f64 / TABLE_1D as f64) as f32)
646                .collect()
647        })
648        .collect();
649    let matrix = matrix.map(|(r, c, m, o)| {
650        (
651            r,
652            c,
653            m.iter().map(|v| *v as f32).collect(),
654            o.iter().map(|v| *v as f32).collect(),
655        )
656    });
657    Core::Shaper {
658        curves8,
659        curves,
660        matrix,
661    }
662}
663
664#[inline]
665fn table(t: &[f32], x: f32) -> f32 {
666    // Sampled over [0, 1] with TABLE_1D segments; values outside extrapolate linearly from
667    // the end segments so HDR floats stay usable in the fast path.
668    let n = t.len() - 1;
669    let p = x * n as f32;
670    let i = (p.floor().max(0.0) as usize).min(n - 1);
671    let f = p - i as f32;
672    t[i] + (t[i + 1] - t[i]) * f
673}
674
675#[inline]
676fn apply_matrix(
677    m: &Option<(usize, usize, Vec<f32>, Vec<f32>)>,
678    v: &[f32; 16],
679    out: &mut [f32; 16],
680    n: usize,
681) {
682    match m {
683        None => out[..n].copy_from_slice(&v[..n]),
684        Some((rows, cols, m, off)) => {
685            for r in 0..*rows {
686                let mut s = off[r];
687                for c in 0..*cols {
688                    s += m[r * cols + c] * v[c];
689                }
690                out[r] = s;
691            }
692        }
693    }
694}
695
696// ------------------------------------------------------------ parallel helpers
697
698#[cfg(not(target_arch = "wasm32"))]
699const PAR_MIN_PIXELS: usize = 16 * 1024;
700#[cfg(not(target_arch = "wasm32"))]
701const PAR_CHUNK_PIXELS: usize = 8 * 1024;
702
703#[cfg(not(target_arch = "wasm32"))]
704fn par_rows<S: Sync, D: Send>(
705    src: &[S],
706    ss: usize,
707    dst: &mut [D],
708    ds: usize,
709    f: impl Fn(&[S], &mut [D]) + Sync,
710) {
711    use rayon::prelude::*;
712    let n = (src.len() / ss).min(dst.len() / ds);
713    let (src, dst) = (&src[..n * ss], &mut dst[..n * ds]);
714    if n < PAR_MIN_PIXELS {
715        return f(src, dst);
716    }
717    src.par_chunks(PAR_CHUNK_PIXELS * ss)
718        .zip(dst.par_chunks_mut(PAR_CHUNK_PIXELS * ds))
719        .for_each(|(s, d)| f(s, d));
720}
721
722#[cfg(target_arch = "wasm32")]
723fn par_rows<S: Sync, D: Send>(
724    src: &[S],
725    ss: usize,
726    dst: &mut [D],
727    ds: usize,
728    f: impl Fn(&[S], &mut [D]) + Sync,
729) {
730    let n = (src.len() / ss).min(dst.len() / ds);
731    f(&src[..n * ss], &mut dst[..n * ds]);
732}
733
734#[cfg(not(target_arch = "wasm32"))]
735fn par_inplace(buf: &mut [f32], stride: usize, f: impl Fn(&mut [f32]) + Sync) {
736    use rayon::prelude::*;
737    if buf.len() / stride < PAR_MIN_PIXELS {
738        return f(buf);
739    }
740    buf.par_chunks_mut(PAR_CHUNK_PIXELS * stride).for_each(&f);
741}
742
743#[cfg(target_arch = "wasm32")]
744fn par_inplace(buf: &mut [f32], _stride: usize, f: impl Fn(&mut [f32]) + Sync) {
745    f(buf)
746}
747
748// ------------------------------------------------------------ linking
749
750/// Stages from `src` device values to `dst` device values.
751pub(crate) fn link_stages(
752    src: &Profile,
753    dst: &Profile,
754    intent: Intent,
755    bpc: bool,
756) -> Result<Vec<Stage>, CmsError> {
757    for p in [src, dst] {
758        // A Lab DeviceLink stands in for an abstract profile only when it also ends in Lab.
759        let lab_to_lab = p.color_space == ColorSpace::Lab
760            && p.a2b.iter().flatten().all(|l| l.outputs == 3)
761            && p.b2a.iter().flatten().all(|l| l.inputs == 3);
762        if matches!(
763            p.class,
764            ProfileClass::DeviceLink | ProfileClass::NamedColor | ProfileClass::Abstract
765        ) && !lab_to_lab
766        {
767            return Err(CmsError::Unsupported(format!(
768                "{:?} profiles cannot be used as a source or destination",
769                p.class
770            )));
771        }
772    }
773    let (mut stages, s_pcs) = src.device_to_pcs(intent)?;
774    let (d_stages, d_pcs) = dst.pcs_to_device(intent)?;
775    let adjust = connection(src, dst, intent, bpc)?;
776    match adjust {
777        Some((scale, offset)) => {
778            if s_pcs == Pcs::Lab {
779                stages.push(Stage::LabToXyz);
780            }
781            stages.push(Stage::Matrix {
782                rows: 3,
783                cols: 3,
784                m: vec![scale[0], 0.0, 0.0, 0.0, scale[1], 0.0, 0.0, 0.0, scale[2]],
785                offset: offset.to_vec(),
786            });
787            if d_pcs == Pcs::Lab {
788                stages.push(Stage::XyzToLab);
789            }
790        }
791        None => match (s_pcs, d_pcs) {
792            (Pcs::Lab, Pcs::Xyz) => stages.push(Stage::LabToXyz),
793            (Pcs::Xyz, Pcs::Lab) => stages.push(Stage::XyzToLab),
794            _ => {}
795        },
796    }
797    stages.extend(d_stages);
798    Ok(stages)
799}
800
801/// Per-component XYZ scale and offset applied in the PCS: absolute colorimetric media-white
802/// scaling or black point compensation. `None` = identity.
803/// Per-component XYZ `(scale, offset)`.
804type Affine3 = ([f64; 3], [f64; 3]);
805
806fn connection(
807    src: &Profile,
808    dst: &Profile,
809    intent: Intent,
810    bpc: bool,
811) -> Result<Option<Affine3>, CmsError> {
812    if intent == Intent::AbsoluteColorimetric {
813        let (ws, wd) = (src.media_white(), dst.media_white());
814        // `wtpt` comes straight from the file. A zero, negative or non-finite component would
815        // make the scale NaN or infinite and poison every colour the transform produces, so a
816        // profile with such a media white is refused for this intent instead.
817        let usable = |w: &[f64; 3]| w.iter().all(|v| v.is_finite() && *v > 0.0);
818        if !usable(&ws) || !usable(&wd) {
819            return Err(CmsError::Invalid(format!("absolute colorimetric needs a positive media white point (source {ws:?}, destination {wd:?})")));
820        }
821        let s = [ws[0] / wd[0], ws[1] / wd[1], ws[2] / wd[2]];
822        if s.iter().all(|v| (v - 1.0).abs() < 1e-6) {
823            return Ok(None);
824        }
825        return Ok(Some((s, [0.0; 3])));
826    }
827    if !bpc {
828        return Ok(None);
829    }
830    let bs = black_point(src, intent, true)?;
831    let bd = black_point(dst, intent, false)?;
832    if (bs - bd).abs() < 1e-6 {
833        return Ok(None);
834    }
835    // Neutral black points (luminance only, as in Adobe's BPC), mapped linearly in XYZ so that
836    // the source black lands on the destination black and the white stays fixed.
837    let w = math::D50;
838    let mut scale = [1.0; 3];
839    let mut offset = [0.0; 3];
840    for i in 0..3 {
841        let (s, d) = (bs * w[i], bd * w[i]);
842        let a = (w[i] - d) / (w[i] - s);
843        scale[i] = a;
844        offset[i] = w[i] * (1.0 - a);
845    }
846    Ok(Some((scale, offset)))
847}
848
849/// Luminance (Y, D50-relative) of the profile's black point for `intent`.
850///
851/// Follows the structure of Adobe's published BPC algorithm: matrix/TRC profiles use device
852/// zero; v4 LUT profiles in perceptual/saturation use the perceptual reference black; other LUT
853/// profiles use the darkest colour the device reaches (Lab 0 round-tripped through BToA/AToB,
854/// or device black for additive spaces). The destination-side curve fitting of the paper is
855/// not implemented; the round-trip black is used directly.
856pub fn black_point(p: &Profile, intent: Intent, _input: bool) -> Result<f64, CmsError> {
857    if matches!(p.color_space, ColorSpace::Lab | ColorSpace::Xyz) {
858        return Ok(0.0);
859    }
860    let lut_based = p.a2b.iter().any(Option::is_some);
861    if lut_based && p.version.0 >= 4 && matches!(intent, Intent::Perceptual | Intent::Saturation) {
862        return Ok(PERCEPTUAL_BLACK[1]);
863    }
864    let pcs_y = |st: Vec<Stage>, pcs: Pcs, dev: &[f32]| -> f64 {
865        let pipe = Pipeline::new(p.channels(), st);
866        let mut o = [0.0f32; 16];
867        pipe.eval(dev, &mut o);
868        let y = match pcs {
869            Pcs::Xyz => o[1] as f64,
870            Pcs::Lab => math::lab_to_xyz([o[0] as f64, 0.0, 0.0], math::D50)[1],
871        };
872        y.clamp(0.0, 0.5)
873    };
874    let (to_pcs, pcs) = p.device_to_pcs(intent)?;
875    let additive = matches!(p.color_space, ColorSpace::Rgb | ColorSpace::Gray);
876    if additive || !lut_based {
877        let zero = vec![0.0f32; p.channels()];
878        return Ok(pcs_y(to_pcs, pcs, &zero));
879    }
880    // Subtractive LUT profile: darkest reachable colour.
881    let colorimetric = if intent == Intent::Saturation {
882        Intent::Saturation
883    } else {
884        Intent::RelativeColorimetric
885    };
886    match p.pcs_to_device(colorimetric) {
887        Ok((from_pcs, fpcs)) => {
888            let mut st = Vec::new();
889            if fpcs == Pcs::Xyz {
890                st.push(Stage::LabToXyz);
891            }
892            st.extend(from_pcs);
893            let pipe = Pipeline::new(3, st);
894            let mut dev = [0.0f32; 16];
895            pipe.eval(&[0.0, 0.0, 0.0], &mut dev);
896            Ok(pcs_y(to_pcs, pcs, &dev[..p.channels()]))
897        }
898        Err(_) => {
899            let ones = vec![1.0f32; p.channels()];
900            Ok(pcs_y(to_pcs, pcs, &ones))
901        }
902    }
903}
904
905// ------------------------------------------------------------ cache
906
907type Key = (u64, u64, TransformOptions);
908
909/// Process-wide cache of transforms keyed by profile content and options.
910pub fn cached(
911    src: &Profile,
912    dst: &Profile,
913    opts: TransformOptions,
914) -> Result<Arc<Transform>, CmsError> {
915    static CACHE: OnceLock<Mutex<HashMap<Key, Arc<Transform>>>> = OnceLock::new();
916    let key = (src.content_hash(), dst.content_hash(), opts);
917    let cache = CACHE.get_or_init(Default::default);
918    if let Some(t) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&key) {
919        return Ok(t.clone());
920    }
921    let t = Arc::new(Transform::with_options(src, dst, opts)?);
922    let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
923    if c.len() > 64 {
924        c.clear();
925    }
926    c.insert(key, t.clone());
927    Ok(t)
928}
929
930impl Clut {
931    /// Tetrahedral interpolation in one cube (crate-internal fast paths).
932    #[inline]
933    pub(crate) fn tetra_pub(&self, base: usize, s: [usize; 3], r: [f32; 3], out: &mut [f32; 16]) {
934        let d = &self.data;
935        let [rx, ry, rz] = r;
936        let [sx, sy, sz] = s;
937        let (p1, p2, p3, w1, w2, w3) = if rx >= ry {
938            if ry >= rz {
939                (sx, sx + sy, sx + sy + sz, rx, ry, rz)
940            } else if rx >= rz {
941                (sx, sx + sz, sx + sy + sz, rx, rz, ry)
942            } else {
943                (sz, sx + sz, sx + sy + sz, rz, rx, ry)
944            }
945        } else if rx >= rz {
946            (sy, sx + sy, sx + sy + sz, ry, rx, rz)
947        } else if ry >= rz {
948            (sy, sy + sz, sx + sy + sz, ry, rz, rx)
949        } else {
950            (sz, sy + sz, sx + sy + sz, rz, ry, rx)
951        };
952        let o = self.outputs.min(MAX_CHANNELS);
953        for k in 0..o {
954            let v0 = d[base + k];
955            let v1 = d[base + p1 + k];
956            let v2 = d[base + p2 + k];
957            let v3 = d[base + p3 + k];
958            out[k] = v0 + (v1 - v0) * w1 + (v2 - v1) * w2 + (v3 - v2) * w3;
959        }
960    }
961}