rosier 0.5.0

A fast picture and video viewer for large folders
//! Color management for pictures: a picture with an embedded ICC profile
//! (Display P3 from phones, Adobe RGB from cameras, ProPhoto from editors)
//! is converted to sRGB, the space the window is drawn in. Without this,
//! wide-gamut pictures look dull and their hues drift.
//!
//! The profile is read from JPEG (APP2), PNG (iCCP), WebP (ICCP) and TIFF;
//! the conversion is moxcms (pure Rust, already in the build through the
//! image crate). Pictures without a profile, or whose profile already is
//! sRGB, are left as they are.

use moxcms::{ColorProfile, DataColorSpace, Layout, TransformOptions};

use crate::turbo::Bgra;

/// The ICC profile embedded in an encoded picture, if any.
pub fn embedded(data: &[u8]) -> Option<Vec<u8>> {
    if data.starts_with(&[0xFF, 0xD8]) {
        return jpeg_profile(data);
    }
    if data.len() > 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP" {
        return riff_chunk(&data[12..], b"ICCP").map(<[u8]>::to_vec);
    }
    use image::ImageDecoder as _;
    let mut decoder =
        image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format().ok()?.into_decoder().ok()?;
    decoder.icc_profile().ok().flatten()
}

/// Joins the "ICC_PROFILE" APP2 segments of a JPEG, in their numbered order.
fn jpeg_profile(data: &[u8]) -> Option<Vec<u8>> {
    let mut parts: Vec<(u8, &[u8])> = Vec::new();
    let mut i = 2;
    while i + 4 <= data.len() && data[i] == 0xFF {
        let marker = data[i + 1];
        // Start of scan: no more headers.
        if marker == 0xDA {
            break;
        }
        let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
        let body = data.get(i + 4..i + 2 + len)?;
        if marker == 0xE2 && body.len() > 14 && body.starts_with(b"ICC_PROFILE\0") {
            parts.push((body[12], &body[14..]));
        }
        i += 2 + len;
    }
    if parts.is_empty() {
        return None;
    }
    parts.sort_by_key(|p| p.0);
    Some(parts.into_iter().flat_map(|p| p.1.iter().copied()).collect())
}

/// The body of the first `id` chunk in a RIFF chunk list.
fn riff_chunk<'a>(mut d: &'a [u8], id: &[u8; 4]) -> Option<&'a [u8]> {
    while d.len() >= 8 {
        let len = u32::from_le_bytes([d[4], d[5], d[6], d[7]]) as usize;
        let body = d.get(8..8 + len)?;
        if &d[..4] == id {
            return Some(body);
        }
        // Chunks are padded to an even length.
        d = d.get(8 + len + (len & 1)..)?;
    }
    None
}

/// Converts `b` from the color space `icc` describes to sRGB, in place.
/// Returns whether anything changed: false for profiles that are not RGB,
/// that cannot be read, or that already are sRGB.
fn to_srgb(b: &mut Bgra, icc: &[u8]) -> bool {
    let Ok(src) = ColorProfile::new_from_slice(icc) else { return false };
    if src.color_space != DataColorSpace::Rgb {
        return false;
    }
    let Ok(t) =
        src.create_transform_8bit(Layout::Rgba, &ColorProfile::new_srgb(), Layout::Rgba, TransformOptions::default())
    else {
        return false;
    };
    // An sRGB profile (most cameras and the web) maps every color to
    // itself: skip the work.
    const PROBES: [[u8; 4]; 6] = [
        [255, 0, 0, 255],
        [0, 255, 0, 255],
        [0, 0, 255, 255],
        [128, 128, 128, 255],
        [250, 200, 40, 255],
        [20, 90, 160, 255],
    ];
    let probe: Vec<u8> = PROBES.concat();
    let mut out = vec![0u8; probe.len()];
    if t.transform(&probe, &mut out).is_err() {
        return false;
    }
    if probe.iter().zip(&out).all(|(a, b)| a.abs_diff(*b) <= 1) {
        return false;
    }
    // BGRA in, BGRA out: swap to RGBA around the transform.
    let swap = |px: &mut [u8]| {
        for p in px.as_chunks_mut::<4>().0 {
            p.swap(0, 2);
        }
    };
    swap(&mut b.pixels);
    let mut dst = vec![0u8; b.pixels.len()];
    let ok = t.transform(&b.pixels, &mut dst).is_ok();
    if ok {
        b.pixels = dst;
    }
    swap(&mut b.pixels);
    ok
}

