f-office-paint 0.2.3

Display list: the contract between layout and output.
Documentation
//! TIFF files of 8-bit palette pixels (TIFF 6.0, section 5, "Palette-color Images"), which the
//! `image` crate does not decode: it has no color type for them, and the `tiff` crate under it
//! refuses them. The `tiff` crate reads the file's first IFD and its `ColorMap`. A copy of the file
//! whose `PhotometricInterpretation` says gray goes to the `image` crate, which reads the indices
//! as 8-bit gray samples, and the `ColorMap` expands them.
//!
//! TIFF 6.0 stores the 8-bit indices of a palette image as it stores the 8-bit samples of a gray
//! image (section 5: like a grayscale image, one component a pixel, used as an index into the
//! `ColorMap`), with the same compression, predictor and strips, so only the one tag's value
//! changes in the copy.

use std::io::Cursor;

use image::{DynamicImage, RgbImage};
use tiff::decoder::Decoder;
use tiff::tags::{ByteOrder, PhotometricInterpretation, Tag, Type};

use crate::ImageFault;

/// The bits of an index, the one depth that the decode reads.
const INDEX_BITS: u16 = 8;
/// The values of the `ColorMap` for each of red, green and blue: one for each 8-bit index.
const INDICES: usize = 1 << INDEX_BITS;
/// The version in the header of a classic TIFF file, at byte 2 (TIFF 6.0, section 2).
const CLASSIC_VERSION: u16 = 42;
/// The place of the version in the header.
const VERSION_AT: u64 = 2;
/// The bytes of the count of entries at the start of a classic IFD, and of one entry: a tag, a
/// type, a count and a value (TIFF 6.0, section 2).
const COUNT_BYTES: u64 = 2;
const ENTRY_BYTES: u64 = 12;
/// The place of an entry's value within the entry.
const VALUE_AT: u64 = 8;
/// The full intensity of a `ColorMap` value (TIFF 6.0, section 5: 0 is none, 65,535 the most).
const FULL_INTENSITY: u32 = 65_535;

/// A TIFF file of 8-bit palette pixels: a copy of the file that says gray, and the color of
/// each index.
pub(super) struct Palette {
    gray_file: Vec<u8>,
    colors: Vec<[u8; 3]>,
}

impl Palette {
    /// Reads `data` as a TIFF file whose first IFD says palette pixels: `None` for any other
    /// TIFF file, and for a file that the `tiff` crate does not read, which the `image` crate
    /// then reads or refuses as before.
    ///
    /// # Errors
    ///
    /// [`ImageFault::Data`] for a palette file that the decode does not read: indices of other
    /// than 8 bits, more than one sample, no `ColorMap` of 3 × 256 values, or an IFD whose entry
    /// of the `PhotometricInterpretation` is not where a classic TIFF file in tag order keeps it.
    pub(super) fn read(data: &[u8]) -> Result<Option<Self>, ImageFault> {
        let Ok(mut decoder) = Decoder::new(Cursor::new(data)) else {
            return Ok(None);
        };
        let palette = PhotometricInterpretation::RGBPalette.to_u16();
        if decoder
            .find_tag_unsigned::<u16>(Tag::PhotometricInterpretation)
            .ok()
            .flatten()
            != Some(palette)
        {
            return Ok(None);
        }
        let bits = decoder
            .find_tag_unsigned_vec::<u16>(Tag::BitsPerSample)
            .map_err(|_| ImageFault::Data)?
            .unwrap_or_else(|| vec![1]);
        let samples = decoder
            .find_tag_unsigned::<u16>(Tag::SamplesPerPixel)
            .map_err(|_| ImageFault::Data)?
            .unwrap_or(1);
        if bits != [INDEX_BITS] || samples != 1 {
            return Err(ImageFault::Data);
        }
        let color_map = decoder
            .get_tag_u16_vec(Tag::ColorMap)
            .map_err(|_| ImageFault::Data)?;
        let colors = colors(&color_map).ok_or(ImageFault::Data)?;
        let value = photometric_value(&mut decoder).ok_or(ImageFault::Data)?;
        let gray = PhotometricInterpretation::BlackIsZero.to_u16();
        let gray = match decoder.byte_order() {
            ByteOrder::LittleEndian => gray.to_le_bytes(),
            ByteOrder::BigEndian => gray.to_be_bytes(),
        };
        let mut gray_file = data.to_vec();
        let end = value.checked_add(gray.len()).ok_or(ImageFault::Data)?;
        gray_file
            .get_mut(value..end)
            .ok_or(ImageFault::Data)?
            .copy_from_slice(&gray);
        Ok(Some(Self { gray_file, colors }))
    }

