Skip to main content

zenpixels_convert/
cms.rs

1//! Clean Color Management System (`CmsBackend`) trait, named/quoted [`CmsBinding`],
2//! shared [`ColorServices`] / [`CmsChoice`], and optional `MoxCms` / `Lcms` adapters.
3//!
4//! Only invoked when converting arbitrary [`ColorSpace::Icc`](zenpixels::ColorSpace::Icc)
5//! profiles (that don't match a safe matrix+TRC fingerprint) or [`ColorSpace::Cmyk`](zenpixels::ColorSpace::Cmyk).
6
7use alloc::boxed::Box;
8use alloc::sync::Arc;
9use core::fmt::Debug;
10use how_far::Pulse;
11use whereat::At;
12use zenpixels::PixelFormat;
13
14use crate::error::ConvertError;
15use crate::tonemap::ToneMapper;
16
17/// Shareable, stateless row-level CMS transform executor (`Send + Sync`).
18pub trait CmsTransform: Send + Sync {
19    /// Transform one row of `width_pixels` pixels from `src` bytes to `dst` bytes.
20    fn transform_row(
21        &self,
22        src: &[u8],
23        dst: &mut [u8],
24        width_pixels: u32,
25    ) -> Result<(), At<ConvertError>>;
26}
27
28/// Pluggable ICC / CMYK Color Management System backend.
29pub trait CmsBackend: Send + Sync + Debug {
30    /// Fast, allocation-free check whether this backend supports the `(src, dst)`
31    /// layouts, sample types, and color families (used by [`Negotiate`](crate::Negotiate)
32    /// to avoid selecting unbuildable candidates).
33    fn supports_formats(&self, _src: &PixelFormat, _dst: &PixelFormat) -> bool {
34        true
35    }
36
37    /// Build a row transform from `src` to `dst`, observing optional cooperative
38    /// cancellation and progress via `pulse`.
39    ///
40    /// Pass `None` when cancellation and progress reporting are not needed, or
41    /// `Some(pulse)` (e.g. `Some(&StopOnly::borrowed(stop))` for cancellation
42    /// alone). Backends that parse ICC profiles or construct 3D CLUT / MPE
43    /// transforms should call `pulse.check()` before and during expensive
44    /// setup work and map [`StopReason`](how_far::StopReason) into
45    /// [`ConvertError::Cancelled`]. Per `how-far`'s contract, implementations
46    /// borrow `pulse` and never finish it.
47    fn build_transform(
48        &self,
49        src: &PixelFormat,
50        dst: &PixelFormat,
51        pulse: Option<&dyn Pulse>,
52    ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>>;
53}
54
55/// Conservative capability, memory, stack, and concurrency quote for a [`CmsBinding`].
56///
57/// Hosts and routing planners inspect this quote before admitting a CMS transform
58/// against memory limits, constrained thread stacks (such as 256 KiB IIS worker stacks),
59/// or concurrency pools. `None` means the bound is unknown/unproven for arbitrary
60/// profiles and cannot authorize a strict hard limit without route qualification or
61/// explicit best-effort policy.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
63#[non_exhaustive]
64pub struct CmsQuote {
65    /// Supports `SampleType::U8` transforms.
66    pub supports_u8: bool,
67    /// Supports `SampleType::U16` transforms.
68    pub supports_u16: bool,
69    /// Supports `SampleType::F16` transforms.
70    pub supports_f16: bool,
71    /// Supports `SampleType::F32` transforms.
72    pub supports_f32: bool,
73    /// Supports `ColorSpace::Cmyk` ink transforms.
74    pub supports_cmyk: bool,
75    /// Supports `RenderingIntent::AbsoluteColorimetric` (media-white / `chad` un-adaptation).
76    pub supports_absolute_colorimetric: bool,
77    /// Supports ICC v4 float `D2B*`/`B2D*` MPE pipelines.
78    pub supports_float_mpe: bool,
79    /// Proven conservative heap bytes allocated while building one transform (`None` = unknown).
80    pub build_memory_bytes: Option<u64>,
81    /// Proven conservative heap bytes retained per live [`CmsTransform`] (`None` = unknown).
82    pub transform_memory_bytes: Option<u64>,
83    /// Proven conservative heap bytes allocated per `transform_row` call (`Some(0)` = zero-alloc apply; `None` = unknown).
84    pub apply_scratch_bytes: Option<u64>,
85    /// Proven conservative peak stack bytes consumed by `build_transform` / `transform_row` (`None` = unknown).
86    pub peak_stack_bytes: Option<u32>,
87    /// Whether `build_transform` and `transform_row` are qualified for constrained 256 KiB stacks.
88    pub small_stack_qualified: bool,
89    /// Whether concurrent `transform_row` calls across threads are lock-free / contention-free.
90    pub concurrent_apply: bool,
91}
92
93impl CmsQuote {
94    /// Conservative empty quote with all capabilities disabled, unknown bounds (`None`),
95    /// and `small_stack_qualified = false`.
96    #[inline]
97    #[must_use]
98    pub const fn new() -> Self {
99        Self {
100            supports_u8: false,
101            supports_u16: false,
102            supports_f16: false,
103            supports_f32: false,
104            supports_cmyk: false,
105            supports_absolute_colorimetric: false,
106            supports_float_mpe: false,
107            build_memory_bytes: None,
108            transform_memory_bytes: None,
109            apply_scratch_bytes: None,
110            peak_stack_bytes: None,
111            small_stack_qualified: false,
112            concurrent_apply: false,
113        }
114    }
115
116    /// Set `U8` support.
117    #[inline]
118    #[must_use]
119    pub const fn with_u8(mut self, yes: bool) -> Self {
120        self.supports_u8 = yes;
121        self
122    }
123
124    /// Set `U16` support.
125    #[inline]
126    #[must_use]
127    pub const fn with_u16(mut self, yes: bool) -> Self {
128        self.supports_u16 = yes;
129        self
130    }
131
132    /// Set `F16` support.
133    #[inline]
134    #[must_use]
135    pub const fn with_f16(mut self, yes: bool) -> Self {
136        self.supports_f16 = yes;
137        self
138    }
139
140    /// Set `F32` support.
141    #[inline]
142    #[must_use]
143    pub const fn with_f32(mut self, yes: bool) -> Self {
144        self.supports_f32 = yes;
145        self
146    }
147
148    /// Set `ColorSpace::Cmyk` support.
149    #[inline]
150    #[must_use]
151    pub const fn with_cmyk(mut self, yes: bool) -> Self {
152        self.supports_cmyk = yes;
153        self
154    }
155
156    /// Set `RenderingIntent::AbsoluteColorimetric` support.
157    #[inline]
158    #[must_use]
159    pub const fn with_absolute_colorimetric(mut self, yes: bool) -> Self {
160        self.supports_absolute_colorimetric = yes;
161        self
162    }
163
164    /// Set ICC v4 float MPE (`D2B*`/`B2D*`) support.
165    #[inline]
166    #[must_use]
167    pub const fn with_float_mpe(mut self, yes: bool) -> Self {
168        self.supports_float_mpe = yes;
169        self
170    }
171
172    /// Set proven conservative heap bytes used while building one transform (`None` = unknown).
173    #[inline]
174    #[must_use]
175    pub const fn with_build_memory_bytes(mut self, bytes: Option<u64>) -> Self {
176        self.build_memory_bytes = bytes;
177        self
178    }
179
180    /// Set proven conservative heap bytes retained per live [`CmsTransform`] (`None` = unknown).
181    #[inline]
182    #[must_use]
183    pub const fn with_transform_memory_bytes(mut self, bytes: Option<u64>) -> Self {
184        self.transform_memory_bytes = bytes;
185        self
186    }
187
188    /// Set proven conservative heap bytes allocated per `transform_row` call (`Some(0)` = zero-alloc apply).
189    #[inline]
190    #[must_use]
191    pub const fn with_apply_scratch_bytes(mut self, bytes: Option<u64>) -> Self {
192        self.apply_scratch_bytes = bytes;
193        self
194    }
195
196    /// Set proven conservative peak stack bytes used by `build_transform` and `transform_row`.
197    #[inline]
198    #[must_use]
199    pub const fn with_peak_stack_bytes(mut self, bytes: Option<u32>) -> Self {
200        self.peak_stack_bytes = bytes;
201        self
202    }
203
204    /// Declare whether this backend is qualified for constrained 256 KiB thread stacks.
205    #[inline]
206    #[must_use]
207    pub const fn with_small_stack_qualified(mut self, yes: bool) -> Self {
208        self.small_stack_qualified = yes;
209        self
210    }
211
212    /// Declare whether concurrent `transform_row` calls across threads are contention-free.
213    #[inline]
214    #[must_use]
215    pub const fn with_concurrent_apply(mut self, yes: bool) -> Self {
216        self.concurrent_apply = yes;
217        self
218    }
219}
220
221/// Named, versioned [`CmsBackend`] binding with conservative resource and capability quotes.
222///
223/// Swap CMS implementations (such as `MoxCms`, pure-Rust `Lcms`, C `lcms2`, or a custom
224/// provider) across `zenpixels-convert`, `zencodec-render`, `zencodecs`, `zenpipe`, and
225/// hosts by substituting this binding alone.
226#[derive(Clone, Debug)]
227pub struct CmsBinding {
228    id: Box<str>,
229    revision: Box<str>,
230    backend: Arc<dyn CmsBackend>,
231    quote: CmsQuote,
232}
233
234impl CmsBinding {
235    /// Construct a named, versioned CMS binding.
236    ///
237    /// Prefer stable reverse-DNS provider identifiers (e.g. `"org.imazen.cms.moxcms"`,
238    /// `"org.imazen.cms.lcms"`) and a revision string that changes whenever transform output
239    /// or qualification changes so downstream route caches invalidate deterministically.
240    #[must_use]
241    pub fn new(
242        id: impl Into<Box<str>>,
243        revision: impl Into<Box<str>>,
244        backend: Arc<dyn CmsBackend>,
245        quote: CmsQuote,
246    ) -> Self {
247        Self {
248            id: id.into(),
249            revision: revision.into(),
250            backend,
251            quote,
252        }
253    }
254
255    /// Stable provider identifier (e.g. `"org.imazen.cms.moxcms"`).
256    #[inline]
257    #[must_use]
258    pub fn id(&self) -> &str {
259        &self.id
260    }
261
262    /// Provider revision / version string for deterministic cache keys and diagnostics.
263    #[inline]
264    #[must_use]
265    pub fn revision(&self) -> &str {
266        &self.revision
267    }
268
269    /// Cache identity pair `(id, revision)`.
270    #[inline]
271    #[must_use]
272    pub fn cache_key(&self) -> (&str, &str) {
273        (&self.id, &self.revision)
274    }
275
276    /// Underlying [`CmsBackend`] implementation.
277    #[inline]
278    #[must_use]
279    pub fn backend(&self) -> &Arc<dyn CmsBackend> {
280        &self.backend
281    }
282
283    /// Conservative resource and capability quote.
284    #[inline]
285    #[must_use]
286    pub const fn quote(&self) -> CmsQuote {
287        self.quote
288    }
289}
290
291/// Explicit color-management provider selection for a conversion or pipeline run.
292#[derive(Clone, Debug, Default)]
293#[non_exhaustive]
294pub enum CmsChoice {
295    /// Inherit the parent or host default CMS binding when resolved at run binding.
296    #[default]
297    Inherit,
298    /// Forbid both ICC CMS evaluation and inferred matrix+TRC ICC substitution.
299    ///
300    /// Validated ICC profile carriage (pass-through when source and destination carry
301    /// equivalent profiles) and pure known-space math remain permitted.
302    StrictNoIcc,
303    /// Use this exact named [`CmsBinding`] for arbitrary ICC and CMYK conversions.
304    Use(CmsBinding),
305}
306
307impl CmsChoice {
308    /// Returns `true` when this choice is concrete (`StrictNoIcc` or `Use`), not `Inherit`.
309    #[inline]
310    #[must_use]
311    pub const fn is_frozen(&self) -> bool {
312        !matches!(self, Self::Inherit)
313    }
314
315    /// Borrow the bound [`CmsBinding`] if `self` is [`CmsChoice::Use`].
316    #[inline]
317    #[must_use]
318    pub fn binding(&self) -> Option<&CmsBinding> {
319        match self {
320            Self::Use(b) => Some(b),
321            _ => None,
322        }
323    }
324}
325
326/// Shared color-management and tone-mapping service bundle.
327///
328/// Hosts configure a default [`ColorServices`] once, resolve per-run overrides via
329/// [`resolve_against`](Self::resolve_against) or [`freeze_or_strict`](Self::freeze_or_strict),
330/// and stamp the frozen services onto [`ConvertPolicy::with_color_services`](crate::ConvertPolicy::with_color_services).
331#[derive(Clone, Debug, Default)]
332#[non_exhaustive]
333pub struct ColorServices {
334    /// CMS provider choice (`Inherit`, `StrictNoIcc`, or `Use(CmsBinding)`).
335    pub cms: CmsChoice,
336    /// Optional custom HDR → SDR tone mapper shared across conversions.
337    pub tone_mapper: Option<Arc<dyn ToneMapper>>,
338}
339
340impl ColorServices {
341    /// Inherit both CMS selection and tone mapper from the enclosing scope.
342    #[inline]
343    #[must_use]
344    pub fn inherit() -> Self {
345        Self::default()
346    }
347
348    /// Forbid ICC CMS evaluation and inferred ICC substitution while permitting
349    /// validated profile carriage and known-space math.
350    #[inline]
351    #[must_use]
352    pub fn strict_no_icc() -> Self {
353        Self {
354            cms: CmsChoice::StrictNoIcc,
355            tone_mapper: None,
356        }
357    }
358
359    /// Create a service bundle bound to a specific [`CmsBinding`].
360    #[inline]
361    #[must_use]
362    pub fn with_cms_binding(binding: CmsBinding) -> Self {
363        Self {
364            cms: CmsChoice::Use(binding),
365            tone_mapper: None,
366        }
367    }
368
369    /// Replace the [`CmsChoice`].
370    #[inline]
371    #[must_use]
372    pub fn with_cms(mut self, choice: CmsChoice) -> Self {
373        self.cms = choice;
374        self
375    }
376
377    /// Attach a custom [`ToneMapper`].
378    #[inline]
379    #[must_use]
380    pub fn with_tone_mapper(mut self, mapper: Arc<dyn ToneMapper>) -> Self {
381        self.tone_mapper = Some(mapper);
382        self
383    }
384
385    /// Returns `true` when [`cms`](Self::cms) is no longer [`CmsChoice::Inherit`].
386    #[inline]
387    #[must_use]
388    pub const fn is_frozen(&self) -> bool {
389        self.cms.is_frozen()
390    }
391
392    /// Borrow the active [`CmsChoice`].
393    #[inline]
394    #[must_use]
395    pub const fn cms_choice(&self) -> &CmsChoice {
396        &self.cms
397    }
398
399    /// Borrow the selected [`CmsBinding`], if [`CmsChoice::Use`].
400    #[inline]
401    #[must_use]
402    pub fn cms_binding(&self) -> Option<&CmsBinding> {
403        self.cms.binding()
404    }
405
406    /// Borrow the configured [`ToneMapper`], if any.
407    #[inline]
408    #[must_use]
409    pub fn tone_mapper(&self) -> Option<&Arc<dyn ToneMapper>> {
410        self.tone_mapper.as_ref()
411    }
412
413    /// Resolve [`CmsChoice::Inherit`] and missing `tone_mapper` against `parent`.
414    ///
415    /// Explicit [`CmsChoice::StrictNoIcc`] and [`CmsChoice::Use`] choices on `self`
416    /// override `parent`.
417    #[must_use]
418    pub fn resolve_against(&self, parent: &Self) -> Self {
419        let cms = match &self.cms {
420            CmsChoice::Inherit => parent.cms.clone(),
421            explicit => explicit.clone(),
422        };
423        let tone_mapper = self
424            .tone_mapper
425            .as_ref()
426            .or(parent.tone_mapper.as_ref())
427            .map(Arc::clone);
428        Self { cms, tone_mapper }
429    }
430
431    /// Freeze inheritance for a run: [`CmsChoice::Inherit`] resolves to `Use(default_cms)`
432    /// if provided, or [`CmsChoice::StrictNoIcc`] if `None`.
433    #[must_use]
434    pub fn freeze_or_strict(&self, default_cms: Option<&CmsBinding>) -> Self {
435        let cms = match &self.cms {
436            CmsChoice::Inherit => match default_cms {
437                Some(b) => CmsChoice::Use(b.clone()),
438                None => CmsChoice::StrictNoIcc,
439            },
440            explicit => explicit.clone(),
441        };
442        Self {
443            cms,
444            tone_mapper: self.tone_mapper.as_ref().map(Arc::clone),
445        }
446    }
447}
448
449#[cfg(feature = "cms-moxcms")]
450mod moxcms_impl {
451    use super::*;
452    use crate::error::err_at;
453    use zenpixels::{
454        AlphaMode, ChannelOrder, ColorSpace, Primaries, RenderingIntent, SampleType, SignalRange,
455        Transfer,
456    };
457
458    const CHUNK_PX: usize = 64;
459
460    /// Pure-Rust `moxcms` ICC CMS backend.
461    ///
462    /// Note: `moxcms` 0.9 does not implement ICC.1 §D.3 media-white / `chad` un-adaptation for
463    /// [`RenderingIntent::AbsoluteColorimetric`]; rather than silently substituting
464    /// `RelativeColorimetric`, [`MoxCms`] refuses `AbsoluteColorimetric` with
465    /// [`ConvertError::UnsupportedRoute`]. Use `Lcms` (with feature `cms-lcms`) for `AbsoluteColorimetric`.
466    #[derive(Clone, Copy, Debug, Default)]
467    pub struct MoxCms;
468
469    impl MoxCms {
470        /// Canonical named, conservatively quoted [`CmsBinding`] for `moxcms`
471        /// (`"org.imazen.cms.moxcms"`).
472        ///
473        /// Heap build/transform size and peak stack depend on profile structure and are left
474        /// unknown (`None` / `small_stack_qualified = false`) until qualified per route.
475        #[must_use]
476        pub fn binding() -> CmsBinding {
477            CmsBinding::new(
478                "org.imazen.cms.moxcms",
479                concat!("moxcms-0.9/zenpixels-convert-", env!("CARGO_PKG_VERSION")),
480                Arc::new(Self),
481                CmsQuote::new()
482                    .with_u8(true)
483                    .with_u16(true)
484                    .with_f16(false)
485                    .with_f32(true)
486                    .with_cmyk(true)
487                    .with_absolute_colorimetric(false)
488                    .with_float_mpe(false)
489                    .with_concurrent_apply(true),
490            )
491        }
492    }
493
494    fn to_mox_intent(intent: RenderingIntent) -> moxcms::RenderingIntent {
495        match intent {
496            RenderingIntent::Perceptual => moxcms::RenderingIntent::Perceptual,
497            RenderingIntent::RelativeColorimetric => moxcms::RenderingIntent::RelativeColorimetric,
498            RenderingIntent::Saturation => moxcms::RenderingIntent::Saturation,
499            RenderingIntent::AbsoluteColorimetric => moxcms::RenderingIntent::AbsoluteColorimetric,
500            _ => moxcms::RenderingIntent::Perceptual,
501        }
502    }
503
504    fn to_mox_layout(order: ChannelOrder) -> Option<moxcms::Layout> {
505        match order {
506            ChannelOrder::Gray => Some(moxcms::Layout::Gray),
507            ChannelOrder::GrayAlpha => Some(moxcms::Layout::GrayAlpha),
508            ChannelOrder::Rgb => Some(moxcms::Layout::Rgb),
509            ChannelOrder::Rgba => Some(moxcms::Layout::Rgba),
510            ChannelOrder::Cmyk | ChannelOrder::CmykInverted => Some(moxcms::Layout::Rgba),
511            _ => None,
512        }
513    }
514
515    /// `moxcms` 0.9 does not evaluate ICC.1 §8.10.2 float `D2B*`/`B2D*` MPE tags.
516    /// Decline profiles carrying the active rendering intent's float MPE tag rather than
517    /// silently degrading to fallback integer LUTs.
518    fn has_float_pipeline(bytes: &[u8], intent: RenderingIntent, is_source: bool) -> bool {
519        let sig: &[u8; 4] = match (is_source, intent) {
520            (true, RenderingIntent::Perceptual) => b"D2B0",
521            (true, RenderingIntent::RelativeColorimetric) => b"D2B1",
522            (true, RenderingIntent::Saturation) => b"D2B2",
523            (false, RenderingIntent::Perceptual) => b"B2D0",
524            (false, RenderingIntent::RelativeColorimetric) => b"B2D1",
525            (false, RenderingIntent::Saturation) => b"B2D2",
526            _ => return false,
527        };
528        let Some(header) = bytes.get(..132) else {
529            return false;
530        };
531        let count = u32::from_be_bytes(header[128..132].try_into().unwrap()) as usize;
532        let available = (bytes.len() - 132) / 12;
533        bytes[132..]
534            .as_chunks::<12>()
535            .0
536            .iter()
537            .take(count.min(available))
538            .any(|entry| &entry[..4] == sig)
539    }
540
541    /// Guard against `moxcms` 0.9 curve-sharing bugs when an RGB profile has only two
542    /// adjacent channel TRCs equal (`(r == g || g == b) && r != b`).
543    fn validate_channel_curves(profile: &moxcms::ColorProfile) -> bool {
544        if profile.color_space == moxcms::DataColorSpace::Rgb
545            && let (Some(red), Some(green), Some(blue)) =
546                (&profile.red_trc, &profile.green_trc, &profile.blue_trc)
547            && (red == green || green == blue)
548            && red != blue
549        {
550            return false;
551        }
552        true
553    }
554
555    /// Explicit ICC profiles must evaluate their own curves rather than letting an
556    /// embedded `cicp` tag override the profile's TRC/LUTs.
557    fn prefer_icc_curves(profile: &mut moxcms::ColorProfile) {
558        profile.cicp = None;
559    }
560
561    /// Scale a generated `moxcms` RGB profile's colorants so they sum to the ICC PCS D50 white
562    /// (`[0.9642, 1.0, 0.8249]`) rather than CIE D50 (`Z = 0.82521`). Without this, white from
563    /// any ICC profile into generated sRGB/P3/BT.2020 shifts blue by 0.04% (`(255, 255, 254)`).
564    fn with_pcs_white(mut profile: moxcms::ColorProfile) -> moxcms::ColorProfile {
565        const PCS_WHITE: [f64; 3] = [0.9642, 1.0, 0.8249];
566        let (r, g, b) = (
567            profile.red_colorant,
568            profile.green_colorant,
569            profile.blue_colorant,
570        );
571        let scale = [
572            PCS_WHITE[0] / (r.x + g.x + b.x),
573            PCS_WHITE[1] / (r.y + g.y + b.y),
574            PCS_WHITE[2] / (r.z + g.z + b.z),
575        ];
576        if scale.iter().all(|v| v.is_finite()) {
577            for colorant in [
578                &mut profile.red_colorant,
579                &mut profile.green_colorant,
580                &mut profile.blue_colorant,
581            ] {
582                colorant.x *= scale[0];
583                colorant.y *= scale[1];
584                colorant.z *= scale[2];
585            }
586        }
587        profile
588    }
589
590    fn icc_bytes_of(cs: &ColorSpace) -> Option<&[u8]> {
591        match cs {
592            ColorSpace::Icc { profile, .. } => Some(profile),
593            ColorSpace::Cmyk { icc: Some(b), .. } => Some(b),
594            _ => None,
595        }
596    }
597
598    fn profile_from_color_space(
599        cs: &ColorSpace,
600    ) -> Result<(moxcms::ColorProfile, Option<RenderingIntent>), At<ConvertError>> {
601        match cs {
602            ColorSpace::Icc {
603                profile, intent, ..
604            } => {
605                let mut p = moxcms::ColorProfile::new_from_slice(profile)
606                    .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
607                prefer_icc_curves(&mut p);
608                if !validate_channel_curves(&p) {
609                    return Err(err_at(ConvertError::UnsupportedRoute));
610                }
611                Ok((p, Some(*intent)))
612            }
613            ColorSpace::Cmyk { icc, .. } => {
614                let bytes = icc
615                    .as_ref()
616                    .ok_or_else(|| err_at(ConvertError::CmsRequired))?;
617                let mut p = moxcms::ColorProfile::new_from_slice(bytes)
618                    .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
619                prefer_icc_curves(&mut p);
620                Ok((p, Some(RenderingIntent::RelativeColorimetric)))
621            }
622            ColorSpace::Rgb {
623                primaries,
624                transfer,
625                range,
626                ..
627            } => {
628                if *range != SignalRange::Full {
629                    return Err(err_at(ConvertError::UnsupportedRoute));
630                }
631                let p = match (primaries, transfer) {
632                    (Primaries::Bt709, Transfer::Srgb) => {
633                        moxcms::ColorProfile::new_from_cicp(moxcms::CicpProfile {
634                            color_primaries: moxcms::CicpColorPrimaries::Bt709,
635                            transfer_characteristics: moxcms::TransferCharacteristics::Srgb,
636                            matrix_coefficients: moxcms::MatrixCoefficients::Identity,
637                            full_range: true,
638                        })
639                    }
640                    (Primaries::DisplayP3, Transfer::Srgb) => {
641                        moxcms::ColorProfile::new_from_cicp(moxcms::CicpProfile {
642                            color_primaries: moxcms::CicpColorPrimaries::Smpte432,
643                            transfer_characteristics: moxcms::TransferCharacteristics::Srgb,
644                            matrix_coefficients: moxcms::MatrixCoefficients::Identity,
645                            full_range: true,
646                        })
647                    }
648                    (Primaries::AdobeRgb, Transfer::AdobeRgb) => {
649                        moxcms::ColorProfile::new_adobe_rgb()
650                    }
651                    (Primaries::Bt2020, Transfer::Bt709) => {
652                        moxcms::ColorProfile::new_from_cicp(moxcms::CicpProfile {
653                            color_primaries: moxcms::CicpColorPrimaries::Bt2020,
654                            transfer_characteristics: moxcms::TransferCharacteristics::Bt709,
655                            matrix_coefficients: moxcms::MatrixCoefficients::Identity,
656                            full_range: true,
657                        })
658                    }
659                    (Primaries::Bt2020, Transfer::Pq) => moxcms::ColorProfile::new_bt2020_pq(),
660                    (
661                        p_id @ (Primaries::Bt709 | Primaries::DisplayP3 | Primaries::Bt2020),
662                        Transfer::Linear,
663                    ) => {
664                        let mut prof = match p_id {
665                            Primaries::Bt709 => moxcms::ColorProfile::new_srgb(),
666                            Primaries::DisplayP3 => moxcms::ColorProfile::new_display_p3(),
667                            Primaries::Bt2020 => moxcms::ColorProfile::new_bt2020(),
668                            _ => unreachable!(),
669                        };
670                        let lin = moxcms::ToneReprCurve::Parametric(alloc::vec![1.0]);
671                        prof.cicp = None;
672                        prof.red_trc = Some(lin.clone());
673                        prof.green_trc = Some(lin.clone());
674                        prof.blue_trc = Some(lin);
675                        prof
676                    }
677                    (Primaries::Bt709, Transfer::Gamma22) => {
678                        let mut prof = moxcms::ColorProfile::new_srgb();
679                        let g22 = moxcms::ToneReprCurve::Parametric(alloc::vec![2.2]);
680                        prof.cicp = None;
681                        prof.red_trc = Some(g22.clone());
682                        prof.green_trc = Some(g22.clone());
683                        prof.blue_trc = Some(g22);
684                        prof
685                    }
686                    // HLG requires BT.2100-3 display OOTF which ICC profiles cannot carry faithfully.
687                    _ => return Err(err_at(ConvertError::UnsupportedRoute)),
688                };
689                Ok((with_pcs_white(p), None))
690            }
691            ColorSpace::Gray {
692                transfer, range, ..
693            } => {
694                if *range != SignalRange::Full {
695                    return Err(err_at(ConvertError::UnsupportedRoute));
696                }
697                let p = match transfer {
698                    Transfer::Srgb => {
699                        let mut p = moxcms::ColorProfile::new_gray_with_gamma(1.0);
700                        p.gray_trc = moxcms::ColorProfile::new_srgb().red_trc;
701                        p
702                    }
703                    Transfer::Linear => moxcms::ColorProfile::new_gray_with_gamma(1.0),
704                    Transfer::Gamma22 => moxcms::ColorProfile::new_gray_with_gamma(2.2),
705                    Transfer::AdobeRgb => moxcms::ColorProfile::new_gray_with_gamma(563.0 / 256.0),
706                    Transfer::Gamma(g) => moxcms::ColorProfile::new_gray_with_gamma(g.exponent()),
707                    _ => return Err(err_at(ConvertError::UnsupportedRoute)),
708                };
709                Ok((p, None))
710            }
711            _ => Err(err_at(ConvertError::UnsupportedRoute)),
712        }
713    }
714
715    /// Compute D50 luminance `Y` of a CMYK profile's black point for relative-colorimetric
716    /// black-point compensation (matches `Lcms` / `lcms2` BPC when targeting sRGB).
717    fn cmyk_black_point_y(
718        cmyk: &moxcms::ColorProfile,
719        linear_dst: &moxcms::ColorProfile,
720        relative: moxcms::TransformOptions,
721    ) -> Option<f32> {
722        let perceptual = moxcms::TransformOptions {
723            rendering_intent: moxcms::RenderingIntent::Perceptual,
724            ..relative
725        };
726        let to_cmyk = linear_dst
727            .create_transform_f32(moxcms::Layout::Rgb, cmyk, moxcms::Layout::Rgba, perceptual)
728            .ok()?;
729        let to_rgb = cmyk
730            .create_transform_f32(
731                moxcms::Layout::Rgba,
732                linear_dst,
733                moxcms::Layout::Rgb,
734                relative,
735            )
736            .ok()?;
737        let mut ink = [0.0f32; 4];
738        to_cmyk.transform(&[0.0, 0.0, 0.0], &mut ink).ok()?;
739        let mut rgb = [0.0f32; 3];
740        to_rgb.transform(&ink, &mut rgb).ok()?;
741        let y = linear_dst.red_colorant.y * f64::from(rgb[0])
742            + linear_dst.green_colorant.y * f64::from(rgb[1])
743            + linear_dst.blue_colorant.y * f64::from(rgb[2]);
744        Some(y.clamp(0.0, 0.184_186) as f32)
745    }
746
747    /// CMYK F32 -> sRGB F32 wrapper: runs `moxcms` into linear sRGB, applies relative
748    /// black-point compensation, then encodes with exact sign-preserving sRGB OETF
749    /// (avoiding `moxcms`'s coarse post-CLUT sRGB curve and matching `Lcms` BPC).
750    struct MoxCmykToSrgbF32 {
751        inner: Arc<dyn moxcms::TransformExecutor<f32> + Send + Sync>,
752        black_point_y: f32,
753        dst_ch: usize,
754    }
755
756    impl moxcms::TransformExecutor<f32> for MoxCmykToSrgbF32 {
757        fn transform(&self, src: &[f32], dst: &mut [f32]) -> Result<(), moxcms::CmsError> {
758            self.inner.transform(src, dst)?;
759            let bp = self.black_point_y;
760            let tc = self.dst_ch;
761            if bp > 0.0 {
762                let scale = 1.0 / (1.0 - bp);
763                for px in dst.chunks_exact_mut(tc) {
764                    px[0] = (px[0] - bp) * scale;
765                    px[1] = (px[1] - bp) * scale;
766                    px[2] = (px[2] - bp) * scale;
767                }
768            }
769            if tc == 4 {
770                linear_srgb::default::linear_to_srgb_extended_rgba_slice(dst);
771            } else {
772                linear_srgb::default::linear_to_srgb_extended_slice(dst);
773            }
774            Ok(())
775        }
776    }
777
778    enum MoxExec {
779        U8(Arc<dyn moxcms::TransformExecutor<u8> + Send + Sync>),
780        U16(Arc<dyn moxcms::TransformExecutor<u16> + Send + Sync>),
781        F32(Arc<dyn moxcms::TransformExecutor<f32> + Send + Sync>),
782    }
783
784    struct MoxRowTransform {
785        exec: MoxExec,
786        src_bpp: usize,
787        dst_bpp: usize,
788        src_ch: usize,
789        dst_ch: usize,
790        dst_sample: SampleType,
791        src_cmyk_inverted: bool,
792        dst_cmyk_inverted: bool,
793        fill_opaque_alpha: bool,
794    }
795
796    impl CmsTransform for MoxRowTransform {
797        fn transform_row(
798            &self,
799            src: &[u8],
800            dst: &mut [u8],
801            width: u32,
802        ) -> Result<(), At<ConvertError>> {
803            let w = width as usize;
804            let s_len = w
805                .checked_mul(self.src_bpp)
806                .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
807            let d_len = w
808                .checked_mul(self.dst_bpp)
809                .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
810            if src.len() < s_len || dst.len() < d_len {
811                return Err(err_at(ConvertError::DimensionMismatch));
812            }
813            if w == 0 {
814                return Ok(());
815            }
816            let s = &src[..s_len];
817            let d = &mut dst[..d_len];
818            match &self.exec {
819                MoxExec::U8(ex) => {
820                    if !self.src_cmyk_inverted {
821                        ex.transform(s, d)
822                            .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
823                    } else {
824                        let mut inv = [0u8; CHUNK_PX * 4];
825                        let mut pos = 0;
826                        while pos < w {
827                            let n = (w - pos).min(CHUNK_PX);
828                            let sb = &s[pos * self.src_bpp..(pos + n) * self.src_bpp];
829                            let db = &mut d[pos * self.dst_bpp..(pos + n) * self.dst_bpp];
830                            let tmp = &mut inv[..sb.len()];
831                            for (o, &b) in tmp.iter_mut().zip(sb) {
832                                *o = !b;
833                            }
834                            ex.transform(tmp, db)
835                                .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
836                            pos += n;
837                        }
838                    }
839                    if self.dst_cmyk_inverted {
840                        for b in d.iter_mut() {
841                            *b = !*b;
842                        }
843                    }
844                }
845                MoxExec::U16(ex) => {
846                    if !self.src_cmyk_inverted
847                        && !self.dst_cmyk_inverted
848                        && let (Ok(s16), Ok(d16)) = (
849                            bytemuck::try_cast_slice::<u8, u16>(s),
850                            bytemuck::try_cast_slice_mut::<u8, u16>(d),
851                        )
852                    {
853                        ex.transform(s16, d16)
854                            .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
855                    } else {
856                        let mut s_buf = [0u16; CHUNK_PX * 4];
857                        let mut d_buf = [0u16; CHUNK_PX * 4];
858                        let mut pos = 0;
859                        while pos < w {
860                            let n = (w - pos).min(CHUNK_PX);
861                            let sc = n * self.src_ch;
862                            let dc = n * self.dst_ch;
863                            let sb = &s[pos * self.src_bpp..(pos + n) * self.src_bpp];
864                            for (dst_s, chunk) in s_buf[..sc].iter_mut().zip(sb.as_chunks::<2>().0)
865                            {
866                                let v = u16::from_ne_bytes(*chunk);
867                                *dst_s = if self.src_cmyk_inverted { !v } else { v };
868                            }
869                            ex.transform(&s_buf[..sc], &mut d_buf[..dc])
870                                .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
871                            let db = &mut d[pos * self.dst_bpp..(pos + n) * self.dst_bpp];
872                            for (&v, chunk) in d_buf[..dc].iter().zip(db.as_chunks_mut::<2>().0) {
873                                let out = if self.dst_cmyk_inverted { !v } else { v };
874                                *chunk = out.to_ne_bytes();
875                            }
876                            pos += n;
877                        }
878                    }
879                }
880                MoxExec::F32(ex) => {
881                    if !self.src_cmyk_inverted
882                        && !self.dst_cmyk_inverted
883                        && let (Ok(sf), Ok(df)) = (
884                            bytemuck::try_cast_slice::<u8, f32>(s),
885                            bytemuck::try_cast_slice_mut::<u8, f32>(d),
886                        )
887                    {
888                        ex.transform(sf, df)
889                            .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
890                    } else {
891                        let mut s_buf = [0.0f32; CHUNK_PX * 4];
892                        let mut d_buf = [0.0f32; CHUNK_PX * 4];
893                        let mut pos = 0;
894                        while pos < w {
895                            let n = (w - pos).min(CHUNK_PX);
896                            let sc = n * self.src_ch;
897                            let dc = n * self.dst_ch;
898                            let sb = &s[pos * self.src_bpp..(pos + n) * self.src_bpp];
899                            for (dst_s, chunk) in s_buf[..sc].iter_mut().zip(sb.as_chunks::<4>().0)
900                            {
901                                let v = f32::from_ne_bytes(*chunk);
902                                *dst_s = if self.src_cmyk_inverted { 1.0 - v } else { v };
903                            }
904                            ex.transform(&s_buf[..sc], &mut d_buf[..dc])
905                                .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
906                            let db = &mut d[pos * self.dst_bpp..(pos + n) * self.dst_bpp];
907                            for (&v, chunk) in d_buf[..dc].iter().zip(db.as_chunks_mut::<4>().0) {
908                                let out = if self.dst_cmyk_inverted { 1.0 - v } else { v };
909                                *chunk = out.to_ne_bytes();
910                            }
911                            pos += n;
912                        }
913                    }
914                }
915            }
916            if self.fill_opaque_alpha {
917                let sz = self.dst_sample.byte_size();
918                let opaque: &[u8] = match self.dst_sample {
919                    SampleType::U8 => &[255],
920                    SampleType::U16 => &[255, 255],
921                    SampleType::F32 => &1.0f32.to_ne_bytes(),
922                    _ => return Err(err_at(ConvertError::UnsupportedRoute)),
923                };
924                for px in d.chunks_exact_mut(self.dst_bpp) {
925                    px[self.dst_bpp - sz..].copy_from_slice(opaque);
926                }
927            }
928            Ok(())
929        }
930    }
931
932    impl CmsBackend for MoxCms {
933        fn supports_formats(&self, src: &PixelFormat, dst: &PixelFormat) -> bool {
934            let eff_intent = match (&src.color(), &dst.color()) {
935                (ColorSpace::Icc { intent, .. }, _) => *intent,
936                (_, ColorSpace::Icc { intent, .. }) => *intent,
937                _ => RenderingIntent::RelativeColorimetric,
938            };
939            if eff_intent == RenderingIntent::AbsoluteColorimetric {
940                return false;
941            }
942            if src.layout().sample() != dst.layout().sample()
943                || !matches!(
944                    src.layout().sample(),
945                    SampleType::U8 | SampleType::U16 | SampleType::F32
946                )
947                || !src.layout().packing().is_full()
948                || !dst.layout().packing().is_full()
949                || src.color().alpha() == AlphaMode::Premultiplied
950                || dst.color().alpha() == AlphaMode::Premultiplied
951            {
952                return false;
953            }
954            if to_mox_layout(src.layout().order()).is_none()
955                || to_mox_layout(dst.layout().order()).is_none()
956            {
957                return false;
958            }
959            if let Some(sb) = icc_bytes_of(src.color())
960                && has_float_pipeline(sb, eff_intent, true)
961            {
962                return false;
963            }
964            if let Some(db) = icc_bytes_of(dst.color())
965                && has_float_pipeline(db, eff_intent, false)
966            {
967                return false;
968            }
969            let color_ok = |c: &ColorSpace| match c {
970                ColorSpace::Icc { profile, .. } => {
971                    if profile.len() < 128 || &profile[36..40] != b"acsp" {
972                        return false;
973                    }
974                    moxcms::ColorProfile::new_from_slice(profile)
975                        .map(|p| validate_channel_curves(&p))
976                        .unwrap_or(false)
977                }
978                ColorSpace::Cmyk { icc: Some(p), .. } => p.len() >= 128 && &p[36..40] == b"acsp",
979                ColorSpace::Cmyk { icc: None, .. } => false,
980                ColorSpace::Rgb {
981                    primaries,
982                    transfer,
983                    range,
984                    ..
985                } => {
986                    *range == SignalRange::Full
987                        && matches!(
988                            (primaries, transfer),
989                            (
990                                Primaries::Bt709,
991                                Transfer::Srgb | Transfer::Linear | Transfer::Gamma22
992                            ) | (Primaries::DisplayP3, Transfer::Srgb | Transfer::Linear)
993                                | (Primaries::AdobeRgb, Transfer::AdobeRgb)
994                                | (
995                                    Primaries::Bt2020,
996                                    Transfer::Bt709 | Transfer::Pq | Transfer::Linear
997                                )
998                        )
999                }
1000                ColorSpace::Gray {
1001                    range, transfer, ..
1002                } => {
1003                    *range == SignalRange::Full
1004                        && matches!(
1005                            transfer,
1006                            Transfer::Srgb
1007                                | Transfer::Linear
1008                                | Transfer::Gamma22
1009                                | Transfer::AdobeRgb
1010                                | Transfer::Gamma(_)
1011                        )
1012                }
1013                _ => false,
1014            };
1015            color_ok(src.color()) && color_ok(dst.color())
1016        }
1017
1018        fn build_transform(
1019            &self,
1020            src: &PixelFormat,
1021            dst: &PixelFormat,
1022            pulse: Option<&dyn Pulse>,
1023        ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>> {
1024            let pulse = crate::pulse::live_pulse(pulse);
1025            crate::pulse::check_pulse(pulse)?;
1026            if src.layout().sample() != dst.layout().sample()
1027                || !src.layout().packing().is_full()
1028                || !dst.layout().packing().is_full()
1029                || src.color().alpha() == AlphaMode::Premultiplied
1030                || dst.color().alpha() == AlphaMode::Premultiplied
1031            {
1032                return Err(err_at(ConvertError::UnsupportedRoute));
1033            }
1034            let (src_p, src_intent) = profile_from_color_space(src.color())?;
1035            crate::pulse::check_pulse(pulse)?;
1036            let (dst_p, dst_intent) = profile_from_color_space(dst.color())?;
1037            crate::pulse::check_pulse(pulse)?;
1038            let eff_intent = src_intent
1039                .or(dst_intent)
1040                .unwrap_or(RenderingIntent::RelativeColorimetric);
1041            if eff_intent == RenderingIntent::AbsoluteColorimetric {
1042                return Err(err_at(ConvertError::UnsupportedRoute));
1043            }
1044            if let Some(sb) = icc_bytes_of(src.color())
1045                && has_float_pipeline(sb, eff_intent, true)
1046            {
1047                return Err(err_at(ConvertError::UnsupportedRoute));
1048            }
1049            if let Some(db) = icc_bytes_of(dst.color())
1050                && has_float_pipeline(db, eff_intent, false)
1051            {
1052                return Err(err_at(ConvertError::UnsupportedRoute));
1053            }
1054            let src_l = to_mox_layout(src.layout().order())
1055                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1056            let dst_l = to_mox_layout(dst.layout().order())
1057                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1058            let is_f32 = src.layout().sample() == SampleType::F32;
1059            let mut mox_intent = to_mox_intent(eff_intent);
1060            // ICC.1 §8.10.2 Table 25: fall back to A2B0/B2A0 when colorimetric LUTs & TRCs are absent.
1061            if eff_intent == RenderingIntent::RelativeColorimetric
1062                && ((src_p.lut_a_to_b_colorimetric.is_none()
1063                    && src_p.lut_a_to_b_perceptual.is_some()
1064                    && src_p.red_trc.is_none())
1065                    || (dst_p.lut_b_to_a_colorimetric.is_none()
1066                        && dst_p.lut_b_to_a_perceptual.is_some()
1067                        && dst_p.red_trc.is_none()))
1068            {
1069                mox_intent = moxcms::RenderingIntent::Perceptual;
1070            }
1071            let shared_curve = |p: &moxcms::ColorProfile| {
1072                p.color_space != moxcms::DataColorSpace::Rgb
1073                    || (p.red_trc == p.green_trc && p.red_trc == p.blue_trc)
1074            };
1075            #[allow(clippy::needless_update)]
1076            let opts = moxcms::TransformOptions {
1077                rendering_intent: mox_intent,
1078                allow_use_cicp_transfer: false,
1079                interpolation_method: moxcms::InterpolationMethod::Tetrahedral,
1080                barycentric_weight_scale: if is_f32 {
1081                    moxcms::BarycentricWeightScale::High
1082                } else {
1083                    moxcms::BarycentricWeightScale::Low
1084                },
1085                // Fixed-point Q2.13 is fine for 8-bit but loses up to 7 8-bit codes on U16 wide-gamut transforms.
1086                prefer_fixed_point: src.layout().sample() == SampleType::U8,
1087                allow_extended_range_rgb_xyz: is_f32
1088                    && shared_curve(&src_p)
1089                    && shared_curve(&dst_p),
1090                ..Default::default()
1091            };
1092            let cmyk_to_srgb_f32 = is_f32
1093                && matches!(src.color(), ColorSpace::Cmyk { .. })
1094                && matches!(
1095                    dst.color(),
1096                    ColorSpace::Rgb {
1097                        primaries: Primaries::Bt709,
1098                        transfer: Transfer::Srgb,
1099                        ..
1100                    }
1101                )
1102                && matches!(dst_l, moxcms::Layout::Rgb | moxcms::Layout::Rgba);
1103            let exec = match src.layout().sample() {
1104                SampleType::U8 => MoxExec::U8(
1105                    src_p
1106                        .create_transform_8bit(src_l, &dst_p, dst_l, opts)
1107                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?,
1108                ),
1109                SampleType::U16 => MoxExec::U16(
1110                    src_p
1111                        .create_transform_16bit(src_l, &dst_p, dst_l, opts)
1112                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?,
1113                ),
1114                SampleType::F32 if cmyk_to_srgb_f32 => {
1115                    let mut linear_dst = dst_p.clone();
1116                    linear_dst.cicp = None;
1117                    let ident = moxcms::ToneReprCurve::Lut(alloc::vec::Vec::new());
1118                    linear_dst.red_trc = Some(ident.clone());
1119                    linear_dst.green_trc = Some(ident.clone());
1120                    linear_dst.blue_trc = Some(ident);
1121                    #[allow(clippy::needless_update)]
1122                    let lin_opts = moxcms::TransformOptions {
1123                        allow_extended_range_rgb_xyz: true,
1124                        ..opts
1125                    };
1126                    let black_point_y = if eff_intent == RenderingIntent::RelativeColorimetric {
1127                        cmyk_black_point_y(&src_p, &linear_dst, lin_opts).unwrap_or(0.0)
1128                    } else {
1129                        0.0
1130                    };
1131                    crate::pulse::check_pulse(pulse)?;
1132                    let inner = src_p
1133                        .create_transform_f32(src_l, &linear_dst, dst_l, lin_opts)
1134                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1135                    MoxExec::F32(Arc::new(MoxCmykToSrgbF32 {
1136                        inner,
1137                        black_point_y,
1138                        dst_ch: dst.layout().channels(),
1139                    }))
1140                }
1141                SampleType::F32 => MoxExec::F32(
1142                    src_p
1143                        .create_transform_f32(src_l, &dst_p, dst_l, opts)
1144                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?,
1145                ),
1146                _ => return Err(err_at(ConvertError::UnsupportedRoute)),
1147            };
1148            let fill_opaque_alpha = dst.layout().order().has_alpha_slot()
1149                && (dst.color().alpha() == AlphaMode::Opaque
1150                    || !src.layout().order().has_alpha_slot()
1151                    || src.color().alpha() == AlphaMode::Opaque);
1152            Ok(Arc::new(MoxRowTransform {
1153                exec,
1154                src_bpp: src.layout().bytes_per_pixel(),
1155                dst_bpp: dst.layout().bytes_per_pixel(),
1156                src_ch: src.layout().channels(),
1157                dst_ch: dst.layout().channels(),
1158                dst_sample: dst.layout().sample(),
1159                src_cmyk_inverted: matches!(src.color(), ColorSpace::Cmyk { inverted: true, .. })
1160                    || src.layout().order() == ChannelOrder::CmykInverted,
1161                dst_cmyk_inverted: matches!(dst.color(), ColorSpace::Cmyk { inverted: true, .. })
1162                    || dst.layout().order() == ChannelOrder::CmykInverted,
1163                fill_opaque_alpha,
1164            }))
1165        }
1166    }
1167}
1168
1169#[cfg(feature = "cms-moxcms")]
1170pub use moxcms_impl::MoxCms;
1171
1172#[cfg(feature = "cms-lcms")]
1173mod lcms_impl {
1174    use super::*;
1175    use crate::error::err_at;
1176    use crate::icc_profiles::SynthesizedIcc;
1177    use lcms::api::{
1178        CiexyY, CiexyYTriple, D65, Format, Intent, Plan, PlanOptions, Profile, ToneCurve, flags,
1179    };
1180    use zenpixels::{
1181        AlphaMode, ChannelOrder, Cicp, ColorSpace, Primaries, RenderingIntent, SampleLayout,
1182        SampleType, SignalRange, Transfer,
1183    };
1184
1185    const CHUNK_PX: usize = 64;
1186
1187    const PT_GRAY: u32 = 3;
1188    const PT_RGB: u32 = 4;
1189    const PT_CMYK: u32 = 6;
1190    const DOSWAP_SH: u32 = 1 << 10;
1191    const SWAPFIRST_SH: u32 = 1 << 14;
1192    const FLOAT_SH: u32 = 1 << 22;
1193
1194    /// Pure-Rust Little CMS (`imazen/lcms`) ICC CMS backend.
1195    ///
1196    /// Stateless and safe to share (`Send + Sync`); built transforms hold an
1197    /// immutable, lock-free `lcms::api::Plan` with AVX2/SIMD pipeline
1198    /// optimization enabled and stack-only per-row scratch (zero heap
1199    /// allocation per row).
1200    #[derive(Clone, Copy, Debug, Default)]
1201    pub struct Lcms;
1202
1203    impl Lcms {
1204        /// Canonical named, conservatively quoted [`CmsBinding`] for pure-Rust `lcms`
1205        /// (`"org.imazen.cms.lcms"`).
1206        ///
1207        /// Row execution uses stack-only scratch (`apply_scratch_bytes = Some(0)`). Profile
1208        /// build/transform heap and peak stack remain unknown (`None` / `small_stack_qualified = false`)
1209        /// until qualified per route.
1210        #[must_use]
1211        pub fn binding() -> CmsBinding {
1212            CmsBinding::new(
1213                "org.imazen.cms.lcms",
1214                concat!(
1215                    "lcms-rust-opt/zenpixels-convert-",
1216                    env!("CARGO_PKG_VERSION")
1217                ),
1218                Arc::new(Self),
1219                CmsQuote::new()
1220                    .with_u8(true)
1221                    .with_u16(true)
1222                    .with_f16(true)
1223                    .with_f32(true)
1224                    .with_cmyk(true)
1225                    .with_absolute_colorimetric(true)
1226                    .with_float_mpe(true)
1227                    .with_apply_scratch_bytes(Some(0))
1228                    .with_concurrent_apply(true),
1229            )
1230        }
1231    }
1232
1233    /// Pure-Rust Little CMS backend with `FLAGS_NOOPTIMIZE` enabled.
1234    ///
1235    /// Evaluates profile stages directly without resampling into a 16-bit
1236    /// integer CLUT — slower on integer formats, useful for high-dynamic-range
1237    /// float-pipeline MPE profiles (such as PQ ICC profiles) where a 33-point
1238    /// integer CLUT loses shadow precision.
1239    #[derive(Clone, Copy, Debug, Default)]
1240    pub struct LcmsUnoptimized;
1241
1242    impl LcmsUnoptimized {
1243        /// Canonical named, conservatively quoted [`CmsBinding`] for unoptimized pure-Rust `lcms`
1244        /// (`"org.imazen.cms.lcms_unoptimized"`).
1245        #[must_use]
1246        pub fn binding() -> CmsBinding {
1247            CmsBinding::new(
1248                "org.imazen.cms.lcms_unoptimized",
1249                concat!(
1250                    "lcms-rust-noopt/zenpixels-convert-",
1251                    env!("CARGO_PKG_VERSION")
1252                ),
1253                Arc::new(Self),
1254                CmsQuote::new()
1255                    .with_u8(true)
1256                    .with_u16(true)
1257                    .with_f16(true)
1258                    .with_f32(true)
1259                    .with_cmyk(true)
1260                    .with_absolute_colorimetric(true)
1261                    .with_float_mpe(true)
1262                    .with_apply_scratch_bytes(Some(0))
1263                    .with_concurrent_apply(true),
1264            )
1265        }
1266    }
1267
1268    #[derive(Clone, Copy, PartialEq, Eq)]
1269    enum InkMode {
1270        None,
1271        InvertedInt,
1272        FloatPercent,
1273        FloatInvertedPercent,
1274    }
1275
1276    #[derive(Clone, Copy)]
1277    struct LcmsFormatInfo {
1278        format: Format,
1279        bpp: usize,
1280        sample: SampleType,
1281        has_alpha: bool,
1282        ink: InkMode,
1283    }
1284
1285    fn describe_layout(layout: SampleLayout, color: &ColorSpace) -> Option<LcmsFormatInfo> {
1286        if !layout.packing().is_full() {
1287            return None;
1288        }
1289        let sample = layout.sample();
1290        if !matches!(
1291            sample,
1292            SampleType::U8 | SampleType::U16 | SampleType::F16 | SampleType::F32
1293        ) {
1294            return None;
1295        }
1296        let inverted_cmyk = matches!(color, ColorSpace::Cmyk { inverted: true, .. })
1297            || layout.order() == ChannelOrder::CmykInverted;
1298
1299        let (space, colors, extra, swap, first, ink) = match layout.order() {
1300            ChannelOrder::Gray => (PT_GRAY, 1u32, 0u32, false, false, InkMode::None),
1301            ChannelOrder::GrayAlpha => {
1302                if sample == SampleType::F16 {
1303                    return None;
1304                }
1305                (PT_GRAY, 1, 1, false, false, InkMode::None)
1306            }
1307            ChannelOrder::Rgb => (PT_RGB, 3, 0, false, false, InkMode::None),
1308            ChannelOrder::Bgr => {
1309                if sample == SampleType::F16 {
1310                    return None;
1311                }
1312                (PT_RGB, 3, 0, true, false, InkMode::None)
1313            }
1314            ChannelOrder::Rgba | ChannelOrder::Rgbx => (PT_RGB, 3, 1, false, false, InkMode::None),
1315            ChannelOrder::Bgra | ChannelOrder::Bgrx => {
1316                if sample == SampleType::F16 {
1317                    return None;
1318                }
1319                (PT_RGB, 3, 1, true, true, InkMode::None)
1320            }
1321            ChannelOrder::Cmyk | ChannelOrder::CmykInverted => {
1322                let ink = match (sample, inverted_cmyk) {
1323                    (SampleType::U8 | SampleType::U16, false) => InkMode::None,
1324                    (SampleType::U8 | SampleType::U16, true) => InkMode::InvertedInt,
1325                    (SampleType::F32, false) => InkMode::FloatPercent,
1326                    (SampleType::F32, true) => InkMode::FloatInvertedPercent,
1327                    _ => return None,
1328                };
1329                (PT_CMYK, 4, 0, false, false, ink)
1330            }
1331            _ => return None,
1332        };
1333
1334        let float_bit = if sample.is_float() { FLOAT_SH } else { 0 };
1335        let code = float_bit
1336            | (space << 16)
1337            | (u32::from(first) * SWAPFIRST_SH)
1338            | (u32::from(swap) * DOSWAP_SH)
1339            | (extra << 7)
1340            | (colors << 3)
1341            | (sample.byte_size() as u32);
1342
1343        Some(LcmsFormatInfo {
1344            format: Format::from_u32(code),
1345            bpp: layout.bytes_per_pixel(),
1346            sample,
1347            has_alpha: layout.order().has_alpha_slot(),
1348            ink,
1349        })
1350    }
1351
1352    fn to_lcms_intent(intent: RenderingIntent) -> Intent {
1353        match intent {
1354            RenderingIntent::Perceptual => Intent::Perceptual,
1355            RenderingIntent::RelativeColorimetric => Intent::RelativeColorimetric,
1356            RenderingIntent::Saturation => Intent::Saturation,
1357            RenderingIntent::AbsoluteColorimetric => Intent::AbsoluteColorimetric,
1358            _ => Intent::RelativeColorimetric,
1359        }
1360    }
1361
1362    fn tone_curve_for_transfer(transfer: Transfer) -> Result<Option<ToneCurve>, At<ConvertError>> {
1363        match transfer {
1364            Transfer::Srgb => Ok(Some(ToneCurve::srgb())),
1365            Transfer::Linear => Ok(Some(ToneCurve::linear())),
1366            Transfer::Gamma22 => ToneCurve::gamma(2.2)
1367                .map(Some)
1368                .map_err(|_| err_at(ConvertError::CmsBackendFailed)),
1369            Transfer::AdobeRgb => ToneCurve::gamma(563.0 / 256.0)
1370                .map(Some)
1371                .map_err(|_| err_at(ConvertError::CmsBackendFailed)),
1372            Transfer::Gamma(g) => ToneCurve::gamma(f64::from(g.exponent()))
1373                .map(Some)
1374                .map_err(|_| err_at(ConvertError::CmsBackendFailed)),
1375            Transfer::Bt709 => ToneCurve::parametric(
1376                4,
1377                &[1.0 / 0.45, 1.0 / 1.099, 0.099 / 1.099, 1.0 / 4.5, 0.081],
1378            )
1379            .map(Some)
1380            .map_err(|_| err_at(ConvertError::CmsBackendFailed)),
1381            _ => Ok(None),
1382        }
1383    }
1384
1385    fn chromaticity_triple(
1386        (rx, ry): (f32, f32),
1387        (gx, gy): (f32, f32),
1388        (bx, by): (f32, f32),
1389        (wx, wy): (f32, f32),
1390    ) -> Option<(CiexyY, CiexyYTriple)> {
1391        // `lcms::Profile::rgb` divides by each primary's `y`, so skip `y == 0` (e.g. `Primaries::Xyz`).
1392        // Negative `y` (such as ACES AP0 `y_B = -0.0770`) is finite and well-defined.
1393        if ry == 0.0 || gy == 0.0 || by == 0.0 || wy <= 0.0 {
1394            return None;
1395        }
1396        Some((
1397            CiexyY {
1398                x: f64::from(wx),
1399                y: f64::from(wy),
1400                Y: 1.0,
1401            },
1402            CiexyYTriple {
1403                Red: CiexyY {
1404                    x: f64::from(rx),
1405                    y: f64::from(ry),
1406                    Y: 1.0,
1407                },
1408                Green: CiexyY {
1409                    x: f64::from(gx),
1410                    y: f64::from(gy),
1411                    Y: 1.0,
1412                },
1413                Blue: CiexyY {
1414                    x: f64::from(bx),
1415                    y: f64::from(by),
1416                    Y: 1.0,
1417                },
1418            },
1419        ))
1420    }
1421
1422    fn primaries_triple(primaries: Primaries) -> Option<(CiexyY, CiexyYTriple)> {
1423        let ((r, g, b), w) = (primaries.chromaticity()?, primaries.white_point()?);
1424        chromaticity_triple(r, g, b, w)
1425    }
1426
1427    fn custom_primaries_triple(
1428        primaries: zenpixels::CustomPrimaries,
1429    ) -> Option<(CiexyY, CiexyYTriple)> {
1430        let (r, g, b) = primaries.chromaticity();
1431        chromaticity_triple(r, g, b, primaries.white_point().xy())
1432    }
1433
1434    fn profile_from_color_space(
1435        cs: &ColorSpace,
1436    ) -> Result<(Profile, Option<RenderingIntent>), At<ConvertError>> {
1437        match cs {
1438            ColorSpace::Icc {
1439                profile, intent, ..
1440            } => {
1441                let p =
1442                    Profile::open(profile).map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1443                Ok((p, Some(*intent)))
1444            }
1445            ColorSpace::Cmyk { icc, .. } => {
1446                let bytes = icc
1447                    .as_ref()
1448                    .ok_or_else(|| err_at(ConvertError::CmsRequired))?;
1449                let p = Profile::open(bytes).map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1450                Ok((p, Some(RenderingIntent::RelativeColorimetric)))
1451            }
1452            ColorSpace::Rgb {
1453                primaries,
1454                transfer,
1455                range,
1456                ..
1457            } => {
1458                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1459                    return Err(err_at(ConvertError::UnsupportedRoute));
1460                }
1461                if *primaries == Primaries::AdobeRgb && *transfer == Transfer::AdobeRgb {
1462                    let p = Profile::open(crate::icc_profiles::ADOBE_RGB)
1463                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1464                    return Ok((p, None));
1465                }
1466                // Build sRGB and all standard / custom RGB spaces using each space's actual white
1467                // point (D65, D50, D60, DCI, C, or custom) + ToneCurve rather than `Profile::srgb()`
1468                // (which uses legacy 0.3291 D65).
1469                if let (Some((wp, triple)), Some(curve)) = (
1470                    primaries_triple(*primaries),
1471                    tone_curve_for_transfer(*transfer)?,
1472                ) {
1473                    let p = Profile::rgb(&wp, &triple, [&curve, &curve, &curve])
1474                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1475                    return Ok((p, None));
1476                }
1477                if let (Some(p_code), Some(t_code)) = (primaries.to_cicp(), transfer.to_cicp())
1478                    && let SynthesizedIcc::Profile(bytes) =
1479                        SynthesizedIcc::for_cicp(Cicp::new(p_code, t_code, 0, true))
1480                {
1481                    let p = Profile::open(&bytes)
1482                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1483                    return Ok((p, None));
1484                }
1485                Err(err_at(ConvertError::UnsupportedRoute))
1486            }
1487            ColorSpace::RgbCustom {
1488                primaries,
1489                transfer,
1490                range,
1491                ..
1492            } => {
1493                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1494                    return Err(err_at(ConvertError::UnsupportedRoute));
1495                }
1496                if let (Some((wp, triple)), Some(curve)) = (
1497                    custom_primaries_triple(**primaries),
1498                    tone_curve_for_transfer(*transfer)?,
1499                ) {
1500                    let p = Profile::rgb(&wp, &triple, [&curve, &curve, &curve])
1501                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1502                    return Ok((p, None));
1503                }
1504                Err(err_at(ConvertError::UnsupportedRoute))
1505            }
1506            ColorSpace::Gray {
1507                transfer, range, ..
1508            } => {
1509                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1510                    return Err(err_at(ConvertError::UnsupportedRoute));
1511                }
1512                if let Some(curve) = tone_curve_for_transfer(*transfer)? {
1513                    let p = Profile::gray_curve(&D65, &curve)
1514                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1515                    return Ok((p, None));
1516                }
1517                if let Some(t_code) = transfer.to_cicp()
1518                    && let SynthesizedIcc::Profile(bytes) =
1519                        SynthesizedIcc::for_gray_cicp(Cicp::new(1, t_code, 0, true))
1520                {
1521                    let p = Profile::open(&bytes)
1522                        .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1523                    return Ok((p, None));
1524                }
1525                Err(err_at(ConvertError::UnsupportedRoute))
1526            }
1527            _ => Err(err_at(ConvertError::UnsupportedRoute)),
1528        }
1529    }
1530
1531    struct LcmsRowTransform {
1532        plan: Plan,
1533        src: LcmsFormatInfo,
1534        dst: LcmsFormatInfo,
1535        /// Write canonical opaque alpha (1.0 / max code) to dst alpha slot.
1536        fill_opaque_alpha: bool,
1537        /// Guard for float RGBA CLUT fast paths in `lcms` that zero the 4th f32 lane
1538        /// after `handle_extra_channels` has already copied alpha.
1539        copy_f32_alpha_after: bool,
1540    }
1541
1542    fn build_lcms_transform(
1543        src: &PixelFormat,
1544        dst: &PixelFormat,
1545        no_optimize: bool,
1546        pulse: Option<&dyn Pulse>,
1547    ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>> {
1548        let pulse = crate::pulse::live_pulse(pulse);
1549        crate::pulse::check_pulse(pulse)?;
1550        if src.color().alpha() == AlphaMode::Premultiplied
1551            || dst.color().alpha() == AlphaMode::Premultiplied
1552        {
1553            return Err(err_at(ConvertError::UnsupportedRoute));
1554        }
1555        let from = describe_layout(src.layout(), src.color())
1556            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1557        let to = describe_layout(dst.layout(), dst.color())
1558            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1559
1560        let (src_profile, src_intent) = profile_from_color_space(src.color())?;
1561        crate::pulse::check_pulse(pulse)?;
1562        let (dst_profile, dst_intent) = profile_from_color_space(dst.color())?;
1563        crate::pulse::check_pulse(pulse)?;
1564        let eff_intent = src_intent
1565            .or(dst_intent)
1566            .unwrap_or(RenderingIntent::RelativeColorimetric);
1567
1568        let lcms_intent = to_lcms_intent(eff_intent);
1569        let bpc = matches!(src.color(), ColorSpace::Cmyk { .. })
1570            && eff_intent == RenderingIntent::RelativeColorimetric;
1571        let adaptation = if eff_intent == RenderingIntent::AbsoluteColorimetric {
1572            0.0
1573        } else {
1574            1.0
1575        };
1576
1577        let fill_opaque_alpha = to.has_alpha
1578            && (dst.color().alpha() == AlphaMode::Opaque
1579                || !from.has_alpha
1580                || src.color().alpha() == AlphaMode::Opaque);
1581
1582        // `NO_CACHE` enables lcms's fused AVX2/SIMD loops (Prelin8, Clut8, MatShaper)
1583        // for 8-bit transforms while keeping per-row execution cache-independent.
1584        // For U16 / F16 / F32, disable pipeline resampling (`NO_OPTIMIZE`) so lcms
1585        // evaluates exact curves/matrices without 16-bit CLUT quantization or F32 clipping.
1586        let mut transform_flags = flags::NO_CACHE;
1587        if no_optimize || from.sample != SampleType::U8 || to.sample != SampleType::U8 {
1588            transform_flags |= flags::NO_OPTIMIZE;
1589        }
1590        if from.has_alpha && to.has_alpha && !fill_opaque_alpha {
1591            transform_flags |= flags::COPY_ALPHA;
1592        }
1593        if bpc {
1594            transform_flags |= flags::BLACK_POINT_COMPENSATION;
1595        }
1596
1597        let opts = PlanOptions::new()
1598            .intent(lcms_intent)
1599            .flags(transform_flags)
1600            .adaptation_state(adaptation);
1601
1602        let plan = Plan::with_options(&src_profile, &dst_profile, from.format, to.format, &opts)
1603            .map_err(|_| err_at(ConvertError::CmsBackendFailed))?;
1604
1605        let copy_f32_alpha_after = from.has_alpha
1606            && to.has_alpha
1607            && !fill_opaque_alpha
1608            && from.sample == SampleType::F32
1609            && to.sample == SampleType::F32
1610            && from.bpp == 16
1611            && to.bpp == 16;
1612
1613        Ok(Arc::new(LcmsRowTransform {
1614            plan,
1615            src: from,
1616            dst: to,
1617            fill_opaque_alpha,
1618            copy_f32_alpha_after,
1619        }))
1620    }
1621
1622    impl CmsTransform for LcmsRowTransform {
1623        fn transform_row(
1624            &self,
1625            src: &[u8],
1626            dst: &mut [u8],
1627            width: u32,
1628        ) -> Result<(), At<ConvertError>> {
1629            let w = width as usize;
1630            let s_len = w
1631                .checked_mul(self.src.bpp)
1632                .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1633            let d_len = w
1634                .checked_mul(self.dst.bpp)
1635                .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1636            if src.len() < s_len || dst.len() < d_len {
1637                return Err(err_at(ConvertError::DimensionMismatch));
1638            }
1639            if w == 0 {
1640                return Ok(());
1641            }
1642
1643            let s = &src[..s_len];
1644            let d = &mut dst[..d_len];
1645            let mut scratch = self.plan.scratch();
1646
1647            match self.src.ink {
1648                InkMode::None => {
1649                    self.plan.apply_n(&mut scratch, s, d, width);
1650                }
1651                InkMode::InvertedInt => {
1652                    // Bitwise NOT inverts both u8 (`255 - x`) and native-endian u16 (`65535 - x`).
1653                    // Max CMYK integer bpp is 8 bytes (CMYK16), so 64 px = 512 B on stack.
1654                    let mut staged = [0u8; CHUNK_PX * 8];
1655                    let mut pos = 0;
1656                    while pos < w {
1657                        let n = (w - pos).min(CHUNK_PX);
1658                        let sb = &s[pos * self.src.bpp..(pos + n) * self.src.bpp];
1659                        let db = &mut d[pos * self.dst.bpp..(pos + n) * self.dst.bpp];
1660                        let tmp = &mut staged[..sb.len()];
1661                        for (o, &b) in tmp.iter_mut().zip(sb) {
1662                            *o = !b;
1663                        }
1664                        self.plan.apply_n(&mut scratch, tmp, db, n as u32);
1665                        pos += n;
1666                    }
1667                }
1668                InkMode::FloatPercent | InkMode::FloatInvertedPercent => {
1669                    let invert = self.src.ink == InkMode::FloatInvertedPercent;
1670                    let mut staged = [0.0f32; CHUNK_PX * 4];
1671                    let mut pos = 0;
1672                    while pos < w {
1673                        let n = (w - pos).min(CHUNK_PX);
1674                        let sb = &s[pos * self.src.bpp..(pos + n) * self.src.bpp];
1675                        let db = &mut d[pos * self.dst.bpp..(pos + n) * self.dst.bpp];
1676                        let tmp = &mut staged[..n * 4];
1677                        for (o, bytes) in tmp.iter_mut().zip(sb.as_chunks::<4>().0) {
1678                            let v = f32::from_ne_bytes(*bytes);
1679                            *o = 100.0 * if invert { 1.0 - v } else { v };
1680                        }
1681                        self.plan
1682                            .apply_n(&mut scratch, bytemuck::cast_slice(tmp), db, n as u32);
1683                        pos += n;
1684                    }
1685                }
1686            }
1687
1688            // Destination CMYK post-processing (inversion / percent -> [0, 1]).
1689            match self.dst.ink {
1690                InkMode::None => {}
1691                InkMode::InvertedInt => {
1692                    for b in d.iter_mut() {
1693                        *b = !*b;
1694                    }
1695                }
1696                InkMode::FloatPercent => {
1697                    for chunk in d.as_chunks_mut::<4>().0 {
1698                        let v = f32::from_ne_bytes(*chunk) * 0.01;
1699                        *chunk = v.to_ne_bytes();
1700                    }
1701                }
1702                InkMode::FloatInvertedPercent => {
1703                    for chunk in d.as_chunks_mut::<4>().0 {
1704                        let v = 1.0 - f32::from_ne_bytes(*chunk) * 0.01;
1705                        *chunk = v.to_ne_bytes();
1706                    }
1707                }
1708            }
1709
1710            // Fill opaque alpha when adding an alpha channel or canonicalizing Opaque alpha.
1711            if self.fill_opaque_alpha {
1712                let sz = self.dst.sample.byte_size();
1713                let opaque: &[u8] = match self.dst.sample {
1714                    SampleType::U8 => &[255],
1715                    SampleType::U16 => &[255, 255],
1716                    SampleType::F16 => &0x3C00u16.to_ne_bytes(),
1717                    SampleType::F32 => &1.0f32.to_ne_bytes(),
1718                    _ => return Err(err_at(ConvertError::UnsupportedRoute)),
1719                };
1720                for px in d.chunks_exact_mut(self.dst.bpp) {
1721                    px[self.dst.bpp - sz..].copy_from_slice(opaque);
1722                }
1723            }
1724
1725            // Guard against RGBA_FLT CLUT fast paths overwriting the 4th f32 lane.
1726            if self.copy_f32_alpha_after {
1727                for (sp, dp) in s.as_chunks::<16>().0.iter().zip(d.as_chunks_mut::<16>().0) {
1728                    dp[12..16].copy_from_slice(&sp[12..16]);
1729                }
1730            }
1731
1732            Ok(())
1733        }
1734    }
1735
1736    fn lcms_supports_specs(src: &PixelFormat, dst: &PixelFormat) -> bool {
1737        if src.color().alpha() == AlphaMode::Premultiplied
1738            || dst.color().alpha() == AlphaMode::Premultiplied
1739        {
1740            return false;
1741        }
1742        if describe_layout(src.layout(), src.color()).is_none()
1743            || describe_layout(dst.layout(), dst.color()).is_none()
1744        {
1745            return false;
1746        }
1747        let color_ok = |c: &ColorSpace| match c {
1748            ColorSpace::Icc { profile, .. } => profile.len() >= 128 && &profile[36..40] == b"acsp",
1749            ColorSpace::Cmyk { icc: Some(p), .. } => p.len() >= 128 && &p[36..40] == b"acsp",
1750            ColorSpace::Cmyk { icc: None, .. } => false,
1751            ColorSpace::Rgb {
1752                primaries,
1753                transfer,
1754                range,
1755                ..
1756            } => {
1757                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1758                    return false;
1759                }
1760                if *primaries == Primaries::Bt709 && *transfer == Transfer::Srgb {
1761                    return true;
1762                }
1763                if *primaries == Primaries::AdobeRgb && *transfer == Transfer::AdobeRgb {
1764                    return true;
1765                }
1766                if primaries_triple(*primaries).is_some()
1767                    && matches!(
1768                        transfer,
1769                        Transfer::Srgb
1770                            | Transfer::Linear
1771                            | Transfer::Gamma22
1772                            | Transfer::AdobeRgb
1773                            | Transfer::Gamma(_)
1774                            | Transfer::Bt709
1775                    )
1776                {
1777                    return true;
1778                }
1779                if let (Some(p_code), Some(t_code)) = (primaries.to_cicp(), transfer.to_cicp()) {
1780                    return matches!(
1781                        SynthesizedIcc::for_cicp(Cicp::new(p_code, t_code, 0, true)),
1782                        SynthesizedIcc::Profile(_)
1783                    );
1784                }
1785                false
1786            }
1787            ColorSpace::RgbCustom {
1788                primaries,
1789                transfer,
1790                range,
1791                ..
1792            } => {
1793                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1794                    return false;
1795                }
1796                custom_primaries_triple(**primaries).is_some()
1797                    && matches!(
1798                        transfer,
1799                        Transfer::Srgb
1800                            | Transfer::Linear
1801                            | Transfer::Gamma22
1802                            | Transfer::AdobeRgb
1803                            | Transfer::Gamma(_)
1804                            | Transfer::Bt709
1805                    )
1806            }
1807            ColorSpace::Gray {
1808                range, transfer, ..
1809            } => {
1810                if *range != SignalRange::Full || matches!(transfer, Transfer::Hlg(_)) {
1811                    return false;
1812                }
1813                if matches!(
1814                    transfer,
1815                    Transfer::Srgb
1816                        | Transfer::Linear
1817                        | Transfer::Gamma22
1818                        | Transfer::AdobeRgb
1819                        | Transfer::Gamma(_)
1820                        | Transfer::Bt709
1821                ) {
1822                    return true;
1823                }
1824                if let Some(t_code) = transfer.to_cicp() {
1825                    return matches!(
1826                        SynthesizedIcc::for_gray_cicp(Cicp::new(1, t_code, 0, true)),
1827                        SynthesizedIcc::Profile(_)
1828                    );
1829                }
1830                false
1831            }
1832            _ => false,
1833        };
1834        color_ok(src.color()) && color_ok(dst.color())
1835    }
1836
1837    impl CmsBackend for Lcms {
1838        fn supports_formats(&self, src: &PixelFormat, dst: &PixelFormat) -> bool {
1839            lcms_supports_specs(src, dst)
1840        }
1841
1842        fn build_transform(
1843            &self,
1844            src: &PixelFormat,
1845            dst: &PixelFormat,
1846            pulse: Option<&dyn Pulse>,
1847        ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>> {
1848            build_lcms_transform(src, dst, false, pulse)
1849        }
1850    }
1851
1852    impl CmsBackend for LcmsUnoptimized {
1853        fn supports_formats(&self, src: &PixelFormat, dst: &PixelFormat) -> bool {
1854            lcms_supports_specs(src, dst)
1855        }
1856
1857        fn build_transform(
1858            &self,
1859            src: &PixelFormat,
1860            dst: &PixelFormat,
1861            pulse: Option<&dyn Pulse>,
1862        ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>> {
1863            build_lcms_transform(src, dst, true, pulse)
1864        }
1865    }
1866}
1867
1868#[cfg(feature = "cms-lcms")]
1869pub use lcms_impl::{Lcms, LcmsUnoptimized};
1870
1871#[cfg(test)]
1872mod tests {
1873    use super::*;
1874    use crate::pulse::check_pulse;
1875    #[cfg(any(feature = "cms-moxcms", feature = "cms-lcms"))]
1876    use core::sync::atomic::{AtomicUsize, Ordering};
1877    use how_far::{NoPulse, Stop, StopOnly, StopReason};
1878
1879    #[allow(dead_code)]
1880    fn _assert_obj_safe_cms_backend(_: &dyn CmsBackend) {}
1881
1882    #[allow(dead_code)]
1883    fn _assert_obj_safe_cms_transform(_: &dyn CmsTransform) {}
1884
1885    struct CancelledStop(StopReason);
1886    impl Stop for CancelledStop {
1887        fn check(&self) -> Result<(), StopReason> {
1888            Err(self.0)
1889        }
1890    }
1891
1892    #[cfg(any(feature = "cms-moxcms", feature = "cms-lcms"))]
1893    struct CountingStop {
1894        checks: AtomicUsize,
1895        cancel_on_check: usize,
1896    }
1897    #[cfg(any(feature = "cms-moxcms", feature = "cms-lcms"))]
1898    impl Stop for CountingStop {
1899        fn check(&self) -> Result<(), StopReason> {
1900            let n = self.checks.fetch_add(1, Ordering::Relaxed) + 1;
1901            if n >= self.cancel_on_check {
1902                Err(StopReason::Cancelled)
1903            } else {
1904                Ok(())
1905            }
1906        }
1907    }
1908
1909    #[derive(Debug)]
1910    struct DummyTransform;
1911    impl CmsTransform for DummyTransform {
1912        fn transform_row(
1913            &self,
1914            src: &[u8],
1915            dst: &mut [u8],
1916            _width_pixels: u32,
1917        ) -> Result<(), At<ConvertError>> {
1918            dst[..src.len()].copy_from_slice(src);
1919            Ok(())
1920        }
1921    }
1922
1923    #[derive(Debug)]
1924    struct SpyCmsBackend;
1925    impl CmsBackend for SpyCmsBackend {
1926        fn build_transform(
1927            &self,
1928            _src: &PixelFormat,
1929            _dst: &PixelFormat,
1930            pulse: Option<&dyn Pulse>,
1931        ) -> Result<Arc<dyn CmsTransform>, At<ConvertError>> {
1932            check_pulse(pulse)?;
1933            Ok(Arc::new(DummyTransform))
1934        }
1935    }
1936
1937    #[test]
1938    fn custom_cms_backend_observes_pulse() {
1939        let cms: &dyn CmsBackend = &SpyCmsBackend;
1940        assert!(
1941            cms.build_transform(&PixelFormat::RGB8_SRGB, &PixelFormat::RGB8_SRGB, None)
1942                .is_ok()
1943        );
1944        assert!(
1945            cms.build_transform(
1946                &PixelFormat::RGB8_SRGB,
1947                &PixelFormat::RGB8_SRGB,
1948                Some(&NoPulse),
1949            )
1950            .is_ok()
1951        );
1952        let cancel = CancelledStop(StopReason::Cancelled);
1953        let pulse = StopOnly::borrowed(&cancel);
1954        let err = cms
1955            .build_transform(
1956                &PixelFormat::RGB8_SRGB,
1957                &PixelFormat::RGB8_SRGB,
1958                Some(&pulse),
1959            )
1960            .err()
1961            .expect("cancelled pulse must abort build_transform");
1962        assert_eq!(*err.error(), ConvertError::Cancelled(StopReason::Cancelled));
1963    }
1964
1965    #[cfg(feature = "cms-moxcms")]
1966    #[test]
1967    fn moxcms_build_transform_honors_pulse_cancellation() {
1968        let src = PixelFormat::RGB8_SRGB;
1969        let dst = PixelFormat::RGB8_SRGB;
1970
1971        let cancel = CancelledStop(StopReason::Cancelled);
1972        let pulse = StopOnly::borrowed(&cancel);
1973        let err = MoxCms
1974            .build_transform(&src, &dst, Some(&pulse))
1975            .err()
1976            .expect("pre-cancelled pulse must abort MoxCms::build_transform");
1977        assert_eq!(*err.error(), ConvertError::Cancelled(StopReason::Cancelled));
1978
1979        // Cancel on the second check (after parsing src profile, before dst profile / CLUT build).
1980        let mid = CountingStop {
1981            checks: AtomicUsize::new(0),
1982            cancel_on_check: 2,
1983        };
1984        let mid_pulse = StopOnly::borrowed(&mid);
1985        let err = MoxCms
1986            .build_transform(&src, &dst, Some(&mid_pulse))
1987            .err()
1988            .expect("mid-build cancellation must abort MoxCms::build_transform");
1989        assert_eq!(*err.error(), ConvertError::Cancelled(StopReason::Cancelled));
1990        assert!(mid.checks.load(Ordering::Relaxed) >= 2);
1991    }
1992
1993    #[cfg(feature = "cms-lcms")]
1994    #[test]
1995    fn lcms_build_transform_honors_pulse_cancellation() {
1996        let src = PixelFormat::RGB8_SRGB;
1997        let dst = PixelFormat::RGB8_SRGB;
1998
1999        let cancel = CancelledStop(StopReason::TimedOut);
2000        let pulse = StopOnly::borrowed(&cancel);
2001        for backend in [
2002            &Lcms as &dyn CmsBackend,
2003            &LcmsUnoptimized as &dyn CmsBackend,
2004        ] {
2005            let err = backend
2006                .build_transform(&src, &dst, Some(&pulse))
2007                .err()
2008                .expect("pre-cancelled pulse must abort Lcms::build_transform");
2009            assert_eq!(*err.error(), ConvertError::Cancelled(StopReason::TimedOut));
2010        }
2011
2012        // Cancel on the second check (after parsing src profile, before dst profile / Plan build).
2013        let mid = CountingStop {
2014            checks: AtomicUsize::new(0),
2015            cancel_on_check: 2,
2016        };
2017        let mid_pulse = StopOnly::borrowed(&mid);
2018        let err = Lcms
2019            .build_transform(&src, &dst, Some(&mid_pulse))
2020            .err()
2021            .expect("mid-build cancellation must abort Lcms::build_transform");
2022        assert_eq!(*err.error(), ConvertError::Cancelled(StopReason::Cancelled));
2023        assert!(mid.checks.load(Ordering::Relaxed) >= 2);
2024    }
2025}