f-office-paint 0.2.1

Display list: the contract between layout and output.
Documentation
//! The ICC profiles that picture files embed and that the picture decode does not apply.

use std::ops::Range;

use crate::ImageFormat;

/// The signature of a PNG file (ISO/IEC 15948, clause 5.2).
const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];

/// The bytes of a PNG chunk around its data: its length, its type and its CRC.
const PNG_CHUNK_FRAME: usize = 12;

/// The start of the data of an APP2 segment that holds a piece of an ICC profile (ICC.1,
/// Annex B.4).
const JPEG_PROFILE_MARK: &[u8] = b"ICC_PROFILE\0";

/// The file `data` of a PNG image, or of a JPEG image of one or three components, without the
/// ICC profile that it embeds, or `None` when it embeds none, when it is a JPEG file of four
/// components, whose CMYK profile the picture decode applies, when it has another format, or
/// when its chunks or segments do not read. The picture decode draws the stored colors of such a
/// file whatever profile it embeds; an output that hands the file to a library that would keep
/// the profile hands it this file instead, and draws the same colors.
#[must_use]
pub fn without_profile(data: &[u8], format: ImageFormat) -> Option<Vec<u8>> {
    let profiles = match format {
        ImageFormat::Png => png_profiles(data)?,
        ImageFormat::Jpeg => jpeg_profiles(data)?,
        ImageFormat::Gif
        | ImageFormat::Bmp
        | ImageFormat::Tiff
        | ImageFormat::Emf
        | ImageFormat::Wmf
        | ImageFormat::EffectPicture
        | ImageFormat::Unknown => return None,
    };
    if profiles.is_empty() {
        return None;
    }
    let mut kept = Vec::with_capacity(data.len());
    let mut at = 0;
    for profile in profiles {
        kept.extend_from_slice(data.get(at..profile.start)?);
        at = profile.end;
    }
    kept.extend_from_slice(data.get(at..)?);
    Some(kept)
}

/// The byte ranges of the iCCP chunks of a PNG file (ISO/IEC 15948, clause 11.3.3.3), which
/// come before its image data.
fn png_profiles(data: &[u8]) -> Option<Vec<Range<usize>>> {
    if *data.first_chunk::<8>()? != PNG_SIGNATURE {
        return None;
    }
    let mut at = PNG_SIGNATURE.len();
    let mut profiles = Vec::new();
    loop {
        let (length, rest) = data.get(at..)?.split_first_chunk::<4>()?;
        let kind = rest.first_chunk::<4>()?;
        let length = usize::try_from(u32::from_be_bytes(*length)).ok()?;
        let end = at.checked_add(PNG_CHUNK_FRAME)?.checked_add(length)?;
        match kind {
            b"iCCP" => profiles.push(at..end),
            b"IDAT" | b"IEND" => return Some(profiles),
            _ => {}
        }
        at = end;
    }
}

/// What a marker segment of a JPEG file before its first scan says about the file's profile.
enum Segment {
    /// A piece of the ICC profile.
    Profile,
    /// The frame header, with the number of components.
    Frame(u8),
    /// The start of the first scan.
    Scan,
    /// Any other segment.
    Other,
}

impl Segment {
    /// The segment of `marker` whose data is `body`, or `None` for a frame header too short to
    /// hold the number of components.
    fn of(marker: u8, body: &[u8]) -> Option<Self> {
        Some(match marker {
            0xE2 if body.starts_with(JPEG_PROFILE_MARK) => Self::Profile,
            // The frame headers SOF0 to SOF15, without DHT (C4), JPG (C8) and DAC (CC); the
            // number of components follows the precision, the height and the width.
            0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => Self::Frame(*body.get(5)?),
            0xDA => Self::Scan,
            _ => Self::Other,
        })
    }
}

/// The marker and the byte range of the marker segment of a JPEG file at `at`, after the fill
/// bytes before its marker.
fn jpeg_segment(data: &[u8], mut at: usize) -> Option<(u8, Range<usize>)> {
    loop {
        let (&[prefix, marker], rest) = data.get(at..)?.split_first_chunk::<2>()?;
        if prefix != 0xFF {
            return None;
        }
        if marker != 0xFF {
            let length = usize::from(u16::from_be_bytes(*rest.first_chunk::<2>()?));
            return Some((marker, at..at.checked_add(2)?.checked_add(length)?));
        }
        // A fill byte before a marker.
        at = at.checked_add(1)?;
    }
}

/// The number of components of a JPEG file, from its frame header, or `None` when its
/// segments do not read up to the frame header.
pub(super) fn jpeg_components(data: &[u8]) -> Option<u8> {
    if *data.first_chunk::<2>()? != [0xFF, 0xD8] {
        return None;
    }
    let mut at = 2;
    loop {
        let (marker, segment) = jpeg_segment(data, at)?;
        at = segment.end;
        match Segment::of(
            marker,
            data.get(segment.start.checked_add(4)?..segment.end)?,
        )? {
            Segment::Frame(components) => return Some(components),
            Segment::Scan => return None,
            Segment::Profile | Segment::Other => {}
        }
    }
}

