f-office-paint 0.2.1

Display list: the contract between layout and output.
Documentation
//! JPEG files of four components: with [`InkConversion::EmbeddedProfile`], the pixels of a file
//! that embeds a CMYK profile (ICC.1, Annex B.4, the profile in `APP2` segments) convert
//! through the profile into sRGB, with the perceptual intent; with
//! [`InkConversion::InkTable`], the pixels of every such file convert through the ink table.
//! The `image` crate turns every file of four components into RGB by multiplying each ink's
//! complement with black's complement, whatever profile the file holds; with the embedded
//! profile, a file without a CMYK profile, or whose profile does not read or convert, still
//! goes that way.
//!
//! The four components hold the complements of the ink amounts, as Adobe's applications write
//! them and as the `image` crate reads them too: 255 is no ink. A CMYK file holds them as
//! they are. A YCCK file, which an Adobe segment with the transform 2 names, holds the
//! complements of cyan, magenta and yellow as the R, G and B of a YCbCr triple and black as it
//! is; the R, G and B of the triple are then the amounts of cyan, magenta and yellow.

use std::sync::Arc;

use image::RgbImage;
use moxcms::{
    ColorProfile, DataColorSpace, Layout, RenderingIntent, Transform8BitExecutor, TransformOptions,
};
use zune_core::bytestream::ZCursor;
use zune_core::colorspace::ColorSpace;
use zune_core::options::DecoderOptions;
use zune_jpeg::JpegDecoder;

use super::ink_table;
use crate::{ImageFault, InkConversion};

/// The values of a pixel of four components, and of an RGB pixel.
const FOUR: usize = 4;
const THREE: usize = 3;

/// What the inks of a file convert through.
enum Through {
    /// The transform of the file's own CMYK profile into sRGB.
    Profile(Arc<Transform8BitExecutor>),
    /// The ink table.
    InkTable,
}

/// Decodes the JPEG file `data` when it holds four components and `inks` converts them: through
/// the ink table always, through the embedded profile when the file embeds a CMYK profile that
/// converts into sRGB. Its RGB pixels, else `None`. The caller has checked the size of its
/// pixels against its limit from the file's header.
///
/// # Errors
///
/// [`ImageFault::Data`] for a header or pixels that do not decode.
pub(super) fn decode(data: &[u8], inks: InkConversion) -> Result<Option<RgbImage>, ImageFault> {
    let mut decoder = JpegDecoder::new_with_options(ZCursor::new(data), options());
    decoder.decode_headers().map_err(|_| ImageFault::Data)?;
    let Some(stored @ (ColorSpace::CMYK | ColorSpace::YCCK)) = decoder.input_colorspace() else {
        return Ok(None);
    };
    let through = match inks {
        InkConversion::EmbeddedProfile => {
            let Some(transform) = decoder.icc_profile().as_deref().and_then(to_srgb) else {
                return Ok(None);
            };
            Through::Profile(transform)
        }
        InkConversion::InkTable => Through::InkTable,
    };
    let (width, height) = decoder.dimensions().ok_or(ImageFault::Data)?;
    decoder.set_options(options().jpeg_set_out_colorspace(stored));
    let mut pixels = decoder.decode().map_err(|_| ImageFault::Data)?;
    to_inks(stored, &mut pixels);
    match through {
        Through::Profile(transform) => convert(transform.as_ref(), width, &mut pixels)?,
        Through::InkTable => through_table(&mut pixels),
    }
    let width = u32::try_from(width).map_err(|_| ImageFault::Data)?;
    let height = u32::try_from(height).map_err(|_| ImageFault::Data)?;
    RgbImage::from_raw(width, height, pixels)
        .map(Some)
        .ok_or(ImageFault::Data)
}

/// The decoder's options: as the `image` crate sets them, with no limit of the size, which the
/// caller has checked.
fn options() -> DecoderOptions {
    DecoderOptions::default()
        .set_strict_mode(false)
        .set_max_width(usize::MAX)
        .set_max_height(usize::MAX)
}

/// The transform of the ink amounts of the CMYK profile `icc` into sRGB, with the perceptual
/// intent, or `None` for a profile that does not read, is not of CMYK or does not convert.
fn to_srgb(icc: &[u8]) -> Option<Arc<Transform8BitExecutor>> {
    let profile = ColorProfile::new_from_slice(icc).ok()?;
    if profile.color_space != DataColorSpace::Cmyk {
        return None;
    }
    let options = TransformOptions {
        rendering_intent: RenderingIntent::Perceptual,
        ..TransformOptions::default()
    };
    profile
        .create_transform_8bit(
            Layout::Rgba,
            &ColorProfile::new_srgb(),
            Layout::Rgb,
            options,
        )
        .ok()
}

/// Turns the stored values of `pixels`, four to a pixel, into the amounts of cyan, magenta,
/// yellow and black, in place.
fn to_inks(stored: ColorSpace, pixels: &mut [u8]) {
    let (pixels, _) = pixels.as_chunks_mut::<FOUR>();
    for [first, second, third, black] in pixels {
        if stored == ColorSpace::YCCK {
            [*first, *second, *third] = f_office_jpeg::rgb([*first, *second, *third]);
        } else {
            [*first, *second, *third] = [!*first, !*second, !*third];
        }
        *black = !*black;
    }
}

/// Converts the ink amounts of `pixels`, rows of `width` pixels of four values, into RGB
/// pixels of three values through `transform`, in place, row by row: the RGB values of a row
/// end before the next row's inks start, so a copy of one row is the only other memory.
fn convert(
    transform: &Transform8BitExecutor,
    width: usize,
    pixels: &mut Vec<u8>,
) -> Result<(), ImageFault> {
    let row = width.checked_mul(FOUR).ok_or(ImageFault::Data)?;
    let rgb_row = width.checked_mul(THREE).ok_or(ImageFault::Data)?;
    let rows = pixels.len().checked_div(row).unwrap_or(0);
    let mut inks = vec![0; row];
    for index in 0..rows {
        let from = index * row;
        let to = index * rgb_row;
        inks.copy_from_slice(pixels.get(from..from + row).ok_or(ImageFault::Data)?);
        let out = pixels.get_mut(to..to + rgb_row).ok_or(ImageFault::Data)?;
        transform
            .transform(&inks, out)
            .map_err(|_| ImageFault::Data)?;
    }
    pixels.truncate(rows * rgb_row);
    Ok(())
}

/// Converts the ink amounts of `pixels`, four values to a pixel, into RGB pixels of three
/// values through the ink table, in place: each pixel's RGB values end before the next pixel's
/// inks start.
fn through_table(pixels: &mut Vec<u8>) {
    let count = pixels.len() / FOUR;
    for index in 0..count {
        let from = index * FOUR;
        let Some(&inks) = pixels
            .get(from..from + FOUR)
            .and_then(<[u8]>::first_chunk::<FOUR>)
        else {
            break;
        };
        let to = index * THREE;
        if let Some(out) = pixels.get_mut(to..to + THREE) {
            out.copy_from_slice(&ink_table::rgb(inks));
        }
    }
    pixels.truncate(count * THREE);
}