lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Decode ordinary static SVG image resources with checked dimensions.
//! Vector SVG publication retains the original encoded resources.

use std::io::Cursor;

use super::png::{ColorConversion, PngSamples};
use crate::{Error, Result};

fn refusal(error: impl std::fmt::Display) -> Error {
    Error::Render(format!("embedded SVG raster image: {error}").into())
}

pub(super) fn decode(mime: &str, bytes: &[u8]) -> Result<PngSamples> {
    match mime {
        "image/jpeg" | "image/jpg" => jpeg(bytes),
        "image/gif" => gif(bytes),
        "image/webp" => webp(bytes),
        _ => Err(refusal(format!("unsupported image type {mime}"))),
    }
}

fn jpeg(bytes: &[u8]) -> Result<PngSamples> {
    use zune_jpeg::zune_core::{colorspace::ColorSpace, options::DecoderOptions};
    let options = DecoderOptions::default().jpeg_set_out_colorspace(ColorSpace::RGBA);
    let mut decoder = zune_jpeg::JpegDecoder::new_with_options(Cursor::new(bytes), options);
    decoder.decode_headers().map_err(refusal)?;
    let (width, height) = decoder
        .dimensions()
        .ok_or_else(|| refusal("JPEG has no frame"))?;
    let width = u32::try_from(width).map_err(refusal)?;
    let height = u32::try_from(height).map_err(refusal)?;
    crate::scene::validate_png_target_dimensions(width, height)?;
    let gray = decoder.input_colorspace() == Some(ColorSpace::Luma);
    if !matches!(
        decoder.input_colorspace(),
        Some(ColorSpace::Luma | ColorSpace::RGB | ColorSpace::YCbCr)
    ) || decoder.output_colorspace() != Some(ColorSpace::RGBA)
    {
        return Err(refusal(
            "JPEG color model is not a supported RGB or grayscale source",
        ));
    }
    if decoder.exif().is_some_and(|data| !unrotated(data)) {
        return Err(refusal("JPEG requires an EXIF orientation transform"));
    }
    let profile = decoder.icc_profile();
    let data = decoder.decode().map_err(refusal)?;
    samples(width, height, &data, true, gray, profile.as_deref())
}

fn gif(bytes: &[u8]) -> Result<PngSamples> {
    let mut options = gif::DecodeOptions::new();
    options.set_color_output(gif::ColorOutput::RGBA);
    let mut reader = options.read_info(bytes).map_err(refusal)?;
    let (width, height) = (reader.width(), reader.height());
    crate::scene::validate_png_target_dimensions(width.into(), height.into())?;
    let first = reader
        .read_next_frame()
        .map_err(refusal)?
        .ok_or_else(|| refusal("GIF has no frame"))?;
    if first.left != 0 || first.top != 0 || first.width != width || first.height != height {
        return Err(refusal("GIF subframe does not cover its logical screen"));
    }
    let result = samples(
        width.into(),
        height.into(),
        &first.buffer,
        true,
        false,
        None,
    )?;
    if reader.read_next_frame().map_err(refusal)?.is_some() {
        return Err(refusal("animated GIF is not a static image"));
    }
    Ok(result)
}

fn webp(bytes: &[u8]) -> Result<PngSamples> {
    let mut reader = image_webp::WebPDecoder::new(Cursor::new(bytes)).map_err(refusal)?;
    if reader.is_animated() {
        return Err(refusal("animated WebP is not a static image"));
    }
    let (width, height) = reader.dimensions();
    crate::scene::validate_png_target_dimensions(width, height)?;
    if reader
        .exif_metadata()
        .map_err(refusal)?
        .is_some_and(|data| !unrotated(&data))
    {
        return Err(refusal("WebP requires an EXIF orientation transform"));
    }
    let profile = reader.icc_profile().map_err(refusal)?;
    let size = reader
        .output_buffer_size()
        .ok_or_else(|| refusal("WebP sample size overflow"))?;
    let mut data = Vec::new();
    crate::data::source::reserve_source(&mut data, size)?;
    data.resize(size, 0);
    reader.read_image(&mut data).map_err(refusal)?;
    samples(
        width,
        height,
        &data,
        reader.has_alpha(),
        false,
        profile.as_deref(),
    )
}

// Read only the primary TIFF directory's orientation. An unrecognized or
// truncated directory is not evidence that the unrotated device is correct.
fn unrotated(data: &[u8]) -> bool {
    let data = data.strip_prefix(b"Exif\0\0").unwrap_or(data);
    let Some(order) = data.get(..2) else {
        return false;
    };
    let little = match order {
        b"II" => true,
        b"MM" => false,
        _ => return false,
    };
    let short = |offset: usize| {
        let bytes = data.get(offset..offset.checked_add(2)?)?.try_into().ok()?;
        Some(if little {
            u16::from_le_bytes(bytes)
        } else {
            u16::from_be_bytes(bytes)
        })
    };
    let long = |offset: usize| {
        let bytes = data.get(offset..offset.checked_add(4)?)?.try_into().ok()?;
        Some(if little {
            u32::from_le_bytes(bytes)
        } else {
            u32::from_be_bytes(bytes)
        })
    };
    if short(2) != Some(42) {
        return false;
    }
    let Some(directory) = long(4).map(|offset| offset as usize) else {
        return false;
    };
    let Some(count) = short(directory) else {
        return false;
    };
    for index in 0..usize::from(count) {
        let Some(entry) = directory.checked_add(2 + index * 12) else {
            return false;
        };
        match short(entry) {
            Some(0x0112) => {
                return short(entry + 2) == Some(3)
                    && long(entry + 4) == Some(1)
                    && short(entry + 8) == Some(1)
            }
            Some(_) => {}
            None => return false,
        }
    }
    true
}

fn samples(
    width: u32,
    height: u32,
    bytes: &[u8],
    alpha: bool,
    gray: bool,
    profile: Option<&[u8]>,
) -> Result<PngSamples> {
    let profile = profile.map(super::png::icc_profile).transpose()?;
    let conversion = profile
        .as_ref()
        .map(|profile| ColorConversion::new(profile, gray))
        .transpose()?;
    let channels = if alpha { 4 } else { 3 };
    let count = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| refusal("image pixel count overflow"))?;
    if count.checked_mul(channels) != Some(bytes.len()) {
        return Err(refusal(
            "decoded sample count does not match image dimensions",
        ));
    }
    let mut rgba = Vec::new();
    crate::data::source::reserve_source(&mut rgba, count)?;
    for (index, pixel) in bytes.chunks_exact(channels).enumerate() {
        if index.is_multiple_of(4096) {
            crate::operation::checkpoint()?;
        }
        let channel = |index: usize| u16::from(pixel[index]) * 257;
        let mut pixel = [
            channel(0),
            channel(1),
            channel(2),
            if alpha { channel(3) } else { 65535 },
        ];
        if let Some(conversion) = &conversion {
            conversion.apply(&mut pixel)?;
        }
        rgba.push(pixel);
    }
    Ok(PngSamples {
        width,
        height,
        rgba,
    })
}