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;
88
89use crate::object::{Dict, Object};
90
91/// Hard ceiling on a single stream's decoded size.
92///
93/// pdfcer policy (ARCHITECTURE.md §10.1): no Annex C limit exists for
94/// this; 256 MiB decoded is beyond any legitimate single stream
95/// (content streams are KBs; even a 300-DPI A4 uncompressed RGB image
96/// is ~35 MB) while bounding a decompression bomb's blast radius.
97pub const MAX_DECODED_LEN: usize = 256 * 1024 * 1024;
98
99/// A filter-decode error.
100#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
101#[non_exhaustive]
102pub enum FilterError {
103    /// The compressed data is invalid (bad zlib header, corrupt
104    /// deflate stream, checksum structurally unreadable, …).
105    #[error("corrupt {filter} data: {detail}")]
106    Corrupt {
107        /// Which filter failed.
108        filter: &'static str,
109        /// Human-readable failure detail from the underlying decoder.
110        detail: String,
111    },
112    /// The stream ended before the filter's own end-of-data — a
113    /// truncated stream (§7.3.8.2 extent inconsistency).
114    #[error("{filter} stream truncated")]
115    Truncated {
116        /// Which filter detected the truncation.
117        filter: &'static str,
118    },
119    /// Decoded output crossed [`MAX_DECODED_LEN`] (pdfcer guard) — the
120    /// decode was aborted mid-stream.
121    #[error("decoded output exceeds MAX_DECODED_LEN ({MAX_DECODED_LEN} bytes)")]
122    OutputTooLarge,
123    /// `/DecodeParms` carried an invalid parameter combination
124    /// (unknown `Predictor` value, zero `Columns`, bad
125    /// `BitsPerComponent`, …).
126    #[error("invalid decode parameters: {0}")]
127    BadParams(&'static str),
128    /// Predicted data length is not a whole number of rows — wrong
129    /// parameters or truncation (`filter__predictors.md` row
130    /// arithmetic).
131    #[error("predicted data is not a whole number of rows")]
132    RaggedRows,
133    /// A PNG row carried an algorithm tag outside 0–4 (RFC 2083 §6:
134    /// an error).
135    #[error("unknown PNG predictor tag {0}")]
136    UnknownPngTag(u8),
137    /// A standard filter pdfcer doesn't implement yet (Pass 1 scope).
138    /// The payload is the filter name as written.
139    #[error("filter {0:?} is not yet supported")]
140    UnsupportedFilter(String),
141    /// The chain reaches an image codec, which [`decode_stream`] does
142    /// not handle **by design** (decision 005 R23). Decode it through
143    /// `pdfcer_core::image_codec::decode_image`, which has the `&Document`
144    /// and the image dictionary that these codecs require, and which
145    /// returns the codec-declared geometry and colour model that a
146    /// `Vec<u8>` cannot carry.
147    ///
148    /// Deliberately distinct from [`FilterError::UnsupportedFilter`]:
149    /// that one means "pdfcer cannot decode this at all", this one means
150    /// "you called the wrong entry point." A caller that only wants
151    /// bytes (an xref stream, an object stream) genuinely cannot
152    /// proceed, so it is still an error there — but the operator-facing
153    /// message stays honest about which of the two situations it is.
154    #[error("filter {0:?} is an image codec; decode it via image_codec::decode_image")]
155    ImageCodec(String),
156    /// `/Filter` held something other than a name or array of names.
157    #[error("malformed /Filter entry")]
158    BadFilterEntry,
159}
160
161/// Divergences that did **not** stop a stream from decoding.
162///
163/// Separate from [`FilterError`] because the operator's question is
164/// different: an error means "these bytes are unusable", a note means
165/// "these bytes are fine but the file that produced them is not
166/// conformant." Accumulated across the whole `/Filter` chain.
167#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
168#[non_exhaustive]
169pub struct FilterNotes {
170    /// LZW streams that did not begin with a `ClearCode`, or that ended
171    /// without an `EndOfInformation`. Both are non-conformant (TIFF 6.0
172    /// §13; ISO 32000-1 §7.4.4.2), both are recovered, both are
173    /// reported. See [`lzw`] for the sourced recovery rules.
174    pub lzw_framing_anomalies: usize,
175}
176
177/// Decode a stream's raw bytes through its full `/Filter` chain.
178///
179/// `dict` is the stream dictionary; `raw` its encoded bytes (the
180/// `data_span` slice). Handles the Table 5 shapes: `/Filter` absent
181/// (identity), a single name, or an array of zero or more names
182/// applied **in array order** (decode order = written order, Table 5);
183/// `/DecodeParms` correspondingly a dict, an array (with `null` for
184/// parameterless positions), or absent.
185///
186/// # Errors
187///
188/// [`FilterError`] — see the variants; fail-clean per the module docs.
189pub fn decode_stream(dict: &Dict, raw: &[u8]) -> Result<Vec<u8>, FilterError> {
190    decode_stream_with_notes(dict, raw).map(|(data, _)| data)
191}
192
193/// [`decode_stream`], keeping the non-fatal [`FilterNotes`].
194///
195/// Use this wherever the notes have somewhere to go — the image path
196/// surfaces them in the renderer's diagnostics. Every other caller
197/// (xref streams, object streams, content streams) has no diagnostics
198/// channel and uses [`decode_stream`].
199///
200/// # Errors
201///
202/// Identical to [`decode_stream`].
203pub fn decode_stream_with_notes(
204    dict: &Dict,
205    raw: &[u8],
206) -> Result<(Vec<u8>, FilterNotes), FilterError> {
207    let filters = filter_names(dict)?;
208    let mut notes = FilterNotes::default();
209    let data = decode_prefix(dict, raw, filters.len(), &mut notes)?;
210    Ok((data, notes))
211}
212
213/// Apply the first `take` filters of `dict`'s chain to `raw`.
214///
215/// Exists so `pdfcer_core::image_codec` can run the **byte-stream prefix**
216/// of a chain that ends in an image codec (e.g.
217/// `/Filter [/ASCII85Decode /DCTDecode]`, which is a real and legal
218/// shape) and then dispatch the terminal codec itself. `take` equal to
219/// the full chain length is the ordinary [`decode_stream`] case.
220///
221/// # Errors
222///
223/// [`FilterError`] from any stage; in particular
224/// [`FilterError::ImageCodec`] if a codec name falls inside the prefix,
225/// which means the caller mis-computed where the chain's byte-stream
226/// part ends.
227#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
228pub fn decode_prefix(
229    dict: &Dict,
230    raw: &[u8],
231    take: usize,
232    notes: &mut FilterNotes,
233) -> Result<Vec<u8>, FilterError> {
234    let filters = filter_names(dict)?;
235    let mut data: Vec<u8> = raw.to_vec();
236    for (i, name) in filters.iter().enumerate().take(take) {
237        let parms = decode_parms_for(dict, i, filters.len());
238        data = apply_one(name, parms, &data, notes)?;
239    }
240    Ok(data)
241}
242
243/// Apply a single named filter.
244///
245/// Abbreviated spellings (Table 94) are accepted alongside the full
246/// names because inline images legally use them; `pdfcer_model::content`
247/// normalizes the ones it sees, but a stream dictionary that spells a
248/// filter the short way is not worth refusing.
249fn apply_one(
250    name: &[u8],
251    parms: Option<&Dict>,
252    data: &[u8],
253    notes: &mut FilterNotes,
254) -> Result<Vec<u8>, FilterError> {
255    match name {
256        b"FlateDecode" | b"Fl" => flate::decode(data, parms),
257        // EXTN-BROTLI-1 §5.2. NO ABBREVIATION: the extension defines none,
258        // and Table 92's abbreviations exist for inline images, which this
259        // filter `SHALL NOT` be used for. MuPDF accepts a `/Br` alias that
260        // does not exist in the extension -- that is MuPDF's behaviour, not
261        // the specification, and pdfcer does not follow it. Accepting `/Br`
262        // would make pdfcer read files no conformant writer produces and no
263        // other reader agrees on.
264        b"BrotliDecode" => brotli::decode(data, parms),
265        // §7.4.2/§7.4.3 — parameterless (Table 6), so `parms` is
266        // deliberately not forwarded.
267        b"ASCIIHexDecode" | b"AHx" => ascii::decode_hex(data),
268        b"ASCII85Decode" | b"A85" => ascii::decode_85(data),
269        b"LZWDecode" | b"LZW" => lzw::decode(data, parms, notes),
270        // §7.4.5 — parameterless (Table 6).
271        b"RunLengthDecode" | b"RL" => runlength::decode(data),
272        // Image codecs are a TERMINAL stage, not a byte-stream filter
273        // (R23). Named separately so the operator-facing message says
274        // "wrong entry point", not "unsupported".
275        b"DCTDecode" | b"DCT" | b"CCITTFaxDecode" | b"CCF" | b"JBIG2Decode" | b"JPXDecode"
276        | b"JXLDecode" => Err(FilterError::ImageCodec(
277            String::from_utf8_lossy(name).into_owned(),
278        )),
279        // Anything else: a crypt filter, or a non-standard name.
280        // Refused with a precise diagnostic rather than guessed at.
281        other => Err(FilterError::UnsupportedFilter(
282            String::from_utf8_lossy(other).into_owned(),
283        )),
284    }
285}
286
287/// Extract the ordered filter-name list from `/Filter` (name, array of
288/// names, or absent → empty).
289#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
290pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
291    match dict.get(b"Filter") {
292        None => Ok(Vec::new()),
293        Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
294        Some(Object::Array(items)) => items
295            .iter()
296            .map(|o| match o {
297                Object::Name(n) => Ok(n.as_bytes().to_vec()),
298                _ => Err(FilterError::BadFilterEntry),
299            })
300            .collect(),
301        Some(_) => Err(FilterError::BadFilterEntry),
302    }
303}
304
305/// The `/DecodeParms` entry for filter position `i` of `total`
306/// (Table 5 shape rules). `None` = defaults. A malformed entry is
307/// treated as absent — the individual filter then validates whatever
308/// it actually needs; parameters it never looks at can't hurt it.
309fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
310    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
311    match parms {
312        Object::Dict(d) if total == 1 => Some(d),
313        Object::Array(items) => match items.get(i) {
314            Some(Object::Dict(d)) => Some(d),
315            _ => None, // null / absent position = defaults (Table 5)
316        },
317        _ => None,
318    }
319}
320
321#[cfg(test)]
322#[allow(
323    clippy::unwrap_used,
324    clippy::expect_used,
325    clippy::panic,
326    clippy::indexing_slicing
327)]
328mod tests {
329    use super::*;
330    use crate::object::Name;
331
332    fn dict_with_filter(filter: Object) -> Dict {
333        let mut d = Dict::new();
334        d.insert(Name::from(b"Filter"), filter);
335        d
336    }
337
338    #[test]
339    fn no_filter_is_identity() {
340        let d = Dict::new();
341        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
342    }
343
344    #[test]
345    fn empty_filter_array_is_identity() {
346        // Table 5: an array of ZERO names is legal.
347        let d = dict_with_filter(Object::Array(vec![]));
348        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
349    }
350
351    #[test]
352    fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
353        // R23: `decode_stream` never decodes a codec, and says so in a
354        // way distinguishable from "pdfcer cannot do this at all".
355        for name in [
356            &b"DCTDecode"[..],
357            b"CCITTFaxDecode",
358            b"JBIG2Decode",
359            b"JPXDecode",
360            b"JXLDecode",
361        ] {
362            let d = dict_with_filter(Object::Name(Name::from(name)));
363            let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
364            assert_eq!(
365                e,
366                FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
367            );
368        }
369    }
370
371    #[test]
372    fn unsupported_filter_is_named_in_error() {
373        let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
374        let e = decode_stream(&d, b"anything").unwrap_err();
375        assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
376    }
377
378    /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
379    ///
380    /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
381    /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
382    /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
383    /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
384    /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
385    ///
386    /// This is a behaviour-versus-specification split, and following the
387    /// behaviour would be the worse choice in both directions — pdfcer would
388    /// read files no conformant writer emits, and would disagree with every
389    /// reader that is not MuPDF. Pinned as a test so a future reader who
390    /// meets a `/Br` in the wild adds it deliberately, with a decision
391    /// record, rather than as an obvious-looking omission.
392    #[test]
393    fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
394        let mut notes = FilterNotes::default();
395        let e = apply_one(b"Br", None, b"anything", &mut notes).unwrap_err();
396        assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
397    }
398
399    /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
400    ///
401    /// Asserted through the DISPATCH rather than by calling `brotli::decode`
402    /// directly: the filter module's own tests prove the decoder works, and
403    /// this proves the name is wired to it. Those are different claims, and
404    /// `Pass 2.x`'s history has an instance of each passing while the other
405    /// failed.
406    #[test]
407    fn brotli_decode_is_dispatched_and_not_refused() {
408        let mut notes = FilterNotes::default();
409        // Deliberately invalid Brotli. Success here would mean the name was
410        // silently ignored; what must happen is that the BROTLI decoder
411        // refuses it, which is a differently-shaped error from
412        // `UnsupportedFilter` and is what distinguishes "wired" from "not".
413        let e = apply_one(b"BrotliDecode", None, &[0xff; 32], &mut notes).unwrap_err();
414        assert!(
415            !matches!(e, FilterError::UnsupportedFilter(_)),
416            "/BrotliDecode must reach its decoder, got {e:?}"
417        );
418    }
419
420    #[test]
421    fn runlength_runs_in_the_cascade() {
422        let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
423        assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
424    }
425
426    #[test]
427    fn lzw_notes_reach_the_caller_through_the_cascade() {
428        // A stream that does not begin with a ClearCode still decodes,
429        // and the non-conformance is COUNTED rather than absorbed.
430        let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
431        let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
432        assert_eq!(data, b"A");
433        assert_eq!(notes.lzw_framing_anomalies, 1);
434    }
435
436    #[test]
437    fn non_name_filter_entry_is_error() {
438        let d = dict_with_filter(Object::Integer(5));
439        assert_eq!(
440            decode_stream(&d, b"x").unwrap_err(),
441            FilterError::BadFilterEntry
442        );
443    }
444
445    #[test]
446    fn flate_roundtrip_via_pipeline() {
447        use flate2::Compression;
448        use flate2::write::ZlibEncoder;
449        use std::io::Write as _;
450
451        let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
452        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
453        enc.write_all(&original).unwrap();
454        let compressed = enc.finish().unwrap();
455
456        let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
457        assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
458    }
459}