f-office-pdf 0.2.2

Writes a display list as PDF.
Documentation
//! Immediate streaming emission and deduplication of PDF Image `XObject`s.
//!
//! Each distinct image is decoded/encoded and flushed straight to [`StreamPdf`] on first
//! encounter; the deduplication table keeps only the 4-byte indirect [`Ref`], never pinning raw
//! image bytes across pages.

use std::collections::HashMap;
use std::io::{Cursor, Write};

use f_office_paint::{self as paint, Image, ImageColor, ImageFault, ImageFormat, InkConversion};
use image::ImageReader;
use pdf_writer::{Chunk, Filter, Finish, Ref};

use crate::Error;
use crate::stream::{StreamPdf, deflate};

/// Key identifying a unique emitted Image `XObject`.
type ImageKey = (paint::ImageKey, ImageFormat, ImageColor, InkConversion);

/// Deduplicates emitted images by storing only their PDF object reference (or fault).
#[derive(Default)]
pub(crate) struct EmittedImages {
    emitted: HashMap<ImageKey, Result<Ref, ImageFault>>,
}

impl EmittedImages {
    /// Returns the PDF object `Ref` of `image`, streaming it straight to `pdf` on first use.
    pub(crate) fn get_or_emit<W: Write>(
        &mut self,
        image: &Image,
        pdf: &mut StreamPdf<'_, W>,
    ) -> Result<Result<Ref, ImageFault>, Error> {
        let key = (
            image.cache_key(),
            image.format,
            image.color.clone(),
            image.inks,
        );
        if let Some(cached) = self.emitted.get(&key) {
            return Ok(*cached);
        }
        let outcome = emit_image(image, pdf)?;
        self.emitted.insert(key, outcome);
        Ok(outcome)
    }
}

