Skip to main content

rust_motion_cms/
profile.rs

1//! ICC profiles: the parsed model, the reader (ICC.1:2001-04 v2 and ICC.1:2010 v4) and the
2//! connection of a profile to the PCS as evaluation stages.
3
4use std::sync::Arc;
5
6use crate::clut::Clut;
7use crate::curve::Curve;
8use crate::math::{self, Mat3};
9use crate::pipeline::Stage;
10use crate::{CmsError, Intent};
11
12/// Profile/device class (header bytes 12..16).
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
14pub enum ProfileClass {
15    Input,
16    Display,
17    Output,
18    DeviceLink,
19    ColorSpace,
20    Abstract,
21    NamedColor,
22    Unknown(u32),
23}
24
25impl ProfileClass {
26    pub fn from_sig(s: u32) -> Self {
27        match &s.to_be_bytes() {
28            b"scnr" => Self::Input,
29            b"mntr" => Self::Display,
30            b"prtr" => Self::Output,
31            b"link" => Self::DeviceLink,
32            b"spac" => Self::ColorSpace,
33            b"abst" => Self::Abstract,
34            b"nmcl" => Self::NamedColor,
35            _ => Self::Unknown(s),
36        }
37    }
38    pub fn sig(self) -> u32 {
39        u32::from_be_bytes(*match self {
40            Self::Input => b"scnr",
41            Self::Display => b"mntr",
42            Self::Output => b"prtr",
43            Self::DeviceLink => b"link",
44            Self::ColorSpace => b"spac",
45            Self::Abstract => b"abst",
46            Self::NamedColor => b"nmcl",
47            Self::Unknown(s) => return s,
48        })
49    }
50}
51
52/// Data colour space (header bytes 16..20).
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub enum ColorSpace {
55    Xyz,
56    Lab,
57    Luv,
58    YCbCr,
59    Yxy,
60    Rgb,
61    Gray,
62    Hsv,
63    Hls,
64    Cmyk,
65    Cmy,
66    /// `nCLR` spaces with n = 2..=15 colorants.
67    Color(u8),
68    Unknown(u32),
69}
70
71impl ColorSpace {
72    pub fn from_sig(s: u32) -> Self {
73        let b = s.to_be_bytes();
74        match &b {
75            b"XYZ " => Self::Xyz,
76            b"Lab " => Self::Lab,
77            b"Luv " => Self::Luv,
78            b"YCbr" => Self::YCbCr,
79            b"Yxy " => Self::Yxy,
80            b"RGB " => Self::Rgb,
81            b"GRAY" => Self::Gray,
82            b"HSV " => Self::Hsv,
83            b"HLS " => Self::Hls,
84            b"CMYK" => Self::Cmyk,
85            b"CMY " => Self::Cmy,
86            [d, b'C', b'L', b'R'] => match *d {
87                b'2'..=b'9' => Self::Color(d - b'0'),
88                b'A'..=b'F' => Self::Color(d - b'A' + 10),
89                _ => Self::Unknown(s),
90            },
91            _ => Self::Unknown(s),
92        }
93    }
94    pub fn sig(self) -> u32 {
95        u32::from_be_bytes(match self {
96            Self::Xyz => *b"XYZ ",
97            Self::Lab => *b"Lab ",
98            Self::Luv => *b"Luv ",
99            Self::YCbCr => *b"YCbr",
100            Self::Yxy => *b"Yxy ",
101            Self::Rgb => *b"RGB ",
102            Self::Gray => *b"GRAY",
103            Self::Hsv => *b"HSV ",
104            Self::Hls => *b"HLS ",
105            Self::Cmyk => *b"CMYK",
106            Self::Cmy => *b"CMY ",
107            Self::Color(n) => [
108                if n < 10 { b'0' + n } else { b'A' + n - 10 },
109                b'C',
110                b'L',
111                b'R',
112            ],
113            Self::Unknown(s) => return s,
114        })
115    }
116    /// Number of channels of the space.
117    pub fn channels(self) -> usize {
118        match self {
119            Self::Gray => 1,
120            Self::Cmyk => 4,
121            Self::Color(n) => n as usize,
122            Self::Unknown(_) => 0,
123            _ => 3,
124        }
125    }
126}
127
128/// Which PCS a stage list ends in (float values: XYZ with Y = 1 for the white, or Lab L 0–100).
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum Pcs {
131    Xyz,
132    Lab,
133}
134
135/// Encoding family of a LUT tag, which fixes how its PCS side is encoded.
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub enum LutKind {
138    /// `mft1` (8-bit), v4-style Lab encoding.
139    Lut8,
140    /// `mft2` (16-bit), legacy v2 Lab encoding.
141    Lut16,
142    /// `mAB ` / `mBA ` (v4), v4 Lab encoding.
143    Ab,
144}
145
146/// A parsed `AToB`/`BToA` tag: device-side and PCS-side values are normalised to `[0, 1]`.
147#[derive(Clone, Debug, PartialEq)]
148pub struct Lut {
149    pub kind: LutKind,
150    pub inputs: usize,
151    pub outputs: usize,
152    pub stages: Vec<Stage>,
153}
154
155/// Largest colour difference (CIE ΔE*ab) for which [`Profile::same_colors`] treats two profiles
156/// as one colour space: invisible, yet 20× what re-encoding a profile costs (sRGB as v2 tables
157/// against v4 parametric curves differs by 0.025). Moving sRGB's red primary 2% costs 1.0.
158pub const SAME_COLORS_MAX_DELTA_E: f64 = 0.5;
159
160/// A parsed ICC profile.
161#[derive(Clone, Debug, PartialEq)]
162pub struct Profile {
163    /// Major version and minor.bugfix byte (e.g. `(4, 0x30)` for 4.3, `(2, 0x10)` for 2.1).
164    pub version: (u8, u8),
165    pub class: ProfileClass,
166    pub color_space: ColorSpace,
167    pub pcs: Pcs,
168    pub rendering_intent: Intent,
169    pub description: String,
170    pub copyright: String,
171    /// `wtpt` as stored (XYZ; D50 when absent).
172    pub white_point: [f64; 3],
173    /// `bkpt` when present.
174    pub black_point: Option<[f64; 3]>,
175    /// `chad` chromatic adaptation matrix when present.
176    pub chad: Option<Mat3>,
177    /// Colorant matrix (columns rXYZ, gXYZ, bXYZ), D50-adapted.
178    pub matrix: Option<Mat3>,
179    pub trc: Option<[Curve; 3]>,
180    pub gray_trc: Option<Curve>,
181    /// A2B0/A2B1/A2B2 (perceptual, colorimetric, saturation).
182    pub a2b: [Option<Lut>; 3],
183    pub b2a: [Option<Lut>; 3],
184    /// The bytes this profile was parsed from (or encoded to), kept for byte-exact embedding.
185    pub(crate) bytes: Option<Arc<Vec<u8>>>,
186    pub(crate) hash: std::sync::OnceLock<u64>,
187}
188
189impl Profile {
190    /// Parses ICC profile bytes.
191    pub fn parse(bytes: &[u8]) -> Result<Profile, CmsError> {
192        let mut p = parse_profile(bytes)?;
193        p.bytes = Some(Arc::new(bytes.to_vec()));
194        Ok(p)
195    }
196
197    /// The ICC bytes of this profile: the original bytes when it was parsed, otherwise a fresh
198    /// ICC v4 encoding.
199    pub fn to_bytes(&self) -> Arc<Vec<u8>> {
200        match &self.bytes {
201            Some(b) => b.clone(),
202            None => Arc::new(crate::write::encode(self)),
203        }
204    }
205
206    /// Re-encodes the model as ICC v4 bytes and caches them (used for built-in profiles).
207    pub fn with_encoded_bytes(mut self) -> Profile {
208        self.bytes = None;
209        self.hash = Default::default();
210        let b = crate::write::encode(&self);
211        self.bytes = Some(Arc::new(b));
212        self
213    }
214
215    pub fn channels(&self) -> usize {
216        self.color_space.channels()
217    }
218
219    /// Hash of the profile's ICC bytes (stable within a process; used as a cache key).
220    pub fn content_hash(&self) -> u64 {
221        *self.hash.get_or_init(|| {
222            use std::hash::{Hash, Hasher};
223            let mut h = std::collections::hash_map::DefaultHasher::new();
224            self.to_bytes().hash(&mut h);
225            h.finish()
226        })
227    }
228
229    /// Whether `self` and `other` describe the same colours: same colour space, and every sample
230    /// of a device-value grid has the same colour through both (relative colorimetric, within
231    /// [`SAME_COLORS_MAX_DELTA_E`]). Different encodings of one space are the same colours: the
232    /// sRGB IEC61966-2.1 Photoshop embeds (v2, 1024-entry tables) and the built-in sRGB (v4,
233    /// parametric curves) differ in every byte. Colours are compared rather than round-tripped
234    /// because CMYK → PCS → CMYK is not an identity even through a single profile.
235    pub fn same_colors(&self, other: &Profile) -> bool {
236        if self.content_hash() == other.content_hash() {
237            return true;
238        }
239        let n = self.channels();
240        if self.color_space != other.color_space || n == 0 || n > 4 {
241            return false;
242        }
243        let lab = crate::builtin::Builtin::LabD50.profile();
244        let to_lab = |p: &Profile| {
245            crate::transform::Transform::new(p, lab, Intent::RelativeColorimetric, false)
246        };
247        let (Ok(a), Ok(b)) = (to_lab(self), to_lab(other)) else {
248            return false;
249        };
250        // 17 steps per channel catch a TRC that differs only in its toe; 9 keep CMYK at 6561 samples.
251        let steps: usize = if n <= 3 { 17 } else { 9 };
252        // Lab D50 is the PCS, normalised as in ICC v4.
253        let decode = |o: [f32; 3]| {
254            [
255                f64::from(o[0]) * 100.0,
256                f64::from(o[1]) * 255.0 - 128.0,
257                f64::from(o[2]) * 255.0 - 128.0,
258            ]
259        };
260        let mut input = [0f32; 4];
261        (0..steps.pow(n as u32)).all(|i| {
262            let mut k = i;
263            for v in input.iter_mut().take(n) {
264                *v = (k % steps) as f32 / (steps - 1) as f32;
265                k /= steps;
266            }
267            let (mut la, mut lb) = ([0f32; 3], [0f32; 3]);
268            a.eval(&input[..n], &mut la);
269            b.eval(&input[..n], &mut lb);
270            math::delta_e76(decode(la), decode(lb)) <= SAME_COLORS_MAX_DELTA_E
271        })
272    }
273
274    /// Media white point used for ICC-absolute colorimetry: `wtpt`, except for v2 display
275    /// profiles whose `wtpt` records the (unadapted) display white; those are treated as D50.
276    pub fn media_white(&self) -> [f64; 3] {
277        if self.version.0 < 4 && self.class == ProfileClass::Display {
278            return math::D50;
279        }
280        self.white_point
281    }
282
283    /// An RGB view of a gray TRC profile: each of R, G, B carries the gray curve and maps to a
284    /// third of the white, so `(v, v, v)` has exactly the colour of gray `v`. Used for
285    /// composites of gray documents, which are stored as replicated RGB.
286    pub fn gray_as_rgb(&self) -> Option<Profile> {
287        let c = self.gray_trc.clone()?;
288        if self.pcs != Pcs::Xyz {
289            return None;
290        }
291        let w = math::D50;
292        let m = [[w[0] / 3.0; 3], [w[1] / 3.0; 3], [w[2] / 3.0; 3]];
293        let mut p = self.clone();
294        p.color_space = ColorSpace::Rgb;
295        p.description = format!("{} (as RGB)", self.description);
296        p.matrix = Some(m);
297        p.trc = Some([c.clone(), c.clone(), c]);
298        p.gray_trc = None;
299        // The gray LUTs take one input channel; this profile is the matrix/TRC model above.
300        p.a2b = Default::default();
301        p.b2a = Default::default();
302        p.bytes = None;
303        p.hash = Default::default();
304        Some(p)
305    }
306
307    /// `true` for matrix/TRC RGB or gray TRC profiles without LUTs.
308    pub fn is_matrix_shaper(&self) -> bool {
309        self.a2b.iter().all(Option::is_none)
310            && (self.matrix.is_some() && self.trc.is_some() || self.gray_trc.is_some())
311    }
312
313    /// Whether colours can be converted into this profile for every intent. Input profiles with
314    /// only AToB tables (Apple's Wide Color Sharing Profile on iPhone photos) can't: they
315    /// describe a source but have no PCS → device path.
316    pub fn can_be_destination(&self) -> bool {
317        [
318            Intent::Perceptual,
319            Intent::RelativeColorimetric,
320            Intent::Saturation,
321        ]
322        .into_iter()
323        .all(|i| self.pcs_to_device(i).is_ok())
324    }
325
326    fn lut_for(luts: &[Option<Lut>; 3], intent: Intent) -> Option<&Lut> {
327        let i = match intent {
328            Intent::Perceptual => 0,
329            Intent::RelativeColorimetric | Intent::AbsoluteColorimetric => 1,
330            Intent::Saturation => 2,
331        };
332        luts[i].as_ref().or(luts[0].as_ref())
333    }
334
335    /// Whether the profile has a dedicated table for `intent` (matrix profiles support every
336    /// intent colorimetrically).
337    pub fn supports_intent(&self, intent: Intent, input: bool) -> bool {
338        let luts = if input { &self.a2b } else { &self.b2a };
339        let i = match intent {
340            Intent::Perceptual => 0,
341            Intent::RelativeColorimetric | Intent::AbsoluteColorimetric => 1,
342            Intent::Saturation => 2,
343        };
344        luts[i].is_some() || luts.iter().all(Option::is_none)
345    }
346
347    /// Stages mapping normalised device values to the float PCS.
348    pub fn device_to_pcs(&self, intent: Intent) -> Result<(Vec<Stage>, Pcs), CmsError> {
349        if let Some(l) = Self::lut_for(&self.a2b, intent) {
350            let mut st = l.stages.clone();
351            st.push(decode_pcs(self.pcs, l.kind));
352            return Ok((st, self.pcs));
353        }
354        match self.color_space {
355            ColorSpace::Rgb => {
356                let (Some(m), Some(trc)) = (&self.matrix, &self.trc) else {
357                    return Err(CmsError::Unsupported(
358                        "RGB profile without matrix/TRC or AToB tags".into(),
359                    ));
360                };
361                Ok((
362                    vec![Stage::Curves(trc.to_vec()), Stage::matrix3(m)],
363                    Pcs::Xyz,
364                ))
365            }
366            ColorSpace::Gray => {
367                let c = self
368                    .gray_trc
369                    .clone()
370                    .ok_or_else(|| CmsError::Unsupported("gray profile without kTRC".into()))?;
371                if self.pcs == Pcs::Lab {
372                    // The curve yields L*/100.
373                    let m = Stage::Matrix {
374                        rows: 3,
375                        cols: 1,
376                        m: vec![100.0, 0.0, 0.0],
377                        offset: vec![0.0; 3],
378                    };
379                    Ok((vec![Stage::Curves(vec![c]), m], Pcs::Lab))
380                } else {
381                    let w = math::D50;
382                    let m = Stage::Matrix {
383                        rows: 3,
384                        cols: 1,
385                        m: w.to_vec(),
386                        offset: vec![0.0; 3],
387                    };
388                    Ok((vec![Stage::Curves(vec![c]), m], Pcs::Xyz))
389                }
390            }
391            ColorSpace::Lab => Ok((vec![Stage::DecodeLabV4], Pcs::Lab)),
392            ColorSpace::Xyz => Ok((vec![Stage::DecodeXyz], Pcs::Xyz)),
393            cs => Err(CmsError::Unsupported(format!(
394                "{cs:?} profile without AToB tags"
395            ))),
396        }
397    }
398
399    /// Stages mapping the float PCS (of the returned kind) to normalised device values.
400    pub fn pcs_to_device(&self, intent: Intent) -> Result<(Vec<Stage>, Pcs), CmsError> {
401        if let Some(l) = Self::lut_for(&self.b2a, intent) {
402            let mut st = vec![encode_pcs(self.pcs, l.kind)];
403            st.extend(l.stages.iter().cloned());
404            return Ok((st, self.pcs));
405        }
406        match self.color_space {
407            ColorSpace::Rgb => {
408                let (Some(m), Some(trc)) = (&self.matrix, &self.trc) else {
409                    return Err(CmsError::Unsupported(
410                        "RGB profile without matrix/TRC or BToA tags".into(),
411                    ));
412                };
413                let inv = math::invert(m)
414                    .ok_or_else(|| CmsError::Invalid("singular colorant matrix".into()))?;
415                Ok((
416                    vec![Stage::matrix3(&inv), Stage::InvCurves(trc.to_vec())],
417                    Pcs::Xyz,
418                ))
419            }
420            ColorSpace::Gray => {
421                let c = self
422                    .gray_trc
423                    .clone()
424                    .ok_or_else(|| CmsError::Unsupported("gray profile without kTRC".into()))?;
425                if self.pcs == Pcs::Lab {
426                    let m = Stage::Matrix {
427                        rows: 1,
428                        cols: 3,
429                        m: vec![0.01, 0.0, 0.0],
430                        offset: vec![0.0],
431                    };
432                    Ok((vec![m, Stage::InvCurves(vec![c])], Pcs::Lab))
433                } else {
434                    let m = Stage::Matrix {
435                        rows: 1,
436                        cols: 3,
437                        m: vec![0.0, 1.0, 0.0],
438                        offset: vec![0.0],
439                    };
440                    Ok((vec![m, Stage::InvCurves(vec![c])], Pcs::Xyz))
441                }
442            }
443            ColorSpace::Lab => Ok((vec![Stage::EncodeLabV4], Pcs::Lab)),
444            ColorSpace::Xyz => Ok((vec![Stage::EncodeXyz], Pcs::Xyz)),
445            cs => Err(CmsError::Unsupported(format!(
446                "{cs:?} profile without BToA tags"
447            ))),
448        }
449    }
450}
451
452fn decode_pcs(pcs: Pcs, kind: LutKind) -> Stage {
453    match (pcs, kind) {
454        (Pcs::Xyz, _) => Stage::DecodeXyz,
455        (Pcs::Lab, LutKind::Lut16) => Stage::DecodeLabV2,
456        (Pcs::Lab, _) => Stage::DecodeLabV4,
457    }
458}
459
460fn encode_pcs(pcs: Pcs, kind: LutKind) -> Stage {
461    match (pcs, kind) {
462        (Pcs::Xyz, _) => Stage::EncodeXyz,
463        (Pcs::Lab, LutKind::Lut16) => Stage::EncodeLabV2,
464        (Pcs::Lab, _) => Stage::EncodeLabV4,
465    }
466}
467
468// ---------------------------------------------------------------- reader
469
470struct Reader<'a> {
471    b: &'a [u8],
472}
473
474impl<'a> Reader<'a> {
475    fn slice(&self, off: usize, len: usize) -> Result<&'a [u8], CmsError> {
476        off.checked_add(len)
477            .and_then(|end| self.b.get(off..end))
478            .ok_or(CmsError::Truncated)
479    }
480    fn u8(&self, off: usize) -> Result<u8, CmsError> {
481        self.b.get(off).copied().ok_or(CmsError::Truncated)
482    }
483    fn u16(&self, off: usize) -> Result<u16, CmsError> {
484        let s = self.slice(off, 2)?;
485        Ok(u16::from_be_bytes([s[0], s[1]]))
486    }
487    fn u32(&self, off: usize) -> Result<u32, CmsError> {
488        let s = self.slice(off, 4)?;
489        Ok(u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
490    }
491    fn s15f16(&self, off: usize) -> Result<f64, CmsError> {
492        Ok(self.u32(off)? as i32 as f64 / 65536.0)
493    }
494    fn xyz(&self, off: usize) -> Result<[f64; 3], CmsError> {
495        let r = Reader {
496            b: self.slice(off, 12)?,
497        };
498        Ok([r.s15f16(0)?, r.s15f16(4)?, r.s15f16(8)?])
499    }
500}
501
502/// `base + n * size` for a count or offset read from the file, or `Truncated` when it does not
503/// fit a `usize`. Such fields reach `u32::MAX`, which overflows on 32-bit targets (wasm32):
504/// a panic with overflow checks on, a wrapped offset that reads the wrong bytes without (#4976).
505fn extent(base: usize, n: usize, size: usize) -> Result<usize, CmsError> {
506    n.checked_mul(size)
507        .and_then(|len| base.checked_add(len))
508        .ok_or(CmsError::Truncated)
509}
510
511fn sig(s: &[u8; 4]) -> u32 {
512    u32::from_be_bytes(*s)
513}
514
515/// Upper bound on CLUT nodes × outputs we accept, to reject hostile files.
516const MAX_CLUT_VALUES: usize = 16 * 1024 * 1024;
517
518fn parse_profile(bytes: &[u8]) -> Result<Profile, CmsError> {
519    let r = Reader { b: bytes };
520    if bytes.len() < 132 {
521        return Err(CmsError::Truncated);
522    }
523    if r.slice(36, 4)? != b"acsp" {
524        return Err(CmsError::BadSignature);
525    }
526    let declared = r.u32(0)? as usize;
527    // Some writers pad or truncate; trust the smaller of the two.
528    let end = if declared >= 132 && declared <= bytes.len() {
529        declared
530    } else {
531        bytes.len()
532    };
533    let r = Reader { b: &bytes[..end] };
534    let version = (r.u8(8)?, r.u8(9)?);
535    let class = ProfileClass::from_sig(r.u32(12)?);
536    let color_space = ColorSpace::from_sig(r.u32(16)?);
537    let pcs_sig = r.u32(20)?;
538    let pcs = match &pcs_sig.to_be_bytes() {
539        b"Lab " => Pcs::Lab,
540        _ => Pcs::Xyz,
541    };
542    let rendering_intent = Intent::from_u32(r.u32(64)? & 0xFFFF).unwrap_or(Intent::Perceptual);
543    let count = r.u32(128)? as usize;
544    if count > 1024 {
545        return Err(CmsError::Invalid(format!("{count} tags")));
546    }
547    let mut tags: Vec<(u32, usize, usize)> = Vec::with_capacity(count);
548    for i in 0..count {
549        let o = 132 + i * 12;
550        let (s, off, len) = (r.u32(o)?, r.u32(o + 4)? as usize, r.u32(o + 8)? as usize);
551        tags.push((s, off, len));
552    }
553    let find = |s: &[u8; 4]| tags.iter().find(|t| t.0 == sig(s)).map(|t| (t.1, t.2));
554    let tag_data = |s: &[u8; 4]| -> Result<Option<&[u8]>, CmsError> {
555        match find(s) {
556            Some((off, len)) => Ok(Some(r.slice(off, len)?)),
557            None => Ok(None),
558        }
559    };
560
561    let xyz_tag = |s: &[u8; 4]| -> Result<Option<[f64; 3]>, CmsError> {
562        match tag_data(s)? {
563            Some(d) if d.len() >= 20 && &d[..4] == b"XYZ " => Ok(Some(Reader { b: d }.xyz(8)?)),
564            Some(_) => Err(CmsError::Invalid(format!(
565                "tag {} is not XYZType",
566                String::from_utf8_lossy(s)
567            ))),
568            None => Ok(None),
569        }
570    };
571    let curve_tag = |s: &[u8; 4]| -> Result<Option<Curve>, CmsError> {
572        match tag_data(s)? {
573            Some(d) => Ok(Some(parse_curve(d)?.0)),
574            None => Ok(None),
575        }
576    };
577
578    let white_point = xyz_tag(b"wtpt")?.unwrap_or(math::D50);
579    let black_point = xyz_tag(b"bkpt").ok().flatten();
580    let chad = match tag_data(b"chad")? {
581        Some(d) if d.len() >= 44 && &d[..4] == b"sf32" => {
582            let rd = Reader { b: d };
583            let mut m = [[0.0; 3]; 3];
584            for (i, row) in m.iter_mut().enumerate() {
585                for (j, v) in row.iter_mut().enumerate() {
586                    *v = rd.s15f16(8 + (i * 3 + j) * 4)?;
587                }
588            }
589            Some(m)
590        }
591        _ => None,
592    };
593    let matrix = match (xyz_tag(b"rXYZ")?, xyz_tag(b"gXYZ")?, xyz_tag(b"bXYZ")?) {
594        (Some(rr), Some(g), Some(b)) => Some([
595            [rr[0], g[0], b[0]],
596            [rr[1], g[1], b[1]],
597            [rr[2], g[2], b[2]],
598        ]),
599        _ => None,
600    };
601    let trc = match (
602        curve_tag(b"rTRC")?,
603        curve_tag(b"gTRC")?,
604        curve_tag(b"bTRC")?,
605    ) {
606        (Some(a), Some(b), Some(c)) => Some([a, b, c]),
607        _ => None,
608    };
609    let gray_trc = curve_tag(b"kTRC")?;
610    let lut = |s: &[u8; 4], a2b: bool| -> Result<Option<Lut>, CmsError> {
611        match tag_data(s)? {
612            Some(d) => parse_lut(d, a2b).map(Some),
613            None => Ok(None),
614        }
615    };
616    let a2b = [
617        lut(b"A2B0", true)?,
618        lut(b"A2B1", true)?,
619        lut(b"A2B2", true)?,
620    ];
621    let b2a = [
622        lut(b"B2A0", false)?,
623        lut(b"B2A1", false)?,
624        lut(b"B2A2", false)?,
625    ];
626    let description = tag_data(b"desc")?.map(parse_text).unwrap_or_default();
627    let copyright = tag_data(b"cprt")?.map(parse_text).unwrap_or_default();
628
629    let p = Profile {
630        version,
631        class,
632        color_space,
633        pcs,
634        rendering_intent,
635        description,
636        copyright,
637        white_point,
638        black_point,
639        chad,
640        matrix,
641        trc,
642        gray_trc,
643        a2b,
644        b2a,
645        bytes: None,
646        hash: Default::default(),
647    };
648    // Validate channel counts of LUTs against the header. A DeviceLink connects two device
649    // spaces: its header PCS field holds the output colour space (ICC.1:2010 §7.2.7), so a
650    // CMYK→CMYK link has a 4→4 AToB0.
651    let dev = p.color_space.channels();
652    let conn = if p.class == ProfileClass::DeviceLink {
653        ColorSpace::from_sig(pcs_sig).channels()
654    } else {
655        3
656    };
657    for l in p.a2b.iter().flatten() {
658        if dev != 0 && l.inputs != dev || conn != 0 && l.outputs != conn {
659            return Err(CmsError::Invalid(format!(
660                "AToB tag has {}→{} channels for a {:?} profile",
661                l.inputs, l.outputs, p.color_space
662            )));
663        }
664    }
665    for l in p.b2a.iter().flatten() {
666        if conn != 0 && l.inputs != conn || dev != 0 && l.outputs != dev {
667            return Err(CmsError::Invalid(format!(
668                "BToA tag has {}→{} channels for a {:?} profile",
669                l.inputs, l.outputs, p.color_space
670            )));
671        }
672    }
673    Ok(p)
674}
675
676/// Parses a `curv` or `para` element; returns the curve and the element's byte length
677/// (unpadded).
678fn parse_curve(d: &[u8]) -> Result<(Curve, usize), CmsError> {
679    let r = Reader { b: d };
680    match r.slice(0, 4)? {
681        b"curv" => {
682            let n = r.u32(8)? as usize;
683            // Before any arithmetic on it: `n * 2` overflows a 32-bit `usize` (#4976).
684            if n > 1 << 20 {
685                return Err(CmsError::Invalid("curve too long".into()));
686            }
687            let len = 12 + n * 2;
688            match n {
689                0 => Ok((Curve::Identity, len)),
690                1 => Ok((Curve::Gamma(r.u16(12)? as f64 / 256.0), len)),
691                _ => {
692                    let s = r.slice(12, n * 2)?;
693                    let t = s
694                        .as_chunks::<2>()
695                        .0
696                        .iter()
697                        .map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0)
698                        .collect();
699                    Ok((Curve::Table(t), len))
700                }
701            }
702        }
703        b"para" => {
704            let kind = r.u16(8)?;
705            if kind > 4 {
706                return Err(CmsError::Unsupported(format!(
707                    "parametric curve type {kind}"
708                )));
709            }
710            let n = Curve::param_count(kind);
711            let mut p = [0.0f64; 7];
712            for (i, v) in p.iter_mut().enumerate().take(n) {
713                *v = r.s15f16(12 + i * 4)?;
714            }
715            let len = 12 + n * 4;
716            let c = if kind == 0 {
717                Curve::Gamma(p[0])
718            } else {
719                Curve::Parametric { kind, p }
720            };
721            Ok((c, len))
722        }
723        other => Err(CmsError::Unsupported(format!(
724            "curve type {:?}",
725            String::from_utf8_lossy(other)
726        ))),
727    }
728}
729
730fn parse_curves_at(d: &[u8], off: usize, n: usize) -> Result<Vec<Curve>, CmsError> {
731    let mut out = Vec::with_capacity(n);
732    let mut o = off;
733    for _ in 0..n {
734        let sub = d.get(o..).ok_or(CmsError::Truncated)?;
735        let (c, len) = parse_curve(sub)?;
736        out.push(c);
737        o += (len + 3) & !3;
738    }
739    Ok(out)
740}
741
742fn parse_lut(d: &[u8], a2b: bool) -> Result<Lut, CmsError> {
743    let r = Reader { b: d };
744    let ty = r.slice(0, 4)?;
745    match ty {
746        b"mft1" | b"mft2" => {
747            let wide = ty == b"mft2";
748            let (i, o, g) = (r.u8(8)? as usize, r.u8(9)? as usize, r.u8(10)? as usize);
749            if !(1..=15).contains(&i) || !(1..=15).contains(&o) || g == 0 {
750                return Err(CmsError::Invalid("bad lut dimensions".into()));
751            }
752            let mut m = [[0.0; 3]; 3];
753            for (a, row) in m.iter_mut().enumerate() {
754                for (b, v) in row.iter_mut().enumerate() {
755                    *v = r.s15f16(12 + (a * 3 + b) * 4)?;
756                }
757            }
758            let (n_in, n_out, mut off) = if wide {
759                (r.u16(48)? as usize, r.u16(50)? as usize, 52)
760            } else {
761                (256, 256, 48)
762            };
763            if wide && (!(2..=4096).contains(&n_in) || !(2..=4096).contains(&n_out)) {
764                return Err(CmsError::Invalid("bad lut16 table size".into()));
765            }
766            let bps = if wide { 2 } else { 1 };
767            let read_tables =
768                |off: &mut usize, count: usize, len: usize| -> Result<Vec<Curve>, CmsError> {
769                    let mut v = Vec::with_capacity(count);
770                    for _ in 0..count {
771                        let s = r.slice(*off, len * bps)?;
772                        let t: Vec<f32> = if wide {
773                            s.as_chunks::<2>()
774                                .0
775                                .iter()
776                                .map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0)
777                                .collect()
778                        } else {
779                            s.iter().map(|b| *b as f32 / 255.0).collect()
780                        };
781                        *off += len * bps;
782                        v.push(Curve::Table(t));
783                    }
784                    Ok(v)
785                };
786            let in_curves = read_tables(&mut off, i, n_in)?;
787            let nodes = (g as u64).checked_pow(i as u32).unwrap_or(u64::MAX);
788            if nodes as u128 * o as u128 > MAX_CLUT_VALUES as u128 {
789                return Err(CmsError::Invalid("CLUT too large".into()));
790            }
791            let total = nodes as usize * o;
792            let s = r.slice(off, total * bps)?;
793            let data: Vec<f32> = if wide {
794                s.as_chunks::<2>()
795                    .0
796                    .iter()
797                    .map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0)
798                    .collect()
799            } else {
800                s.iter().map(|b| *b as f32 / 255.0).collect()
801            };
802            off += total * bps;
803            let out_curves = read_tables(&mut off, o, n_out)?;
804            let mut stages = Vec::new();
805            // The matrix only applies when the input is XYZ (BToA with an XYZ PCS).
806            let ident = m.iter().enumerate().all(|(a, row)| {
807                row.iter()
808                    .enumerate()
809                    .all(|(b, v)| (v - if a == b { 1.0 } else { 0.0 }).abs() < 1e-6)
810            });
811            if !a2b && i == 3 && !ident {
812                // Only meaningful for an XYZ PCS; the caller decides (we cannot know the PCS here),
813                // so keep it: for Lab PCS writers are required to store the identity.
814                stages.push(Stage::matrix3(&m));
815            }
816            stages.push(Stage::Curves(in_curves));
817            stages.push(Stage::Clut(Clut::new(vec![g; i], o, data)));
818            stages.push(Stage::Curves(out_curves));
819            Ok(Lut {
820                kind: if wide { LutKind::Lut16 } else { LutKind::Lut8 },
821                inputs: i,
822                outputs: o,
823                stages,
824            })
825        }
826        b"mAB " | b"mBA " => {
827            let (i, o) = (r.u8(8)? as usize, r.u8(9)? as usize);
828            if !(1..=15).contains(&i) || !(1..=15).contains(&o) {
829                return Err(CmsError::Invalid("bad lutAB dimensions".into()));
830            }
831            let (ob, om, omc, oc, oa) = (
832                r.u32(12)? as usize,
833                r.u32(16)? as usize,
834                r.u32(20)? as usize,
835                r.u32(24)? as usize,
836                r.u32(28)? as usize,
837            );
838            let matrix = |off: usize| lut_ab_matrix(&r, off);
839            let clut = |off: usize, cin: usize, cout: usize| lut_ab_clut(&r, off, cin, cout);
840            let mut stages = Vec::new();
841            if ty == b"mAB " {
842                // A curves → CLUT → M curves → matrix → B curves.
843                if oc != 0 {
844                    if oa == 0 {
845                        return Err(CmsError::Invalid(
846                            "lutAtoB with CLUT but no A curves".into(),
847                        ));
848                    }
849                    stages.push(Stage::Curves(parse_curves_at(d, oa, i)?));
850                    stages.push(clut(oc, i, o)?);
851                } else if i != o {
852                    return Err(CmsError::Invalid(
853                        "lutAtoB without CLUT changes channel count".into(),
854                    ));
855                }
856                if om != 0 {
857                    stages.push(Stage::Curves(parse_curves_at(d, omc, o)?));
858                    stages.push(matrix(om)?);
859                }
860                if ob == 0 {
861                    return Err(CmsError::Invalid("lutAtoB without B curves".into()));
862                }
863                stages.push(Stage::Curves(parse_curves_at(d, ob, o)?));
864            } else {
865                // B curves → matrix → M curves → CLUT → A curves.
866                if ob == 0 {
867                    return Err(CmsError::Invalid("lutBtoA without B curves".into()));
868                }
869                stages.push(Stage::Curves(parse_curves_at(d, ob, i)?));
870                if om != 0 {
871                    stages.push(matrix(om)?);
872                    stages.push(Stage::Curves(parse_curves_at(d, omc, i)?));
873                }
874                if oc != 0 {
875                    if oa == 0 {
876                        return Err(CmsError::Invalid(
877                            "lutBtoA with CLUT but no A curves".into(),
878                        ));
879                    }
880                    stages.push(clut(oc, i, o)?);
881                    stages.push(Stage::Curves(parse_curves_at(d, oa, o)?));
882                } else if i != o {
883                    return Err(CmsError::Invalid(
884                        "lutBtoA without CLUT changes channel count".into(),
885                    ));
886                }
887            }
888            Ok(Lut {
889                kind: LutKind::Ab,
890                inputs: i,
891                outputs: o,
892                stages,
893            })
894        }
895        other => Err(CmsError::Unsupported(format!(
896            "LUT type {:?}",
897            String::from_utf8_lossy(other)
898        ))),
899    }
900}
901
902/// The 3×3 matrix and offset of a `mAB `/`mBA ` element at `off`, an offset stored in the file.
903fn lut_ab_matrix(r: &Reader, off: usize) -> Result<Stage, CmsError> {
904    // One bounds-checked slice, then offsets inside it: `off + 44` need not fit a `usize`.
905    let e = Reader {
906        b: r.slice(off, 48)?,
907    };
908    let mut m = vec![0.0; 9];
909    for (k, v) in m.iter_mut().enumerate() {
910        *v = e.s15f16(k * 4)?;
911    }
912    let offset = vec![e.s15f16(36)?, e.s15f16(40)?, e.s15f16(44)?];
913    Ok(Stage::Matrix {
914        rows: 3,
915        cols: 3,
916        m,
917        offset,
918    })
919}
920
921/// The CLUT of a `mAB `/`mBA ` element at `off`, an offset stored in the file.
922fn lut_ab_clut(r: &Reader, off: usize, cin: usize, cout: usize) -> Result<Stage, CmsError> {
923    // Grid points (16 bytes), precision and padding; the samples follow.
924    let head = Reader {
925        b: r.slice(off, 20)?,
926    };
927    let mut grid = Vec::with_capacity(cin);
928    for k in 0..cin {
929        let g = head.u8(k)? as usize;
930        if g < 1 {
931            return Err(CmsError::Invalid("zero grid points".into()));
932        }
933        grid.push(g);
934    }
935    let prec = head.u8(16)? as usize;
936    let nodes: u128 = grid.iter().map(|g| *g as u128).product();
937    if nodes * cout as u128 > MAX_CLUT_VALUES as u128 {
938        return Err(CmsError::Invalid("CLUT too large".into()));
939    }
940    let total = nodes as usize * cout;
941    let samples = extent(off, 20, 1)?;
942    let data: Vec<f32> = match prec {
943        1 => r
944            .slice(samples, total)?
945            .iter()
946            .map(|b| *b as f32 / 255.0)
947            .collect(),
948        2 => r
949            .slice(samples, total * 2)?
950            .as_chunks::<2>()
951            .0
952            .iter()
953            .map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0)
954            .collect(),
955        _ => return Err(CmsError::Invalid(format!("CLUT precision {prec}"))),
956    };
957    Ok(Stage::Clut(Clut::new(grid, cout, data)))
958}
959
960/// Text from `desc` (textDescriptionType), `mluc` (English or first record) or `text`.
961fn parse_text(d: &[u8]) -> String {
962    let r = Reader { b: d };
963    let Ok(ty) = r.slice(0, 4) else {
964        return String::new();
965    };
966    let ascii = |s: &[u8]| {
967        String::from_utf8_lossy(s.split(|b| *b == 0).next().unwrap_or(&[]))
968            .trim()
969            .to_string()
970    };
971    match ty {
972        b"desc" => {
973            let n = r.u32(8).unwrap_or(0) as usize;
974            r.slice(12, n).map(ascii).unwrap_or_default()
975        }
976        b"text" => ascii(d.get(8..).unwrap_or(&[])),
977        b"mluc" => {
978            let (Ok(n), Ok(size)) = (r.u32(8), r.u32(12)) else {
979                return String::new();
980            };
981            let mut best: Option<(usize, usize)> = None;
982            for k in 0..(n as usize).min(256) {
983                // The record size comes from the file: `k * size` can overflow a 32-bit `usize`.
984                let Ok(rec) = extent(16, k, size as usize).and_then(|o| r.slice(o, 12)) else {
985                    break;
986                };
987                let rec = Reader { b: rec };
988                let (Ok(lang), Ok(len), Ok(off)) = (rec.u16(0), rec.u32(4), rec.u32(8)) else {
989                    break;
990                };
991                if best.is_none() || lang == u16::from_be_bytes(*b"en") {
992                    best = Some((off as usize, len as usize));
993                    if lang == u16::from_be_bytes(*b"en") {
994                        break;
995                    }
996                }
997            }
998            let Some((off, len)) = best else {
999                return String::new();
1000            };
1001            let Ok(s) = r.slice(off, len) else {
1002                return String::new();
1003            };
1004            let units: Vec<u16> = s
1005                .as_chunks::<2>()
1006                .0
1007                .iter()
1008                .map(|c| u16::from_be_bytes([c[0], c[1]]))
1009                .collect();
1010            String::from_utf16_lossy(&units)
1011                .trim_end_matches('\0')
1012                .trim()
1013                .to_string()
1014        }
1015        _ => String::new(),
1016    }
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021    use super::*;
1022
1023    fn be(v: u32) -> [u8; 4] {
1024        v.to_be_bytes()
1025    }
1026
1027    /// #4976: offsets and counts stored in a profile reach `u32::MAX`, which is `usize::MAX` on
1028    /// 32-bit targets. The arithmetic on them must report a truncated profile, not overflow.
1029    #[test]
1030    fn offsets_at_the_top_of_the_address_space_are_truncated_not_overflowed() {
1031        let bytes = [0u8; 64];
1032        let r = Reader { b: &bytes };
1033        for off in [
1034            usize::MAX,
1035            usize::MAX - 3,
1036            usize::MAX - 11,
1037            usize::MAX - 19,
1038            usize::MAX - 47,
1039        ] {
1040            assert_eq!(r.xyz(off), Err(CmsError::Truncated), "xyz at {off}");
1041            assert!(
1042                matches!(lut_ab_matrix(&r, off), Err(CmsError::Truncated)),
1043                "matrix at {off}"
1044            );
1045            assert!(
1046                matches!(lut_ab_clut(&r, off, 3, 3), Err(CmsError::Truncated)),
1047                "clut at {off}"
1048            );
1049        }
1050        assert_eq!(extent(16, usize::MAX, 12), Err(CmsError::Truncated));
1051        assert_eq!(extent(usize::MAX, 1, 1), Err(CmsError::Truncated));
1052        assert_eq!(extent(16, 3, 12), Ok(52));
1053    }
1054
1055    #[test]
1056    fn a_curve_count_is_checked_before_its_length_is_computed() {
1057        let mut d = b"curv\0\0\0\0".to_vec();
1058        d.extend(be(u32::MAX));
1059        assert_eq!(
1060            parse_curve(&d).map(|c| c.1),
1061            Err(CmsError::Invalid("curve too long".into()))
1062        );
1063        // Controls: the identity and a two-point table still parse with their lengths.
1064        let mut d = b"curv\0\0\0\0".to_vec();
1065        d.extend(be(0));
1066        assert_eq!(parse_curve(&d).map(|c| c.1), Ok(12));
1067        let mut d = b"curv\0\0\0\0".to_vec();
1068        d.extend(be(2));
1069        d.extend([0, 0, 0xFF, 0xFF]);
1070        assert_eq!(parse_curve(&d).map(|c| c.1), Ok(16));
1071    }
1072
1073    #[test]
1074    fn lut_ab_elements_at_hostile_offsets_are_rejected() {
1075        // A 3→3 lutAtoB with identity B curves at byte 32; then its B-curve, matrix and CLUT
1076        // offsets in turn point at the end of a 32-bit file.
1077        let lut = |b: u32, matrix: u32, m: u32, clut: u32, a: u32| {
1078            let mut d = b"mAB \0\0\0\0".to_vec();
1079            d.extend([3, 3, 0, 0]);
1080            for v in [b, matrix, m, clut, a] {
1081                d.extend(be(v));
1082            }
1083            for _ in 0..3 {
1084                d.extend(b"curv\0\0\0\0");
1085                d.extend(be(0));
1086            }
1087            d
1088        };
1089        assert!(
1090            parse_lut(&lut(32, 0, 0, 0, 0), true).is_ok(),
1091            "the control parses"
1092        );
1093        let top = u32::MAX - 8;
1094        assert!(
1095            parse_lut(&lut(top, 0, 0, 0, 0), true).is_err(),
1096            "B curves offset"
1097        );
1098        assert!(
1099            parse_lut(&lut(32, top, 32, 0, 0), true).is_err(),
1100            "matrix offset"
1101        );
1102        assert!(
1103            parse_lut(&lut(32, 0, 0, top, 32), true).is_err(),
1104            "CLUT offset"
1105        );
1106    }
1107
1108    #[test]
1109    fn multilingual_records_with_a_huge_record_size_give_the_first_record() {
1110        let record = |lang: &[u8; 2], len: u32, off: u32| {
1111            let mut r = lang.to_vec();
1112            r.extend(b"US");
1113            r.extend(be(len));
1114            r.extend(be(off));
1115            r
1116        };
1117        // Two records of the standard 12 bytes: the English one wins.
1118        let mut d = b"mluc\0\0\0\0".to_vec();
1119        d.extend(be(2));
1120        d.extend(be(12));
1121        d.extend(record(b"de", 4, 40));
1122        d.extend(record(b"en", 4, 44));
1123        d.extend([0, b'D', 0, b'E', 0, b'E', 0, b'N']);
1124        assert_eq!(parse_text(&d), "EN");
1125        // A record size of u32::MAX: the second record lies past any file, so the first is used.
1126        d[12..16].copy_from_slice(&be(u32::MAX));
1127        assert_eq!(parse_text(&d), "DE");
1128        // No records at all.
1129        let mut d = b"mluc\0\0\0\0".to_vec();
1130        d.extend(be(u32::MAX));
1131        d.extend(be(u32::MAX));
1132        assert_eq!(parse_text(&d), "");
1133    }
1134}