/// Converts `b` to sRGB if the encoded picture `data` carries a profile.
pub fn correct(data: &[u8], mut b: Bgra) -> Bgra {
    if let Some(icc) = embedded(data) {
        to_srgb(&mut b, &icc);
    }
    b
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;

    /// A JPEG of one flat color with `icc` embedded in an APP2 segment.
    pub fn jpeg_with_profile(rgb: [u8; 3], icc: &[u8]) -> Vec<u8> {
        let mut img = Vec::new();
        image::RgbImage::from_pixel(16, 16, image::Rgb(rgb))
            .write_to(&mut std::io::Cursor::new(&mut img), image::ImageFormat::Jpeg)
            .unwrap();
        let mut seg = b"ICC_PROFILE\0\x01\x01".to_vec();
        seg.extend_from_slice(icc);
        let mut out = img[..2].to_vec();
        out.extend_from_slice(&[0xFF, 0xE2]);
        out.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
        out.extend_from_slice(&seg);
        out.extend_from_slice(&img[2..]);
        out
    }

    #[test]
    fn display_p3_red_becomes_a_redder_srgb_red_than_its_numbers() {
        let p3 = ColorProfile::new_display_p3().encode().unwrap();
        let jpeg = jpeg_with_profile([200, 30, 30], &p3);
        assert_eq!(embedded(&jpeg).as_deref(), Some(p3.as_slice()));
        let mut b = Bgra { width: 1, height: 1, pixels: vec![30, 30, 200, 255] };
        assert!(to_srgb(&mut b, &p3));
        let [bl, g, r, a] = [b.pixels[0], b.pixels[1], b.pixels[2], b.pixels[3]];
        // P3's red is more saturated than sRGB's: in sRGB numbers the red
        // goes up and green and blue go down (toward or below 0).
        assert!(r > 200 && g < 30 && bl < 30 && a == 255, "{:?}", b.pixels);
    }

    #[test]
    fn srgb_and_missing_profiles_leave_pixels_alone() {
        let srgb = ColorProfile::new_srgb().encode().unwrap();
        let mut b = Bgra { width: 1, height: 1, pixels: vec![30, 60, 200, 255] };
        assert!(!to_srgb(&mut b, &srgb));
        assert!(!to_srgb(&mut b, b"not a profile"));
        assert_eq!(b.pixels, vec![30, 60, 200, 255]);
        let mut plain = Vec::new();
        image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut plain), image::ImageFormat::Jpeg).unwrap();
        assert_eq!(embedded(&plain), None);
        let mut png = Vec::new();
        image::RgbImage::new(4, 4).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
        assert_eq!(embedded(&png), None);
    }

    #[test]
    fn reads_a_profile_split_over_several_app2_segments() {
        let mut data = vec![0xFF, 0xD8];
        for (n, part) in [(2u8, &b"world"[..]), (1, &b"hello "[..])] {
            let mut seg = b"ICC_PROFILE\0".to_vec();
            seg.extend_from_slice(&[n, 2]);
            seg.extend_from_slice(part);
            data.extend_from_slice(&[0xFF, 0xE2]);
            data.extend_from_slice(&((seg.len() + 2) as u16).to_be_bytes());
            data.extend_from_slice(&seg);
        }
        data.extend_from_slice(&[0xFF, 0xDA, 0, 2]);
        assert_eq!(embedded(&data).as_deref(), Some(&b"hello world"[..]));
    }

    #[test]
    fn finds_the_iccp_chunk_of_a_webp() {
        let mut d = b"RIFF\0\0\0\0WEBP".to_vec();
        d.extend_from_slice(b"VP8X");
        d.extend_from_slice(&10u32.to_le_bytes());
        d.extend_from_slice(&[0; 10]);
        d.extend_from_slice(b"ICCP");
        d.extend_from_slice(&3u32.to_le_bytes());
        d.extend_from_slice(b"abc\0");
        assert_eq!(embedded(&d).as_deref(), Some(&b"abc"[..]));
    }
}