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;
84#[cfg(test)]
85#[allow(clippy::unwrap_used, clippy::indexing_slicing)] // test assertions
86mod cancel_tests;
87pub mod flate;
88pub mod lzw;
89pub mod predictor;
90pub mod runlength;
91mod stream;
92
93pub use stream::{MAX_DECODE_RATIO, ReadStatus, StreamDecoder};
94
95use crate::object::{Dict, Object};
96
97/// Hard ceiling on a single stream's decoded size.
98///
99/// pdfcer policy (ARCHITECTURE.md §10.1): no Annex C limit exists for
100/// this; 256 MiB decoded is beyond any legitimate single stream
101/// (content streams are KBs; even a 300-DPI A4 uncompressed RGB image
102/// is ~35 MB) while bounding a decompression bomb's blast radius.
103pub const MAX_DECODED_LEN: usize = 256 * 1024 * 1024;
104
105/// Scratch-chunk size every incremental decoder works in: large enough
106/// to amortize the per-call overhead, small enough that a ceiling
107/// overshoots by a negligible amount.
108pub(crate) const CHUNK: usize = 64 * 1024;
109
110/// A decoder that produces its output a chunk at a time.
111///
112/// Both the whole-stream decode ([`drain`]) and the windowed
113/// [`StreamDecoder`] drive the same `pull`, so the two cannot disagree
114/// about a stream's bytes.
115pub(crate) trait Pull {
116    /// Append the next chunk to `out`; `Ok(true)` once the stream has
117    /// ended (anything appended by that call is still output).
118    fn pull(&mut self, out: &mut Vec<u8>) -> Result<bool, FilterError>;
119}
120
121/// How far one filter stage may decode.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub(crate) enum Bound {
124    /// Decode to the end; crossing [`MAX_DECODED_LEN`] is an error.
125    Ceiling,
126    /// Decode this many bytes and stop: the caller knows the stage's
127    /// output length (an image's `h * ceil(w*nc*bpc/8)`), so bytes past it
128    /// are never produced and the ceiling does not apply.
129    StopAt(usize),
130}
131
132impl Bound {
133    /// The bound on the bytes a stage produces BEFORE its predictor runs.
134    /// A PNG predictor adds one tag byte per row, so the pre-predictor
135    /// length is `rows * (row + 1)` with `rows = ceil(n / row)`.
136    fn before(self, params: Option<&predictor::Params>) -> Self {
137        match (self, params) {
138            (Self::StopAt(n), Some(p)) if p.predictor >= 10 => {
139                let row = p.row_data_bytes().max(1);
140                Self::StopAt(n.div_ceil(row).saturating_mul(row.saturating_add(1)))
141            }
142            (b, _) => b,
143        }
144    }
145
146    /// Cut a stage's output to the bound.
147    fn clip(self, mut out: Vec<u8>) -> Vec<u8> {
148        if let Self::StopAt(n) = self {
149            out.truncate(n);
150        }
151        out
152    }
153}
154
155/// Run `p` to its end, or to `bound`, asking `cancelled` before every
156/// [`CHUNK`]-sized pull.
157pub(crate) fn drain(
158    p: &mut impl Pull,
159    bound: Bound,
160    cancelled: &dyn Fn() -> bool,
161) -> Result<Vec<u8>, FilterError> {
162    let mut out = Vec::new();
163    loop {
164        if cancelled() {
165            return Err(FilterError::Cancelled);
166        }
167        let done = p.pull(&mut out)?;
168        match bound {
169            Bound::StopAt(n) if out.len() >= n => return Ok(bound.clip(out)),
170            Bound::Ceiling if out.len() > MAX_DECODED_LEN => {
171                return Err(FilterError::OutputTooLarge);
172            }
173            _ => {}
174        }
175        if done {
176            return Ok(out);
177        }
178    }
179}
180
181/// [`drain`] followed by the stage's `/Predictor` from `parms`, with the
182/// bound applied to the predicted output.
183pub(crate) fn drain_predicted(
184    p: &mut impl Pull,
185    parms: Option<&Dict>,
186    bound: Bound,
187    cancelled: &dyn Fn() -> bool,
188) -> Result<Vec<u8>, FilterError> {
189    let params = predictor::Params::from_dict(parms)?;
190    let raw = drain(p, bound.before(params.as_ref()), cancelled)?;
191    let out = match params {
192        None => raw,
193        Some(p) => predictor::unpredict_polled(raw, &p, cancelled)?,
194    };
195    Ok(bound.clip(out))
196}
197
198/// The poll the uncancellable entry points pass: never cancelled.
199pub(crate) fn never_cancelled() -> bool {
200    false
201}
202
203/// A filter-decode error.
204#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
205#[non_exhaustive]
206pub enum FilterError {
207    /// The compressed data is invalid (bad zlib header, corrupt
208    /// deflate stream, checksum structurally unreadable, …).
209    #[error("corrupt {filter} data: {detail}")]
210    Corrupt {
211        /// Which filter failed.
212        filter: &'static str,
213        /// Human-readable failure detail from the underlying decoder.
214        detail: String,
215    },
216    /// The stream ended before the filter's own end-of-data — a
217    /// truncated stream (§7.3.8.2 extent inconsistency).
218    #[error("{filter} stream truncated")]
219    Truncated {
220        /// Which filter detected the truncation.
221        filter: &'static str,
222    },
223    /// Decoded output crossed [`MAX_DECODED_LEN`] (pdfcer guard) — the
224    /// decode was aborted mid-stream.
225    #[error("decoded output exceeds MAX_DECODED_LEN ({MAX_DECODED_LEN} bytes)")]
226    OutputTooLarge,
227    /// `/DecodeParms` carried an invalid parameter combination
228    /// (unknown `Predictor` value, zero `Columns`, bad
229    /// `BitsPerComponent`, …).
230    #[error("invalid decode parameters: {0}")]
231    BadParams(&'static str),
232    /// Predicted data length is not a whole number of rows — wrong
233    /// parameters or truncation (`filter__predictors.md` row
234    /// arithmetic).
235    #[error("predicted data is not a whole number of rows")]
236    RaggedRows,
237    /// A PNG row carried an algorithm tag outside 0–4 (RFC 2083 §6:
238    /// an error).
239    #[error("unknown PNG predictor tag {0}")]
240    UnknownPngTag(u8),
241    /// A standard filter pdfcer doesn't implement yet (Pass 1 scope).
242    /// The payload is the filter name as written.
243    #[error("filter {0:?} is not yet supported")]
244    UnsupportedFilter(String),
245    /// The chain reaches an image codec, which [`decode_stream`] does
246    /// not handle **by design** (decision 005 R23). Decode it through
247    /// `pdfcer_core::image_codec::decode_image`, which has the `&Document`
248    /// and the image dictionary that these codecs require, and which
249    /// returns the codec-declared geometry and colour model that a
250    /// `Vec<u8>` cannot carry.
251    ///
252    /// Deliberately distinct from [`FilterError::UnsupportedFilter`]:
253    /// that one means "pdfcer cannot decode this at all", this one means
254    /// "you called the wrong entry point." A caller that only wants
255    /// bytes (an xref stream, an object stream) genuinely cannot
256    /// proceed, so it is still an error there — but the operator-facing
257    /// message stays honest about which of the two situations it is.
258    #[error("filter {0:?} is an image codec; decode it via image_codec::decode_image")]
259    ImageCodec(String),
260    /// `/Filter` held something other than a name or array of names.
261    #[error("malformed /Filter entry")]
262    BadFilterEntry,
263    /// The caller's cancel poll answered `true` mid-decode
264    /// ([`decode_stream_cancellable`]); no partial output is returned.
265    #[error("decode cancelled by the caller")]
266    Cancelled,
267}
268
269/// Divergences that did **not** stop a stream from decoding.
270///
271/// Separate from [`FilterError`] because the operator's question is
272/// different: an error means "these bytes are unusable", a note means
273/// "these bytes are fine but the file that produced them is not
274/// conformant." Accumulated across the whole `/Filter` chain.
275#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
276#[non_exhaustive]
277pub struct FilterNotes {
278    /// LZW streams that did not begin with a `ClearCode`, or that ended
279    /// without an `EndOfInformation`. Both are non-conformant (TIFF 6.0
280    /// §13; ISO 32000-1 §7.4.4.2), both are recovered, both are
281    /// reported. See [`lzw`] for the sourced recovery rules.
282    pub lzw_framing_anomalies: usize,
283}
284
285/// Decode a stream's raw bytes through its full `/Filter` chain.
286///
287/// `dict` is the stream dictionary; `raw` its encoded bytes (the
288/// `data_span` slice). Handles the Table 5 shapes: `/Filter` absent
289/// (identity), a single name, or an array of zero or more names
290/// applied **in array order** (decode order = written order, Table 5);
291/// `/DecodeParms` correspondingly a dict, an array (with `null` for
292/// parameterless positions), or absent.
293///
294/// # Errors
295///
296/// [`FilterError`] — see the variants; fail-clean per the module docs.
297pub fn decode_stream(dict: &Dict, raw: &[u8]) -> Result<Vec<u8>, FilterError> {
298    decode_stream_with_notes(dict, raw).map(|(data, _)| data)
299}
300
301/// [`decode_stream`], keeping the non-fatal [`FilterNotes`].
302///
303/// Use this wherever the notes have somewhere to go — the image path
304/// surfaces them in the renderer's diagnostics. Every other caller
305/// (xref streams, object streams, content streams) has no diagnostics
306/// channel and uses [`decode_stream`].
307///
308/// # Errors
309///
310/// Identical to [`decode_stream`].
311pub fn decode_stream_with_notes(
312    dict: &Dict,
313    raw: &[u8],
314) -> Result<(Vec<u8>, FilterNotes), FilterError> {
315    let filters = filter_names(dict)?;
316    let mut notes = FilterNotes::default();
317    let data = decode_prefix(dict, raw, filters.len(), &mut notes)?;
318    Ok((data, notes))
319}
320
321/// [`decode_stream_with_notes`], abandoning the decode once `cancelled`
322/// returns `true`.
323///
324/// `cancelled` is polled before each filter stage, before every
325/// 64 KiB chunk the Flate, LZW, Brotli and RunLength decoders produce,
326/// and once per row of a `/Predictor` stage, so a caller that stops
327/// wanting a large stream waits for one chunk or row rather than the
328/// whole decode. `ASCIIHexDecode` and `ASCII85Decode` run each stage
329/// whole. The [`MAX_DECODED_LEN`] ceiling applies unchanged.
330///
331/// The poll is a plain closure so the caller chooses the flag (an
332/// `AtomicBool`, a render token, a deadline); it should be cheap, since
333/// it runs once per chunk and row.
334///
335/// # Errors
336///
337/// As [`decode_stream`], plus [`FilterError::Cancelled`] once
338/// `cancelled` returns `true`. No partial output is returned.
339///
340/// # Examples
341///
342/// ```
343/// use pdfcer_model::filters::{FilterError, decode_stream_cancellable};
344/// use pdfcer_model::object::{Dict, Name, Object};
345///
346/// let mut dict = Dict::new();
347/// dict.insert(Name::from(b"Filter"), Object::Name(Name::from(b"ASCIIHexDecode")));
348///
349/// let (bytes, _notes) = decode_stream_cancellable(&dict, b"4869>", &|| false)?;
350/// assert_eq!(bytes, b"Hi");
351///
352/// let refused = decode_stream_cancellable(&dict, b"4869>", &|| true);
353/// assert_eq!(refused, Err(FilterError::Cancelled));
354/// # Ok::<(), FilterError>(())
355/// ```
356pub fn decode_stream_cancellable(
357    dict: &Dict,
358    raw: &[u8],
359    cancelled: &dyn Fn() -> bool,
360) -> Result<(Vec<u8>, FilterNotes), FilterError> {
361    let filters = filter_names(dict)?;
362    let mut notes = FilterNotes::default();
363    let data = decode_prefix_polled(dict, raw, filters.len(), &mut notes, cancelled)?;
364    Ok((data, notes))
365}
366
367/// Apply the first `take` filters of `dict`'s chain to `raw`.
368///
369/// Exists so `pdfcer_core::image_codec` can run the **byte-stream prefix**
370/// of a chain that ends in an image codec (e.g.
371/// `/Filter [/ASCII85Decode /DCTDecode]`, which is a real and legal
372/// shape) and then dispatch the terminal codec itself. `take` equal to
373/// the full chain length is the ordinary [`decode_stream`] case.
374///
375/// # Errors
376///
377/// [`FilterError`] from any stage; in particular
378/// [`FilterError::ImageCodec`] if a codec name falls inside the prefix,
379/// which means the caller mis-computed where the chain's byte-stream
380/// part ends.
381#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
382pub fn decode_prefix(
383    dict: &Dict,
384    raw: &[u8],
385    take: usize,
386    notes: &mut FilterNotes,
387) -> Result<Vec<u8>, FilterError> {
388    decode_prefix_polled(dict, raw, take, notes, &never_cancelled)
389}
390
391/// [`decode_prefix_polled`] for a prefix whose output length the caller
392/// already knows (an uncoded image's `h * ceil(w*nc*bpc/8)`, decision
393/// 227): the last stage stops after `expected` bytes and never decodes
394/// the rest, and [`MAX_DECODED_LEN`] does not apply to it, so a
395/// legitimate image larger than the ceiling decodes. Earlier stages keep
396/// the ceiling. The caller refuses an `expected` the raw bytes could not
397/// produce, and budgets the memory.
398///
399/// # Errors
400///
401/// As [`decode_prefix_polled`].
402#[doc(hidden)] // workspace-internal: called by pdfcer-image-codec, not API
403pub fn decode_prefix_bounded(
404    dict: &Dict,
405    raw: &[u8],
406    take: usize,
407    expected: usize,
408    notes: &mut FilterNotes,
409    cancelled: &dyn Fn() -> bool,
410) -> Result<Vec<u8>, FilterError> {
411    decode_prefix_inner(dict, raw, take, Some(expected), notes, cancelled)
412}
413
414/// [`decode_prefix`] under a cancel poll, as [`decode_stream_cancellable`]
415/// describes.
416///
417/// # Errors
418///
419/// As [`decode_prefix`], plus [`FilterError::Cancelled`].
420#[doc(hidden)] // workspace-internal: called by pdfcer-image-codec, not API
421pub fn decode_prefix_polled(
422    dict: &Dict,
423    raw: &[u8],
424    take: usize,
425    notes: &mut FilterNotes,
426    cancelled: &dyn Fn() -> bool,
427) -> Result<Vec<u8>, FilterError> {
428    decode_prefix_inner(dict, raw, take, None, notes, cancelled)
429}
430
431fn decode_prefix_inner(
432    dict: &Dict,
433    raw: &[u8],
434    take: usize,
435    expected: Option<usize>,
436    notes: &mut FilterNotes,
437    cancelled: &dyn Fn() -> bool,
438) -> Result<Vec<u8>, FilterError> {
439    let filters = filter_names(dict)?;
440    let take = take.min(filters.len());
441    let mut data: Vec<u8> = raw.to_vec();
442    for (i, name) in filters.iter().enumerate().take(take) {
443        if cancelled() {
444            return Err(FilterError::Cancelled);
445        }
446        let parms = decode_parms_for(dict, i, filters.len());
447        let bound = match expected {
448            Some(n) if i + 1 == take => Bound::StopAt(n),
449            _ => Bound::Ceiling,
450        };
451        data = apply_one(name, parms, &data, bound, notes, cancelled)?;
452    }
453    Ok(data)
454}
455
456/// Apply a single named filter.
457///
458/// Abbreviated spellings (Table 94) are accepted alongside the full
459/// names because inline images legally use them; `pdfcer_model::content`
460/// normalizes the ones it sees, but a stream dictionary that spells a
461/// filter the short way is not worth refusing.
462fn apply_one(
463    name: &[u8],
464    parms: Option<&Dict>,
465    data: &[u8],
466    bound: Bound,
467    notes: &mut FilterNotes,
468    cancelled: &dyn Fn() -> bool,
469) -> Result<Vec<u8>, FilterError> {
470    match name {
471        b"FlateDecode" | b"Fl" => flate::decode_polled(data, parms, bound, cancelled),
472        // EXTN-BROTLI-1 §5.2. NO ABBREVIATION: the extension defines none,
473        // and Table 92's abbreviations exist for inline images, which this
474        // filter `SHALL NOT` be used for. MuPDF accepts a `/Br` alias that
475        // does not exist in the extension -- that is MuPDF's behaviour, not
476        // the specification, and pdfcer does not follow it. Accepting `/Br`
477        // would make pdfcer read files no conformant writer produces and no
478        // other reader agrees on.
479        b"BrotliDecode" => brotli::decode_polled(data, parms, bound, cancelled),
480        // §7.4.2/§7.4.3 — parameterless (Table 6), so `parms` is
481        // deliberately not forwarded.
482        b"ASCIIHexDecode" | b"AHx" => ascii::decode_hex(data).map(|d| bound.clip(d)),
483        b"ASCII85Decode" | b"A85" => ascii::decode_85(data).map(|d| bound.clip(d)),
484        b"LZWDecode" | b"LZW" => lzw::decode_polled(data, parms, bound, notes, cancelled),
485        // §7.4.5 — parameterless (Table 6).
486        b"RunLengthDecode" | b"RL" => runlength::decode_polled(data, bound, cancelled),
487        // Image codecs are a TERMINAL stage, not a byte-stream filter
488        // (R23). Named separately so the operator-facing message says
489        // "wrong entry point", not "unsupported".
490        b"DCTDecode" | b"DCT" | b"CCITTFaxDecode" | b"CCF" | b"JBIG2Decode" | b"JPXDecode"
491        | b"JXLDecode" => Err(FilterError::ImageCodec(
492            String::from_utf8_lossy(name).into_owned(),
493        )),
494        // Anything else: a crypt filter, or a non-standard name.
495        // Refused with a precise diagnostic rather than guessed at.
496        other => Err(FilterError::UnsupportedFilter(
497            String::from_utf8_lossy(other).into_owned(),
498        )),
499    }
500}
501
502/// Extract the ordered filter-name list from `/Filter` (name, array of
503/// names, or absent → empty).
504#[doc(hidden)] // workspace-internal: called by pdfcer-core, not API
505pub fn filter_names(dict: &Dict) -> Result<Vec<Vec<u8>>, FilterError> {
506    match dict.get(b"Filter") {
507        None => Ok(Vec::new()),
508        Some(Object::Name(n)) => Ok(vec![n.as_bytes().to_vec()]),
509        Some(Object::Array(items)) => items
510            .iter()
511            .map(|o| match o {
512                Object::Name(n) => Ok(n.as_bytes().to_vec()),
513                _ => Err(FilterError::BadFilterEntry),
514            })
515            .collect(),
516        Some(_) => Err(FilterError::BadFilterEntry),
517    }
518}
519
520/// The `/DecodeParms` entry for filter position `i` of `total`
521/// (Table 5 shape rules). `None` = defaults. A malformed entry is
522/// treated as absent — the individual filter then validates whatever
523/// it actually needs; parameters it never looks at can't hurt it.
524fn decode_parms_for(dict: &Dict, i: usize, total: usize) -> Option<&Dict> {
525    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
526    match parms {
527        Object::Dict(d) if total == 1 => Some(d),
528        Object::Array(items) => match items.get(i) {
529            Some(Object::Dict(d)) => Some(d),
530            _ => None, // null / absent position = defaults (Table 5)
531        },
532        _ => None,
533    }
534}
535
536#[cfg(test)]
537#[allow(
538    clippy::unwrap_used,
539    clippy::expect_used,
540    clippy::panic,
541    clippy::indexing_slicing
542)]
543mod tests {
544    use super::*;
545    use crate::object::Name;
546
547    fn dict_with_filter(filter: Object) -> Dict {
548        let mut d = Dict::new();
549        d.insert(Name::from(b"Filter"), filter);
550        d
551    }
552
553    fn png_flate(columns: i64) -> Dict {
554        let mut parms = Dict::new();
555        parms.insert(Name::from(b"Predictor"), Object::Integer(10));
556        parms.insert(Name::from(b"Columns"), Object::Integer(columns));
557        let mut d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
558        d.insert(Name::from(b"DecodeParms"), Object::Dict(parms));
559        d
560    }
561
562    #[test]
563    fn a_bounded_prefix_stops_at_the_expected_length_through_a_png_predictor() {
564        // Four PNG `None` rows of two bytes; the caller expects five.
565        let rows = [0u8, 1, 2, 0, 3, 4, 0, 5, 6, 0, 7, 8];
566        let raw = flate::encode(&rows);
567        let mut notes = FilterNotes::default();
568        let out =
569            decode_prefix_bounded(&png_flate(2), &raw, 1, 5, &mut notes, &never_cancelled).unwrap();
570        assert_eq!(out, [1, 2, 3, 4, 5]);
571    }
572
573    #[test]
574    fn a_bounded_prefix_bounds_only_its_last_stage() {
575        // ASCIIHex then Flate: the hex stage decodes whole, the Flate stage
576        // stops at three bytes.
577        let inner = flate::encode(b"abcdef");
578        let hex: Vec<u8> = inner
579            .iter()
580            .flat_map(|b| format!("{b:02x}").into_bytes())
581            .collect();
582        let d = dict_with_filter(Object::Array(vec![
583            Object::Name(Name::from(b"ASCIIHexDecode")),
584            Object::Name(Name::from(b"FlateDecode")),
585        ]));
586        let mut notes = FilterNotes::default();
587        let out = decode_prefix_bounded(&d, &hex, 2, 3, &mut notes, &never_cancelled).unwrap();
588        assert_eq!(out, b"abc");
589    }
590
591    #[test]
592    fn no_filter_is_identity() {
593        let d = Dict::new();
594        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
595    }
596
597    #[test]
598    fn empty_filter_array_is_identity() {
599        // Table 5: an array of ZERO names is legal.
600        let d = dict_with_filter(Object::Array(vec![]));
601        assert_eq!(decode_stream(&d, b"plain").unwrap(), b"plain");
602    }
603
604    #[test]
605    fn image_codec_in_the_byte_stream_cascade_is_its_own_error() {
606        // R23: `decode_stream` never decodes a codec, and says so in a
607        // way distinguishable from "pdfcer cannot do this at all".
608        for name in [
609            &b"DCTDecode"[..],
610            b"CCITTFaxDecode",
611            b"JBIG2Decode",
612            b"JPXDecode",
613            b"JXLDecode",
614        ] {
615            let d = dict_with_filter(Object::Name(Name::from(name)));
616            let e = decode_stream(&d, b"\xFF\xD8").unwrap_err();
617            assert_eq!(
618                e,
619                FilterError::ImageCodec(String::from_utf8_lossy(name).into_owned())
620            );
621        }
622    }
623
624    #[test]
625    fn unsupported_filter_is_named_in_error() {
626        let d = dict_with_filter(Object::Name(Name::from(b"Crypt")));
627        let e = decode_stream(&d, b"anything").unwrap_err();
628        assert_eq!(e, FilterError::UnsupportedFilter("Crypt".into()));
629    }
630
631    /// `/Br` IS NOT A FILTER NAME, and pdfcer refuses it on purpose.
632    ///
633    /// **MuPDF accepts `/Br` as an alias for `/BrotliDecode`** — its
634    /// `pdf-stream.c` tests `pdf_name_eq(f, PDF_NAME(BrotliDecode)) ||
635    /// pdf_name_eq(f, PDF_NAME(Br))`. **The extension defines no such
636    /// abbreviation**, and could not sensibly: Table 92's abbreviations exist
637    /// for inline images, and `/BrotliDecode` `SHALL NOT` appear in one.
638    ///
639    /// This is a behaviour-versus-specification split, and following the
640    /// behaviour would be the worse choice in both directions — pdfcer would
641    /// read files no conformant writer emits, and would disagree with every
642    /// reader that is not MuPDF. Pinned as a test so a future reader who
643    /// meets a `/Br` in the wild adds it deliberately, with a decision
644    /// record, rather than as an obvious-looking omission.
645    #[test]
646    fn br_is_not_accepted_as_an_abbreviation_for_brotli() {
647        let mut notes = FilterNotes::default();
648        let e = apply_one(
649            b"Br",
650            None,
651            b"anything",
652            Bound::Ceiling,
653            &mut notes,
654            &never_cancelled,
655        )
656        .unwrap_err();
657        assert_eq!(e, FilterError::UnsupportedFilter("Br".into()));
658    }
659
660    /// `/BrotliDecode` reaches its decoder rather than the unsupported arm.
661    ///
662    /// Asserted through the DISPATCH rather than by calling `brotli::decode`
663    /// directly: the filter module's own tests prove the decoder works, and
664    /// this proves the name is wired to it. Those are different claims, and
665    /// `Pass 2.x`'s history has an instance of each passing while the other
666    /// failed.
667    #[test]
668    fn brotli_decode_is_dispatched_and_not_refused() {
669        let mut notes = FilterNotes::default();
670        // Deliberately invalid Brotli. Success here would mean the name was
671        // silently ignored; what must happen is that the BROTLI decoder
672        // refuses it, which is a differently-shaped error from
673        // `UnsupportedFilter` and is what distinguishes "wired" from "not".
674        let e = apply_one(
675            b"BrotliDecode",
676            None,
677            &[0xff; 32],
678            Bound::Ceiling,
679            &mut notes,
680            &never_cancelled,
681        )
682        .unwrap_err();
683        assert!(
684            !matches!(e, FilterError::UnsupportedFilter(_)),
685            "/BrotliDecode must reach its decoder, got {e:?}"
686        );
687    }
688
689    #[test]
690    fn runlength_runs_in_the_cascade() {
691        let d = dict_with_filter(Object::Name(Name::from(b"RunLengthDecode")));
692        assert_eq!(decode_stream(&d, b"\x02abc\xFEz\x80").unwrap(), b"abczzz");
693    }
694
695    #[test]
696    fn lzw_notes_reach_the_caller_through_the_cascade() {
697        // A stream that does not begin with a ClearCode still decodes,
698        // and the non-conformance is COUNTED rather than absorbed.
699        let d = dict_with_filter(Object::Name(Name::from(b"LZWDecode")));
700        let (data, notes) = decode_stream_with_notes(&d, &[0x20, 0xC0, 0x40]).unwrap();
701        assert_eq!(data, b"A");
702        assert_eq!(notes.lzw_framing_anomalies, 1);
703    }
704
705    #[test]
706    fn non_name_filter_entry_is_error() {
707        let d = dict_with_filter(Object::Integer(5));
708        assert_eq!(
709            decode_stream(&d, b"x").unwrap_err(),
710            FilterError::BadFilterEntry
711        );
712    }
713
714    #[test]
715    fn flate_roundtrip_via_pipeline() {
716        use flate2::Compression;
717        use flate2::write::ZlibEncoder;
718        use std::io::Write as _;
719
720        let original = b"BT /F1 12 Tf 72 712 Td (Hello) Tj ET".repeat(10);
721        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
722        enc.write_all(&original).unwrap();
723        let compressed = enc.finish().unwrap();
724
725        let d = dict_with_filter(Object::Name(Name::from(b"FlateDecode")));
726        assert_eq!(decode_stream(&d, &compressed).unwrap(), original);
727    }
728}