/// Loads, validates, and streams one image `XObject` into `pdf`.
fn emit_image<W: Write>(
    image: &Image,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Result<Ref, ImageFault>, Error> {
    let Some((bytes, format)) = image.load_bytes_with_format() else {
        return Ok(Err(ImageFault::Data));
    };
    match format {
        ImageFormat::Emf | ImageFormat::Wmf | ImageFormat::Unknown => {
            return Ok(Err(ImageFault::Format));
        }
        ImageFormat::Gif | ImageFormat::Bmp | ImageFormat::Tiff | ImageFormat::EffectPicture => {
            return emit_decoded_image(image, pdf);
        }
        ImageFormat::Png | ImageFormat::Jpeg => {}
    }
    if image.color != ImageColor::Original || paint::converts_inks(image) {
        return emit_decoded_image(image, pdf);
    }
    if format == ImageFormat::Jpeg {
        return emit_jpeg_passthrough(&bytes, pdf);
    }
    // PNG: decode within MAX_DECODED_BYTES (this also drops unapplied ICC profiles and validates
    // pixel data before streaming).
    let pixels = match paint::decode_file(&bytes, format, paint::MAX_DECODED_BYTES) {
        Ok(img) => img,
        Err(fault) => return Ok(Err(fault)),
    };
    emit_rgba_image(&pixels.to_rgba8(), pdf)
}

/// Decodes `image` through `f-office-paint` (applying color/ink conversions and enforcing
/// `MAX_DECODED_BYTES`) and streams its pixels directly as a Flate-compressed Image `XObject`.
fn emit_decoded_image<W: Write>(
    image: &Image,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Result<Ref, ImageFault>, Error> {
    let pixels = match paint::decode(image) {
        Ok(img) => img,
        Err(fault) => return Ok(Err(fault)),
    };
    emit_rgba_image(&pixels, pdf)
}

/// Streams a JPEG file directly using `/DCTDecode` after stripping any unapplied ICC profile.
fn emit_jpeg_passthrough<W: Write>(
    bytes: &[u8],
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Result<Ref, ImageFault>, Error> {
    let stripped = paint::without_profile(bytes, ImageFormat::Jpeg);
    let data = stripped.as_deref().unwrap_or(bytes);
    let Ok((width, height)) =
        ImageReader::with_format(Cursor::new(data), image::ImageFormat::Jpeg).into_dimensions()
    else {
        return Ok(Err(ImageFault::Data));
    };
    let Some(components) = jpeg_components(data) else {
        return Ok(Err(ImageFault::Data));
    };
    if width == 0 || height == 0 || !matches!(components, 1 | 3 | 4) {
        return Ok(Err(ImageFault::Data));
    }
    let (Ok(w), Ok(h)) = (i32::try_from(width), i32::try_from(height)) else {
        return Ok(Err(ImageFault::Data));
    };
    let xobj_ref = pdf.alloc();
    let mut chunk = Chunk::new();
    let mut xobj = chunk.image_xobject(xobj_ref, data);
    xobj.width(w)
        .height(h)
        .bits_per_component(8)
        .interpolate(true);
    match components {
        1 => {
            xobj.color_space().device_gray();
        }
        3 => {
            xobj.color_space().device_rgb();
        }
        4 => {
            xobj.color_space().device_cmyk();
            xobj.decode([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]);
        }
        _ => return Ok(Err(ImageFault::Data)),
    }
    xobj.filter(Filter::DctDecode);
    xobj.finish();
    pdf.emit(xobj_ref, &chunk)?;
    Ok(Ok(xobj_ref))
}

/// Reads the JPEG SOF marker to determine the number of color components (1=Gray, 3=RGB, 4=CMYK).
fn jpeg_components(data: &[u8]) -> Option<u8> {
    if data.get(..2) != Some(&[0xFF, 0xD8]) {
        return None;
    }
    let mut pos = 2;
    while let Some((marker, next_pos)) = next_jpeg_marker(data, pos) {
        pos = next_pos;
        if marker == 0xD9 || marker == 0xDA {
            return None;
        }
        if (0xD0..=0xD8).contains(&marker) || marker == 0x01 {
            continue;
        }
        let seg_len = (usize::from(*data.get(pos)?) << 8) | usize::from(*data.get(pos + 1)?);
        if seg_len < 2 {
            return None;
        }
        if is_sof_marker(marker) {
            return data.get(pos + 7).copied();
        }
        pos = pos.checked_add(seg_len)?;
    }
    None
}

fn next_jpeg_marker(data: &[u8], mut pos: usize) -> Option<(u8, usize)> {
    while data.get(pos) == Some(&0xFF) {
        pos += 1;
    }
    let marker = *data.get(pos)?;
    Some((marker, pos + 1))
}

const fn is_sof_marker(marker: u8) -> bool {
    matches!(
        marker,
        0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF
    )
}

/// Streams a decoded `RgbaImage` as a `/FlateDecode` `DeviceRGB` Image `XObject`, plus an
/// optional `/SMask` `DeviceGray` Image `XObject` when any pixel has alpha < 255.
fn emit_rgba_image<W: Write>(
    rgba: &image::RgbaImage,
    pdf: &mut StreamPdf<'_, W>,
) -> Result<Result<Ref, ImageFault>, Error> {
    let (width, height) = rgba.dimensions();
    if width == 0 || height == 0 {
        return Ok(Err(ImageFault::Data));
    }
    let (Ok(w), Ok(h)) = (i32::try_from(width), i32::try_from(height)) else {
        return Ok(Err(ImageFault::Data));
    };
    let pixel_count = usize::try_from(width)
        .ok()
        .and_then(|x| usize::try_from(height).ok().and_then(|y| x.checked_mul(y)))
        .ok_or(ImageFault::Data);
    let Ok(pixel_count) = pixel_count else {
        return Ok(Err(ImageFault::Data));
    };
    let mut rgb = Vec::with_capacity(pixel_count.saturating_mul(3));
    let mut alpha = Vec::with_capacity(pixel_count);
    let mut has_alpha = false;
    for px in rgba.pixels() {
        rgb.push(px.0[0]);
        rgb.push(px.0[1]);
        rgb.push(px.0[2]);
        let a = px.0[3];
        if a != 255 {
            has_alpha = true;
        }
        alpha.push(a);
    }

    let smask_ref = if has_alpha {
        let compressed_alpha = deflate(&alpha)?;
        drop(alpha);
        let mask_ref = pdf.alloc();
        let mut chunk = Chunk::new();
        let mut mask = chunk.image_xobject(mask_ref, &compressed_alpha);
        mask.width(w)
            .height(h)
            .bits_per_component(8)
            .interpolate(true)
            .color_space()
            .device_gray();
        mask.filter(Filter::FlateDecode);
        mask.finish();
        pdf.emit(mask_ref, &chunk)?;
        Some(mask_ref)
    } else {
        drop(alpha);
        None
    };

    let compressed_rgb = deflate(&rgb)?;
    drop(rgb);
    let xobj_ref = pdf.alloc();
    let mut chunk = Chunk::new();
    let mut xobj = chunk.image_xobject(xobj_ref, &compressed_rgb);
    xobj.width(w)
        .height(h)
        .bits_per_component(8)
        .interpolate(true);
    xobj.color_space().device_rgb();
    if let Some(mask_ref) = smask_ref {
        xobj.s_mask(mask_ref);
    }
    xobj.filter(Filter::FlateDecode);
    xobj.finish();
    pdf.emit(xobj_ref, &chunk)?;
    Ok(Ok(xobj_ref))
}