pdfcer-image-codec 0.191.0

pdfcer terminal image codecs: DCTDecode, CCITTFaxDecode, JBIG2Decode and JPXDecode (ISO 32000-1 7.4.6-7.4.9). Re-exported by pdfcer-core as `image_codec`.
Documentation
//! The decode-time check of [`DecodeLimits`] (decision 227 sources (a)
//! and (c)), run before the filter chain touches the data.

use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::Dict;
use pdfcer_model::view::DocumentView;

use crate::peak::{DecodeLimits, predict_peak};
use crate::{CmykJpegPolarity, ImageCodecError};

/// Which limit refused an image ([`ImageCodecError::LimitExceeded`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SizeLimit {
    /// [`DecodeLimits::memory_budget`]: the predicted peak heap bytes,
    /// plus what the caller allocates per pixel afterwards. Figures are
    /// bytes.
    MemoryBudget,
    /// [`DecodeLimits::max_pixels`], the operator's strict mode. Figures
    /// are pixels.
    OperatorPixelCap,
    /// A side length past what the format or its decoder can represent:
    /// JBIG2 through `hayro-jbig2`, 65,535 samples. A fact about the data
    /// path, not a policy. Figures are samples per side.
    FormatField,
}

impl SizeLimit {
    /// Stable refusal key: `image/limit/memory-budget`,
    /// `image/limit/pixel-cap` or `image/limit/format-field`.
    #[must_use]
    pub const fn refusal_key(self) -> &'static str {
        match self {
            Self::MemoryBudget => "image/limit/memory-budget",
            Self::OperatorPixelCap => "image/limit/pixel-cap",
            Self::FormatField => "image/limit/format-field",
        }
    }

    /// The unit `needed` and `allowed` are counted in, for messages.
    #[must_use]
    pub const fn unit(self) -> &'static str {
        match self {
            Self::MemoryBudget => "bytes",
            Self::OperatorPixelCap => "pixels",
            Self::FormatField => "samples per side",
        }
    }
}

/// Per-decode options for [`crate::decode_image_view_with`].
///
/// # Examples
///
/// ```
/// use pdfcer_image_codec::peak::DecodeLimits;
/// use pdfcer_image_codec::{CmykJpegPolarity, DecodeOptions};
///
/// let options = DecodeOptions::default()
///     .with_cmyk_jpeg_polarity(CmykJpegPolarity::InvertOnApp14)
///     .with_limits(DecodeLimits::new(64 << 20).with_max_pixels(Some(1_000_000)));
/// assert_eq!(options.limits.memory_budget, 64 << 20);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct DecodeOptions {
    /// The `DCT-A1` polarity rule (R169).
    pub cmyk_jpeg_polarity: CmykJpegPolarity,
    /// The memory budget and pixel cap the image is checked against.
    pub limits: DecodeLimits,
}

impl DecodeOptions {
    /// Sets the `DCT-A1` polarity rule.
    #[must_use]
    pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
        self.cmyk_jpeg_polarity = polarity;
        self
    }

    /// Sets the limits.
    #[must_use]
    pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
        self.limits = limits;
        self
    }
}

/// Refuse an image that crosses `limits`, from its dictionary and raw
/// bytes alone.
///
/// The pixel cap is checked first, against the dictionary's
/// `/Width x /Height`. The memory figure is [`predict_peak`] plus
/// `width * height * downstream_bytes_per_pixel`; where the peak cannot be
/// predicted only the downstream term is checked, and the decode is
/// otherwise bounded by fallible allocation.
pub(crate) fn check(
    doc: &DocumentView<'_>,
    dict: &Dict,
    raw: &[u8],
    limits: &DecodeLimits,
) -> Result<(), ImageCodecError> {
    let pixels = declared_pixels(doc, dict);
    if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
        && pixels > cap
    {
        return Err(ImageCodecError::LimitExceeded {
            limit: SizeLimit::OperatorPixelCap,
            needed: pixels,
            allowed: cap,
        });
    }
    let downstream = pixels
        .unwrap_or(0)
        .saturating_mul(limits.downstream_bytes_per_pixel);
    let needed = predict_peak(doc, dict, raw)
        .unwrap_or(0)
        .saturating_add(downstream);
    if needed > limits.memory_budget {
        return Err(ImageCodecError::LimitExceeded {
            limit: SizeLimit::MemoryBudget,
            needed,
            allowed: limits.memory_budget,
        });
    }
    Ok(())
}

/// Refuse `needed` bytes past [`DecodeLimits::memory_budget`]: the check a
/// codec makes on its own header geometry, which the dictionary-level
/// [`check`] cannot see when a filter sits in front of the codec.
pub(crate) fn admit(limits: &DecodeLimits, needed: u64) -> Result<(), ImageCodecError> {
    if needed > limits.memory_budget {
        return Err(ImageCodecError::LimitExceeded {
            limit: SizeLimit::MemoryBudget,
            needed,
            allowed: limits.memory_budget,
        });
    }
    Ok(())
}

fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
    let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
        let entry = dict.get(key).or_else(|| dict.get(short))?;
        u64::try_from(doc.resolve(entry).as_int()?).ok()
    };
    Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
}