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
//! An uncoded image's stream is held to its expected length (decision 227,
//! Pass 780.6): refused when it cannot decode that far, decoded past the
//! 256 MiB filter ceiling when it can, and never decoded beyond it.

use pdfcer_image_codec::peak::DecodeLimits;
use pdfcer_image_codec::{DecodeOptions, ImageCodecError, decode_image_view_with};
use pdfcer_model::object::Dict;

use crate::peak_memory::{empty_document, image_dict, peak_of};

/// Fixed-Huffman deflate (RFC 1951 §3.2.6) written bit by bit, so a stream
/// of hundreds of megabytes of zeros costs a few megabytes to build.
struct Deflate {
    out: Vec<u8>,
    bit: u32,
}

impl Deflate {
    /// zlib header (RFC 1950: CM 8, CINFO 7, FCHECK so the pair is a
    /// multiple of 31), then the final fixed-Huffman block's header.
    fn new() -> Self {
        let mut d = Self {
            out: vec![0x78, 0x01],
            bit: 0,
        };
        d.bits(1, 1);
        d.bits(1, 2);
        d
    }

    /// `n` bits of `value`, least significant first (header fields).
    fn bits(&mut self, value: u32, n: u32) {
        for i in 0..n {
            self.push((value >> i) & 1);
        }
    }

    /// A Huffman code of `n` bits, most significant first.
    fn code(&mut self, value: u32, n: u32) {
        for i in (0..n).rev() {
            self.push((value >> i) & 1);
        }
    }

    fn push(&mut self, b: u32) {
        if self.bit == 0 {
            self.out.push(0);
        }
        *self.out.last_mut().expect("pushed") |= u8::try_from(b << self.bit).expect("bit");
        self.bit = (self.bit + 1) % 8;
    }

    /// At least `n` zero bytes: a literal zero, then copies of 258 at
    /// distance 1 (length code 285, distance code 0). Returns the count.
    fn zeros(&mut self, n: u64) -> u64 {
        self.code(0b0011_0000, 8);
        let copies = n.saturating_sub(1).div_ceil(258);
        for _ in 0..copies {
            self.code(0b1100_0101, 8);
            self.code(0, 5);
        }
        1 + copies * 258
    }

    /// Literal/length code 286, which no stream may use (§3.2.6).
    fn invalid(&mut self) {
        self.code(0b1100_0110, 8);
    }

    /// End-of-block, then the Adler-32 of `n` zero bytes.
    fn finish(mut self, n: u64) -> Vec<u8> {
        self.code(0, 7);
        let b = u32::try_from(n % 65_521).expect("fits");
        self.out.extend_from_slice(&((b << 16) | 1).to_be_bytes());
        self.out
    }
}

fn decode(dict: &Dict, raw: &[u8]) -> Result<pdfcer_image_codec::CodedImage, ImageCodecError> {
    decode_within(dict, raw, DecodeLimits::default())
}

fn decode_within(
    dict: &Dict,
    raw: &[u8],
    limits: DecodeLimits,
) -> Result<pdfcer_image_codec::CodedImage, ImageCodecError> {
    let options = DecodeOptions::default().with_limits(limits);
    decode_image_view_with(&empty_document().view(), dict, raw, false, options)
}

#[test]
fn a_1_kib_flate_stream_declaring_2_gpx_is_refused_by_evidence_before_allocating() {
    let raw = vec![0u8; 1024];
    let dict = image_dict(Some(b"FlateDecode"), 65_536, 32_768, 8, b"DeviceGray");
    let (peak, result) = peak_of(|| decode(&dict, &raw));
    let e = result.expect_err("a 1 KiB stream cannot inflate to 2 GiB");
    assert_eq!(e.refusal_key(), Some("image/evidence/stream"), "{e:?}");
    match e {
        ImageCodecError::DeclaredSizeExceedsStream {
            expected_bytes,
            max_bytes,
            have_bytes,
        } => assert_eq!(
            (expected_bytes, max_bytes, have_bytes),
            (1 << 31, 1024 * 1032, 1024)
        ),
        other => panic!("{other:?}"),
    }
    assert!(peak < 1 << 20, "refused after allocating {peak} bytes");
}

#[test]
fn a_flate_stream_exactly_at_the_1032_bound_is_not_refused_by_evidence() {
    // 10 raw bytes reach 10,320; an image needing exactly that passes the
    // evidence check and fails only as the corrupt data it is.
    let dict = image_dict(Some(b"FlateDecode"), 10_320, 1, 8, b"DeviceGray");
    let e = decode(&dict, &[0u8; 10]).expect_err("not a zlib stream");
    assert_ne!(e.refusal_key(), Some("image/evidence/stream"), "{e:?}");
}

#[test]
fn a_90_mpx_rgb_flate_image_decodes_past_the_filter_ceiling() {
    // 10000 x 9000 RGB = 270,000,000 bytes, over the 268,435,456-byte
    // ceiling that refused it before this Pass.
    let (w, h) = (10_000u32, 9_000u32);
    let expected = u64::from(w) * u64::from(h) * 3;
    let mut z = Deflate::new();
    let n = z.zeros(expected);
    let raw = z.finish(n);
    let dict = image_dict(Some(b"FlateDecode"), w, h, 8, b"DeviceRGB");
    let img = decode(&dict, &raw).expect("decodes");
    assert_eq!(img.samples.len() as u64, expected);
    assert!(img.samples.iter().all(|&s| s == 0));
}

#[test]
fn data_past_the_expected_length_is_never_decoded() {
    // The image's bytes, a megabyte of surplus, then a code no stream may
    // contain. A decode that ran to the end would meet it and fail.
    let (w, h) = (1_000u32, 1_000u32);
    let mut z = Deflate::new();
    z.zeros(u64::from(w) * u64::from(h) + (1 << 20));
    z.invalid();
    let raw = z.finish(0);
    let dict = image_dict(Some(b"FlateDecode"), w, h, 8, b"DeviceGray");
    let img = decode(&dict, &raw).expect("stops before the corrupt tail");
    assert_eq!(img.samples.len(), 1_000_000);

    let whole = pdfcer_model::filters::decode_stream(&dict, &raw);
    assert!(whole.is_err(), "the tail is corrupt when decoded");
}

#[test]
fn a_short_unfiltered_image_is_a_truncation_not_an_evidence_refusal() {
    // 100 x 100 gray needs 10,000 bytes; 9,999 is a truncated image that
    // the renderer draws and marks, not a fabricated size.
    let dict = image_dict(None, 100, 100, 8, b"DeviceGray");
    let img = decode(&dict, &[0x80; 9_999]).expect("decodes");
    assert_eq!(img.samples.len(), 9_999);
    let hex = image_dict(Some(b"ASCIIHexDecode"), 100, 100, 8, b"DeviceGray");
    assert!(decode(&hex, b"8080>").is_ok());
}

#[test]
fn a_chain_with_lzw_is_left_to_the_memory_budget() {
    let dict = image_dict(Some(b"LZWDecode"), 65_536, 32_768, 8, b"DeviceGray");
    let e = decode_within(&dict, &[0x80; 1024], DecodeLimits::new(1 << 30)).expect_err("refused");
    assert_eq!(e.refusal_key(), Some("image/limit/memory-budget"), "{e:?}");
}