    /// The copy of the file whose `PhotometricInterpretation` says gray (`BlackIsZero`), for the
    /// `image` crate.
    pub(super) fn gray_file(&self) -> &[u8] {
        &self.gray_file
    }

    /// The RGB pixels of the indices that the `image` crate decoded from the gray copy.
    ///
    /// # Errors
    ///
    /// [`ImageFault::Data`] when the decoded pixels are not 8-bit gray.
    pub(super) fn expand(&self, indices: DynamicImage) -> Result<DynamicImage, ImageFault> {
        let DynamicImage::ImageLuma8(indices) = indices else {
            return Err(ImageFault::Data);
        };
        let (width, height) = indices.dimensions();
        let pixels = indices
            .into_raw()
            .into_iter()
            .map(|index| self.colors.get(usize::from(index)).copied())
            .collect::<Option<Vec<[u8; 3]>>>()
            .ok_or(ImageFault::Data)?;
        RgbImage::from_raw(width, height, pixels.into_flattened())
            .map(DynamicImage::ImageRgb8)
            .ok_or(ImageFault::Data)
    }
}

/// The color of each index from the `ColorMap`'s values: the red values of all indices, then the
/// green ones, then the blue ones, each scaled from 16 to 8 bits and rounded (TIFF 6.0,
/// section 5). `None` unless the `ColorMap` holds 3 × 256 values.
fn colors(color_map: &[u16]) -> Option<Vec<[u8; 3]>> {
    let (planes, []) = color_map.as_chunks::<INDICES>() else {
        return None;
    };
    let [red, green, blue] = planes else {
        return None;
    };
    Some(
        red.iter()
            .zip(green)
            .zip(blue)
            .map(|((&red, &green), &blue)| [red, green, blue].map(eight_bits))
            .collect(),
    )
}

/// A `ColorMap` value of 16 bits scaled to 8 bits, rounded to the nearest.
fn eight_bits(value: u16) -> u8 {
    let scaled = (u32::from(value) * 255 + FULL_INTENSITY / 2) / FULL_INTENSITY;
    u8::try_from(scaled).unwrap_or(u8::MAX)
}

/// The place in the file of the value of the first IFD's entry of the `PhotometricInterpretation`,
/// read through the `tiff` crate: a classic TIFF file keeps the entries of an IFD in ascending
/// order of their tags after their count (TIFF 6.0, section 2), so the entry's place follows
/// from its rank among the IFD's tags. `None` unless the file is a classic TIFF file and the
/// entry at that place holds the tag with one SHORT value.
fn photometric_value(decoder: &mut Decoder<Cursor<&[u8]>>) -> Option<usize> {
    let ifd = decoder.ifd_pointer()?;
    let directory = decoder.read_directory(ifd).ok()?;
    let rank = directory
        .iter()
        .position(|(tag, _)| tag == Tag::PhotometricInterpretation)?;
    let entry = ifd
        .0
        .checked_add(COUNT_BYTES)?
        .checked_add(ENTRY_BYTES.checked_mul(u64::try_from(rank).ok()?)?)?;
    let expected = Guard {
        version: CLASSIC_VERSION,
        count: u16::try_from(directory.len()).ok()?,
        tag: Tag::PhotometricInterpretation.to_u16(),
        kind: Type::SHORT.to_u16(),
        values: 1,
    };
    if Guard::read(decoder, ifd.0, entry)? != expected {
        return None;
    }
    usize::try_from(entry.checked_add(VALUE_AT)?).ok()
}

/// What [`photometric_value`] checks before it names a place: the file's version, the count of
/// the IFD's entries, and the tag, the type and the count of values of the entry at the place.
#[derive(PartialEq, Eq)]
struct Guard {
    version: u16,
    count: u16,
    tag: u16,
    kind: u16,
    values: u32,
}

impl Guard {
    /// Reads the guard's fields through the `tiff` crate, in the file's byte order: the version
    /// in the header, the count at the IFD's place `ifd`, and the entry at the place `entry`.
    fn read(decoder: &mut Decoder<Cursor<&[u8]>>, ifd: u64, entry: u64) -> Option<Self> {
        decoder.goto_offset_u64(VERSION_AT).ok()?;
        let version = decoder.read_short().ok()?;
        decoder.goto_offset_u64(ifd).ok()?;
        let count = decoder.read_short().ok()?;
        decoder.goto_offset_u64(entry).ok()?;
        Some(Self {
            version,
            count,
            tag: decoder.read_short().ok()?,
            kind: decoder.read_short().ok()?,
            values: decoder.read_long().ok()?,
        })
    }
}