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" => Err(
276 FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned()),
277 ),
278 // Anything else: a crypt filter, or a non-standard name.
279 // Refused with a precise diagnostic rather than guessed at.
280 other => Err(FilterError::UnsupportedFilter(
281 String::from_utf8_lossy(other).into_owned(),
282 )),
283 }
284}
285
286/// Extract the ordered filter-name list from `/Filter` (name, array of
287/// names, or absent → empty).
288#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
289pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
290 match dict.get(b"Filter") {
291 None => Ok(Vec::new()),
292 Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
293 Some(Object::Array(items)) => items
294 .iter()
295 .map(|o| match o {
296 Object::Name(n) => Ok(n.as_bytes().to_vec()),
297 _ => Err(FilterError::BadFilterEntry),
298 })
299 .collect(),
300 Some(_) => Err(FilterError::BadFilterEntry),
301 }
302}
303
304/// The `/DecodeParms` entry for filter position `i` of `total`
305/// (Table 5 shape rules). `None` = defaults. A malformed entry is
306/// treated as absent — the individual filter then validates whatever
307/// it actually needs; parameters it never looks at can't hurt it.
308fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
309 let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
310 match parms {
311 Object::Dict(d) if total == 1 => Some(d),
312 Object::Array(items) => match items.get(i) {
313 Some(Object::Dict(d)) => Some(d),
314 _ => None, // null / absent position = defaults (Table 5)
315 },
316 _ => None,
317 }
318}
319
320#[cfg(test)]
321#[allow(
322 clippy::unwrap_used,
323 clippy::expect_used,
324 clippy::panic,
325 clippy::indexing_slicing
326)]
327mod tests {
328 use super::*;
329 use crate::object::Name;
330
331 fn dict_with_filter(filter: Object) -> Dict {
332 let mut d = Dict::new();
333 d.insert(Name::from(b"Filter"), filter);
334 d
335 }
336
337 #[test]
338 fn no_filter_is_identity() {
339 let d = Dict::new();
340 assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
341 }
342
343 #[test]
344 fn empty_filter_array_is_identity() {
345 // Table 5: an array of ZERO names is legal.
346 let d = dict_with_filter(Object::Array(vec![]));
347 assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
348 }
349
350 #[test]
351 fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
352 // R23: `decode_stream` never decodes a codec, and says so in a
353 // way distinguishable from "pdfcer cannot do this at all".
354 for name in [
355 &b"DCTDecode"[..],
356 b"CCITTFaxDecode",
357 b"JBIG2Decode",
358 b"JPXDecode",
359 ] {
360 let d = dict_with_filter(Object::Name(Name::from(name)));
361 let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
362 assert_eq!(
363 e,
364 FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
365 );
366 }
367 }
368
369 #[test]
370 fn unsupported_filter_is_named_in_error() {
371 let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
372 let e = decode_stream(&d, b"anything").unwrap_err();
373 assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
374 }
375
376 /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
377 ///
378 /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
379 /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
380 /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
381 /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
382 /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
383 ///
384 /// This is a behaviour-versus-specification split, and following the
385 /// behaviour would be the worse choice in both directions — pdfcer would
386 /// read files no conformant writer emits, and would disagree with every
387 /// reader that is not MuPDF. Pinned as a test so a future reader who
388 /// meets a `/Br` in the wild adds it deliberately, with a decision
389 /// record, rather than as an obvious-looking omission.
390 #[test]
391 fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
392 let mut notes = FilterNotes::default();
393 let e = apply_one(b"Br", None, b"anything", &mut notes).unwrap_err();
394 assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
395 }
396
397 /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
398 ///
399 /// Asserted through the DISPATCH rather than by calling `brotli::decode`
400 /// directly: the filter module's own tests prove the decoder works, and
401 /// this proves the name is wired to it. Those are different claims, and
402 /// `Pass 2.x`'s history has an instance of each passing while the other
403 /// failed.
404 #[test]
405 fn brotli_decode_is_dispatched_and_not_refused() {
406 let mut notes = FilterNotes::default();
407 // Deliberately invalid Brotli. Success here would mean the name was
408 // silently ignored; what must happen is that the BROTLI decoder
409 // refuses it, which is a differently-shaped error from
410 // `UnsupportedFilter` and is what distinguishes "wired" from "not".
411 let e = apply_one(b"BrotliDecode", None, &[0xff; 32], &mut notes).unwrap_err();
412 assert!(
413 !matches!(e, FilterError::UnsupportedFilter(_)),
414 "/BrotliDecode must reach its decoder, got {e:?}"
415 );
416 }
417
418 #[test]
419 fn runlength_runs_in_the_cascade() {
420 let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
421 assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
422 }
423
424 #[test]
425 fn lzw_notes_reach_the_caller_through_the_cascade() {
426 // A stream that does not begin with a ClearCode still decodes,
427 // and the non-conformance is COUNTED rather than absorbed.
428 let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
429 let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
430 assert_eq!(data, b"A");
431 assert_eq!(notes.lzw_framing_anomalies, 1);
432 }
433
434 #[test]
435 fn non_name_filter_entry_is_error() {
436 let d = dict_with_filter(Object::Integer(5));
437 assert_eq!(
438 decode_stream(&d, b"x").unwrap_err(),
439 FilterError::BadFilterEntry
440 );
441 }
442
443 #[test]
444 fn flate_roundtrip_via_pipeline() {
445 use flate2::Compression;
446 use flate2::write::ZlibEncoder;
447 use std::io::Write as _;
448
449 let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
450 let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
451 enc.write_all(&original).unwrap();
452 let compressed = enc.finish().unwrap();
453
454 let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
455 assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
456 }
457}