/// The byte ranges of the APP2 segments of a JPEG file that hold the pieces of its ICC profile,
/// before its first scan, or `None` for a file of four components.
fn jpeg_profiles(data: &[u8]) -> Option<Vec<Range<usize>>> {
    if *data.first_chunk::<2>()? != [0xFF, 0xD8] {
        return None;
    }
    let mut at = 2;
    let mut profiles = Vec::new();
    loop {
        let (marker, segment) = jpeg_segment(data, at)?;
        at = segment.end;
        match Segment::of(
            marker,
            data.get(segment.start.checked_add(4)?..segment.end)?,
        )? {
            Segment::Profile => profiles.push(segment),
            Segment::Frame(4) => return None,
            Segment::Scan => return Some(profiles),
            Segment::Frame(_) | Segment::Other => {}
        }
    }
}

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

    fn png_chunk(kind: [u8; 4], data: &[u8]) -> Vec<u8> {
        let mut chunk = u32::try_from(data.len()).unwrap().to_be_bytes().to_vec();
        chunk.extend_from_slice(&kind);
        chunk.extend_from_slice(data);
        // The CRC, which the walk does not read.
        chunk.extend_from_slice(&[0; 4]);
        chunk
    }

    fn png(profile: bool) -> Vec<u8> {
        let mut file = PNG_SIGNATURE.to_vec();
        file.extend(png_chunk(
            *b"IHDR",
            &[0, 0, 0, 1, 0, 0, 0, 1, 8, 2, 0, 0, 0],
        ));
        if profile {
            file.extend(png_chunk(*b"iCCP", b"p\0\0compressed"));
        }
        file.extend(png_chunk(*b"gAMA", &[0, 0, 0xB1, 0x8F]));
        file.extend(png_chunk(*b"IDAT", &[1, 2, 3]));
        file.extend(png_chunk(*b"IEND", &[]));
        file
    }

    fn jpeg_segment(marker: u8, data: &[u8]) -> Vec<u8> {
        let mut segment = vec![0xFF, marker];
        segment.extend_from_slice(&u16::try_from(data.len() + 2).unwrap().to_be_bytes());
        segment.extend_from_slice(data);
        segment
    }

    fn jpeg(components: u8, profile: bool) -> Vec<u8> {
        let mut file = vec![0xFF, 0xD8];
        file.extend(jpeg_segment(0xE0, b"JFIF\0\x01\x01\0\0\x01\0\x01\0\0"));
        if profile {
            file.extend(jpeg_segment(0xE2, b"ICC_PROFILE\0\x01\x01bytes"));
        }
        let mut frame = vec![8, 0, 1, 0, 1, components];
        frame.extend((1..=components).flat_map(|id| [id, 0x11, 0]));
        file.extend(jpeg_segment(0xC0, &frame));
        file.extend(jpeg_segment(0xDA, &[1, 1, 0, 0, 0x3F, 0]));
        file.extend_from_slice(&[0x12, 0x34, 0xFF, 0xD9]);
        file
    }

    #[test]
    fn a_png_file_loses_its_icc_chunk_and_keeps_every_other_chunk() {
        assert_eq!(
            without_profile(&png(true), ImageFormat::Png),
            Some(png(false))
        );
        assert_eq!(without_profile(&png(false), ImageFormat::Png), None);
    }

    #[test]
    fn a_jpeg_file_of_one_or_three_components_loses_its_profile_segments() {
        for components in [1, 3] {
            assert_eq!(
                without_profile(&jpeg(components, true), ImageFormat::Jpeg),
                Some(jpeg(components, false))
            );
            assert_eq!(
                without_profile(&jpeg(components, false), ImageFormat::Jpeg),
                None
            );
        }
    }

    #[test]
    fn a_jpeg_file_of_four_components_keeps_its_profile() {
        assert_eq!(without_profile(&jpeg(4, true), ImageFormat::Jpeg), None);
    }

    #[test]
    fn the_frame_header_gives_the_components_of_a_jpeg_file() {
        for components in [1, 3, 4] {
            assert_eq!(jpeg_components(&jpeg(components, true)), Some(components));
        }
        assert_eq!(jpeg_components(&png(true)), None);
        let mut short = jpeg(4, false);
        short.truncate(10);
        assert_eq!(jpeg_components(&short), None);
    }

    #[test]
    fn a_file_that_does_not_read_or_has_another_format_stays_as_it_is() {
        let mut cut = png(true);
        cut.truncate(PNG_SIGNATURE.len() + 30);
        assert_eq!(without_profile(&cut, ImageFormat::Png), None);
        assert_eq!(without_profile(&png(true), ImageFormat::Jpeg), None);
        assert_eq!(without_profile(&jpeg(3, true), ImageFormat::Png), None);
        assert_eq!(without_profile(&png(true), ImageFormat::Gif), None);
        let mut short = jpeg(3, true);
        short.truncate(8);
        assert_eq!(without_profile(&short, ImageFormat::Jpeg), None);
    }
}