zenpixels_convert/icc_profiles.rs
1//! Embedded CC0-licensed ICC profiles for common wide-gamut color spaces.
2//!
3//! The four compact constants are from [Compact-ICC-Profiles](https://github.com/saucecontrol/Compact-ICC-Profiles)
4//! by Clinton Ingram, released under the [CC0 1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/)
5//! public domain dedication. They are embedded at compile time via `include_bytes!()`.
6//! The full `icc-db` CICP database is generated separately; it is not this
7//! collection of compact constants.
8//!
9//! # Available profiles
10//!
11//! | Constant | Color space | Format | Size | TRC form |
12//! |----------|-------------|--------|------|----------|
13//! | [`DISPLAY_P3_V4`] | Display P3 | ICC v4 | 480 bytes | paraType-3 sRGB |
14//! | [`DISPLAY_P3_V2`] | Display P3 | ICC v2 | 736 bytes | 182-point sampled sRGB |
15//! | [`ADOBE_RGB`] | Adobe RGB (1998) | ICC v2 | 374 bytes | **curv count=1** (pure gamma) |
16//! | `REC2020_V4` | Rec. 2020 | ICC v4 | 480 bytes | paraType-3 BT.709 |
17//!
18//! # Notes on choices
19//!
20//! ## Adobe RGB — pure gamma, not paraType-3
21//!
22//! We deliberately bundle the saucecontrol **v2** variant (`curv count=1`,
23//! gamma 2.19921875, no linear toe) rather than their **v4** variant
24//! (`paraType funcType=3` with linear toe). Rationale: surveying the in-the-wild
25//! corpus, ~85% of Adobe RGB ICC profiles encode the TRC as pure gamma
26//! (Adobe CS4 distribution, Windows `ClayRGB1998` / `AdobeRGB1998`, macOS
27//! `AdobeRGB1998`, Linux `AdobeRGB1998`/`compatibleWithAdobeRGB1998`, Nikon,
28//! and per-camera profiles). The Adobe RGB 1998 encoding spec (§4.3.4.2)
29//! itself defines pure gamma with no toe. Bundling the pure-gamma form
30//! matches both the spec and the majority of the ecosystem, and means the
31//! embedded profile round-trips byte-exact against moxcms's `new_adobe_rgb()`
32//! canonical reference.
33//!
34//! ## ProPhoto — not bundled
35//!
36//! Unlike Adobe RGB, real-world ProPhoto / ROMM ICC profiles are fragmented:
37//! ~50% pure gamma 1.8, ~30% `paraType funcType=3` with the ISO 22028-2 toe
38//! (`c=1/16, d=1/32`), some with a non-standard Apple `d=1/512`, one
39//! `ProPhotoLin.icm` with a linear TRC despite the name, and two ISO 22028-2
40//! v4 profiles that are mAB/mBA LUTs (no rTRC at all). Picking any single
41//! "canonical" ProPhoto profile to embed would misrepresent the other
42//! variants. Instead we leave ProPhoto un-accelerated: callers handing us a
43//! ProPhoto ICC profile fall through to full CMS so the exact encoded curve
44//! is honored.
45//!
46//! ## Display P3 / Rec. 2020 — compact constants, not what synthesis emits
47//!
48//! The DisplayP3Compat and Rec2020Compat profiles use saucecontrol's
49//! compatibility rebalancing: the adapted red primary's negative Z is set to
50//! zero, with other colorants and `chad` adjusted to compensate. This changes
51//! the represented colorimetry, and these constants carry no `cicp` tag.
52//! ICC.1:2022 permits negative PCSXYZ in signed `s15Fixed16Number` `XYZType`
53//! colorant tags (and float32 `multiProcessElementsType`); retaining such a
54//! value is spec-conformant. Older ICC wording and reader behavior motivated the
55//! separate compatibility variants. See the linked correctness overview below.
56//! Some readers identify a gamut by colorant tags within a tolerance:
57//! our libultrahdr colorant-matching regression (0.001 tolerance) rejects
58//! `DISPLAY_P3_V4` as an exact P3 match. P3 synthesis uses separately qualified
59//! compact P3/sRGB and P3/BT.709 exports in both default and no-db builds.
60//! Other database-supported pairs use the generated CICP-tagged bundle.
61//! Compatibility constants remain available for callers selecting them explicitly.
62//!
63//! Profile format, colorimetry, precision and reader compatibility are separate
64//! checks: <https://github.com/imazen/zenpixels/blob/review/first-class-lcms-20261108/docs/color-correctness-and-compatibility.md>.
65//!
66//! # Precision warnings
67//!
68//! Rec. 2020 has a very wide gamut. Using 8-bit precision with Rec. 2020
69//! will cause visible banding in gradients. Use 16-bit or f32 precision.
70
71use alloc::borrow::Cow;
72
73use zenpixels::{Cicp, Primaries, Transfer};
74
75#[cfg(feature = "icc-db")]
76mod cicp_bundle;
77#[cfg(feature = "icc-db")]
78#[rustfmt::skip]
79mod cicp_bundle_index;
80#[cfg(test)]
81mod canonical;
82#[cfg(all(test, feature = "icc-db"))]
83mod colourimetry_tests;
84#[cfg(all(test, feature = "cms-moxcms", feature = "cms-lcms"))]
85mod synthesis;
86
87// ---------------------------------------------------------------------------
88// Embedded ICC profiles (CC0 license from Compact-ICC-Profiles)
89// https://github.com/saucecontrol/Compact-ICC-Profiles
90// ---------------------------------------------------------------------------
91
92/// Display P3 Compatible ICC profile, v4 format (480 bytes).
93///
94/// This compatibility variant adjusts the colorants to avoid negative red Z.
95/// For CICP synthesis, prefer [`SynthesizedIcc::for_cicp`], which uses the
96/// generated database when `icc-db` is enabled.
97///
98/// Source: <https://github.com/saucecontrol/Compact-ICC-Profiles> (CC0)
99pub const DISPLAY_P3_V4: &[u8] = include_bytes!("profiles/DisplayP3Compat-v4.icc");
100
101// Small qualified exports: exact bytes of the current generated bundle.
102// Historical constants remain unchanged for explicit compatibility/recognition.
103const P3_EXPORT_SRGB: &[u8] = include!("icc_profiles/p3_export_13.inc");
104const P3_EXPORT_BT709: &[u8] = include!("icc_profiles/p3_export_1.inc");
105
106/// Display P3 Compatible ICC profile, v2 format (736 bytes).
107///
108/// Use this for compatibility with older software that doesn't support ICC v4.
109/// The "magic" variant stores an optimized 182-point sampled curve.
110///
111/// Source: <https://github.com/saucecontrol/Compact-ICC-Profiles> (CC0)
112pub const DISPLAY_P3_V2: &[u8] = include_bytes!("profiles/DisplayP3Compat-v2-magic.icc");
113
114/// Adobe RGB (1998) Compatible ICC profile, v2 format (374 bytes, **pure gamma**).
115///
116/// Encodes the rTRC/gTRC/bTRC as `curv count=1` with gamma 2.19921875 (= 563/256),
117/// matching the Adobe RGB 1998 spec and ~85% of real-world Adobe RGB ICC
118/// profiles. See the module-level docs for the rationale on picking pure gamma
119/// over the paraType-3 toe form.
120///
121/// Source: <https://github.com/saucecontrol/Compact-ICC-Profiles> (CC0)
122pub const ADOBE_RGB: &[u8] = include_bytes!("profiles/AdobeCompat-v2.icc");
123
124/// Rec. 2020 Compatible ICC profile, v4 format (480 bytes).
125///
126/// Rec. 2020 has a very wide gamut (~75% of visible colors).
127/// **Use 16-bit or f32 precision** to avoid banding.
128///
129/// Source: <https://github.com/saucecontrol/Compact-ICC-Profiles> (CC0)
130pub(crate) const REC2020_V4: &[u8] = include_bytes!("profiles/Rec2020Compat-v4.icc");
131
132// ProPhoto / ROMM RGB is intentionally not bundled — see the module-level
133// "ProPhoto — not bundled" note for the fragmentation analysis.
134
135/// Get a bundled `&'static` ICC profile whose tone curve is exactly the
136/// requested transfer function on exactly the requested primaries.
137///
138/// This accessor matches against the TRC encoded in each bundled profile, so `(Bt2020,
139/// Bt709)` gets the Rec. 2020 profile while `(Bt2020, Srgb)` and `(Bt2020,
140/// Pq)` get `None`. sRGB and BT.709 are different curves (at linear 0.18 they
141/// encode 0.461 and 0.409, 13 code values apart at 8 bits), so neither stands
142/// in for the other.
143///
144/// # Currently bundled combinations
145///
146/// | Primaries | Transfer | Returned profile |
147/// |-----------|----------|------------------|
148/// | [`Primaries::Bt709`] | [`Transfer::Srgb`] | `None` — sRGB is the assumed default |
149/// | [`Primaries::DisplayP3`] | [`Transfer::Srgb`] or [`Transfer::Bt709`] | compact generated export |
150/// | [`Primaries::Bt2020`] | [`Transfer::Bt709`] | `REC2020_V4` |
151/// | [`Primaries::AdobeRgb`] | [`Transfer::AdobeRgb`] | [`ADOBE_RGB`] |
152///
153/// # Not bundled (returns `None`)
154///
155/// - HDR transfers ([`Transfer::Pq`], [`Transfer::Hlg`])
156/// on any primaries. Ultra HDR / HDR10 / HLG broadcast workflows that need
157/// a PQ- or HLG-tagged profile should either generate one via a CMS crate
158/// (e.g., `moxcms::ColorProfile::new_bt2020_pq().encode()`) or signal color
159/// via CICP instead of ICC.
160/// - [`Transfer::Linear`] on any primaries. Linear-light
161/// working spaces are typically expressed with CICP transfer code 8
162/// rather than an ICC profile.
163/// - Adobe RGB with any transfer other than [`Transfer::AdobeRgb`] (`563/256`).
164/// - Display P3 with any transfer other than `Srgb` or `Bt709`, and BT.2020 with any
165/// transfer other than `Bt709`.
166///
167/// [`SynthesizedIcc::for_cicp`] serves every assigned pair (these included)
168/// from the `icc-db` blob; this table is its fallback without that feature.
169#[inline]
170pub const fn bundled_icc_profile(
171 primaries: Primaries,
172 transfer: Transfer,
173) -> Option<&'static [u8]> {
174 match (primaries, transfer) {
175 (Primaries::DisplayP3, Transfer::Srgb) => Some(P3_EXPORT_SRGB),
176 (Primaries::DisplayP3, Transfer::Bt709) => Some(P3_EXPORT_BT709),
177 (Primaries::Bt2020, Transfer::Bt709) => Some(REC2020_V4),
178 (Primaries::AdobeRgb, Transfer::AdobeRgb) => Some(ADOBE_RGB),
179 _ => None,
180 }
181}
182
183/// Whether `p` is an assigned H.273 colour-primaries code in the CICP export grid.
184#[inline]
185const fn is_assigned_primaries(p: u8) -> bool {
186 matches!(p, 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 22)
187}
188
189/// Whether `t` is an assigned H.273 transfer-characteristics code in the CICP export grid.
190#[inline]
191const fn is_assigned_transfer(t: u8) -> bool {
192 matches!(
193 t,
194 1 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18
195 )
196}
197
198/// Outcome of [`SynthesizedIcc::for_cicp`] — what ICC profile (if any) to embed for a
199/// CICP color description, and *why* there are no bytes when there aren't.
200///
201/// The point is to make lowering an `IccDisposition::SynthesizeFrom` explicit:
202/// an implementer can tell apart "got bytes", "no profile needed", "we'd need a
203/// CMS for this one", and "even the CMS couldn't" — instead of an ambiguous
204/// `Option` that conflates them.
205#[derive(Clone, Debug, PartialEq, Eq)]
206#[non_exhaustive]
207pub enum SynthesizedIcc {
208 /// A profile is available — embed these bytes. From
209 /// [`SynthesizedIcc::for_cicp`] this is always `Cow::Borrowed`: either a
210 /// bundled `&'static` const, or a zero-copy slice of a decoded bundle group
211 /// held in a `'static` cache (no allocation per call). `Cow::Owned` remains
212 /// part of the type for callers that construct their own outcomes.
213 Profile(Cow<'static, [u8]>),
214 /// No ICC is needed: the CICP is the universally-assumed sRGB / BT.709 default,
215 /// so omitting a profile loses nothing.
216 ///
217 /// In the encode pipeline this *shouldn't* occur — `resolve_color_emit` never
218 /// asks to synthesize for sRGB (its `synth_worthwhile` test excludes it) — but
219 /// it's surfaced explicitly rather than masquerading as a missing profile.
220 NotNeeded,
221 /// The requested assigned H.273 pair is covered by the `icc-db` bundle, which is
222 /// disabled in this build (and no curated compact fallback exists for it).
223 ///
224 /// Note that enabling a transform backend (`cms-moxcms` / `cms-lcms`) does **not**
225 /// synthesize export bytes here — enable the `icc-db` feature to serve the full grid.
226 /// Unassigned / reserved code points, CIE XYZ RGB (`CP=10`), and HLG (`TC=18`)
227 /// always return [`Unsupported`](Self::Unsupported) regardless of `icc-db`.
228 #[doc(alias = "NeedsCms")]
229 IccDbDisabled,
230 /// This export path cannot supply a qualified profile for the CICP.
231 /// This includes unsupported/reserved code points, CIE XYZ RGB (`CP=10`), and HLG
232 /// without a rendering target. Preserve native CICP where the container permits it;
233 /// an ICC-only caller must report the limitation or explicitly convert to a supported output.
234 #[doc(alias = "CmsUnsupported")]
235 Unsupported,
236}
237
238impl SynthesizedIcc {
239 /// The profile to embed for `cicp`, by transfer and primaries together.
240 ///
241 /// The input supplies color primaries and transfer only. Matrix coefficients
242 /// and signal range describe coded samples and are not applied by synthesis.
243 /// The returned RGB profile describes samples after the caller has decoded
244 /// the matrix and expanded range. It must not be attached to raw YCbCr or
245 /// limited-range code values as though synthesis had converted them.
246 /// See the variants and precision caveats for supported combinations.
247 /// HLG returns [`Unsupported`](Self::Unsupported) without a rendering target.
248 #[must_use]
249 pub fn for_cicp(cicp: Cicp) -> Self {
250 synthesize_icc_for_cicp(cicp)
251 }
252
253 /// The GRAY-class counterpart of [`for_cicp`](Self::for_cicp), for gray images: containers such as
254 /// PNG refuse an RGB profile on a gray image.
255 /// As with `for_cicp`, the caller must first decode coded matrix/range;
256 /// synthesis describes color and does not transform sample values.
257 #[must_use]
258 pub fn for_gray_cicp(cicp: Cicp) -> Self {
259 synthesize_gray_icc_for_cicp(cicp)
260 }
261}
262
263/// Resolve an ICC profile for a full [`Cicp`] color description (primaries **and**
264/// transfer), returning a [`SynthesizedIcc`] that says exactly what happened.
265///
266/// Resolve primaries and transfer together. Reserved/unsupported code points
267/// return [`Unsupported`](SynthesizedIcc::Unsupported). HLG also refuses:
268/// CICP alone provides no rendering target for its full RGB OOTF. Preserve native
269/// CICP where permitted; ICC-only output requires an explicit supported choice.
270///
271/// With `icc-db`, 149 non-default RGB pairs are eligible after excluding CIE XYZ
272/// primaries and HLG. Runtime reads the stored bundle without a CMS. The current
273/// asset retains historical quantized curves; staged corrected definitions and
274/// qualification limits are documented in `docs/corrected-icc-export.md`.
275///
276/// Without `icc-db`, compact generated P3/sRGB and P3/BT.709 exports plus the
277/// curated BT.2020/BT.709 and Adobe RGB constants
278/// serve their respective combinations; other eligible pairs return
279/// [`IccDbDisabled`](SynthesizedIcc::IccDbDisabled). The constants have compatibility-adjusted
280/// colorimetry and are distinct from the generated definitions.
281///
282/// sRGB and unspecified defaults return [`NotNeeded`](SynthesizedIcc::NotNeeded).
283/// Primaries 10 denotes XYZ, not a valid RGB gamut for this constructor.
284///
285/// # PQ precision
286///
287/// The current integer PQ curve loses positive shadow values through both tested
288/// CMS engines. This is a property of its serialized representation and evaluator,
289/// not an unavoidable limit of every ICC profile. Prefer native CICP when possible.
290/// A float-pipeline representation is being qualified separately; enabling a CMS
291/// feature does not regenerate the stored bytes or supply missing HLG conditions.
292///
293/// # Examples
294/// ```
295/// use zenpixels_convert::icc_profiles::SynthesizedIcc;
296/// use zenpixels_convert::Cicp;
297///
298/// // Display-P3 → a bundled profile.
299/// assert!(matches!(SynthesizedIcc::for_cicp(Cicp::DISPLAY_P3), SynthesizedIcc::Profile(_)));
300/// // sRGB → no profile needed.
301/// assert_eq!(SynthesizedIcc::for_cicp(Cicp::SRGB), SynthesizedIcc::NotNeeded);
302/// ```
303pub(crate) fn synthesize_icc_for_cicp(cicp: Cicp) -> SynthesizedIcc {
304 // CICP alone does not supply the target display/OOTF. A fixed neutral
305 // gamma is not a faithful substitute for a complete HLG RGB transform.
306 if cicp.transfer_characteristics == 18 {
307 return SynthesizedIcc::Unsupported;
308 }
309 // sRGB / unspecified defaults need no embedded ICC. BT.709 transfer
310 // with specified BT.709 primaries (1,1) is a different curve from sRGB.
311 //
312 // This is gated on the **raw** H.273 code points, NOT the enum mapping:
313 // `color_primaries_enum` folds every gamut zenpixels doesn't model (BT.601 = 6,
314 // SMPTE240 = 7, BT.470M/BG = 4/5, EBU3213 = 22, …) into `Unknown`, so an
315 // enum-based check would treat those real, non-sRGB gamuts as "sRGB default"
316 // and drop their colour — and worse, skip the blob lookup below that actually
317 // carries them. Only colour-primaries 1 (BT.709) / 2 (unspecified) with
318 // transfer 2 (unspecified) / 13 (sRGB) is the assumed default;
319 // (2,1) has no specified gamut to describe.
320 if (matches!(cicp.color_primaries, 1 | 2) && matches!(cicp.transfer_characteristics, 2 | 13))
321 || (cicp.color_primaries == 2 && cicp.transfer_characteristics == 1)
322 {
323 return SynthesizedIcc::NotNeeded;
324 }
325
326 // H.273 primaries 10 denotes CIE XYZ. The generator's RGB model
327 // collapses its colorants to rank 1; never serve those bytes, including
328 // in builds without the database.
329 if cicp.color_primaries == 10
330 || !is_assigned_primaries(cicp.color_primaries)
331 || !is_assigned_transfer(cicp.transfer_characteristics)
332 {
333 return SynthesizedIcc::Unsupported;
334 }
335
336 // Stored export bytes are keyed on raw code points, independent of the
337 // smaller enum set. A CICP tag is metadata, not proof of transform accuracy.
338 #[cfg(feature = "icc-db")]
339 {
340 if let Some(bytes) = cicp_bundle::bundled_profile_for_cicp(
341 cicp.color_primaries,
342 cicp.transfer_characteristics,
343 ) {
344 return SynthesizedIcc::Profile(bytes);
345 }
346
347 // The supported table has no entry. Transform backends are separate
348 // from export synthesis and cannot silently invent a replacement here.
349 SynthesizedIcc::Unsupported
350 }
351 // Without the database: a curated const whose curve is exactly the
352 // requested transfer, else IccDbDisabled ("enable `icc-db`") for eligible assigned pairs.
353 #[cfg(not(feature = "icc-db"))]
354 {
355 let cp = Primaries::from_cicp(cicp.color_primaries).unwrap_or(Primaries::Unknown);
356 let tf = Transfer::from_cicp(cicp.transfer_characteristics).unwrap_or(Transfer::Unknown);
357 match bundled_icc_profile(cp, tf) {
358 Some(bytes) => SynthesizedIcc::Profile(Cow::Borrowed(bytes)),
359 None => SynthesizedIcc::IccDbDisabled,
360 }
361 }
362}
363
364/// Resolve a **GRAY-class** ICC profile for a [`Cicp`] color description —
365/// the profile to embed alongside single-channel (Gray / GrayAlpha) output
366/// whose color is described by CICP code points.
367///
368/// An ICC profile's header declares a device color space class (`'RGB '`,
369/// `'GRAY'`, …), and consumers enforce it: libpng rejects a gray PNG paired
370/// with an RGB-class profile. So a gray image can't reuse
371/// [`SynthesizedIcc::for_cicp`]'s output — it needs this single-channel
372/// variant. Matrix coefficients are ignored for gray; H.273 primaries select
373/// its native white rather than an RGB gamut.
374///
375/// Unspecified primaries (`CP=2`) on a known non-default transfer (such as
376/// `(2, 8)` linear gray or `(2, 4)` gamma-2.2 gray) default explicitly to D65
377/// white (`CP=1`), matching standard sRGB/H.273 grayscale display white.
378///
379/// After HLG refusal, 164 non-default gray pairs remain eligible with `icc-db`.
380/// Primaries 10 is valid here because only its equal-energy white is needed.
381/// Without `icc-db`, eligible assigned pairs return [`IccDbDisabled`](SynthesizedIcc::IccDbDisabled);
382/// unassigned/reserved codes and HLG return [`CmsUnsupported`](SynthesizedIcc::Unsupported)
383/// in every build.
384pub(crate) fn synthesize_gray_icc_for_cicp(cicp: Cicp) -> SynthesizedIcc {
385 if cicp.transfer_characteristics == 18 {
386 return SynthesizedIcc::Unsupported;
387 }
388 // Same raw-code-point default gate as the RGB variant (see its comment
389 // for why the enum mapping must not be used here).
390 if (matches!(cicp.color_primaries, 1 | 2) && matches!(cicp.transfer_characteristics, 2 | 13))
391 || (cicp.color_primaries == 2 && cicp.transfer_characteristics == 1)
392 {
393 return SynthesizedIcc::NotNeeded;
394 }
395
396 // B13: Gray images with CP=2 (Unspecified) + a known non-default assigned transfer
397 // (e.g., Linear TC=8, Gamma 2.2 TC=4) explicitly assume D65 white (CP=1).
398 let eff_cp = if cicp.color_primaries == 2 {
399 1
400 } else {
401 cicp.color_primaries
402 };
403 if !is_assigned_primaries(eff_cp) || !is_assigned_transfer(cicp.transfer_characteristics) {
404 return SynthesizedIcc::Unsupported;
405 }
406
407 // The bundle's gray table covers the full assigned grid (`icc-db`);
408 // there are no curated `&'static` gray consts (nothing in the wild to
409 // byte-match).
410 #[cfg(feature = "icc-db")]
411 {
412 if let Some(bytes) =
413 cicp_bundle::bundled_gray_profile_for_cicp(eff_cp, cicp.transfer_characteristics)
414 {
415 return SynthesizedIcc::Profile(bytes);
416 }
417
418 // Outside the assigned grid — same terminal state as the RGB
419 // variant.
420 SynthesizedIcc::Unsupported
421 }
422 #[cfg(not(feature = "icc-db"))]
423 {
424 SynthesizedIcc::IccDbDisabled
425 }
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431
432 #[test]
433 fn v4_profiles_valid_structure() {
434 let profiles: &[(&[u8], &str)] = &[
435 (DISPLAY_P3_V4, "Display P3 v4"),
436 (REC2020_V4, "Rec. 2020 v4"),
437 ];
438
439 for (profile, name) in profiles {
440 assert_eq!(profile.len(), 480, "{name}: expected 480 bytes");
441 assert_eq!(
442 &profile[36..40],
443 b"acsp",
444 "{name}: missing ICC 'acsp' signature at offset 36"
445 );
446 assert_eq!(
447 &profile[12..16],
448 b"mntr",
449 "{name}: expected 'mntr' (monitor) profile class at offset 12"
450 );
451 }
452 }
453
454 #[test]
455 fn adobe_rgb_profile_valid_structure() {
456 assert_eq!(
457 ADOBE_RGB.len(),
458 374,
459 "Adobe RGB: expected 374 bytes (ICC v2)"
460 );
461 assert_eq!(
462 &ADOBE_RGB[36..40],
463 b"acsp",
464 "Adobe RGB: missing ICC 'acsp' signature at offset 36"
465 );
466 assert_eq!(
467 &ADOBE_RGB[12..16],
468 b"mntr",
469 "Adobe RGB: expected 'mntr' (monitor) profile class at offset 12"
470 );
471 // TRC is `curv count=1` (pure gamma) — offset at rTRC tag, 14 bytes.
472 // `curv` signature (4) + reserved (4) + count=1 (4) + u16 gamma (2) = 14.
473 // This is the marker distinguishing the v2 pure-gamma variant from the
474 // v4 paraType-3 variant (32+ bytes).
475 let tag_count = u32::from_be_bytes([
476 ADOBE_RGB[128],
477 ADOBE_RGB[129],
478 ADOBE_RGB[130],
479 ADOBE_RGB[131],
480 ]) as usize;
481 let mut found_pure_gamma_trc = false;
482 for i in 0..tag_count {
483 let b = 132 + i * 12;
484 if &ADOBE_RGB[b..b + 4] == b"rTRC" {
485 let off = u32::from_be_bytes([
486 ADOBE_RGB[b + 4],
487 ADOBE_RGB[b + 5],
488 ADOBE_RGB[b + 6],
489 ADOBE_RGB[b + 7],
490 ]) as usize;
491 assert_eq!(
492 &ADOBE_RGB[off..off + 4],
493 b"curv",
494 "Adobe RGB: rTRC must be curveType (pure gamma)"
495 );
496 let count = u32::from_be_bytes([
497 ADOBE_RGB[off + 8],
498 ADOBE_RGB[off + 9],
499 ADOBE_RGB[off + 10],
500 ADOBE_RGB[off + 11],
501 ]);
502 assert_eq!(
503 count, 1,
504 "Adobe RGB: curveType count must be 1 (pure gamma, no toe)"
505 );
506 found_pure_gamma_trc = true;
507 break;
508 }
509 }
510 assert!(found_pure_gamma_trc, "Adobe RGB: rTRC tag not found");
511 }
512
513 #[test]
514 fn v2_profile_valid_structure() {
515 assert_eq!(
516 DISPLAY_P3_V2.len(),
517 736,
518 "Display P3 v2: expected 736 bytes"
519 );
520 assert_eq!(
521 &DISPLAY_P3_V2[36..40],
522 b"acsp",
523 "Display P3 v2: missing ICC 'acsp' signature at offset 36"
524 );
525 assert_eq!(
526 &DISPLAY_P3_V2[12..16],
527 b"mntr",
528 "Display P3 v2: expected 'mntr' (monitor) profile class at offset 12"
529 );
530 }
531
532 #[cfg(feature = "icc-db")]
533 #[test]
534 fn compact_p3_exports_match_current_bundle() {
535 for (transfer, expected) in [(13, P3_EXPORT_SRGB), (1, P3_EXPORT_BT709)] {
536 let mut cicp = Cicp::DISPLAY_P3;
537 cicp.transfer_characteristics = transfer;
538 let SynthesizedIcc::Profile(bytes) = SynthesizedIcc::for_cicp(cicp) else {
539 panic!("missing P3 export")
540 };
541 assert_eq!(&*bytes, expected);
542 }
543 }
544
545 #[test]
546 fn bundled_icc_profile_hits_combinations() {
547 assert_eq!(
548 bundled_icc_profile(Primaries::DisplayP3, Transfer::Srgb),
549 Some(P3_EXPORT_SRGB)
550 );
551 assert_eq!(
552 bundled_icc_profile(Primaries::Bt2020, Transfer::Bt709),
553 Some(REC2020_V4)
554 );
555 assert_eq!(
556 bundled_icc_profile(Primaries::AdobeRgb, Transfer::AdobeRgb),
557 Some(ADOBE_RGB)
558 );
559 assert_eq!(
560 bundled_icc_profile(Primaries::AdobeRgb, Transfer::Gamma22),
561 None
562 );
563 }
564
565 #[test]
566 fn bundled_icc_profile_rejects_hdr_transfers() {
567 assert!(bundled_icc_profile(Primaries::Bt2020, Transfer::Pq).is_none());
568 assert!(
569 bundled_icc_profile(Primaries::Bt2020, Transfer::Hlg(zenpixels::HlgMode::Scene))
570 .is_none()
571 );
572 assert!(bundled_icc_profile(Primaries::DisplayP3, Transfer::Pq).is_none());
573 assert!(
574 bundled_icc_profile(
575 Primaries::DisplayP3,
576 Transfer::Hlg(zenpixels::HlgMode::Scene)
577 )
578 .is_none()
579 );
580 assert!(bundled_icc_profile(Primaries::Bt2020, Transfer::Linear).is_none());
581 assert!(bundled_icc_profile(Primaries::DisplayP3, Transfer::Linear).is_none());
582 }
583
584 #[test]
585 fn synthesize_icc_for_cicp_srgb_is_not_needed() {
586 // sRGB / BT.709 is the universally-assumed default — no profile to embed.
587 assert_eq!(
588 synthesize_icc_for_cicp(Cicp::SRGB),
589 SynthesizedIcc::NotNeeded
590 );
591 }
592
593 #[test]
594 fn synthesize_icc_for_cicp_display_p3_is_bundled_borrowed() {
595 // Display P3 (sRGB TRC) resolves with no CMS and no allocation: a
596 // borrowed profile. With `icc-db` it is the blob's cicp-tagged
597 // profile, not the curated const (zenpixels#87).
598 match synthesize_icc_for_cicp(Cicp::DISPLAY_P3) {
599 SynthesizedIcc::Profile(Cow::Borrowed(bytes)) => {
600 #[cfg(feature = "icc-db")]
601 assert_ne!(bytes, DISPLAY_P3_V4);
602 #[cfg(not(feature = "icc-db"))]
603 assert_eq!(bytes, P3_EXPORT_SRGB);
604 }
605 other => panic!("expected bundled borrowed Display P3 profile, got {other:?}"),
606 }
607 }
608
609 /// An s15Fixed16 XYZ triple from tag `sig` of an ICC profile.
610 #[cfg(feature = "icc-db")]
611 fn xyz_tag(icc: &[u8], sig: &[u8; 4]) -> Option<[f64; 3]> {
612 let count = u32::from_be_bytes(icc[128..132].try_into().ok()?) as usize;
613 (0..count).find_map(|i| {
614 let e = 132 + 12 * i;
615 let entry = icc.get(e..e + 12)?;
616 if &entry[..4] != sig {
617 return None;
618 }
619 let off = u32::from_be_bytes(entry[4..8].try_into().ok()?) as usize;
620 let body = icc.get(off..off + 20)?;
621 let s15 = |b: &[u8]| f64::from(i32::from_be_bytes(b.try_into().unwrap())) / 65536.0;
622 Some([s15(&body[8..12]), s15(&body[12..16]), s15(&body[16..20])])
623 })
624 }
625
626 #[test]
627 #[cfg(feature = "icc-db")]
628 fn synthesized_profiles_carry_their_own_cicp_over_the_full_grid() {
629 // Every synthesized profile names its own pair in a `cicp` tag
630 // (matrix 0, full range), so a reader resolving the tag gets the
631 // signal the caller asked for. And identification, where it
632 // recognises the bytes, agrees with the pair: the curated aliases
633 // (zenpixels#86) would fail here.
634 const ASSIGNED_PRIMARIES: &[u8] = &[1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 22];
635 const ASSIGNED_TRANSFERS: &[u8] =
636 &[1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
637 let mut checked = 0;
638 for &p in ASSIGNED_PRIMARIES {
639 for &t in ASSIGNED_TRANSFERS {
640 let asked = Cicp::new(p, t, 0, true);
641 let SynthesizedIcc::Profile(bytes) = synthesize_icc_for_cicp(asked) else {
642 continue;
643 };
644 let tag = zenpixels::Cicp::from_icc(&bytes)
645 .unwrap_or_else(|| panic!("({p}, {t}): no cicp tag"));
646 assert_eq!(tag, asked, "({p}, {t}): cicp tag names another signal");
647 // Identification, where it recognises the bytes, names the
648 // same primaries and transfer wherever the CICP code maps to
649 // a known enum value. (Code 4, BT.470M "gamma 2.2", maps to
650 // Unknown while the profile identifies as Gamma22: a mapping
651 // gap, not a profile error, so Unknown fields are skipped.)
652 if let Some(id) = zenpixels::icc::IccIdentification::from_icc(&bytes) {
653 if let Some(want_p) = Primaries::from_cicp(asked.color_primaries) {
654 assert!(
655 id.primaries().same_chromaticity(want_p),
656 "({p}, {t}): identified primaries {:?} vs {want_p:?}",
657 id.primaries()
658 );
659 }
660 if let Some(want_t) = Transfer::from_cicp(asked.transfer_characteristics) {
661 // ICC v4 TRC tags only encode `[0, 1]`, where BT.1361 (TC=12) is
662 // identical to BT.709 (TC=1); only negative extended values differ.
663 let unit_trc_match = id.transfer().same_curve(want_t)
664 || (id.transfer() == Transfer::Bt709 && want_t == Transfer::Bt1361);
665 assert!(
666 unit_trc_match,
667 "({p}, {t}): identified transfer {:?} vs {want_t:?}",
668 id.transfer()
669 );
670 }
671 }
672 checked += 1;
673 }
674 }
675 assert_eq!(checked, 149);
676 }
677
678 #[test]
679 #[cfg(feature = "icc-db")]
680 fn display_p3_colorants_match_libultrahdr_within_its_tolerance() {
681 // libultrahdr reads a `cicp` tag first, then matches colorant tags
682 // against its own table within 0.001 (`lib/src/icc.cpp`,
683 // `IccHelper::tagsEqualToMatrix`; table `kDisplayP3` in
684 // `lib/include/ultrahdr/icc.h`). The curated DISPLAY_P3_V4 fails both
685 // (no tag; red Z 0 and blue Z 0.783081), so libultrahdr decoded
686 // Display P3 Ultra HDR bases as BT.709 (zenpixels#87).
687 const KDISPLAYP3: [[f64; 3]; 3] = [
688 [0.515102, 0.241182, -0.00104941],
689 [0.291965, 0.692236, 0.0418818],
690 [0.157153, 0.0665819, 0.784378],
691 ];
692 for transfer in [13u8, 1] {
693 let SynthesizedIcc::Profile(bytes) =
694 synthesize_icc_for_cicp(Cicp::new(12, transfer, 0, true))
695 else {
696 panic!("Display P3 (transfer {transfer}) not synthesized");
697 };
698 for (sig, want) in [b"rXYZ", b"gXYZ", b"bXYZ"].iter().zip(KDISPLAYP3) {
699 let got = xyz_tag(&bytes, sig).expect("colorant tag");
700 for (g, w) in got.iter().zip(want) {
701 assert!(
702 (g - w).abs() <= 0.001,
703 "transfer {transfer}: {} {got:?} vs libultrahdr {want:?}",
704 core::str::from_utf8(*sig).unwrap()
705 );
706 }
707 }
708 }
709 // The curated const misses, which is why synthesis must not serve it.
710 let curated = xyz_tag(DISPLAY_P3_V4, b"rXYZ").unwrap();
711 assert!((curated[2] - KDISPLAYP3[0][2]).abs() > 0.001);
712 }
713
714 #[test]
715 #[cfg(feature = "icc-db")]
716 fn sdr_bt2020_with_srgb_transfer_gets_the_srgb_curve() {
717 // zenpixels#86: (BT.2020, sRGB) got REC2020_V4, whose curve is
718 // BT.709's. The synthesized profile names (9, 13) and is not the
719 // BT.709-curve const.
720 let SynthesizedIcc::Profile(bytes) = synthesize_icc_for_cicp(Cicp::new(9, 13, 0, true))
721 else {
722 panic!("BT.2020 + sRGB not synthesized");
723 };
724 assert_ne!(&*bytes, REC2020_V4);
725 assert_eq!(
726 zenpixels::Cicp::from_icc(&bytes),
727 Some(Cicp::new(9, 13, 0, true))
728 );
729 }
730
731 #[test]
732 #[cfg(feature = "icc-db")]
733 fn synthesize_icc_for_cicp_hdr_pq_is_bundled_in_every_build() {
734 // BT.2020 PQ: an HDR transfer with no `&'static` const, but it IS in the
735 // full-grid blob now — so a profile comes back in BOTH builds, never a
736 // mis-tagged SDR profile and never `IccDbDisabled`. (The bytes are the
737 // blob's; byte-equality with moxcms is verified by the roundtrip test.)
738 let bt2020_pq = Cicp::new(9, 16, 9, false); // primaries 9, transfer 16 (PQ)
739 match synthesize_icc_for_cicp(bt2020_pq) {
740 SynthesizedIcc::Profile(bytes) => {
741 assert!(!bytes.is_empty());
742 assert_eq!(&bytes[36..40], b"acsp", "must be a valid ICC profile");
743 }
744 other => panic!("expected a bundled PQ profile, got {other:?}"),
745 }
746 }
747
748 #[test]
749 #[cfg(feature = "icc-db")]
750 fn synthesize_icc_for_cicp_reserved_transfer_is_unsupported_not_mistagged() {
751 // Recognized primaries (BT.2020) but a *reserved* transfer code (0). It's
752 // outside the assigned H.273 grid, so it isn't in the blob — synthesis
753 // must refuse rather than mis-tag. The blob is the coverage source now,
754 // so a no-CMS build reports `CmsUnsupported` (not `IccDbDisabled`): there is
755 // no CMS that could add what the blob lacks for an unassigned code.
756 let bt2020_reserved_trc = Cicp::new(9, 0, 9, false);
757 assert_eq!(
758 synthesize_icc_for_cicp(bt2020_reserved_trc),
759 SynthesizedIcc::Unsupported
760 );
761 }
762
763 #[test]
764 #[cfg(feature = "icc-db")]
765 fn synthesize_icc_for_cicp_real_gamut_not_assumed_srgb() {
766 // BT.601 primaries (code 6) + gamma-2.2 transfer (code 4): a real, non-sRGB
767 // colour description that zenpixels' enum folds into `Unknown`/`Unknown`.
768 // It must NOT be treated as the sRGB default — that would silently drop the
769 // gamut. The `NotNeeded` gate keys on raw code points, and it's an assigned
770 // grid point, so it resolves from the blob in EVERY build.
771 let bt601_g22 = Cicp::new(6, 4, 0, false);
772 let got = synthesize_icc_for_cicp(bt601_g22);
773 assert_ne!(
774 got,
775 SynthesizedIcc::NotNeeded,
776 "a real non-sRGB gamut must never be assumed to be the sRGB default"
777 );
778 assert!(
779 matches!(got, SynthesizedIcc::Profile(_)),
780 "an assigned H.273 grid point must resolve from the blob in every build, got {got:?}"
781 );
782 }
783
784 #[test]
785 #[cfg(feature = "icc-db")]
786 fn synthesize_icc_for_cicp_full_grid_coverage_without_cms() {
787 // The headline property: the blob gives a profile for every assigned-grid
788 // combo except primaries 10 and the sRGB-default `NotNeeded` pair — with no dependence
789 // on a CMS. The blob lookup sits *before* the moxcms fallback, so every
790 // covered combo comes back as a `Cow::Borrowed` (the blob's zero-copy
791 // slice, or one of the 4 `&'static` consts) — never a `Cow::Owned`, which
792 // is what moxcms would produce. Asserting `Borrowed` proves the no-CMS
793 // path serves these regardless of whether `cms-moxcms` is compiled in
794 // (it's forced on for this crate's tests by a dev-dependency).
795 const ASSIGNED_PRIMARIES: &[u8] = &[1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 22];
796 const ASSIGNED_TRANSFERS: &[u8] =
797 &[1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18];
798 let mut profiles = 0usize;
799 let mut not_needed = 0usize;
800 let mut unsupported = 0usize;
801 for &p in ASSIGNED_PRIMARIES {
802 for &t in ASSIGNED_TRANSFERS {
803 let got = synthesize_icc_for_cicp(Cicp::new(p, t, 0, true));
804 match got {
805 SynthesizedIcc::Profile(bytes) => {
806 assert!(
807 matches!(bytes, Cow::Borrowed(_)),
808 "({p}, {t}) was served by the CMS (Cow::Owned) — must come \
809 from the blob/const (Cow::Borrowed) so coverage holds without a CMS"
810 );
811 assert_eq!(&bytes[36..40], b"acsp", "({p}, {t}) produced non-ICC bytes");
812 profiles += 1;
813 }
814 SynthesizedIcc::NotNeeded => {
815 // Only the BT.709 sRGB-default pairs.
816 assert!(p == 1 && t == 13, "({p}, {t}) unexpectedly NotNeeded");
817 not_needed += 1;
818 }
819 SynthesizedIcc::Unsupported if p == 10 || t == 18 => unsupported += 1,
820 other => panic!("({p}, {t}) gave {other:?} — expected full blob coverage"),
821 }
822 }
823 }
824 assert_eq!(profiles, 149, "expected 149 profile-yielding combos");
825 assert_eq!(unsupported, 26, "XYZ and HLG pairs refused");
826 assert_eq!(
827 not_needed, 1,
828 "expected exactly 1 sRGB-default NotNeeded combo"
829 );
830 }
831}