f-office-paint 0.2.3

Display list: the contract between layout and output.
Documentation
//! Hand-written sample files for picture decode tests,
//! behind the feature `files`: a baseline JPEG file of four components whose blocks each hold
//! one value (ITU-T T.81), and a CMYK profile of ICC version 2.1 for an output device, from its
//! tags.

/// The pixels across and down of a block of a JPEG file.
pub const BLOCK: u16 = 8;
/// The one quantizer of the JPEG file's table: the DC coefficient of a block of one value `v`
/// is `8 × (v − 128)` (T.81, A.3.3), so it quantizes to `v − 128` exactly.
const QUANTIZER: u8 = 8;
/// The codes of the DC categories 0 to 11: 4 bits each, the category's own number, as T.81's
/// Annex C gives the codes of 12 symbols of length 4 in order.
const CATEGORIES: u8 = 12;
const CATEGORY_BITS: u32 = 4;
/// The header of an ICC profile, and the bytes of one entry of its tag table (ICC.1, 7.2 and
/// 7.3).
const HEADER: usize = 128;
const TAG_ENTRY: usize = 12;
/// D50, the illuminant of the connection space, in `s15Fixed16Number`s (ICC.1, 7.2.16).
const D50: [i32; 3] = [0xF6D6, 0x1_0000, 0xD32D];
/// One in `s15Fixed16Number`.
const ONE: i32 = 0x1_0000;

/// A baseline JPEG file of `size` pixels across and down, each a multiple of [`BLOCK`], whose
/// four components hold at every pixel of the block in column `x` and row `y` the values
/// `block(x, y)`, with an Adobe segment of the transform `transform` (0 for CMYK, 2 for YCCK)
/// and `profile` in one `APP2` segment (ICC.1, Annex B.4), if any. Each component has a
/// sampling of 1 by 1, so that a block of each makes one MCU, and each block has only a DC
/// coefficient. `None` when a side is no multiple of [`BLOCK`] or a segment is longer than its
/// length field.
#[must_use]
pub fn four_component_jpeg(
    size: (u16, u16),
    transform: u8,
    profile: Option<&[u8]>,
    block: impl Fn(u16, u16) -> [u8; 4],
) -> Option<Vec<u8>> {
    let (width, height) = size;
    if width % BLOCK != 0 || height % BLOCK != 0 {
        return None;
    }
    let mut file = vec![0xFF, 0xD8];
    let adobe = [
        b"Adobe".as_slice(),
        &100_u16.to_be_bytes(),
        &[0, 0, 0, 0, transform],
    ];
    segment(&mut file, 0xEE, &adobe.concat())?;
    if let Some(profile) = profile {
        segment(
            &mut file,
            0xE2,
            &[b"ICC_PROFILE\0".as_slice(), &[1, 1], profile].concat(),
        )?;
    }
    for (marker, data) in tables(size) {
        segment(&mut file, marker, &data)?;
    }
    let mut bits = Vec::new();
    let mut before = [0_i32; 4];
    for y in 0..height / BLOCK {
        for x in 0..width / BLOCK {
            for (value, last) in block(x, y).into_iter().zip(before.iter_mut()) {
                let level = i32::from(value) - 128;
                put_difference(&mut bits, level - *last);
                *last = level;
            }
        }
    }
    file.extend(entropy(&bits));
    file.extend([0xFF, 0xD9]);
    Some(file)
}

/// A JPEG file of 8 by 8 pixels whose four components hold the values `stored` at every pixel:
/// [`four_component_jpeg`] of one block.
#[must_use]
pub fn cmyk_jpeg(stored: [u8; 4], transform: u8, profile: Option<&[u8]>) -> Option<Vec<u8>> {
    four_component_jpeg((BLOCK, BLOCK), transform, profile, |_, _| stored)
}

/// The segments after the application segments: the quantization table, the frame of four
/// components of `size` with a sampling of 1 by 1, the DC table of the categories 0 to 11 and
/// the AC table of the end of block alone, and the scan of the four components (T.81, B.2).
fn tables((width, height): (u16, u16)) -> [(u8, Vec<u8>); 5] {
    let components = 1..=4_u8;
    let quantization = [[0].as_slice(), &[QUANTIZER; 64]].concat();
    let mut frame = vec![8];
    frame.extend(height.to_be_bytes());
    frame.extend(width.to_be_bytes());
    frame.push(4);
    frame.extend(
        components
            .clone()
            .flat_map(|component| [component, 0x11, 0]),
    );
    let mut dc = vec![0x00, 0, 0, 0, CATEGORIES];
    dc.extend([0; 12]);
    dc.extend(0..CATEGORIES);
    let ac = [[0x10, 1].as_slice(), &[0; 15], &[0x00]].concat();
    let mut scan = vec![4];
    scan.extend(components.flat_map(|component| [component, 0x00]));
    scan.extend([0, 63, 0]);
    [
        (0xDB, quantization),
        (0xC0, frame),
        (0xC4, dc),
        (0xC4, ac),
        (0xDA, scan),
    ]
}

/// Puts the bits of one block: the DC difference `difference` in its category's code and bits,
/// then the end of the block.
fn put_difference(bits: &mut Vec<bool>, difference: i32) {
    let category = 32 - difference.unsigned_abs().leading_zeros();
    put(bits, category, CATEGORY_BITS);
    // T.81, F.1.2.1: a negative difference is sent as its value minus 1 in its category's bits.
    let extra = if difference < 0 {
        difference - 1
    } else {
        difference
    };
    put(bits, extra.cast_unsigned(), category);
    // The end of the block: the one code of the AC table, a 0 bit.
    bits.push(false);
}

