lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Decode image samples only for a device that needs them. Preserve the
//! original PNG bytes in SVG publication.

use std::io::Cursor;

use crate::{Error, Result};
use moxcms::{ColorProfile, DataColorSpace, Layout, TransformF64Executor, TransformOptions};

fn invalid(error: impl std::fmt::Display) -> Error {
    Error::Data(format!("PNG asset: {error}").into())
}

fn conversion(error: impl std::fmt::Display) -> Error {
    Error::Render(format!("PNG asset color conversion to sRGB: {error}").into())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Coverage {
    Empty,
    Full,
    Partial,
}

#[derive(Debug, Clone, Copy)]
pub(super) struct PngMetadata {
    pub size: (u32, u32),
    pub coverage: Coverage,
}

pub(super) fn metadata(bytes: &[u8]) -> Result<PngMetadata> {
    let mut decoder = png::Decoder::new(Cursor::new(bytes));
    decoder.set_transformations(png::Transformations::EXPAND);
    let mut reader = decoder.read_info().map_err(invalid)?;
    let info = reader.info();
    if info.animation_control.is_some() {
        return Err(invalid("animated PNG is not a static image"));
    }
    let size = info.size();
    let (color, depth) = reader.output_color_type();
    let has_alpha = matches!(color, png::ColorType::Rgba | png::ColorType::GrayscaleAlpha);
    let coverage = if has_alpha {
        let bytes_per_channel = if depth == png::BitDepth::Sixteen {
            2
        } else {
            1
        };
        let bytes_per_pixel = color.samples() * bytes_per_channel;
        let mut any = false;
        let mut all = true;
        while let Some(row) = reader.next_interlaced_row().map_err(invalid)? {
            crate::operation::checkpoint()?;
            for pixel in row.data().chunks_exact(bytes_per_pixel) {
                let nonzero = pixel[bytes_per_pixel - bytes_per_channel..]
                    .iter()
                    .any(|&value| value != 0);
                any |= nonzero;
                all &= nonzero;
            }
        }
        if !any {
            Coverage::Empty
        } else if all {
            Coverage::Full
        } else {
            Coverage::Partial
        }
    } else {
        // Even an opaque source must have valid image rows. Reading the
        // trailing chunks alone does not validate its compressed samples.
        while reader.next_interlaced_row().map_err(invalid)?.is_some() {
            crate::operation::checkpoint()?;
        }
        Coverage::Full
    };
    reader.finish().map_err(invalid)?;
    Ok(PngMetadata { size, coverage })
}

// Valid higher-priority color declarations never fall through to a different
// interpretation of the numerical RGB channels.
fn color_profile(info: &png::Info<'_>) -> Result<Option<ColorProfile>> {
    if let Some(cicp) = info.coding_independent_code_points {
        if cicp.matrix_coefficients != 0 || !cicp.is_video_full_range_image {
            return Err(conversion("unsupported cICP matrix or sample range"));
        }
        if (cicp.color_primaries, cicp.transfer_function) == (1, 13) {
            return Ok(None);
        }
        if !matches!(cicp.color_primaries, 1 | 9 | 12)
            || !matches!(cicp.transfer_function, 1 | 4 | 5 | 6 | 8 | 13 | 14 | 15)
        {
            return Err(conversion(format!(
                "unsupported cICP primaries/transfer {}/{}",
                cicp.color_primaries, cicp.transfer_function
            )));
        }
        let profile = ColorProfile::new_from_cicp(moxcms::CicpProfile {
            color_primaries: cicp.color_primaries.try_into().map_err(conversion)?,
            transfer_characteristics: cicp.transfer_function.try_into().map_err(conversion)?,
            matrix_coefficients: moxcms::MatrixCoefficients::Identity,
            full_range: true,
        });
        if profile.red_trc.is_none() {
            return Err(conversion("cICP transfer curve is not supported"));
        }
        return Ok(Some(profile));
    }
    if let Some(icc) = &info.icc_profile {
        return icc_profile(icc).map(Some);
    }
    if info.srgb.is_some() || (info.gama_chunk.is_none() && info.chrm_chunk.is_none()) {
        return Ok(None);
    }
    let mut profile = ColorProfile::new_srgb();
    // The conventional sRGB fallback chunks carry the rounded PNG values.
    // Without an actual sRGB declaration gAMA still specifies a power law.
    profile.cicp = None;
    if let Some(chrm) = info.chrm_chunk {
        let xy = |(x, y): (png::ScaledFloat, png::ScaledFloat)| -> Result<moxcms::Chromaticity> {
            let x = x.into_value();
            let y = y.into_value();
            if x < 0. || y <= 0. || x + y > 1. {
                return Err(conversion("invalid cHRM chromaticity"));
            }
            Ok(moxcms::Chromaticity { x, y })
        };
        let white = xy(chrm.white)?;
        profile.update_rgb_colorimetry(
            moxcms::XyY::new(f64::from(white.x), f64::from(white.y), 1.),
            moxcms::ColorPrimaries {
                red: xy(chrm.red)?,
                green: xy(chrm.green)?,
                blue: xy(chrm.blue)?,
            },
        );
    }
    if let Some(gamma) = info.gama_chunk {
        if gamma.into_scaled() == 0 {
            return Err(conversion("zero gAMA"));
        }
        let curve = moxcms::ToneReprCurve::Parametric(vec![1. / gamma.into_value()]);
        profile.red_trc = Some(curve.clone());
        profile.green_trc = Some(curve.clone());
        profile.blue_trc = Some(curve);
    }
    Ok(Some(profile))
}

pub(super) fn icc_profile(bytes: &[u8]) -> Result<ColorProfile> {
    let profile = ColorProfile::new_from_slice(bytes).map_err(conversion)?;
    if profile.cicp.as_ref().is_some_and(|cicp| {
        matches!(
            cicp.transfer_characteristics,
            moxcms::TransferCharacteristics::Smpte2084 | moxcms::TransferCharacteristics::Hlg
        )
    }) {
        return Err(conversion(
            "HDR ICC profile is not supported by the sRGB output",
        ));
    }
    Ok(profile)
}

pub(super) struct ColorConversion {
    transform: std::sync::Arc<TransformF64Executor>,
    gray: bool,
}

impl ColorConversion {
    pub(super) fn new(profile: &ColorProfile, gray: bool) -> Result<Self> {
        // Grayscale PNGs with an RGB colorimetry declaration represent equal
        // RGB components. An ICC gray profile has an actual one-channel TRC.
        let profile_gray = profile.color_space == DataColorSpace::Gray;
        if profile_gray && !gray {
            return Err(conversion("grayscale ICC profile on an RGB image"));
        }
        if !matches!(
            profile.color_space,
            DataColorSpace::Rgb | DataColorSpace::Gray
        ) {
            return Err(conversion("ICC profile is not an RGB or grayscale profile"));
        }
        let transform = profile
            .create_transform_f64(
                if profile_gray {
                    Layout::Gray
                } else {
                    Layout::Rgb
                },
                &ColorProfile::new_srgb(),
                Layout::Rgb,
                TransformOptions {
                    rendering_intent: profile.rendering_intent,
                    ..TransformOptions::default()
                },
            )
            .map_err(conversion)?;
        Ok(Self {
            transform,
            gray: profile_gray,
        })
    }

    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "color samples are clamped to the u16 device-independent working range"
    )]
    pub(super) fn apply(&self, pixel: &mut [u16; 4]) -> Result<()> {
        let rgb = [pixel[0], pixel[1], pixel[2]].map(|value| f64::from(value) / 65535.);
        let mut result = [0.; 3];
        self.transform
            .transform(if self.gray { &rgb[..1] } else { &rgb }, &mut result)
            .map_err(conversion)?;
        if !result.into_iter().all(f64::is_finite) {
            return Err(conversion("nonfinite converted channel"));
        }
        for (channel, value) in pixel[..3].iter_mut().zip(result) {
            *channel = (value.clamp(0., 1.) * 65535.).round_ties_even() as u16;
        }
        Ok(())
    }
}

