zenpixels-convert 0.2.14

Transfer-function-aware pixel conversion, gamut mapping, and codec format negotiation for zenpixels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! CMS backend using [moxcms](https://crates.io/crates/moxcms).
//!
//! Provides a concrete [`ColorManagement`] implementation backed by the moxcms
//! ICC profile engine. Requires the `cms-moxcms` feature.
//!
//! # Supported formats
//!
//! Transforms are created at the native bit depth (u8, u16, or f32) and layout
//! (RGB, RGBA, Gray, GrayAlpha) of the source and destination pixel formats.
//! Formats without a direct moxcms layout mapping (Bgra, Rgbx, Bgrx, Oklab)
//! fall back to u8 RGB.
//!
//! # Example
//!
//! ```rust,ignore
//! use zenpixels_convert::cms_moxcms::MoxCms;
//! use zenpixels_convert::output::{finalize_for_output, OutputProfile};
//!
//! let ready = finalize_for_output(
//!     &buffer, &origin,
//!     OutputProfile::Icc(dst_icc.into()),
//!     PixelFormat::Rgb8,
//!     &MoxCms,
//! )?;
//! ```

use alloc::boxed::Box;
use alloc::format;
use alloc::sync::Arc;

use moxcms::{
    BarycentricWeightScale, ColorProfile, InterpolationMethod, Layout, TransformExecutor,
    TransformOptions,
};

use crate::cms::{ColorPriority, RenderingIntent};

/// Build moxcms [`TransformOptions`] from a [`ColorPriority`] and
/// [`RenderingIntent`].
///
/// This is the single entry point for constructing moxcms transform options.
/// It applies our quality defaults (tetrahedral interpolation, high-precision
/// barycentric weights) and maps the backend-agnostic enums to moxcms types.
///
/// # Parameters
///
/// - `priority` — which transfer function metadata to trust. Use
///   [`ColorPriority::PreferIcc`] for standard ICC workflows (JPEG, PNG, TIFF,
///   WebP). Use [`ColorPriority::PreferCicp`] for CICP-native formats (JPEG XL,
///   HEIF, AVIF) where the CICP code is the authoritative description and the
///   ICC profile is a backwards-compatibility fallback.
///
/// - `intent` — ICC rendering intent. Use
///   [`RenderingIntent::RelativeColorimetric`] (the default) for display output.
///   See [`RenderingIntent`] docs for when to use other intents.
///
/// # Quality settings
///
/// The following are always applied regardless of arguments:
///
/// - **Tetrahedral interpolation** over trilinear for 3D CLUTs. Produces
///   higher accuracy in saturated regions where trilinear interpolation
///   crosses cube diagonals. No measurable performance cost for the image
///   sizes we handle.
///
/// - **High barycentric weight scale.** Cuts LUT interpolation error from
///   max ≤ 14 to max ≤ 2 (code values, u8 scale) vs. lcms2 for standard
///   ICC LUT profiles. The 5% performance cost cited in moxcms docs is
///   negligible at our call granularity (row-level transforms, not
///   pixel-level).
///
/// # Rendering intent vs. profile LUT availability
///
/// Requesting an intent whose LUT is absent in the profile causes a silent
/// fallback to the profile's default intent (typically relative colorimetric).
/// Most display profiles only ship one LUT. See [`RenderingIntent`] docs for
/// details on which profiles actually honor which intents.
///
/// # Examples
///
/// ```rust,ignore
/// use zenpixels_convert::cms::{ColorPriority, RenderingIntent};
/// use zenpixels_convert::cms_moxcms::transform_opts;
///
/// // Standard ICC workflow (JPEG, PNG, etc.)
/// let opts = transform_opts(ColorPriority::PreferIcc, RenderingIntent::RelativeColorimetric);
///
/// // JPEG XL decode — trust CICP transfer characteristics
/// let opts = transform_opts(ColorPriority::PreferCicp, RenderingIntent::RelativeColorimetric);
///
/// // Soft-proofing: simulate print appearance on screen
/// let opts = transform_opts(ColorPriority::PreferIcc, RenderingIntent::AbsoluteColorimetric);
/// ```
pub fn transform_opts(priority: ColorPriority, intent: RenderingIntent) -> TransformOptions {
    TransformOptions {
        rendering_intent: match intent {
            RenderingIntent::Perceptual => moxcms::RenderingIntent::Perceptual,
            RenderingIntent::RelativeColorimetric => moxcms::RenderingIntent::RelativeColorimetric,
            RenderingIntent::Saturation => moxcms::RenderingIntent::Saturation,
            RenderingIntent::AbsoluteColorimetric => moxcms::RenderingIntent::AbsoluteColorimetric,
        },
        allow_use_cicp_transfer: matches!(priority, ColorPriority::PreferCicp),
        barycentric_weight_scale: BarycentricWeightScale::High,
        interpolation_method: InterpolationMethod::Tetrahedral,
        ..Default::default()
    }
}

/// Standard moxcms transform options for ICC LUT transforms.
///
/// # Deprecated
///
/// Use [`transform_opts`]`(`[`ColorPriority::PreferIcc`]`,
/// `[`RenderingIntent::RelativeColorimetric`]`)` instead, which lets you
/// specify the rendering intent explicitly.
#[deprecated(
    since = "0.2.3",
    note = "use transform_opts(ColorPriority::PreferIcc, RenderingIntent::RelativeColorimetric) instead"
)]
pub fn lut_transform_opts() -> TransformOptions {
    transform_opts(
        ColorPriority::PreferIcc,
        RenderingIntent::RelativeColorimetric,
    )
}

