pdfcer-image-codec 0.190.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
//! Expected-length bound for an uncoded image stream (decision 227).
//!
//! An image with no terminal codec decodes to exactly
//! `h * ceil(w * nc * bpc / 8)` bytes. Each byte-stream filter has a
//! largest possible expansion, so a stream whose raw length times the
//! product of those expansions falls short of that length cannot be the
//! image it declares, and is refused before anything is sized from it.
//! A stream that passes decodes only to the expected length.
//!
//! Expansions, from the spec RAG: Flate 1032 (RFC 1951 §3.2.5, a strict
//! upper bound: 258 bytes per 2 bits), RunLength 64 (§7.4.5: 2 bytes give
//! 128), ASCII85 4 (§7.4.3: `z` gives four zeros), ASCIIHex 1/2 (§7.4.2).
//! LZW and Brotli admit no useful bound, so a chain containing either
//! relies on the memory budget alone. Predictors never expand.
//!
//! Only a chain with a compressing filter (Flate, RunLength) is checked.
//! Raw or ASCII-only data that falls short is a truncated image, which the
//! renderer draws and marks truncated; its size is held by the budget.

use pdfcer_model::filters;
use pdfcer_model::object::Dict;
use pdfcer_model::view::DocumentView;

use crate::ImageCodecError;
use crate::peak::{bits_per_component, dim, sample_components};

/// `h * ceil(w * nc * bpc / 8)`, or `None` when the dictionary does not
/// determine it (missing dimensions, a colour space whose component
/// count is unknown).
pub(crate) fn expected_len(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
    let width = dim(doc, dict, b"Width", b"W")?;
    let height = dim(doc, dict, b"Height", b"H")?;
    let row = width
        .checked_mul(sample_components(doc, dict)?)?
        .checked_mul(bits_per_component(doc, dict)?)?
        .div_ceil(8);
    row.checked_mul(height)
}

/// Most bytes `have` raw bytes can decode to through `names`, or `None`
/// when a filter in the chain has no bound.
fn max_output(names: &[Vec<u8>], have: u64) -> Option<u128> {
    let (mut num, mut den) = (u128::from(have), 1u128);
    for name in names {
        let (n, d) = match name.as_slice() {
            b"FlateDecode" | b"Fl" => (1032, 1),
            b"RunLengthDecode" | b"RL" => (64, 1),
            b"ASCII85Decode" | b"A85" => (4, 1),
            b"ASCIIHexDecode" | b"AHx" => (1, 2),
            _ => return None,
        };
        num = num.checked_mul(n)?;
        den = den.checked_mul(d)?;
    }
    Some(num / den)
}

/// Refuse an uncoded image whose stream cannot decode to `expected`
/// bytes through `names`, when the chain compresses.
pub(crate) fn check(names: &[Vec<u8>], raw: &[u8], expected: u64) -> Result<(), ImageCodecError> {
    let compresses = names.iter().any(|n| {
        matches!(
            n.as_slice(),
            b"FlateDecode" | b"Fl" | b"RunLengthDecode" | b"RL"
        )
    });
    if !compresses {
        return Ok(());
    }
    let have = u64::try_from(raw.len()).unwrap_or(u64::MAX);
    let Some(max) = max_output(names, have) else {
        return Ok(());
    };
    if u128::from(expected) <= max {
        return Ok(());
    }
    Err(ImageCodecError::DeclaredSizeExceedsStream {
        expected_bytes: expected,
        max_bytes: u64::try_from(max).unwrap_or(u64::MAX),
        have_bytes: have,
    })
}

/// Decode an uncoded image's byte-stream chain, stopping at `expected`
/// bytes when it is known (see [`filters::decode_prefix_bounded`]).
pub(crate) fn decode(
    dict: &Dict,
    raw: &[u8],
    take: usize,
    expected: Option<u64>,
    notes: &mut filters::FilterNotes,
    cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, filters::FilterError> {
    match expected.and_then(|n| usize::try_from(n).ok()) {
        Some(n) => filters::decode_prefix_bounded(dict, raw, take, n, notes, cancelled),
        None => filters::decode_prefix_polled(dict, raw, take, notes, cancelled),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn n(s: &[u8]) -> Vec<u8> {
        s.to_vec()
    }

    #[test]
    fn expansions_multiply_along_the_chain() {
        assert_eq!(max_output(&[], 10), Some(10));
        assert_eq!(max_output(&[n(b"FlateDecode")], 10), Some(10_320));
        assert_eq!(max_output(&[n(b"A85"), n(b"Fl")], 10), Some(41_280));
        assert_eq!(max_output(&[n(b"AHx")], 11), Some(5));
        assert_eq!(max_output(&[n(b"RL")], 2), Some(128));
    }

    #[test]
    fn lzw_or_brotli_anywhere_leaves_the_chain_unbounded() {
        assert_eq!(max_output(&[n(b"LZWDecode")], 10), None);
        assert_eq!(max_output(&[n(b"Fl"), n(b"BrotliDecode")], 10), None);
    }

    #[test]
    fn the_bound_is_inclusive() {
        let fl = [n(b"FlateDecode")];
        assert!(check(&fl, &[0; 10], 10_320).is_ok());
        let key = check(&fl, &[0; 10], 10_321)
            .err()
            .and_then(|e| e.refusal_key());
        assert_eq!(key, Some("image/evidence/stream"));
    }
}