GitCorner

Code

ossartcrafttexturecraft🌐
d84914ef1e5a
//! ICC v2.1 export policy; byte serialization is shared with craft-cms.
use craft_cms_icc_v2::write_v2::{MatrixProfile, ToneCurve, matrix_profile};
use texturecraft_texel::{ColorSpace, srgb_to_linear};
const CURVE_POINTS: usize = 1024;

fn description(space: ColorSpace) -> &'static str {
    match space {
        ColorSpace::Srgb => "sRGB (Rec.709 primaries, sRGB curve)",
        ColorSpace::LinearRec709 => "Linear Rec.709 (sRGB primaries, D65)",
        ColorSpace::AcesCg => "ACEScg (AP1 primaries, linear)",
        ColorSpace::Aces2065 => "ACES2065-1 (AP0 primaries, linear)",
    }
}

/// The ICC profile of `space`, or None if its primaries are degenerate.
pub fn profile(space: ColorSpace) -> Option<Vec<u8>> {
    let matrix = space.to_xyz_d50()?;
    let samples: Vec<u16> = if space == ColorSpace::Srgb {
        (0..CURVE_POINTS)
            .map(|i| {
                let v = f64::from(srgb_to_linear(i as f32 / (CURVE_POINTS - 1) as f32));
                (v * 65535.0).round().clamp(0.0, 65535.0) as u16
            })
            .collect()
    } else {
        Vec::new()
    };
    matrix_profile(&MatrixProfile {
        matrix,
        curve: if samples.is_empty() { ToneCurve::Linear } else { ToneCurve::Samples(&samples) },
        description: description(space),
        copyright: "No copyright, generated by TextureCraft",
        date: [2026, 1, 1, 0, 0, 0],
    })
}

#[cfg(test)]
#[path = "icc_legacy_test.rs"]
mod legacy;

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn all_spaces_match_legacy_wire_bytes() {
        for space in ColorSpace::ALL {
            assert_eq!(profile(space), legacy::profile(space), "{space:?}");
        }
    }

    fn u32_at(b: &[u8], i: usize) -> u32 {
        u32::from_be_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]])
    }

    /// The data of the tag `sig` in a profile.
    fn tag<'a>(p: &'a [u8], sig: &[u8; 4]) -> &'a [u8] {
        let n = u32_at(p, 128) as usize;
        for k in 0..n {
            let e = 132 + 12 * k;
            if &p[e..e + 4] == sig {
                let (at, len) = (u32_at(p, e + 4) as usize, u32_at(p, e + 8) as usize);
                return &p[at..at + len];
            }
        }
        panic!("no {sig:?} tag");
    }

    fn xyz(t: &[u8]) -> [f64; 3] {
        [8, 12, 16].map(|i| f64::from(u32_at(t, i) as i32) / 65536.0)
    }

    #[test]
    fn every_profile_is_well_formed() {
        for s in ColorSpace::ALL {
            let p = profile(s).unwrap();
            assert_eq!(u32_at(&p, 0) as usize, p.len(), "{s:?}: the header names the real size");
            assert_eq!(&p[36..40], b"acsp");
            assert_eq!(&p[12..24], b"mntrRGB XYZ ");
            let n = u32_at(&p, 128) as usize;
            assert_eq!(n, 9);
            for k in 0..n {
                let e = 132 + 12 * k;
                let (at, len) = (u32_at(&p, e + 4) as usize, u32_at(&p, e + 8) as usize);
                assert!(at.is_multiple_of(4) && at >= 132 + 12 * n && at + len <= p.len(), "{s:?} tag {k}: {at}+{len} of {}", p.len());
            }
            assert_eq!(profile(s).unwrap(), p, "the same bytes every time");
        }
    }

    #[test]
    fn colorants_add_up_to_d50_and_the_curves_are_right() {
        for s in ColorSpace::ALL {
            let p = profile(s).unwrap();
            let (r, g, b) = (xyz(tag(&p, b"rXYZ")), xyz(tag(&p, b"gXYZ")), xyz(tag(&p, b"bXYZ")));
            let sum = [0, 1, 2].map(|i| r[i] + g[i] + b[i]);
            assert!((sum[0] - 0.9642).abs() < 1e-3 && (sum[1] - 1.0).abs() < 1e-3 && (sum[2] - 0.8249).abs() < 1e-3, "{s:?} {sum:?}");
            let curve = tag(&p, b"rTRC");
            let count = u32_at(curve, 8) as usize;
            if s == ColorSpace::Srgb {
                assert_eq!(count, CURVE_POINTS);
                let at = |i: usize| f64::from(u16::from_be_bytes([curve[12 + 2 * i], curve[13 + 2 * i]])) / 65535.0;
                assert_eq!((at(0), at(CURVE_POINTS - 1)), (0.0, 1.0));
                // 0.5 encoded is 0.214 linear.
                assert!((at((CURVE_POINTS - 1) / 2) - 0.2140).abs() < 2e-3, "{}", at((CURVE_POINTS - 1) / 2));
            } else {
                assert_eq!((count, u16::from_be_bytes([curve[12], curve[13]])), (1, 0x0100), "{s:?}: a gamma of 1");
            }
        }
        let srgb = profile(ColorSpace::Srgb).unwrap();
        let red = xyz(tag(&srgb, b"rXYZ"));
        assert!((red[0] - 0.4361).abs() < 2e-3 && (red[1] - 0.2225).abs() < 2e-3 && (red[2] - 0.0139).abs() < 2e-3, "{red:?}");
    }
}