/// Standard moxcms transform options for CICP-native formats (e.g. JXL, HEIF).
///
/// # Deprecated
///
/// Use [`transform_opts`]`(`[`ColorPriority::PreferCicp`]`,
/// `[`RenderingIntent::RelativeColorimetric`]`)` instead, which lets you
/// specify the rendering intent explicitly.
#[deprecated(
    since = "0.2.3",
    note = "use transform_opts(ColorPriority::PreferCicp, RenderingIntent::RelativeColorimetric) instead"
)]
pub fn cicp_transform_opts() -> TransformOptions {
    transform_opts(
        ColorPriority::PreferCicp,
        RenderingIntent::RelativeColorimetric,
    )
}

#[allow(deprecated)]
use crate::cms::{ColorManagement, RowTransform};
use crate::{ChannelType, Cicp, PixelFormat};

/// CMS backend using moxcms.
///
/// Stateless — all configuration comes from the ICC profiles and pixel formats
/// passed to each method call. Safe to share across threads.
#[derive(Debug, Clone, Copy, Default)]
pub struct MoxCms;

/// Map a [`PixelFormat`] to the corresponding moxcms [`Layout`].
///
/// Returns `None` for formats that don't have a direct moxcms mapping
/// (Bgra, Rgbx, Bgrx, Oklab variants).
fn pixel_format_to_layout(format: PixelFormat) -> Option<Layout> {
    match format {
        PixelFormat::Rgb8 | PixelFormat::Rgb16 | PixelFormat::RgbF32 => Some(Layout::Rgb),
        PixelFormat::Rgba8 | PixelFormat::Rgba16 | PixelFormat::RgbaF32 => Some(Layout::Rgba),
        PixelFormat::Gray8 | PixelFormat::Gray16 | PixelFormat::GrayF32 => Some(Layout::Gray),
        PixelFormat::GrayA8 | PixelFormat::GrayA16 | PixelFormat::GrayAF32 => {
            Some(Layout::GrayAlpha)
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// RowTransform wrapper
// ---------------------------------------------------------------------------

/// Internal wrapper around moxcms transform executors at different bit depths.
enum MoxTransformInner {
    U8(Arc<dyn TransformExecutor<u8> + Send + Sync>),
    U16(Arc<dyn TransformExecutor<u16> + Send + Sync>),
    F32(Arc<dyn TransformExecutor<f32> + Send + Sync>),
}

struct MoxRowTransform {
    inner: MoxTransformInner,
}

#[allow(deprecated)]
impl RowTransform for MoxRowTransform {
    fn transform_row(&self, src: &[u8], dst: &mut [u8], _width: u32) {
        match &self.inner {
            MoxTransformInner::U8(xform) => {
                xform
                    .transform(src, dst)
                    .expect("moxcms u8 transform: buffer size mismatch");
            }
            MoxTransformInner::U16(xform) => {
                let src_u16: &[u16] = bytemuck::cast_slice(src);
                let dst_u16: &mut [u16] = bytemuck::cast_slice_mut(dst);
                xform
                    .transform(src_u16, dst_u16)
                    .expect("moxcms u16 transform: buffer size mismatch");
            }
            MoxTransformInner::F32(xform) => {
                let src_f32: &[f32] = bytemuck::cast_slice(src);
                let dst_f32: &mut [f32] = bytemuck::cast_slice_mut(dst);
                xform
                    .transform(src_f32, dst_f32)
                    .expect("moxcms f32 transform: buffer size mismatch");
            }
        }
    }
}

// ---------------------------------------------------------------------------
// ColorManagement implementation
// ---------------------------------------------------------------------------

/// Build a [`RowTransform`] from two already-parsed [`ColorProfile`]s.
///
/// Shared implementation for both ICC-to-ICC and CICP-to-ICC paths.
/// Always uses `PreferIcc` / `RelativeColorimetric` — CICP-in-ICC tags
/// are never trusted for TRC (see moxcms issue #154).
fn build_transform_inner(
    src_profile: &ColorProfile,
    dst_profile: &ColorProfile,
    src_format: PixelFormat,
    dst_format: PixelFormat,
) -> Result<Box<dyn RowTransform>, MoxCmsError> {
    let src_layout = pixel_format_to_layout(src_format).unwrap_or(Layout::Rgb);
    let dst_layout = pixel_format_to_layout(dst_format).unwrap_or(Layout::Rgb);
    let opts = transform_opts(ColorPriority::PreferIcc, RenderingIntent::default());

    let depth = src_format.channel_type();

    let inner = match depth {
        ChannelType::U8 => {
            let xform = src_profile
                .create_transform_8bit(src_layout, dst_profile, dst_layout, opts)
                .map_err(|e| MoxCmsError(format!("failed to create u8 transform: {e}")))?;
            MoxTransformInner::U8(xform)
        }
        ChannelType::U16 => {
            let xform = src_profile
                .create_transform_16bit(src_layout, dst_profile, dst_layout, opts)
                .map_err(|e| MoxCmsError(format!("failed to create u16 transform: {e}")))?;
            MoxTransformInner::U16(xform)
        }
        // F16 and F32 both use the f32 transform path (F16 data must be
        // converted to f32 before CMS — IEEE 754 half-floats are not
        // integer-encoded u16 values).
        ChannelType::F16 | ChannelType::F32 | _ => {
            let xform = src_profile
                .create_transform_f32(src_layout, dst_profile, dst_layout, opts)
                .map_err(|e| MoxCmsError(format!("failed to create f32 transform: {e}")))?;
            MoxTransformInner::F32(xform)
        }
    };

    Ok(Box::new(MoxRowTransform { inner }))
}

#[allow(deprecated)]
impl ColorManagement for MoxCms {
    type Error = MoxCmsError;

    fn build_transform(
        &self,
        src_icc: &[u8],
        dst_icc: &[u8],
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        self.build_transform_for_format(src_icc, dst_icc, PixelFormat::Rgb8, PixelFormat::Rgb8)
    }

    fn build_transform_for_format(
        &self,
        src_icc: &[u8],
        dst_icc: &[u8],
        src_format: PixelFormat,
        dst_format: PixelFormat,
    ) -> Result<Box<dyn RowTransform>, Self::Error> {
        let src_profile = ColorProfile::new_from_slice(src_icc)
            .map_err(|e| MoxCmsError(format!("failed to parse source ICC profile: {e}")))?;
        let dst_profile = ColorProfile::new_from_slice(dst_icc)
            .map_err(|e| MoxCmsError(format!("failed to parse destination ICC profile: {e}")))?;

        build_transform_inner(&src_profile, &dst_profile, src_format, dst_format)
    }

    fn identify_profile(&self, icc: &[u8]) -> Option<Cicp> {
        let profile = ColorProfile::new_from_slice(icc).ok()?;

        // If the profile has embedded CICP metadata, use it directly.
        if let Some(cicp) = &profile.cicp {
            return Some(Cicp::new(
                cicp.color_primaries as u8,
                cicp.transfer_characteristics as u8,
                cicp.matrix_coefficients as u8,
                cicp.full_range,
            ));
        }

        // Fall back to comparing colorant matrices against known profiles.
        identify_by_colorants(&profile)
    }

    // TODO(0.3.0): implement build_source_transform once the trait method
    // is added. The plumbing (source_to_moxcms_profile) is already here.
}

/// Convert a [`ColorProfileSource`] to a moxcms [`ColorProfile`].
///
/// Returns `Ok(None)` if the source can't be mapped to moxcms.
// TODO(0.3.0): used by build_source_transform once trait is redesigned.
#[allow(dead_code)]
fn source_to_moxcms_profile(
    src: &crate::ColorProfileSource<'_>,
) -> Result<Option<ColorProfile>, MoxCmsError> {
    match src {
        crate::ColorProfileSource::Icc(icc) => ColorProfile::new_from_slice(icc)
            .map(Some)
            .map_err(|e| MoxCmsError(format!("failed to parse ICC: {e}"))),
        crate::ColorProfileSource::Cicp(cicp) => Ok(Some(cicp_to_moxcms_profile(cicp))),
        crate::ColorProfileSource::Named(named) => {
            let (p, t) = named.to_primaries_transfer();
            primaries_transfer_to_moxcms_profile(p, t)
        }
        crate::ColorProfileSource::PrimariesTransferPair {
            primaries,
            transfer,
        } => primaries_transfer_to_moxcms_profile(*primaries, *transfer),
        _ => Ok(None),
    }
}

/// Generate ICC profile bytes for a CICP via moxcms, or `None` if moxcms doesn't
/// recognize the **color-defining** code points (primaries / transfer).
///
/// Strict on purpose: unlike [`cicp_to_moxcms_profile`] (the transform path, which
/// falls back to Bt709/sRGB defaults), synthesis must never emit a profile whose
/// TRC/gamut contradicts the source — a `None` here surfaces as
/// [`SynthesizedIcc::CmsUnsupported`](crate::icc_profiles::SynthesizedIcc::CmsUnsupported)
/// so the caller carries the color via CICP instead of embedding a wrong profile.
/// Matrix coefficients are irrelevant to an RGB ICC, so they're defaulted rather
/// than required.
///
/// Test-only: the bundled blob (generated from this exact logic at build time) is
/// the runtime coverage source, so `synthesize_icc_for_cicp` no longer calls this.
/// It's retained as the oracle the `blob_decodes_byte_identical_to_moxcms` guard
/// compares the committed blob against — catching a moxcms version bump that would
/// shift the canonical bytes.
#[cfg(test)]
pub(crate) fn icc_bytes_for_cicp(cicp: &Cicp) -> Option<alloc::vec::Vec<u8>> {
    // `try_from` on these moxcms enums never errors: every u8 maps to a variant,
    // with reserved/unassigned codes folding into `Reserved`. So these conversions
    // are NOT the validity gate — the real check is whether moxcms could populate
    // the colorimetry below.
    let color_primaries = moxcms::CicpColorPrimaries::try_from(cicp.color_primaries).ok()?;
    let transfer_characteristics =
        moxcms::TransferCharacteristics::try_from(cicp.transfer_characteristics).ok()?;
    // Matrix coefficients don't affect an RGB ICC's colorimetry; default rather
    // than reject so an unusual matrix code doesn't block synthesis.
    let matrix_coefficients = moxcms::MatrixCoefficients::try_from(cicp.matrix_coefficients)
        .unwrap_or(moxcms::MatrixCoefficients::Identity);

    let profile = ColorProfile::new_from_cicp(moxcms::CicpProfile {
        color_primaries,
        transfer_characteristics,
        matrix_coefficients,
        full_range: cicp.full_range,
    });

    // `new_from_cicp` discards the bool from `update_rgb_colorimetry_from_cicp`, so
    // for `Reserved`/`Unspecified` primaries or transfer it silently returns a base
    // profile with no colorants and no TRC. moxcms sets `red_trc` only after every
    // primaries + white-point + transfer-curve gate passes, so a populated `red_trc`
    // is the signal synthesis was faithful. No TRC ⇒ moxcms can't represent this
    // CICP — bail with None (surfaces as `CmsUnsupported`) rather than emit a
    // degenerate profile whose colorimetry omits or contradicts the requested color.
    profile.red_trc.as_ref()?;
    profile.encode().ok()
}

/// Synthesize a **GRAY-class** ICC for a CICP, exactly as `icc-gen`'s
/// `cicp_bundle_gen` generator does for the committed gray bundle: `kTRC` =
/// the transfer's tone curve (taken from a throwaway RGB synthesis so the
/// gray and RGB recipes can never disagree about a curve), media white point
/// = the primaries' H.273 white, and a per-white Bradford white→D50 `chad`.
/// The generator zeroes the creation timestamp for reproducibility; this
/// fresh path leaves it — the roundtrip test masks bytes 24..36 on both
/// sides.
///
/// Test-only, mirroring [`icc_bytes_for_cicp`]: the bundled gray blob is
/// the runtime coverage source; this is the oracle the gray
/// `blob_decodes_byte_identical_to_moxcms` guard compares the committed
/// blob against.
#[cfg(test)]
pub(crate) fn gray_icc_bytes_for_cicp(cicp: &Cicp) -> Option<alloc::vec::Vec<u8>> {
    let color_primaries = moxcms::CicpColorPrimaries::try_from(cicp.color_primaries).ok()?;
    let transfer_characteristics =
        moxcms::TransferCharacteristics::try_from(cicp.transfer_characteristics).ok()?;
    let matrix_coefficients = moxcms::MatrixCoefficients::try_from(cicp.matrix_coefficients)
        .unwrap_or(moxcms::MatrixCoefficients::Identity);

    let rgb = ColorProfile::new_from_cicp(moxcms::CicpProfile {
        color_primaries,
        transfer_characteristics,
        matrix_coefficients,
        full_range: cicp.full_range,
    });
    // Same faithful-synthesis gate as the RGB path.
    let trc = rgb.red_trc.as_ref()?.clone();

    let (white_name, wx, wy) = h273_white_xy(cicp.color_primaries)?;
    let white = moxcms::Xyzd {
        x: wx / wy,
        y: 1.0,
        z: (1.0 - wx - wy) / wy,
    };

    let mut gray = ColorProfile::new_gray_with_gamma(2.2);
    gray.gray_trc = Some(trc);
    gray.media_white_point = Some(white);
    gray.chromatic_adaptation = Some(moxcms::adaption_matrix_d(
        white.to_xyz(),
        moxcms::WHITE_POINT_D50.to_xyz(),
    ));
    gray.description = Some(moxcms::ProfileText::Localizable(alloc::vec![
        moxcms::LocalizableString::new(
            "en".into(),
            "US".into(),
            format!(
                "Gray H.273 TC{} {white_name} white",
                cicp.transfer_characteristics
            ),
        )
    ]));

    gray.encode().ok()
}

/// The white point of an H.273 colour-primaries code, as CIE xy
/// (Rec. ITU-T H.273 Table 2). Mirror of the table in `icc-gen`'s
/// `cicp_bundle_gen` — the gray-bundle roundtrip test pins the two copies
/// together. The name keys the gray profile's description so primaries
/// sharing a white dedup to identical bytes.
#[cfg(test)]
fn h273_white_xy(primaries: u8) -> Option<(&'static str, f64, f64)> {
    Some(match primaries {
        // D65: BT.709, BT.470BG, SMPTE 170M, SMPTE 240M, BT.2020,
        // P3-D65 (SMPTE EG 432-1), EBU Tech 3213-E.
        1 | 5 | 6 | 7 | 9 | 12 | 22 => ("D65", 0.3127, 0.3290),
        // Illuminant C: BT.470M, generic film.
        4 | 8 => ("C", 0.310, 0.316),
        // Illuminant E: SMPTE ST 428-1 (CIE XYZ).
        10 => ("E", 1.0 / 3.0, 1.0 / 3.0),
        // DCI white: SMPTE RP 431-2 (P3-DCI theater white).
        11 => ("DCI", 0.314, 0.351),
        _ => return None,
    })
}

/// Convert CICP to a moxcms ColorProfile.
#[allow(dead_code)]
fn cicp_to_moxcms_profile(cicp: &Cicp) -> ColorProfile {
    ColorProfile::new_from_cicp(moxcms::CicpProfile {
        color_primaries: moxcms::CicpColorPrimaries::try_from(cicp.color_primaries)
            .unwrap_or(moxcms::CicpColorPrimaries::Bt709),
        transfer_characteristics: moxcms::TransferCharacteristics::try_from(
            cicp.transfer_characteristics,
        )
        .unwrap_or(moxcms::TransferCharacteristics::Srgb),
        matrix_coefficients: moxcms::MatrixCoefficients::try_from(cicp.matrix_coefficients)
            .unwrap_or(moxcms::MatrixCoefficients::Identity),
        full_range: cicp.full_range,
    })
}

/// Convert primaries + transfer to a moxcms ColorProfile via CICP mapping.
#[allow(dead_code)]
fn primaries_transfer_to_moxcms_profile(
    primaries: crate::ColorPrimaries,
    transfer: crate::TransferFunction,
) -> Result<Option<ColorProfile>, MoxCmsError> {
    let cp = match primaries.to_cicp() {
        Some(c) => c,
        None => return Ok(None),
    };
    let tc = match transfer.to_cicp() {
        Some(c) => c,
        None => return Ok(None),
    };
    Ok(Some(cicp_to_moxcms_profile(&Cicp::new(cp, tc, 0, true))))
}

// ---------------------------------------------------------------------------
// Profile identification by colorant comparison
// ---------------------------------------------------------------------------

/// Compare XYZ colorants to identify well-known profiles.
///
/// Checks the profile's red/green/blue colorants against sRGB (BT.709),
/// Display P3, and BT.2020. The colorant values are in PCS (D50-adapted)
/// space, as stored in ICC profiles after Bradford chromatic adaptation
/// from D65. Tolerance is 0.003 in XYZ, tight enough to distinguish
/// these gamuts while tolerating s15Fixed16 quantization.
fn identify_by_colorants(profile: &ColorProfile) -> Option<Cicp> {
    // Known colorant values in D50 PCS space (Bradford-adapted from D65).
    // Computed by applying the standard D65→D50 Bradford matrix to the
    // absolute D65 XYZ colorant matrices from ITU-R specifications.
    struct KnownProfile {
        primaries_code: u8,
        rx: f64,
        ry: f64,
        gx: f64,
        gy: f64,
        bx: f64,
        by: f64,
    }

    const KNOWN: &[KnownProfile] = &[
        // sRGB / BT.709 (D50-adapted)
        KnownProfile {
            primaries_code: 1,
            rx: 0.4361,
            ry: 0.2225,
            gx: 0.3851,
            gy: 0.7169,
            bx: 0.1431,
            by: 0.0606,
        },
        // Display P3 (D50-adapted)
        KnownProfile {
            primaries_code: 12,
            rx: 0.5151,
            ry: 0.2412,
            gx: 0.2919,
            gy: 0.6922,
            bx: 0.1572,
            by: 0.0666,
        },
        // BT.2020 (D50-adapted)
        KnownProfile {
            primaries_code: 9,
            rx: 0.6734,
            ry: 0.2790,
            gx: 0.1656,
            gy: 0.6753,
            bx: 0.1251,
            by: 0.0456,
        },
    ];

    let r = &profile.red_colorant;
    let g = &profile.green_colorant;
    let b = &profile.blue_colorant;

    const TOL: f64 = 0.003;

    for known in KNOWN {
        let matches = (r.x - known.rx).abs() < TOL
            && (r.y - known.ry).abs() < TOL
            && (g.x - known.gx).abs() < TOL
            && (g.y - known.gy).abs() < TOL
            && (b.x - known.bx).abs() < TOL
            && (b.y - known.by).abs() < TOL;

        if matches {
            // Map known primaries to their standard transfer characteristic.
            // sRGB (1) and Display P3 (12) both use the sRGB TRC (13).
            // BT.2020 (9) uses BT.709 TRC (1) as a safe default since
            // the actual TRC (PQ, HLG, or BT.709) can't be identified
            // from colorants alone.
            let transfer = match known.primaries_code {
                1 | 12 => 13, // sRGB and Display P3 use sRGB TRC
                _ => 1,       // BT.2020 etc. default to BT.709 TRC
            };
            return Some(Cicp::new(
                known.primaries_code,
                transfer,
                0, // Identity (RGB)
                true,
            ));
        }
    }

    None
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Error from the moxcms CMS backend.
#[derive(Debug, Clone)]
pub struct MoxCmsError(pub String);

impl core::fmt::Display for MoxCmsError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}