/// Straight sRGB samples, with the original alpha independent of RGB conversion.
/// Sixteen-bit storage also preserves every source eight-bit value exactly.
pub(crate) struct PngSamples {
    pub(crate) width: u32,
    pub(crate) height: u32,
    pub(crate) rgba: Vec<[u16; 4]>,
}

pub(crate) fn png_samples(bytes: &[u8]) -> Result<PngSamples> {
    decode(bytes, true)
}

pub(super) fn decode(bytes: &[u8], color: bool) -> Result<PngSamples> {
    let mut decoder = png::Decoder::new(Cursor::new(bytes));
    decoder.set_transformations(png::Transformations::EXPAND);
    let mut reader = decoder.read_info().map_err(invalid)?;
    let info = reader.info();
    let (width, height) = info.size();
    if info.animation_control.is_some() {
        return Err(invalid("animated PNG is not a static image"));
    }
    // This bounds an actual raster allocation, rather than the area of a
    // scalable vector viewport.
    crate::scene::validate_png_target_dimensions(width, height)?;
    let profile = if color { color_profile(info)? } else { None };
    let gray = matches!(
        info.color_type,
        png::ColorType::Grayscale | png::ColorType::GrayscaleAlpha
    );
    let conversion = profile
        .as_ref()
        .map(|profile| ColorConversion::new(profile, gray))
        .transpose()?;
    let size = reader
        .output_buffer_size()
        .ok_or_else(|| invalid("samples row storage overflows"))?;
    let mut samples = Vec::new();
    crate::data::source::reserve_source(&mut samples, size)?;
    samples.resize(size, 0);
    let frame = reader.next_frame(&mut samples).map_err(invalid)?;
    reader.finish().map_err(invalid)?;
    let depth = match frame.bit_depth {
        png::BitDepth::Eight => 1,
        png::BitDepth::Sixteen => 2,
        _ => {
            return Err(invalid(
                "PNG expansion did not yield eight or sixteen-bit samples",
            ))
        }
    };
    let channels = frame.color_type.samples();
    let mut rgba = Vec::new();
    let count = (width as usize)
        .checked_mul(height as usize)
        .ok_or_else(|| invalid("pixel count overflow"))?;
    crate::data::source::reserve_source(&mut rgba, count)?;
    for (index, pixel) in samples[..frame.buffer_size()]
        .chunks_exact(channels * depth)
        .enumerate()
    {
        if index.is_multiple_of(4096) {
            crate::operation::checkpoint()?;
        }
        let at = |channel: usize| {
            let offset = channel * depth;
            if depth == 1 {
                u16::from(pixel[offset]) * 257
            } else {
                u16::from_be_bytes([pixel[offset], pixel[offset + 1]])
            }
        };
        let mut value = match frame.color_type {
            png::ColorType::Grayscale => [at(0), at(0), at(0), 65535],
            png::ColorType::GrayscaleAlpha => [at(0), at(0), at(0), at(1)],
            png::ColorType::Rgb => [at(0), at(1), at(2), 65535],
            png::ColorType::Rgba => [at(0), at(1), at(2), at(3)],
            png::ColorType::Indexed => return Err(invalid("PNG palette was not expanded")),
        };
        if let Some(conversion) = &conversion {
            conversion.apply(&mut value)?;
        }
        rgba.push(value);
    }
    Ok(PngSamples {
        width,
        height,
        rgba,
    })
}