/// Writes the segment of `marker` with `data` and its length.
fn segment(file: &mut Vec<u8>, marker: u8, data: &[u8]) -> Option<()> {
    file.extend([0xFF, marker]);
    file.extend(u16::try_from(data.len() + 2).ok()?.to_be_bytes());
    file.extend(data);
    Some(())
}

/// Puts the `count` lowest bits of `value`, the highest first.
fn put(bits: &mut Vec<bool>, value: u32, count: u32) {
    bits.extend((0..count).rev().map(|bit| (value >> bit) & 1 == 1));
}

/// The bytes of entropy-coded data: the bits, the last byte filled with 1 bits, and a 0 byte
/// after each byte 0xFF (T.81, F.1.2.3 and B.1.1.5).
fn entropy(bits: &[bool]) -> Vec<u8> {
    let mut bytes = Vec::new();
    for chunk in bits.chunks(8) {
        let mut byte = u8::MAX;
        for (place, bit) in chunk.iter().enumerate() {
            if !bit {
                byte &= !(0x80 >> place);
            }
        }
        bytes.push(byte);
        if byte == u8::MAX {
            bytes.push(0);
        }
    }
    bytes
}

/// A CMYK profile of ICC version 2.1 for an output device, with Lab as its connection space,
/// the rendering intent `header_intent` in its header (0 perceptual, 1 relative colorimetric,
/// 2 saturation, 3 absolute colorimetric) and D50 as its illuminant, which holds `tags`, each
/// a signature and the tag's bytes, in their order, each starting on a multiple of 4 bytes.
/// `None` when a length does not fit in its field.
#[must_use]
pub fn icc_profile(tags: &[(&[u8; 4], Vec<u8>)], header_intent: u8) -> Option<Vec<u8>> {
    let mut table = u32::try_from(tags.len()).ok()?.to_be_bytes().to_vec();
    let mut data = Vec::new();
    let start = HEADER + 4 + TAG_ENTRY * tags.len();
    for (signature, tag) in tags {
        table.extend(*signature);
        table.extend(u32::try_from(start + data.len()).ok()?.to_be_bytes());
        table.extend(u32::try_from(tag.len()).ok()?.to_be_bytes());
        data.extend(tag);
        data.resize(data.len().next_multiple_of(4), 0);
    }
    let size = u32::try_from(HEADER + table.len() + data.len()).ok()?;
    let mut profile = header(size, header_intent);
    profile.extend(table);
    profile.extend(data);
    Some(profile)
}

/// The 128 bytes of the header of [`icc_profile`], of `size` bytes in all (ICC.1, 7.2).
fn header(size: u32, intent: u8) -> Vec<u8> {
    let mut profile = size.to_be_bytes().to_vec();
    profile.extend([0; 4]);
    profile.extend([2, 0x10, 0, 0]);
    profile.extend(b"prtrCMYKLab ");
    for part in [2026_u16, 11, 19, 0, 0, 0] {
        profile.extend(part.to_be_bytes());
    }
    profile.extend(b"acsp");
    profile.resize(64, 0);
    profile.extend(u32::from(intent).to_be_bytes());
    profile.extend(D50.iter().flat_map(|value| value.to_be_bytes()));
    profile.resize(HEADER, 0);
    profile
}

/// A CMYK profile ([`icc_profile`], perceptual intent) whose `A2B0` tag (`lut8Type`,
/// ICC.1:2001-04, 6.5.8) maps the ink amounts through a table of 2 points on each input, whose
/// entry at each corner of the ink cube is `corner` of whether each of cyan, magenta, yellow and
/// black is full there, in the 8-bit encoding of Lab (L × 255 / 100, a + 128, b + 128); its
/// media white point is D50. `None` when a length does not fit in its field.
#[must_use]
pub fn cmyk_profile(corner: impl Fn([bool; 4]) -> [u8; 3]) -> Option<Vec<u8>> {
    let mut white = b"XYZ \0\0\0\0".to_vec();
    white.extend(D50.iter().flat_map(|value| value.to_be_bytes()));
    icc_profile(&[(b"A2B0", lut(corner)), (b"wtpt", white)], 0)
}

/// The `lut8Type` of [`cmyk_profile`]: 4 inputs, 3 outputs and 2 points on each input, the
/// identity matrix, input and output tables that keep each value, and the table of `corner`,
/// in which the first input changes slowest.
fn lut(corner: impl Fn([bool; 4]) -> [u8; 3]) -> Vec<u8> {
    let mut lut = b"mft1\0\0\0\0".to_vec();
    lut.extend([4, 3, 2, 0]);
    for entry in 0..9 {
        let value = if entry % 4 == 0 { ONE } else { 0 };
        lut.extend(value.to_be_bytes());
    }
    for _ in 0..4 {
        lut.extend(0..=u8::MAX);
    }
    for index in 0..16_u8 {
        let full = [index & 8, index & 4, index & 2, index & 1].map(|bit| bit != 0);
        lut.extend(corner(full));
    }
    for _ in 0..3 {
        lut.extend(0..=u8::MAX);
    }
    lut
}