Skip to main content

pdfcer_model/filters/
mod.rs

1//! # Stream filters (ISO 32000-1 §7.4) — the decode pipeline
2//!
3//! Decodes stream data through its `/Filter` chain. Spec sources:
4//! `filter__pipeline.md` (cascade rules), `filter__flate.md`,
5//! `filter__predictors.md` in the PDF-spec RAG; Table 5 of
6//! `iso32000__s__7.3.8.md` for the `/Filter`//`/DecodeParms` shapes.
7//! Clause numbers are ISO 32000-1:2008.
8//!
9//! ## Fail-clean is a TYPE-LEVEL contract here
10//!
11//! Every decoder returns `Result<Vec<u8>, FilterError>`, and **no code
12//! path returns undecoded or partial bytes as if they had decoded**
13//! (docs/decisions/001-oxidize-pdf-adopt-vs-build.md §6.1 item 4).
14//! This is a deliberate divergence from observed prior art: the audited
15//! oxidize-pdf filter layer falls back to returning raw bytes when
16//! zlib/predictor decoding fails, which silently corrupts downstream
17//! consumers. pdfcer's corrupted-stream regression tests (one per
18//! filter) pin the opposite behavior: corrupt in → `Err` out, never
19//! plausible-looking garbage. Truncated-but-partially-decodable
20//! streams also `Err` in Pass 1; a *labeled* best-effort mode for
21//! damaged-file recovery is a later, explicit, corpus-driven feature —
22//! never a silent default.
23//!
24//! ## Resource ceiling (ARCHITECTURE.md §10.1 — pdfcer policy, not spec)
25//!
26//! Deflate's worst case is ~1032:1 expansion — a 1 MB stream can claim
27//! a gigabyte. Every decode enforces [`MAX_DECODED_LEN`] *incrementally*
28//! (abort mid-decode when crossed, never inflate-then-check). `/DL` is
29//! a hint (Table 5) and is deliberately NOT the bound.
30//!
31//! ## This module handles BYTE-STREAM filters only (decision 005 R23)
32//!
33//! A byte-stream filter consumes bytes, produces bytes, and composes
34//! with the next stage of the cascade. An **image codec** —
35//! `DCTDecode`, `CCITTFaxDecode`, `JBIG2Decode`, `JPXDecode` — does
36//! not: its output is *samples* whose geometry and colour model are
37//! declared by the codestream itself, and §8.9.5 Table 89 goes as far
38//! as making the codestream's declarations **outrank the image
39//! dictionary** for JPXDecode. A `Vec<u8>` return type has nowhere to
40//! put that information, and re-deriving it would mean parsing hostile
41//! input twice.
42//!
43//! So [`decode_stream`] never decodes an image codec. Reaching one
44//! returns [`FilterError::ImageCodec`], which says "this is a codec,
45//! decode it through `pdfcer_core::image_codec`" — deliberately distinct
46//! from [`FilterError::UnsupportedFilter`], which says "pdfcer does not
47//! implement this filter at all." The full rationale is in
48//! `docs/decisions/005-image-codecs.md` §1.2, §4.6 and §5.2.
49//!
50//! ## Coverage
51//!
52//! - **FlateDecode** (with PNG/TIFF predictors) — object streams, xref
53//!   streams, content streams, and most images.
54//! - **ASCIIHexDecode / ASCII85Decode** ([`ascii`]) — the ASCII
55//!   armouring filters. They compress nothing, but they are the only
56//!   two filters that make an inline image's data length unambiguous
57//!   (§8.9.7), which is why they land with the image-rendering slice
58//!   rather than later.
59//! - **LZWDecode** ([`lzw`], Pass 2.1) — legacy but still present in
60//!   pre-PDF-1.2 files and legacy tooling output. Shares the predictor
61//!   stage with Flate; `/EarlyChange` is its one extra parameter.
62//! - **RunLengthDecode** ([`runlength`], Pass 2.1) — trivial, no
63//!   parameters, self-limiting.
64//!
65//! Any other name — a codec handled elsewhere, a crypt filter, or
66//! something non-standard — is *recognized* and refused with a precise
67//! diagnostic rather than guessed at, the same detect-don't-misparse
68//! posture as the xref layer.
69//!
70//! ## Notes vs errors
71//!
72//! Some streams decode correctly while still being *non-conformant* in
73//! a way an operator should be able to see (an LZW stream with no
74//! `ClearCode`, for instance). Those are counted in [`FilterNotes`] and
75//! surfaced by [`decode_stream_with_notes`] — "fuzzy, never sneaky"
76//! applied at the filter layer. [`decode_stream`] is the same decode
77//! with the notes dropped, for the many callers (xref streams, object
78//! streams, content streams) that have nowhere to put them.
79
80pub mod ascii;
81/// `/BrotliDecode` — a PDF Association EXTENSION, not ISO 32000-2. See the
82/// module docs before believing any citation you find for it.
83pub mod brotli;
84pub mod flate;
85pub mod lzw;
86pub mod predictor;
87pub mod runlength;
88mod stream;
89
90pub use stream::{MAX_DECODE_RATIO, ReadStatus, StreamDecoder};
91
92use crate::object::{Dict, Object};
93
94/// Hard ceiling on a single stream's decoded size.
95///
96/// pdfcer policy (ARCHITECTURE.md §10.1): no Annex C limit exists for
97/// this; 256 MiB decoded is beyond any legitimate single stream
98/// (content streams are KBs; even a 300-DPI A4 uncompressed RGB image
99/// is ~35 MB) while bounding a decompression bomb's blast radius.
100pub const MAX_DECODED_LEN: usize = 256 * 1024 * 1024;
101
102/// Scratch-chunk size every incremental decoder works in: large enough
103/// to amortize the per-call overhead, small enough that a ceiling
104/// overshoots by a negligible amount.
105pub(crate) const CHUNK: usize = 64 * 1024;
106
107/// A decoder that produces its output a chunk at a time.
108///
109/// Both the whole-stream decode ([`drain`]) and the windowed
110/// [`StreamDecoder`] drive the same `pull`, so the two cannot disagree
111/// about a stream's bytes.
112pub(crate) trait Pull {
113    /// Append the next chunk to `out`; `Ok(true)` once the stream has
114    /// ended (anything appended by that call is still output).
115    fn pull(&mut self, out: &mut Vec<u8>) -> Result<bool, FilterError>;
116}
117
118/// Run `p` to its end under [`MAX_DECODED_LEN`].
119pub(crate) fn drain(p: &mut impl Pull) -> Result<Vec<u8>, FilterError> {
120    let mut out = Vec::new();
121    loop {
122        let done = p.pull(&mut out)?;
123        if out.len() > MAX_DECODED_LEN {
124            return Err(FilterError::OutputTooLarge);
125        }
126        if done {
127            return Ok(out);
128        }
129    }
130}
131
132/// A filter-decode error.
133#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
134#[non_exhaustive]
135pub enum FilterError {
136    /// The compressed data is invalid (bad zlib header, corrupt
137    /// deflate stream, checksum structurally unreadable, …).
138    #[error("corrupt {filter} data: {detail}")]
139    Corrupt {
140        /// Which filter failed.
141        filter: &'static str,
142        /// Human-readable failure detail from the underlying decoder.
143        detail: String,
144    },
145    /// The stream ended before the filter's own end-of-data — a
146    /// truncated stream (§7.3.8.2 extent inconsistency).
147    #[error("{filter} stream truncated")]
148    Truncated {
149        /// Which filter detected the truncation.
150        filter: &'static str,
151    },
152    /// Decoded output crossed [`MAX_DECODED_LEN`] (pdfcer guard) — the
153    /// decode was aborted mid-stream.
154    #[error("decoded output exceeds MAX_DECODED_LEN ({MAX_DECODED_LEN} bytes)")]
155    OutputTooLarge,
156    /// `/DecodeParms` carried an invalid parameter combination
157    /// (unknown `Predictor` value, zero `Columns`, bad
158    /// `BitsPerComponent`, …).
159    #[error("invalid decode parameters: {0}")]
160    BadParams(&'static str),
161    /// Predicted data length is not a whole number of rows — wrong
162    /// parameters or truncation (`filter__predictors.md` row
163    /// arithmetic).
164    #[error("predicted data is not a whole number of rows")]
165    RaggedRows,
166    /// A PNG row carried an algorithm tag outside 0–4 (RFC 2083 §6:
167    /// an error).
168    #[error("unknown PNG predictor tag {0}")]
169    UnknownPngTag(u8),
170    /// A standard filter pdfcer doesn't implement yet (Pass 1 scope).
171    /// The payload is the filter name as written.
172    #[error("filter {0:?} is not yet supported")]
173    UnsupportedFilter(String),
174    /// The chain reaches an image codec, which [`decode_stream`] does
175    /// not handle **by design** (decision 005 R23). Decode it through
176    /// `pdfcer_core::image_codec::decode_image`, which has the `&Document`
177    /// and the image dictionary that these codecs require, and which
178    /// returns the codec-declared geometry and colour model that a
179    /// `Vec<u8>` cannot carry.
180    ///
181    /// Deliberately distinct from [`FilterError::UnsupportedFilter`]:
182    /// that one means "pdfcer cannot decode this at all", this one means
183    /// "you called the wrong entry point." A caller that only wants
184    /// bytes (an xref stream, an object stream) genuinely cannot
185    /// proceed, so it is still an error there — but the operator-facing
186    /// message stays honest about which of the two situations it is.
187    #[error("filter {0:?} is an image codec; decode it via image_codec::decode_image")]
188    ImageCodec(String),
189    /// `/Filter` held something other than a name or array of names.
190    #[error("malformed /Filter entry")]
191    BadFilterEntry,
192}
193
194/// Divergences that did **not** stop a stream from decoding.
195///
196/// Separate from [`FilterError`] because the operator's question is
197/// different: an error means "these bytes are unusable", a note means
198/// "these bytes are fine but the file that produced them is not
199/// conformant." Accumulated across the whole `/Filter` chain.
200#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
201#[non_exhaustive]
202pub struct FilterNotes {
203    /// LZW streams that did not begin with a `ClearCode`, or that ended
204    /// without an `EndOfInformation`. Both are non-conformant (TIFF 6.0
205    /// §13; ISO 32000-1 §7.4.4.2), both are recovered, both are
206    /// reported. See [`lzw`] for the sourced recovery rules.
207    pub lzw_framing_anomalies: usize,
208}
209
210/// Decode a stream's raw bytes through its full `/Filter` chain.
211///
212/// `dict` is the stream dictionary; `raw` its encoded bytes (the
213/// `data_span` slice). Handles the Table 5 shapes: `/Filter` absent
214/// (identity), a single name, or an array of zero or more names
215/// applied **in array order** (decode order = written order, Table 5);
216/// `/DecodeParms` correspondingly a dict, an array (with `null` for
217/// parameterless positions), or absent.
218///
219/// # Errors
220///
221/// [`FilterError`] — see the variants; fail-clean per the module docs.
222pub fn decode_stream(dict: &Dict, raw: &[u8]) -> Result<Vec<u8>, FilterError> {
223    decode_stream_with_notes(dict, raw).map(|(data, _)| data)
224}
225
226/// [`decode_stream`], keeping the non-fatal [`FilterNotes`].
227///
228/// Use this wherever the notes have somewhere to go — the image path
229/// surfaces them in the renderer's diagnostics. Every other caller
230/// (xref streams, object streams, content streams) has no diagnostics
231/// channel and uses [`decode_stream`].
232///
233/// # Errors
234///
235/// Identical to [`decode_stream`].
236pub fn decode_stream_with_notes(
237    dict: &Dict,
238    raw: &[u8],
239) -> Result<(Vec<u8>, FilterNotes), FilterError> {
240    let filters = filter_names(dict)?;
241    let mut notes = FilterNotes::default();
242    let data = decode_prefix(dict, raw, filters.len(), &mut notes)?;
243    Ok((data, notes))
244}
245
246/// Apply the first `take` filters of `dict`'s chain to `raw`.
247///
248/// Exists so `pdfcer_core::image_codec` can run the **byte-stream prefix**
249/// of a chain that ends in an image codec (e.g.
250/// `/Filter [/ASCII85Decode /DCTDecode]`, which is a real and legal
251/// shape) and then dispatch the terminal codec itself. `take` equal to
252/// the full chain length is the ordinary [`decode_stream`] case.
253///
254/// # Errors
255///
256/// [`FilterError`] from any stage; in particular
257/// [`FilterError::ImageCodec`] if a codec name falls inside the prefix,
258/// which means the caller mis-computed where the chain's byte-stream
259/// part ends.
260#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
261pub fn decode_prefix(
262    dict: &Dict,
263    raw: &[u8],
264    take: usize,
265    notes: &mut FilterNotes,
266) -> Result<Vec<u8>, FilterError> {
267    let filters = filter_names(dict)?;
268    let mut data: Vec<u8> = raw.to_vec();
269    for (i, name) in filters.iter().enumerate().take(take) {
270        let parms = decode_parms_for(dict, i, filters.len());
271        data = apply_one(name, parms, &data, notes)?;
272    }
273    Ok(data)
274}
275
276/// Apply a single named filter.
277///
278/// Abbreviated spellings (Table 94) are accepted alongside the full
279/// names because inline images legally use them; `pdfcer_model::content`
280/// normalizes the ones it sees, but a stream dictionary that spells a
281/// filter the short way is not worth refusing.
282fn apply_one(
283    name: &[u8],
284    parms: Option<&Dict>,
285    data: &[u8],
286    notes: &mut FilterNotes,
287) -> Result<Vec<u8>, FilterError> {
288    match name {
289        b"FlateDecode" | b"Fl" => flate::decode(data, parms),
290        // EXTN-BROTLI-1 §5.2. NO ABBREVIATION: the extension defines none,
291        // and Table 92's abbreviations exist for inline images, which this
292        // filter `SHALL NOT` be used for. MuPDF accepts a `/Br` alias that
293        // does not exist in the extension -- that is MuPDF's behaviour, not
294        // the specification, and pdfcer does not follow it. Accepting `/Br`
295        // would make pdfcer read files no conformant writer produces and no
296        // other reader agrees on.
297        b"BrotliDecode" => brotli::decode(data, parms),
298        // §7.4.2/§7.4.3 — parameterless (Table 6), so `parms` is
299        // deliberately not forwarded.
300        b"ASCIIHexDecode" | b"AHx" => ascii::decode_hex(data),
301        b"ASCII85Decode" | b"A85" => ascii::decode_85(data),
302        b"LZWDecode" | b"LZW" => lzw::decode(data, parms, notes),
303        // §7.4.5 — parameterless (Table 6).
304        b"RunLengthDecode" | b"RL" => runlength::decode(data),
305        // Image codecs are a TERMINAL stage, not a byte-stream filter
306        // (R23). Named separately so the operator-facing message says
307        // "wrong entry point", not "unsupported".
308        b"DCTDecode" | b"DCT" | b"CCITTFaxDecode" | b"CCF" | b"JBIG2Decode" | b"JPXDecode"
309        | b"JXLDecode" => Err(FilterError::ImageCodec(
310            String::from_utf8_lossy(name).into_owned(),
311        )),
312        // Anything else: a crypt filter, or a non-standard name.
313        // Refused with a precise diagnostic rather than guessed at.
314        other => Err(FilterError::UnsupportedFilter(
315            String::from_utf8_lossy(other).into_owned(),
316        )),
317    }
318}
319
320/// Extract the ordered filter-name list from `/Filter` (name, array of
321/// names, or absent → empty).
322#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
323pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
324    match dict.get(b"Filter") {
325        None => Ok(Vec::new()),
326        Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
327        Some(Object::Array(items)) => items
328            .iter()
329            .map(|o| match o {
330                Object::Name(n) => Ok(n.as_bytes().to_vec()),
331                _ => Err(FilterError::BadFilterEntry),
332            })
333            .collect(),
334        Some(_) => Err(FilterError::BadFilterEntry),
335    }
336}
337
338/// The `/DecodeParms` entry for filter position `i` of `total`
339/// (Table 5 shape rules). `None` = defaults. A malformed entry is
340/// treated as absent — the individual filter then validates whatever
341/// it actually needs; parameters it never looks at can't hurt it.
342fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
343    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
344    match parms {
345        Object::Dict(d) if total == 1 => Some(d),
346        Object::Array(items) => match items.get(i) {
347            Some(Object::Dict(d)) => Some(d),
348            _ => None, // null / absent position = defaults (Table 5)
349        },
350        _ => None,
351    }
352}
353
354#[cfg(test)]
355#[allow(
356    clippy::unwrap_used,
357    clippy::expect_used,
358    clippy::panic,
359    clippy::indexing_slicing
360)]
361mod tests {
362    use super::*;
363    use crate::object::Name;
364
365    fn dict_with_filter(filter: Object) -> Dict {
366        let mut d = Dict::new();
367        d.insert(Name::from(b"Filter"), filter);
368        d
369    }
370
371    #[test]
372    fn no_filter_is_identity() {
373        let d = Dict::new();
374        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
375    }
376
377    #[test]
378    fn empty_filter_array_is_identity() {
379        // Table 5: an array of ZERO names is legal.
380        let d = dict_with_filter(Object::Array(vec![]));
381        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
382    }
383
384    #[test]
385    fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
386        // R23: `decode_stream` never decodes a codec, and says so in a
387        // way distinguishable from "pdfcer cannot do this at all".
388        for name in [
389            &b"DCTDecode"[..],
390            b"CCITTFaxDecode",
391            b"JBIG2Decode",
392            b"JPXDecode",
393            b"JXLDecode",
394        ] {
395            let d = dict_with_filter(Object::Name(Name::from(name)));
396            let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
397            assert_eq!(
398                e,
399                FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
400            );
401        }
402    }
403
404    #[test]
405    fn unsupported_filter_is_named_in_error() {
406        let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
407        let e = decode_stream(&d, b"anything").unwrap_err();
408        assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
409    }
410
411    /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
412    ///
413    /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
414    /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
415    /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
416    /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
417    /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
418    ///
419    /// This is a behaviour-versus-specification split, and following the
420    /// behaviour would be the worse choice in both directions — pdfcer would
421    /// read files no conformant writer emits, and would disagree with every
422    /// reader that is not MuPDF. Pinned as a test so a future reader who
423    /// meets a `/Br` in the wild adds it deliberately, with a decision
424    /// record, rather than as an obvious-looking omission.
425    #[test]
426    fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
427        let mut notes = FilterNotes::default();
428        let e = apply_one(b"Br", None, b"anything", &mut notes).unwrap_err();
429        assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
430    }
431
432    /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
433    ///
434    /// Asserted through the DISPATCH rather than by calling `brotli::decode`
435    /// directly: the filter module's own tests prove the decoder works, and
436    /// this proves the name is wired to it. Those are different claims, and
437    /// `Pass 2.x`'s history has an instance of each passing while the other
438    /// failed.
439    #[test]
440    fn brotli_decode_is_dispatched_and_not_refused() {
441        let mut notes = FilterNotes::default();
442        // Deliberately invalid Brotli. Success here would mean the name was
443        // silently ignored; what must happen is that the BROTLI decoder
444        // refuses it, which is a differently-shaped error from
445        // `UnsupportedFilter` and is what distinguishes "wired" from "not".
446        let e = apply_one(b"BrotliDecode", None, &[0xff; 32], &mut notes).unwrap_err();
447        assert!(
448            !matches!(e, FilterError::UnsupportedFilter(_)),
449            "/BrotliDecode must reach its decoder, got {e:?}"
450        );
451    }
452
453    #[test]
454    fn runlength_runs_in_the_cascade() {
455        let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
456        assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
457    }
458
459    #[test]
460    fn lzw_notes_reach_the_caller_through_the_cascade() {
461        // A stream that does not begin with a ClearCode still decodes,
462        // and the non-conformance is COUNTED rather than absorbed.
463        let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
464        let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
465        assert_eq!(data, b"A");
466        assert_eq!(notes.lzw_framing_anomalies, 1);
467    }
468
469    #[test]
470    fn non_name_filter_entry_is_error() {
471        let d = dict_with_filter(Object::Integer(5));
472        assert_eq!(
473            decode_stream(&d, b"x").unwrap_err(),
474            FilterError::BadFilterEntry
475        );
476    }
477
478    #[test]
479    fn flate_roundtrip_via_pipeline() {
480        use flate2::Compression;
481        use flate2::write::ZlibEncoder;
482        use std::io::Write as _;
483
484        let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
485        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
486        enc.write_all(&original).unwrap();
487        let compressed = enc.finish().unwrap();
488
489        let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
490        assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
491    }
492}