Skip to main content

pdfcer_image_codec/
lib.rs

1//! # Image codecs (ISO 32000-1 §7.4.6–§7.4.9) — the terminal filter stage
2//!
3//! The second tier of pdfcer's two-tier filter architecture
4//! (`docs/decisions/005-image-codecs.md` §4.6, rule **R23**).
5//! [`pdfcer_model::filters::decode_stream`] handles byte-stream filters —
6//! bytes in, bytes out, chainable. This module handles the four
7//! **image codecs**, which are a different kind of object:
8//!
9//! | Filter | Clause | ITU-T | Pass | Status |
10//! |---|---|---|---|---|
11//! | `DCTDecode` | §7.4.8 | T.81 (JPEG) | 2.1 | **implemented** ([`dct`]) |
12//! | `CCITTFaxDecode` | §7.4.6 | T.4 / T.6 | 2.2 | **implemented** ([`ccitt`]) |
13//! | `JBIG2Decode` | §7.4.7 | T.88 | 2.2 | **implemented** ([`jbig2`]) |
14//! | `JPXDecode` | §7.4.9 | T.800 (JPEG 2000) | 2.3 | **implemented** ([`jpx`]) |
15//!
16//! ## Why these cannot be `Vec<u8>`-returning filters
17//!
18//! Three independent, mechanical reasons — any one of them would force
19//! a different signature (decision 005 §1.2, §5.2):
20//!
21//! 1. **§8.9.5 Table 89 inverts the dictionary's authority for JPX.**
22//!    `/ColorSpace` becomes optional and, when present, "any colour
23//!    space specifications in the JPEG2000 data shall be ignored";
24//!    `/BitsPerComponent` is "optional and shall be ignored if present"
25//!    because "the bit depth is determined by the conforming reader in
26//!    the process of decoding." A function returning bytes has nowhere
27//!    to put the bit depth or colour space it just discovered, so the
28//!    caller would have to re-parse hostile input to recover what the
29//!    decoder already knew.
30//! 2. **§7.4.8's DCT samples carry a colour model that depends on the
31//!    JPEG's own Adobe APP14 marker**, which Table 13 makes *outrank*
32//!    the `/DecodeParms` entry.
33//! 3. **JBIG2 needs `/JBIG2Globals`** — a stream *reference*, requiring
34//!    a [`Document`] — and **CCITT needs `/Height`** from the image
35//!    dictionary when `/Rows` is 0 or absent. Neither is reachable from
36//!    a `(dict, raw)` pair.
37//!
38//! So [`decode_image`] returns a [`CodedImage`]: samples **plus** the
39//! geometry and colour model the codestream itself declares.
40//!
41//! ## Who wins a disagreement is **not** the same for every codec
42//!
43//! [`CodedImage`] reports what the codestream says. It does not decide
44//! whose account is authoritative, because the spec answers that
45//! differently per filter, and getting the direction backwards is a
46//! wrong-colour bug rather than a crash:
47//!
48//! | | `DCTDecode` (and the bilevel pair) | `JPXDecode` |
49//! |---|---|---|
50//! | `/ColorSpace` | **Required.** The dictionary is the only source; a component-count disagreement is a producer bug. | **Optional.** Present → *dictionary wins* and "the colour space specifications in the JPEG2000 data shall be ignored". Absent → *codestream wins*. |
51//! | `/BitsPerComponent` | **Required**, and must agree (DCT is always 8). | **"Optional and shall be ignored if present"** — the codestream wins outright, and honouring a stated value is explicitly wrong. |
52//! | `/Decode` | Applied (§8.9.5.2) — for DCT it is the *only* sanctioned polarity control (rules R29/R30). | **Ignored** unless `/ImageMask` is true. |
53//! | `/Width`, `/Height` | Dictionary is authoritative. | "shall **match**", with **no** conflict rule given. |
54//!
55//! So "the codestream is authoritative for JPX" is true only where the
56//! dictionary is silent or disqualified; a present `/ColorSpace` still
57//! wins. In every case the divergence itself is counted
58//! ([`CodecNotes::geometry_mismatch`]) and never silently absorbed.
59//! `pdfcer-render` implements the per-filter split: the dictionary's
60//! `/Width`//`/Height` size the pixmap (§8.9.4 maps the image onto the
61//! unit square regardless of sample count), while the codestream's
62//! width, component count and bit depth drive the row stride, because
63//! that is the physical layout of the bytes in hand.
64//!
65//! ## The layer boundary (rule R26): this module never decides colour
66//!
67//! `pdfcer-core` hands `pdfcer-render` the codec's own samples and its
68//! declared colour model. Only `pdfcer-render` applies `/Decode`
69//! (§8.9.5.2), resolves `/ColorSpace`, and reconciles the two. Nothing
70//! here applies a `/Decode` array, an "Adobe CMYK inversion", or any
71//! polarity flip of its own — and per decision 006 the "Adobe CMYK
72//! inversion" half of that clause is now **permanent and sourced**
73//! (rule R29: there is no such inversion to apply; `/Decode` is the
74//! sole polarity control). One clarification from the same decision:
75//! a codec adapter **may observe** the image dictionary to classify
76//! diagnostics (e.g. `/Decode` presence for the R30 counter) —
77//! *observing is not applying*. The one named future exception is
78//! CCITT's `/BlackIs1`, which is a Table 11 *filter parameter* and
79//! therefore genuinely belongs to the adapter.
80//!
81//! ## Unsupported sub-features are named, never grey boxes (rule R27)
82//!
83//! Arithmetic-coded JPEG, 12-bit JPEG, lossless JPEG, an unknown Adobe
84//! transform byte: each is a distinct
85//! [`ImageCodecError::FeatureUnsupported`] with a stable `&'static str`
86//! key, counted by name in the renderer's diagnostics. An operator must
87//! be able to tell *which* feature is missing without reading the code.
88//!
89//! ## Resource ceilings are pdfcer's, never the vendor's (rule R25)
90//!
91//! `zune-core`'s `DecoderOptions::default()` caps dimensions at 16,384
92//! pixels. That is sensible for a general image library and a **bug**
93//! here: a 20,000-pixel-wide scanned engineering drawing is legal, fits
94//! any reasonable memory budget, and would be silently refused. Worse, an
95//! inherited bad guard never appears in a diff as a number anyone chose
96//! — and this project has already been bitten twice by
97//! guard-by-intuition (`MAX_TOKEN_LEN`, `MAX_XOBJECT_DEPTH`). Every
98//! ceiling below is therefore set explicitly by pdfcer and documented
99//! with its reasoning.
100
101// Decodes untrusted image data, so a reachable panic is a denial-of-service
102// bug: unwrap/expect/panic!/unchecked indexing are denied crate-wide, and test
103// modules opt out with their own #[allow].
104#![forbid(unsafe_code)]
105#![deny(
106    clippy::unwrap_used,
107    clippy::expect_used,
108    clippy::panic,
109    clippy::indexing_slicing,
110    clippy::unreachable,
111    clippy::todo,
112    clippy::unimplemented
113)]
114
115pub mod ccitt;
116pub mod dct;
117pub mod jbig2;
118#[cfg(feature = "jpx")]
119pub mod jpx;
120#[cfg(feature = "jxl")]
121pub mod jxl;
122pub mod peak;
123
124/// Evidence bounds: declared geometry checked against the codestream's own
125/// length (decision 227).
126mod evidence;
127pub use evidence::DeclaredGeometry;
128
129/// The memory budget and pixel cap, checked before a decode starts.
130mod limits;
131mod stream_bound;
132pub use limits::{DecodeOptions, SizeLimit};
133
134/// Shared 1-bit sample packing for the two fax codecs. Private: it is an
135/// implementation detail of [`ccitt`] and [`jbig2`], not part of the
136/// crate's API surface.
137mod bilevel;
138
139#[cfg(test)]
140pub(crate) mod fixtures;
141
142#[cfg(test)]
143mod fixtures_bilevel;
144
145// Gated with the feature as well as on `test`: these fixtures decode JPX, so
146// without the codec they would not compile, and a `--no-default-features
147// --tests` build is exactly what CI runs to prove the gate is real.
148#[cfg(all(test, feature = "jpx"))]
149mod fixtures_jpx;
150#[cfg(all(test, feature = "jxl"))]
151mod fixtures_jxl;
152
153use pdfcer_model::document::Document;
154use pdfcer_model::filters::{self, FilterError, FilterNotes};
155use pdfcer_model::graph::ObjectGraph;
156use pdfcer_model::object::{Dict, Object};
157use pdfcer_model::view::DocumentView;
158
159/// Widest or tallest JPEG codestream: T.81's SOF frame header stores X
160/// and Y as 16-bit integers, so no JPEG can declare more. A fact about the
161/// format, stated to the decoder because `zune-jpeg`'s own default (16,384)
162/// would refuse legal images; every other size bound is the memory budget
163/// of [`DecodeOptions::limits`] (decision 227).
164pub const MAX_IMAGE_DIMENSION: u32 = 65_535;
165
166/// A zeroed buffer of `len` bytes, or [`ImageCodecError::AllocationFailed`]
167/// when the allocator refuses it.
168#[cfg(any(feature = "jpx", feature = "jxl"))]
169pub(crate) fn zeroed(len: usize) -> Result<Vec<u8>, ImageCodecError> {
170    zeroed_polled(len, &|| false)
171}
172
173/// [`zeroed`], asking `cancelled` before every 4 MiB written: filling a
174/// page-sized sample buffer is tens of milliseconds on its own.
175pub(crate) fn zeroed_polled(
176    len: usize,
177    cancelled: &dyn Fn() -> bool,
178) -> Result<Vec<u8>, ImageCodecError> {
179    const STEP: usize = 4 << 20;
180    let mut buf = Vec::new();
181    buf.try_reserve_exact(len)
182        .map_err(|_| ImageCodecError::AllocationFailed { bytes: len as u64 })?;
183    while buf.len() < len {
184        if cancelled() {
185            return Err(ImageCodecError::Cancelled);
186        }
187        buf.resize(len.min(buf.len().saturating_add(STEP)), 0);
188    }
189    Ok(buf)
190}
191
192/// Which terminal image codec a `/Filter` chain ends in.
193#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
194#[non_exhaustive]
195pub enum Codec {
196    /// `DCTDecode` / `DCT` (§7.4.8) — JPEG, ITU-T T.81.
197    Dct,
198    /// `CCITTFaxDecode` / `CCF` (§7.4.6) — Group 3/4 fax, T.4/T.6.
199    Ccitt,
200    /// `JBIG2Decode` (§7.4.7) — ITU-T T.88.
201    Jbig2,
202    /// `JPXDecode` (§7.4.9) — JPEG 2000, ITU-T T.800.
203    Jpx,
204    /// `JXLDecode` — JPEG XL, ISO/IEC 18181. **Not in ISO 32000**: the
205    /// de-facto name PDFium and PdfCraft read. Every image sets
206    /// [`CodecNotes::jxl_nonstandard`].
207    Jxl,
208}
209
210impl Codec {
211    /// The canonical (unabbreviated) filter name, for diagnostics.
212    #[must_use]
213    pub const fn name(self) -> &'static str {
214        match self {
215            Self::Dct => "DCTDecode",
216            Self::Ccitt => "CCITTFaxDecode",
217            Self::Jbig2 => "JBIG2Decode",
218            Self::Jpx => "JPXDecode",
219            Self::Jxl => "JXLDecode",
220        }
221    }
222
223    /// Does the codestream carry its own colour space, bit depth and
224    /// alpha, so that Table 89's `JPXDecode` rules apply: `/ColorSpace`
225    /// optional (the dictionary wins when present), `/BitsPerComponent`
226    /// ignored, `/Decode` ignored unless `/ImageMask`. True for `Jpx`
227    /// and for the non-standard `Jxl`, which readers treat the same way.
228    #[must_use]
229    pub const fn is_self_describing(self) -> bool {
230        matches!(self, Self::Jpx | Self::Jxl)
231    }
232
233    /// May this codec appear in an **inline image** (`BI`/`ID`/`EI`)?
234    ///
235    /// §8.9.7 restricts inline-image filters, and §7.4.7 states the
236    /// JBIG2 case outright: JBIG2-encoded data may not be used in an
237    /// inline image. JPXDecode is likewise excluded from Table 94's
238    /// abbreviation set and from the inline-image filter list. `DCT`
239    /// and `CCF` *are* legal inline abbreviations (Table 94), so both
240    /// route through the ordinary path.
241    #[must_use]
242    pub const fn allowed_inline(self) -> bool {
243        match self {
244            Self::Dct | Self::Ccitt => true,
245            Self::Jbig2 | Self::Jpx | Self::Jxl => false,
246        }
247    }
248
249    /// Recognize a `/Filter` name, full or Table 94 abbreviation.
250    const fn from_name(name: &[u8]) -> Option<Self> {
251        match name {
252            b"DCTDecode" | b"DCT" => Some(Self::Dct),
253            b"CCITTFaxDecode" | b"CCF" => Some(Self::Ccitt),
254            b"JBIG2Decode" => Some(Self::Jbig2),
255            b"JPXDecode" => Some(Self::Jpx),
256            b"JXLDecode" => Some(Self::Jxl),
257            _ => None,
258        }
259    }
260}
261
262/// The colour model of [`CodedImage::samples`], as the **codec**
263/// declares it — *not* a PDF colour space.
264///
265/// Mapping this onto `/ColorSpace` is `pdfcer-render`'s job (rule R26).
266/// The distinction matters because a JPEG's component meaning comes
267/// from its own APP14 marker under Table 13's precedence rules, which
268/// can disagree with the image dictionary, and because for JPX the
269/// codestream outranks the dictionary outright (Table 89).
270#[derive(Copy, Clone, PartialEq, Eq, Debug)]
271#[non_exhaustive]
272pub enum CodecColorModel {
273    /// One component per sample.
274    Gray,
275    /// Three components, already transformed to RGB by the codec —
276    /// Table 13's `ColorTransform 1` for a 3-component image (the
277    /// default when no Adobe marker and no `/DecodeParms` entry say
278    /// otherwise).
279    Rgb,
280    /// Three components delivered **untransformed** — Table 13's
281    /// `ColorTransform 0`. Per §7.4.8 this does not mean "no colour
282    /// space": it means the codestream's components already *are* the
283    /// `/ColorSpace` components, so the caller interprets them through
284    /// `/ColorSpace` directly.
285    Untransformed3,
286    /// Four components in CMYK order, **raw**: no `/Decode` applied and
287    /// no "Adobe inversion" applied — there is none to apply (decision
288    /// 006, rule R29: the four-engine consensus is never-invert, and
289    /// `/Decode` is the sole polarity control, applied downstream by
290    /// `pdfcer-render`). For YCCK storage the mandated §13.1 inverse
291    /// already recovered true ink; for raw-CMYK storage with no
292    /// `/Decode` the residual ambiguity is counted by name
293    /// ([`CodecNotes::cmyk_polarity_unverifiable`], rule R30).
294    Cmyk,
295    /// Bit depth 1, one component — where `CCITTFaxDecode` and
296    /// `JBIG2Decode` land (§8.9.5 Table 89: both "shall always deliver
297    /// 1-bit samples"). The samples are in the **normal PDF convention**
298    /// for bilevel data, `0 = black`, which Table 11's `BlackIs1`
299    /// description states from the other side. Each adapter has already
300    /// translated its codec's native polarity into that convention:
301    /// CCITT via `/BlackIs1` → `invert_black`, JBIG2 by the
302    /// unconditional inverse of T.88's `1 = black`.
303    Bilevel,
304    /// **No terminal codec ran.** The stream went through byte-stream
305    /// filters only, so the samples are exactly the layout §8.9.3
306    /// describes and only the image dictionary describes them. The
307    /// geometry fields of [`CodedImage`] are then dictionary echoes,
308    /// never independent declarations.
309    Unspecified,
310    /// The codestream declared a component count pdfcer has no PDF
311    /// mapping for. Never rendered; counted by name (rule R27).
312    Unknown {
313        /// Components per sample as declared by the codestream.
314        components: u8,
315    },
316}
317
318/// Per-image honesty counters produced by the codec layer
319/// (decision 005 §6.4; the same disclosure discipline as rule R20).
320#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
321#[non_exhaustive]
322pub struct CodecNotes {
323    /// The codestream's geometry disagreed with the image dictionary
324    /// (`/Width`, `/Height`, `/BitsPerComponent`, or the component
325    /// count implied by `/ColorSpace`). For JPX the codestream *wins*
326    /// by Table 89; for DCT a mismatch is a producer bug. Counted
327    /// either way, never silent.
328    pub geometry_mismatch: bool,
329    /// This is a 4-component DCT image whose effective `ColorTransform`
330    /// is 1 or 2 (YCCK/YUVK storage) — the **benign census** half of
331    /// decision 006 §4.4's split. The mandated YCCK→CMYK inverse ran
332    /// (TN #5116 §13.1; it recovers true ink directly), the samples
333    /// carry no residual polarity ambiguity, and pdfcer's output
334    /// pixel-matches pdfium on every such file in the corpus (9 as of
335    /// 2026-07-31 — the earlier "zero exist" claim here was wrong
336    /// twice over; see 005's addenda). A pure volume counter: no
337    /// warning is warranted (rule R30 covers the shape that does
338    /// warrant one, below).
339    pub cmyk_image: bool,
340    /// This is a 4-component DCT image with effective `ColorTransform`
341    /// **0** (raw CMYK storage) and **no `/Decode` array** — the one
342    /// shape where the undocumented Photoshop inverted-storage
343    /// convention can still produce a photographic negative, because
344    /// neither the codestream nor the dictionary disambiguates the
345    /// polarity (decision 006 §5.3/§5.4, rule **R30**). Reported,
346    /// never repaired: all four reference engines render this shape
347    /// un-inverted and share the gap; pdfcer's differentiator is that
348    /// it names it. Zero exist in the conformance corpus (the 9
349    /// four-component files are all transform 2).
350    pub cmyk_polarity_unverifiable: bool,
351    /// This JPX image's `/SMaskInData` is **2**: Table 89's "the
352    /// image's data stream includes colour channels that have been
353    /// **preblended with a background**; the image data also includes an
354    /// opacity channel", for which a reader "may create a soft-mask
355    /// image **with a `Matte` entry**".
356    ///
357    /// Recognized and deferred, never approximated (see [`jpx`]). The
358    /// colour samples are returned exactly as stored — i.e. already
359    /// composited over that backdrop, which is a recognizable picture
360    /// rather than a grey box — and the opacity channel is *not*
361    /// exposed, because using it without un-premultiplying would
362    /// double-darken every partially transparent pixel. Un-premultiplying
363    /// needs the `Matte` backdrop colour and clause 11's transparency
364    /// model, which decision 005 §7 assigns to `ROADMAP.md` Pass 1.1
365    /// item 6.3.
366    pub jpx_smask_in_data_preblended: bool,
367    /// A JP2 **palette** was left unresolved because the image dictionary
368    /// carries its own `/Indexed` colour space (§8.9 Table 89).
369    ///
370    /// # Why this is worth a field rather than being silent
371    ///
372    /// Two lookup tables describe the same image — the codestream's
373    /// `pclr`/`cmap` boxes and the PDF's `/Indexed` array — and **exactly
374    /// one of them may be applied**. Applying both maps a colour value
375    /// through a palette a second time and paints whatever entry that
376    /// index happens to hit, or black when it hits nothing.
377    ///
378    /// So this records which authority won, and it is not a shortfall:
379    /// Table 89 makes the dictionary's space the answer whenever it is
380    /// present. It is disclosed because the decision is **invisible in the
381    /// output** — a correct render and a double-resolved one are both just
382    /// coloured pixels, and the difference only shows up as the wrong
383    /// colour, which nothing downstream can detect.
384    pub jpx_palette_left_to_pdf: bool,
385    /// The image used the non-standard `/JXLDecode` filter (JPEG XL). It
386    /// decoded, but a conforming PDF reader need not display it, so the
387    /// shells disclose it; preflight flags it.
388    pub jxl_nonstandard: bool,
389    /// LZW framing anomalies seen in the byte-stream prefix of the
390    /// chain (see [`FilterNotes::lzw_framing_anomalies`]).
391    pub lzw_framing_anomalies: usize,
392}
393
394/// A decoded image as the **codec** describes it — before any PDF-level
395/// interpretation.
396///
397/// Nothing here has had `/Decode` applied, and nothing here has been
398/// colour-converted beyond the codec's own mandated transform
399/// (rule R26). That is `pdfcer-render`'s job.
400#[derive(Debug, Clone, PartialEq, Eq)]
401#[non_exhaustive]
402pub struct CodedImage {
403    /// Interleaved samples, row-major, row 0 at the top, packed per
404    /// [`bits_per_component`](CodedImage::bits_per_component) with rows
405    /// padded to a byte boundary (§8.9.3) — the same layout the
406    /// byte-stream filters produce, so `pdfcer-render`'s existing
407    /// unpacking path is unchanged.
408    pub samples: Vec<u8>,
409    /// Which codec produced `samples`, or `None` when the chain was
410    /// byte-stream filters only. When `None`, every geometry field
411    /// below is an echo of the image dictionary and carries no
412    /// independent authority.
413    pub codec: Option<Codec>,
414    /// Width in samples **as the codestream declares it**. May disagree
415    /// with `/Width`; the caller decides which wins and
416    /// [`CodecNotes::geometry_mismatch`] records the divergence.
417    pub width: u32,
418    /// Height in samples as the codestream declares it.
419    pub height: u32,
420    /// Components per sample as the codestream declares it. `0` means
421    /// "not declared by any codec" (see [`CodedImage::codec`]).
422    pub components: u8,
423    /// Bit depth as the codestream declares it. For DCT this is always
424    /// 8 (§7.4.8: "each component value shall occupy a byte", and
425    /// Table 89's "shall always deliver 8-bit samples"). For JPX it
426    /// will be authoritative and `/BitsPerComponent` ignored (Table 89).
427    pub bits_per_component: u8,
428    /// The colour model the samples are actually in.
429    pub color_model: CodecColorModel,
430    /// An ICC profile carried inside the codestream, if any (JPEG APP2
431    /// / JPX `Icc`). Reconciled against `/ColorSpace` by the caller;
432    /// never applied here.
433    pub icc_profile: Option<Vec<u8>>,
434    /// Alpha carried **inside** the codestream, one 8-bit sample per
435    /// pixel in the same row-major order as
436    /// [`samples`](CodedImage::samples).
437    ///
438    /// JPX is the only codec that produces this, and `/SMaskInData`
439    /// (Table 89) is what decides whether it is populated: **0 — the
440    /// default — means "encoded soft-mask image information shall be
441    /// ignored"**, so the common case is `None` even for a codestream
442    /// that does carry an opacity channel. `1` fills it in. `2` leaves
443    /// it `None` and sets
444    /// [`CodecNotes::jpx_smask_in_data_preblended`], because that value
445    /// means the colour channels were preblended with a backdrop and
446    /// reconstructing them needs clause 11's `Matte` machinery (see
447    /// [`jpx`]).
448    ///
449    /// The opacity channel is **always** removed from `samples`
450    /// regardless — it is not a colour component, and leaving it
451    /// interleaved would shift every colour one position to the right.
452    pub embedded_alpha: Option<Vec<u8>>,
453    /// Per-image honesty counters.
454    pub notes: CodecNotes,
455}
456
457/// Why an image stream could not be turned into samples.
458#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
459#[non_exhaustive]
460pub enum ImageCodecError {
461    /// A byte-stream filter in the chain's prefix failed.
462    #[error(transparent)]
463    Filter(#[from] FilterError),
464    /// The codec itself is recognized but not implemented in this
465    /// build. Should be **zero** once Pass 2.3 lands; the variant is
466    /// kept afterwards so a regression stays visible.
467    #[error("{} images are not supported in this build", .codec.name())]
468    Unsupported {
469        /// Which codec.
470        codec: Codec,
471    },
472    /// A specific codec **sub-feature** is unimplemented (rule R27).
473    /// `feature` is a stable diagnostic key such as `"DCT/arithmetic"`
474    /// or `"DCT/12-bit"`, suitable for counting by name.
475    #[error("unsupported codec feature: {feature}")]
476    FeatureUnsupported {
477        /// Stable, greppable feature key.
478        feature: &'static str,
479    },
480    /// The codestream is malformed or truncated.
481    #[error("corrupt {} data: {detail}", .codec.name())]
482    Corrupt {
483        /// Which codec reported it.
484        codec: Codec,
485        /// Human-readable detail from the underlying decoder.
486        detail: String,
487    },
488    /// The codestream declares more geometry than its own bytes could
489    /// encode (decision 227): any conforming encoding of `declared` takes
490    /// at least `min_bytes`, and the codec was handed `have_bytes`. Refused
491    /// before anything is sized from the declared geometry.
492    /// [`ImageCodecError::refusal_key`] names the codec's bound.
493    #[error(
494        "{} data declares {declared} but is {have_bytes} bytes; encoding that takes at \
495         least {min_bytes} bytes",
496        .codec.name()
497    )]
498    DeclaredGeometryExceedsData {
499        /// Which codec's bound refused it.
500        codec: Codec,
501        /// The geometry the codestream or its parameters declared.
502        declared: DeclaredGeometry,
503        /// Fewest bytes any conforming encoding of `declared` takes.
504        min_bytes: u64,
505        /// Bytes the codec was given.
506        have_bytes: u64,
507    },
508    /// An image with no terminal codec declares more sample bytes than
509    /// its stream could decode to (decision 227): `expected_bytes` is
510    /// `h * ceil(w * nc * bpc / 8)`, and `max_bytes` is `have_bytes` times
511    /// each filter's largest expansion (Flate 1032, RunLength 64, ASCII85
512    /// 4, ASCIIHex 1/2). Refused before anything is sized from the
513    /// geometry. A chain containing LZW or Brotli is never refused this way.
514    #[error(
515        "image declares {expected_bytes} sample bytes but its {have_bytes}-byte stream decodes to at most {max_bytes}"
516    )]
517    DeclaredSizeExceedsStream {
518        /// `h * ceil(w * nc * bpc / 8)` from the image dictionary.
519        expected_bytes: u64,
520        /// Most bytes the stream's filters could produce.
521        max_bytes: u64,
522        /// Bytes in the stream.
523        have_bytes: u64,
524    },
525    /// The allocator refused a buffer the image needed. The image is
526    /// within pdfcer's ceilings; the machine lacks the memory (decision
527    /// 226). Never an abort, because on wasm32 an abort traps the module.
528    #[error("not enough memory to decode the image ({bytes} bytes needed)")]
529    AllocationFailed {
530        /// Size of the refused allocation.
531        bytes: u64,
532    },
533    /// The image crosses the caller's [`DecodeOptions::limits`] (decision
534    /// 227): the decode would need `needed` against `allowed`, in the
535    /// limit's [`SizeLimit::unit`]. Refused before any filter runs.
536    #[error(
537        "image needs {needed} {} against an allowed {allowed} ({})",
538        .limit.unit(),
539        .limit.refusal_key()
540    )]
541    LimitExceeded {
542        /// Which limit refused it.
543        limit: SizeLimit,
544        /// What the image needs.
545        needed: u64,
546        /// What the limit allows.
547        allowed: u64,
548    },
549    /// The codec is forbidden inside an inline image (§7.4.7, §8.9.7).
550    #[error("{} data may not appear in an inline image", .codec.name())]
551    NotAllowedInline {
552        /// Which codec.
553        codec: Codec,
554    },
555    /// `/BrotliDecode` appeared in an **inline image's** filter chain, which
556    /// EXTN-BROTLI-1 §5.2 forbids outright.
557    ///
558    /// Distinct from [`ImageCodecError::NotAllowedInline`] deliberately: that
559    /// one names a terminal **codec** the inline form does not admit, while
560    /// this is a **byte-stream filter** that is legal everywhere else a
561    /// stream is legal. Collapsing the two would report "codec not allowed
562    /// inline" about something that is not a codec, and an operator chasing
563    /// that message would look in the wrong half of the file.
564    #[error(
565        "/BrotliDecode may not appear in an inline image (EXTN-BROTLI-1 \u{a7}5.2); \
566         it is legal in any other stream"
567    )]
568    BrotliNotAllowedInline,
569    /// Two or more terminal codecs in one `/Filter` chain, or a codec
570    /// followed by further filters. Neither is meaningful: a codec
571    /// consumes a codestream and produces samples, so nothing can be
572    /// chained after it.
573    #[error("/Filter chain has an image codec that is not the final filter")]
574    CodecNotTerminal,
575    /// The caller's cancel poll answered `true` mid-decode
576    /// ([`decode_image_view_cancellable`]). A cancel inside the filter
577    /// prefix arrives as [`ImageCodecError::Filter`] carrying
578    /// [`FilterError::Cancelled`] instead; callers treat both alike.
579    #[error("image decode cancelled by the caller")]
580    Cancelled,
581}
582
583/// Which terminal codec a `/Filter` chain ends in, if any — so callers
584/// can route **without decoding**.
585///
586/// The inline-image path uses this to reject `JBIG2Decode` and
587/// `JPXDecode` outright before any bytes are touched (§7.4.7, §8.9.7).
588///
589/// # Errors
590///
591/// [`FilterError::BadFilterEntry`] if `/Filter` is neither a name nor
592/// an array of names.
593///
594/// # Examples
595///
596/// ```
597/// use pdfcer_image_codec::{terminal_codec, Codec};
598/// use pdfcer_model::object::{Dict, Name, Object};
599///
600/// let mut dict = Dict::new();
601/// dict.insert(Name::from(b"Filter"), Object::Name(Name::from(b"DCTDecode")));
602/// assert_eq!(terminal_codec(&dict).unwrap(), Some(Codec::Dct));
603///
604/// let empty = Dict::new();
605/// assert_eq!(terminal_codec(&empty).unwrap(), None);
606/// ```
607pub fn terminal_codec(dict: &Dict) -> Result<Option<Codec>, FilterError> {
608    let names = filters::filter_names(dict)?;
609    Ok(names.last().and_then(|n| Codec::from_name(n)))
610}
611
612/// Decode an image stream through its `/Filter` chain.
613///
614/// Runs the byte-stream **prefix** of the chain through
615/// [`pdfcer_model::filters`], then dispatches the single terminal image codec.
616/// A chain with no terminal codec still succeeds — it yields a
617/// [`CodedImage`] with `codec: None` and
618/// [`CodecColorModel::Unspecified`], so the caller has one entry point
619/// for every image rather than two code paths that can drift.
620///
621/// - `doc` resolves indirect values in the image and parameter
622///   dictionaries, and will resolve `/JBIG2Globals` (Table 12) and the
623///   `/Height` fallback for CCITT's absent `/Rows` when those codecs
624///   land.
625/// - `dict` is the image dictionary (Table 89) or an inline image's
626///   already-normalized parameter dictionary.
627/// - `raw` is the still-encoded stream data.
628/// - `inline` selects §8.9.7's stricter filter rules.
629///
630/// This is the **base-revision** entry point, kept with its original
631/// `&Document` signature so that every existing caller — the four
632/// `image_codec_*` fuzz targets, this module's own tests, the
633/// `cmyk_variants` acceptance test — is untouched by decision 018. It is a
634/// thin wrapper over [`decode_image_view`]; a caller that must decode an
635/// image as an editing session currently has it calls that directly.
636///
637/// # Errors
638///
639/// [`ImageCodecError`] — every failure is structured and names the
640/// codec, and the specific unsupported feature where one applies
641/// (rule R27). This function does not panic on any input; the
642/// `image_codec_dct` fuzz target asserts it.
643pub fn decode_image(
644    doc: &Document,
645    dict: &Dict,
646    raw: &[u8],
647    inline: bool,
648) -> Result<CodedImage, ImageCodecError> {
649    decode_image_view(&doc.view(), dict, raw, inline)
650}
651
652/// [`decode_image`] over an explicit [`DocumentView`] — the general form.
653///
654/// Exists because `pdfcer-render` renders **whatever view it was handed**
655/// (decision 018): rasterizing an editing session must resolve an image
656/// dictionary's indirect entries, and a `/JBIG2Globals` payload, against
657/// the session rather than the file on disk. Everything else about the
658/// decode is identical; see [`decode_image`] for the parameter contract and
659/// the error posture.
660///
661/// # Errors
662///
663/// As [`decode_image`].
664pub fn decode_image_view(
665    doc: &DocumentView<'_>,
666    dict: &Dict,
667    raw: &[u8],
668    inline: bool,
669) -> Result<CodedImage, ImageCodecError> {
670    decode_image_view_with(doc, dict, raw, inline, DecodeOptions::default())
671}
672
673/// [`decode_image_view`] with explicit [`DecodeOptions`]: the `DCT-A1`
674/// polarity rule (R169) and the [`peak::DecodeLimits`] the image is checked
675/// against (decision 227).
676///
677/// ## The limits
678///
679/// Checked before any filter runs, from the dictionary and `raw` alone:
680/// the operator pixel cap against `/Width x /Height`, then the memory
681/// budget against [`peak::predict_peak`] plus `width * height *
682/// downstream_bytes_per_pixel`. A crossing is
683/// [`ImageCodecError::LimitExceeded`] naming both figures. Where the peak
684/// cannot be predicted only the downstream term is checked. Each codec
685/// checks the budget again against the geometry its codestream declares,
686/// which the dictionary check cannot see behind a filter.
687/// [`decode_image_view`] uses [`peak::DecodeLimits::default`], the 4 GiB
688/// (64-bit) or 1 GiB (32-bit) fallback budget.
689///
690/// ## What `cmyk_jpeg_polarity` decides, and what it does not
691///
692/// **Only** the one configuration nothing in the file disambiguates: a
693/// `DCTDecode` image with **four components**, an **effective
694/// `ColorTransform` of 0**, an **Adobe APP14 marker present**, and **no
695/// `/Decode` array** in the image dictionary. Everything else about the
696/// decode is unchanged, and in particular:
697///
698/// - the YCCK→CMYK inverse for effective transform 1 or 2 is **mandated**
699///   by Table 13 (*"transformed … from YUVK to CMYK after decoding"*) and
700///   is not a polarity guess — no setting reaches it;
701/// - `/Decode` remains the sanctioned polarity control and remains
702///   `pdfcer-render`'s to apply (rule R26);
703/// - the R30 disclosure
704///   ([`CodecNotes::cmyk_polarity_unverifiable`]) is still raised for the
705///   ambiguous shape whichever way the setting points, because the shape
706///   is a fact about the file and not about pdfcer's configuration.
707///
708/// The default is [`CmykJpegPolarity::NeverInvert`] — standing rule
709/// **R29**, and **evidence tier (c)**: the strongest-sourced default in
710/// the whole ambiguity register (Adobe TN #5116 contains `"invert"` zero
711/// times; APP14 carries no polarity flag to test; all four reference
712/// engines accept the ambiguity rather than inverting on marker presence).
713///
714/// # Errors
715///
716/// As [`decode_image`], plus [`ImageCodecError::LimitExceeded`].
717pub fn decode_image_view_with(
718    doc: &DocumentView<'_>,
719    dict: &Dict,
720    raw: &[u8],
721    inline: bool,
722    options: DecodeOptions,
723) -> Result<CodedImage, ImageCodecError> {
724    decode_image_view_cancellable(doc, dict, raw, inline, options, &|| false)
725}
726
727/// [`decode_image_view_with`], abandoning the decode once `cancelled`
728/// answers `true`.
729///
730/// Where the poll is asked, and so how long a cancel waits:
731///
732/// - **filter prefix** -- before each stage, every 64 KiB of Flate, LZW,
733///   Brotli or RunLength output, and every `/Predictor` row
734///   ([`filters::decode_stream_cancellable`]);
735/// - **`DCTDecode`** -- every ~4 KiB of entropy-coded data, inside the
736///   scan. A progressive JPEG's final dequantise-and-IDCT pass reads no
737///   input and runs whole;
738/// - **`CCITTFaxDecode`, `JBIG2Decode`, `JPXDecode`, `JXLDecode`** -- not
739///   inside the codec; the poll is asked once it returns.
740///
741/// The poll should be cheap (an atomic load); it runs thousands of times
742/// on a large image. A decode that is never cancelled is identical to
743/// [`decode_image_view_with`], output and notes alike.
744///
745/// # Errors
746///
747/// As [`decode_image_view_with`], plus [`ImageCodecError::Cancelled`] or
748/// [`ImageCodecError::Filter`]`(`[`FilterError::Cancelled`]`)` once the
749/// poll fires. No partial image is returned.
750///
751/// # Examples
752///
753/// ```
754/// use std::sync::atomic::{AtomicBool, Ordering};
755///
756/// use pdfcer_image_codec::{
757///     CodedImage, DecodeOptions, ImageCodecError, decode_image_view_cancellable,
758/// };
759/// use pdfcer_model::object::Dict;
760/// use pdfcer_model::view::DocumentView;
761///
762/// /// Decode an image a UI thread may abandon by setting `stop`.
763/// fn decode_unless_stopped(
764///     view: &DocumentView<'_>,
765///     dict: &Dict,
766///     raw: &[u8],
767///     stop: &AtomicBool,
768/// ) -> Result<Option<CodedImage>, ImageCodecError> {
769///     let options = DecodeOptions::default();
770///     let poll = || stop.load(Ordering::Relaxed);
771///     match decode_image_view_cancellable(view, dict, raw, false, options, &poll) {
772///         Ok(image) => Ok(Some(image)),
773///         Err(e) if stop.load(Ordering::Relaxed) => {
774///             let _ = e; // `Cancelled`, or `Filter(FilterError::Cancelled)`
775///             Ok(None)
776///         }
777///         Err(e) => Err(e),
778///     }
779/// }
780/// ```
781pub fn decode_image_view_cancellable(
782    doc: &DocumentView<'_>,
783    dict: &Dict,
784    raw: &[u8],
785    inline: bool,
786    options: DecodeOptions,
787    cancelled: &dyn Fn() -> bool,
788) -> Result<CodedImage, ImageCodecError> {
789    let names = filters::filter_names(dict)?;
790
791    // Locate the terminal codec. A codec anywhere but the last position
792    // is not a chain pdfcer can make sense of — see `CodecNotTerminal`.
793    let codec = names.last().and_then(|n| Codec::from_name(n));
794    if names
795        .iter()
796        .rev()
797        .skip(1)
798        .any(|n| Codec::from_name(n).is_some())
799    {
800        return Err(ImageCodecError::CodecNotTerminal);
801    }
802
803    if let Some(codec) = codec
804        && inline
805        && !codec.allowed_inline()
806    {
807        return Err(ImageCodecError::NotAllowedInline { codec });
808    }
809
810    // EXTN-BROTLI-1 §5.2: "`BrotliDecode` SHALL NOT be used for inline
811    // images." Checked over the WHOLE chain rather than only the terminal
812    // position, because Brotli is a byte-stream filter and its legal place is
813    // the prefix -- so `allowed_inline()`, which classifies terminal CODECS,
814    // structurally cannot see it. The two checks look alike and are asking
815    // different questions.
816    //
817    // pdfium DECODES Brotli on inline images, which the extension forbids.
818    // That is pdfium's behaviour, not the specification, and following it
819    // would mean pdfcer reads files no conformant writer produces. Refusing is
820    // also the safer asymmetry: a file that should not exist gets a named
821    // error rather than a silent, plausible render.
822    //
823    // There is no abbreviation to check for -- the extension defines none,
824    // precisely because Table 92's abbreviations exist for inline images and
825    // this filter may not appear in one. (MuPDF accepts a `/Br` alias that
826    // does not exist; pdfcer does not, at the dispatch in `filters`.)
827    if inline && names.iter().any(|n| n.as_slice() == b"BrotliDecode") {
828        return Err(ImageCodecError::BrotliNotAllowedInline);
829    }
830
831    // An uncoded image's decoded length is known, so its stream is held
832    // to it: refused if it cannot reach it, and never decoded past it.
833    let expected = match codec {
834        None => stream_bound::expected_len(doc, dict),
835        Some(_) => None,
836    };
837    if let Some(expected) = expected {
838        stream_bound::check(&names, raw, expected)?;
839    }
840
841    limits::check(doc, dict, raw, &options.limits)?;
842    // The last stage is no longer held to `MAX_DECODED_LEN`, so its output
843    // is charged to the budget even where no peak is predicted (LZW, Brotli).
844    if let Some(expected) = expected {
845        limits::admit(&options.limits, expected)?;
846    }
847
848    // Byte-stream prefix: everything except the terminal codec.
849    let prefix_len = names.len() - usize::from(codec.is_some());
850    let mut filter_notes = FilterNotes::default();
851    let data = stream_bound::decode(
852        dict,
853        raw,
854        prefix_len,
855        expected,
856        &mut filter_notes,
857        cancelled,
858    )?;
859
860    let mut notes = CodecNotes {
861        lzw_framing_anomalies: filter_notes.lzw_framing_anomalies,
862        ..CodecNotes::default()
863    };
864
865    let Some(codec) = codec else {
866        return Ok(uncoded(doc, dict, data, notes));
867    };
868
869    let parms = codec_parms(dict, names.len());
870    let decoded = match codec {
871        Codec::Dct => dct::decode(doc, &data, parms, dict, &options, &mut notes, cancelled),
872        Codec::Ccitt => ccitt::decode(doc, &data, parms, dict, &options.limits, &mut notes),
873        Codec::Jbig2 => jbig2::decode(doc, &data, parms, dict, &options.limits, &mut notes),
874        // No `parms` argument: Table 6 gives `JPXDecode` no parameters
875        // (VERIFIED — it is one of the four `no`-parameter filters), so
876        // passing one would imply a configurability this filter does not
877        // have. Everything configurable lives in the codestream or in
878        // the image dictionary.
879        #[cfg(feature = "jpx")]
880        Codec::Jpx => jpx::decode(doc, &data, dict, &options.limits, &mut notes),
881        // A build compiled without the `jpx` feature says so BY NAME rather
882        // than returning a blank or a grey box (rule R27). The distinction
883        // matters: "this build cannot decode JPEG 2000" is actionable — get
884        // the full build — where a silently missing image is a document that
885        // looks subtly wrong with no explanation anywhere.
886        #[cfg(not(feature = "jpx"))]
887        Codec::Jpx => Err(ImageCodecError::FeatureUnsupported {
888            feature: "JPX/not-built",
889        }),
890        #[cfg(feature = "jxl")]
891        Codec::Jxl => jxl::decode(doc, &data, dict, &options.limits, &mut notes),
892        #[cfg(not(feature = "jxl"))]
893        Codec::Jxl => Err(ImageCodecError::FeatureUnsupported {
894            feature: "JXL/not-built",
895        }),
896    };
897    if cancelled() {
898        return Err(ImageCodecError::Cancelled);
899    }
900    decoded
901}
902
903/// Build the [`CodedImage`] for a chain with **no** terminal codec.
904///
905/// The geometry fields echo the image dictionary so the caller sees one
906/// uniform shape, and [`CodecColorModel::Unspecified`] states plainly
907/// that no codec declared anything. Missing or nonsensical dictionary
908/// entries become `0` rather than an error: validating Table 89 is the
909/// renderer's job and it already does it, and duplicating that check
910/// here would give two places for the rules to disagree.
911fn uncoded(doc: &DocumentView<'_>, dict: &Dict, samples: Vec<u8>, notes: CodecNotes) -> CodedImage {
912    let int = |key: &[u8]| -> u32 {
913        dict.get(key)
914            .map(|o| doc.resolve(o))
915            .and_then(Object::as_int)
916            .and_then(|v| u32::try_from(v).ok())
917            .unwrap_or(0)
918    };
919    CodedImage {
920        samples,
921        codec: None,
922        width: int(b"Width"),
923        height: int(b"Height"),
924        components: 0,
925        bits_per_component: u8::try_from(int(b"BitsPerComponent")).unwrap_or(0),
926        color_model: CodecColorModel::Unspecified,
927        icc_profile: None,
928        embedded_alpha: None,
929        notes,
930    }
931}
932
933/// The `/DecodeParms` entry belonging to the terminal codec.
934///
935/// Table 5's positional rules apply unchanged: a lone dictionary when
936/// the chain has one filter, otherwise the array position matching the
937/// codec's index (the last one).
938fn codec_parms(dict: &Dict, total: usize) -> Option<&Dict> {
939    let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
940    match parms {
941        Object::Dict(d) if total == 1 => Some(d),
942        Object::Array(items) => match items.get(total.checked_sub(1)?) {
943            Some(Object::Dict(d)) => Some(d),
944            _ => None,
945        },
946        _ => None,
947    }
948}
949
950/// How to read a four-component `DCTDecode` image that declares no
951/// `/Decode` array (spec ambiguity `DCT-A1`).
952///
953/// # The question
954///
955/// A CMYK JPEG with **effective `ColorTransform` 0** and **no `/Decode`**:
956/// are the stored samples direct CMYK, or Adobe-complemented CMYK? Nothing
957/// in the codestream or the image dictionary disambiguates it — the
958/// undocumented 1990s Photoshop convention stores complemented values, and
959/// there is no marker bit that says so.
960///
961/// # Default: [`Self::NeverInvert`] — **EVIDENCE TIER (c)**
962///
963/// Tier (c) means *what other major implementations do, as documented* —
964/// and this is the **strongest-sourced default in the whole ambiguity
965/// register**, the one place it is not a guess:
966///
967/// - the word `"invert"` occurs **zero times** in Adobe TN #5116, the
968///   document ISO 32000-1 §7.4.8 footnote *a* makes normative by
969///   reference (verified 2026-07-31);
970/// - **APP14 carries no polarity flag** — there is no bit to test, so
971///   "invert when the marker is present" keys off mere presence;
972/// - `filter__dct.md` records that all four reference engines accept the
973///   ambiguity rather than inverting on APP14 presence.
974///
975/// This is also pdfcer's standing rule **R29** (decision 006), and the
976/// residual risk is already disclosed rather than repaired by
977/// [`crate::CodecNotes::cmyk_polarity_unverifiable`] (R30).
978/// The setting adds the operator's escape hatch; it does not weaken R29,
979/// which remains what pdfcer does unless the operator says otherwise.
980#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
981pub enum CmykJpegPolarity {
982    /// Take the samples as stored. `/Decode` is the sole polarity control
983    /// (`/Decode [1 0 1 0 1 0 1 0]` *is* the sanctioned way for a producer
984    /// to declare inverted storage).
985    ///
986    /// **The shipped default**, and the standing rule.
987    #[default]
988    NeverInvert,
989    /// Complement all four components (`255 − x`) when the codestream
990    /// carries an Adobe APP14 marker, the effective transform is 0, and
991    /// the image dictionary declares no `/Decode`.
992    ///
993    /// For a library of old Photoshop-authored CMYK JPEGs that genuinely
994    /// do store complemented ink and say so nowhere. Getting this wrong in
995    /// either direction renders a photographic negative — which is at
996    /// least an obvious failure, not a subtle one.
997    InvertOnApp14,
998}
999
1000#[cfg(test)]
1001#[allow(
1002    clippy::unwrap_used,
1003    clippy::expect_used,
1004    clippy::panic,
1005    clippy::indexing_slicing
1006)]
1007mod tests {
1008    use super::*;
1009    use pdfcer_model::object::Name;
1010
1011    fn dict_with(entries: Vec<(&[u8], Object)>) -> Dict {
1012        let mut d = Dict::new();
1013        for (k, v) in entries {
1014            d.insert(Name::from(k), v);
1015        }
1016        d
1017    }
1018
1019    fn name(n: &[u8]) -> Object {
1020        Object::Name(Name::from(n))
1021    }
1022
1023    #[test]
1024    fn terminal_codec_recognizes_all_four_and_their_abbreviations() {
1025        for (spelling, want) in [
1026            (&b"DCTDecode"[..], Codec::Dct),
1027            (b"DCT", Codec::Dct),
1028            (b"CCITTFaxDecode", Codec::Ccitt),
1029            (b"CCF", Codec::Ccitt),
1030            (b"JBIG2Decode", Codec::Jbig2),
1031            (b"JPXDecode", Codec::Jpx),
1032            (b"JXLDecode", Codec::Jxl),
1033        ] {
1034            let d = dict_with(vec![(b"Filter", name(spelling))]);
1035            assert_eq!(terminal_codec(&d).unwrap(), Some(want), "{spelling:?}");
1036        }
1037    }
1038
1039    #[test]
1040    fn terminal_codec_is_none_for_byte_stream_chains() {
1041        let d = dict_with(vec![(b"Filter", name(b"FlateDecode"))]);
1042        assert_eq!(terminal_codec(&d).unwrap(), None);
1043        assert_eq!(terminal_codec(&Dict::new()).unwrap(), None);
1044    }
1045
1046    #[test]
1047    fn terminal_codec_sees_through_an_ascii_prefix() {
1048        // `/Filter [/ASCII85Decode /DCTDecode]` is a real, legal shape.
1049        let d = dict_with(vec![(
1050            b"Filter",
1051            Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
1052        )]);
1053        assert_eq!(terminal_codec(&d).unwrap(), Some(Codec::Dct));
1054    }
1055
1056    #[test]
1057    fn inline_rules_match_the_spec() {
1058        // §8.9.7 Table 94 gives `DCT` and `CCF` abbreviations; §7.4.7
1059        // forbids JBIG2 inline, and JPX has no inline form.
1060        assert!(Codec::Dct.allowed_inline());
1061        assert!(Codec::Ccitt.allowed_inline());
1062        assert!(!Codec::Jbig2.allowed_inline());
1063        assert!(!Codec::Jpx.allowed_inline());
1064        assert!(!Codec::Jxl.allowed_inline());
1065    }
1066
1067    // -----------------------------------------------------------------
1068    // End-to-end decodes over real codestreams (`fixtures`)
1069    // -----------------------------------------------------------------
1070
1071    /// The smallest document `decode_image` will accept a `&Document`
1072    /// from. Nothing in the DCT path reads the file body — `doc` is
1073    /// there for `/JBIG2Globals` and for resolving indirect parameter
1074    /// values — so a two-object catalog is enough.
1075    fn empty_document() -> Document {
1076        let mut buf = b"%PDF-1.7\n".to_vec();
1077        let mut offsets = Vec::new();
1078        for (num, body) in [
1079            (1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
1080            (2, "<< /Type /Pages /Kids [] /Count 0 >>"),
1081        ] {
1082            offsets.push(buf.len());
1083            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
1084        }
1085        let xref_at = buf.len();
1086        buf.extend_from_slice(b"xref\n0 3\n0000000000 65535 f\r\n");
1087        for off in offsets {
1088            buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
1089        }
1090        buf.extend_from_slice(
1091            format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
1092        );
1093        Document::from_bytes(buf).unwrap()
1094    }
1095
1096    /// An image dictionary declaring `DCTDecode` at the stated geometry.
1097    fn dct_dict(width: i64, height: i64) -> Dict {
1098        dict_with(vec![
1099            (b"Filter", name(b"DCTDecode")),
1100            (b"Width", Object::Integer(width)),
1101            (b"Height", Object::Integer(height)),
1102            (b"BitsPerComponent", Object::Integer(8)),
1103        ])
1104    }
1105
1106    fn decode_fixture(bytes: &[u8], dict: &Dict) -> Result<CodedImage, ImageCodecError> {
1107        decode_image(&empty_document(), dict, bytes, false)
1108    }
1109
1110    /// As `decode_fixture` with no memory budget, so the checks behind it
1111    /// (evidence) are the ones a test reaches.
1112    fn decode_fixture_unbudgeted(bytes: &[u8], dict: &Dict) -> Result<CodedImage, ImageCodecError> {
1113        let options = DecodeOptions::default().with_limits(peak::DecodeLimits::new(u64::MAX));
1114        decode_image_view_with(&empty_document().view(), dict, bytes, false, options)
1115    }
1116
1117    fn is_budget_refusal(err: &ImageCodecError) -> bool {
1118        matches!(
1119            err,
1120            ImageCodecError::LimitExceeded {
1121                limit: SizeLimit::MemoryBudget,
1122                ..
1123            }
1124        )
1125    }
1126
1127    #[test]
1128    fn grayscale_jpeg_decodes_to_one_component_per_pixel() {
1129        let img = decode_fixture(fixtures::GRAY_2X2, &dct_dict(2, 2)).unwrap();
1130        assert_eq!(img.codec, Some(Codec::Dct));
1131        assert_eq!((img.width, img.height), (2, 2));
1132        assert_eq!(img.components, 1);
1133        assert_eq!(img.bits_per_component, 8);
1134        assert_eq!(img.color_model, CodecColorModel::Gray);
1135        assert_eq!(img.samples.len(), 4, "2x2 x 1 component");
1136        // Source ramp 0, 85, 170, 255 — monotonic and near the originals
1137        // at quality 90.
1138        assert!(img.samples[0] < 20, "{:?}", img.samples);
1139        assert!(img.samples[3] > 235, "{:?}", img.samples);
1140        assert!(img.samples[0] < img.samples[1]);
1141        assert!(img.samples[1] < img.samples[2]);
1142        assert!(!img.notes.cmyk_image);
1143        assert!(!img.notes.geometry_mismatch);
1144    }
1145
1146    #[test]
1147    fn grayscale_ignores_color_transform_per_table_13() {
1148        // "This option shall be ignored if the image has one or two
1149        // colour components" — so `/ColorTransform 1` on a grayscale
1150        // JPEG is not an error and changes nothing.
1151        let mut dict = dct_dict(2, 2);
1152        dict.insert(
1153            Name::from(b"DecodeParms"),
1154            Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(1))])),
1155        );
1156        let with_parm = decode_fixture(fixtures::GRAY_2X2, &dict).unwrap();
1157        let without = decode_fixture(fixtures::GRAY_2X2, &dct_dict(2, 2)).unwrap();
1158        assert_eq!(with_parm.samples, without.samples);
1159        assert_eq!(with_parm.color_model, CodecColorModel::Gray);
1160    }
1161
1162    /// Assert a 2x2 RGB decode came back as red / green / blue / white.
1163    fn assert_rgb_primaries(samples: &[u8]) {
1164        assert_eq!(samples.len(), 12, "2x2 x 3 components");
1165        let px = |i: usize| (samples[i * 3], samples[i * 3 + 1], samples[i * 3 + 2]);
1166        let (r, g, b) = px(0);
1167        assert!(
1168            r > 200 && g < 60 && b < 60,
1169            "pixel 0 should be red: {r},{g},{b}"
1170        );
1171        let (r, g, b) = px(1);
1172        assert!(
1173            r < 60 && g > 200 && b < 60,
1174            "pixel 1 should be green: {r},{g},{b}"
1175        );
1176        let (r, g, b) = px(2);
1177        assert!(
1178            r < 60 && g < 60 && b > 200,
1179            "pixel 2 should be blue: {r},{g},{b}"
1180        );
1181        let (r, g, b) = px(3);
1182        assert!(
1183            r > 200 && g > 200 && b > 200,
1184            "pixel 3 should be white: {r},{g},{b}"
1185        );
1186    }
1187
1188    #[test]
1189    fn rgb_jpeg_with_no_marker_takes_table_13s_default_transform_of_one() {
1190        let img = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
1191        assert_eq!(img.components, 3);
1192        assert_eq!(img.color_model, CodecColorModel::Rgb);
1193        assert_rgb_primaries(&img.samples);
1194    }
1195
1196    #[test]
1197    fn progressive_jpeg_decodes_identically_to_baseline() {
1198        // §7.4.8: progressive support is required from PDF 1.3, and it
1199        // is 14% of the measured corpus.
1200        let img = decode_fixture(fixtures::RGB_2X2_PROGRESSIVE, &dct_dict(2, 2)).unwrap();
1201        assert_eq!(img.color_model, CodecColorModel::Rgb);
1202        assert_rgb_primaries(&img.samples);
1203    }
1204
1205    #[test]
1206    fn app14_transform_one_reaches_the_same_result_as_the_default() {
1207        let img = decode_fixture(fixtures::RGB_2X2_APP14_T1, &dct_dict(2, 2)).unwrap();
1208        assert_eq!(img.color_model, CodecColorModel::Rgb);
1209        assert_rgb_primaries(&img.samples);
1210    }
1211
1212    #[test]
1213    fn app14_transform_zero_delivers_untransformed_components() {
1214        // THE routing regression test. The stored components are YCbCr,
1215        // so a transform-0 decode hands them back verbatim — visibly
1216        // different from the transform-1 decode of the very same
1217        // entropy-coded data.
1218        let raw = decode_fixture(fixtures::RGB_2X2_APP14_T0, &dct_dict(2, 2)).unwrap();
1219        let transformed = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
1220        assert_eq!(raw.color_model, CodecColorModel::Untransformed3);
1221        assert_eq!(raw.components, 3);
1222        assert_eq!(raw.samples.len(), 12);
1223        assert_ne!(
1224            raw.samples, transformed.samples,
1225            "ColorTransform 0 must NOT apply the YCbCr->RGB inverse"
1226        );
1227    }
1228
1229    #[test]
1230    fn the_marker_outranks_the_dictionary() {
1231        // Table 13, verbatim: "then the colours shall be transformed, or
1232        // not … according to the value provided in the encoded data and
1233        // the value of this dictionary entry shall be ignored."
1234        // /ColorTransform 1 must NOT override an APP14 saying 0.
1235        let mut dict = dct_dict(2, 2);
1236        dict.insert(
1237            Name::from(b"DecodeParms"),
1238            Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(1))])),
1239        );
1240        let img = decode_fixture(fixtures::RGB_2X2_APP14_T0, &dict).unwrap();
1241        assert_eq!(
1242            img.color_model,
1243            CodecColorModel::Untransformed3,
1244            "the APP14 marker wins"
1245        );
1246    }
1247
1248    #[test]
1249    fn the_dictionary_wins_when_there_is_no_marker() {
1250        // Second level of the precedence chain: no Adobe marker, so
1251        // /ColorTransform 0 applies and suppresses the inverse.
1252        let mut dict = dct_dict(2, 2);
1253        dict.insert(
1254            Name::from(b"DecodeParms"),
1255            Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(0))])),
1256        );
1257        let img = decode_fixture(fixtures::RGB_2X2, &dict).unwrap();
1258        assert_eq!(img.color_model, CodecColorModel::Untransformed3);
1259        let default = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
1260        assert_ne!(img.samples, default.samples);
1261    }
1262
1263    #[test]
1264    fn unknown_adobe_transform_is_a_named_diagnostic_not_a_vendor_error() {
1265        // zune-jpeg hard-errors on this inside header parsing; the
1266        // pre-sniff must catch it first (rule R27).
1267        assert_eq!(
1268            decode_fixture(fixtures::RGB_2X2_APP14_T3, &dct_dict(2, 2)).unwrap_err(),
1269            ImageCodecError::FeatureUnsupported {
1270                feature: "DCT/adobe-transform-3"
1271            }
1272        );
1273    }
1274
1275    #[test]
1276    fn cmyk_jpeg_passes_four_raw_components_through_and_is_counted() {
1277        // This fixture is APP14 transform 0 with no /Decode — exactly
1278        // decision 006 §4.4's R30 shape, so it must trip the
1279        // polarity-unverifiable diagnostic and NOT the benign YCCK
1280        // census (which is reserved for effective transform 1/2).
1281        let img = decode_fixture(fixtures::CMYK_2X2, &dct_dict(2, 2)).unwrap();
1282        assert_eq!(img.components, 4);
1283        assert_eq!(img.color_model, CodecColorModel::Cmyk);
1284        assert_eq!(img.samples.len(), 16, "2x2 x 4 components");
1285        assert!(
1286            img.notes.cmyk_polarity_unverifiable,
1287            "transform 0 + no /Decode is the R30 shape and must announce itself (decision 006)"
1288        );
1289        assert!(
1290            !img.notes.cmyk_image,
1291            "the benign census counts YCCK (transform 1/2) only (decision 006 §4.4)"
1292        );
1293        // libjpeg writes APP14 transform 0 for CMYK, so Table 13 says no
1294        // transformation: the samples are exactly what the encoder
1295        // stored. pdfcer applies NO "Adobe inversion" of its own (R29 —
1296        // no shipping PDF engine does), so the stored complement
1297        // survives to `/Decode`.
1298        let first = &img.samples[0..4];
1299        assert!(
1300            first.iter().any(|&v| v > 200),
1301            "raw stored samples, not inverted: {first:?}"
1302        );
1303    }
1304
1305    #[test]
1306    fn cmyk_jpeg_with_a_decode_array_is_not_polarity_unverifiable() {
1307        // Same R30 shape, but the producer DECLARED its polarity via
1308        // /Decode — the sanctioned mechanism (decision 006 §4.3) — so
1309        // the residual-ambiguity diagnostic must stay quiet. The array
1310        // is only OBSERVED here (R26 clarification): applying it is
1311        // pdfcer-render's job, so the samples must be byte-identical to
1312        // the no-/Decode decode.
1313        let mut dict = dct_dict(2, 2);
1314        dict.insert(
1315            Name::from(b"Decode"),
1316            Object::Array(vec![
1317                Object::Integer(1),
1318                Object::Integer(0),
1319                Object::Integer(1),
1320                Object::Integer(0),
1321                Object::Integer(1),
1322                Object::Integer(0),
1323                Object::Integer(1),
1324                Object::Integer(0),
1325            ]),
1326        );
1327        let img = decode_fixture(fixtures::CMYK_2X2, &dict).unwrap();
1328        assert!(!img.notes.cmyk_polarity_unverifiable);
1329        assert!(!img.notes.cmyk_image);
1330        let plain = decode_fixture(fixtures::CMYK_2X2, &dct_dict(2, 2)).unwrap();
1331        assert_eq!(
1332            img.samples, plain.samples,
1333            "/Decode is observed for classification, never applied here"
1334        );
1335    }
1336
1337    #[test]
1338    fn geometry_disagreement_is_counted_and_the_codestream_is_reported() {
1339        // The dictionary claims 7x9; the codestream says 2x2. Both
1340        // numbers survive: the codestream's in `CodedImage`, the
1341        // divergence in `notes`.
1342        let img = decode_fixture(fixtures::RGB_2X2, &dct_dict(7, 9)).unwrap();
1343        assert_eq!((img.width, img.height), (2, 2));
1344        assert!(img.notes.geometry_mismatch);
1345    }
1346
1347    #[test]
1348    fn a_wrong_bits_per_component_is_a_geometry_disagreement() {
1349        // Table 89: a DCTDecode filter "shall always deliver 8-bit
1350        // samples", so any other stated value is inconsistent.
1351        let mut dict = dct_dict(2, 2);
1352        dict.insert(Name::from(b"BitsPerComponent"), Object::Integer(4));
1353        let img = decode_fixture(fixtures::RGB_2X2, &dict).unwrap();
1354        assert_eq!(img.bits_per_component, 8);
1355        assert!(img.notes.geometry_mismatch);
1356    }
1357
1358    #[test]
1359    fn a_codestream_past_max_image_pixels_is_refused_before_allocating() {
1360        // 65535 x 65535 = 4.3 Gpx from 393 bytes. Evidence refuses it first:
1361        // 1x1-sampled 3-component baseline, so each component has 8192^2
1362        // blocks at 2 bits each, 16 MiB of entropy data at the least.
1363        let budgeted = decode_fixture(fixtures::RGB_HUGE_DIMS, &dct_dict(65535, 65535));
1364        assert!(is_budget_refusal(&budgeted.unwrap_err()));
1365        assert_eq!(
1366            decode_fixture_unbudgeted(fixtures::RGB_HUGE_DIMS, &dct_dict(65535, 65535))
1367                .unwrap_err(),
1368            ImageCodecError::DeclaredGeometryExceedsData {
1369                codec: Codec::Dct,
1370                declared: DeclaredGeometry::Pixels {
1371                    width: 65535,
1372                    height: 65535
1373                },
1374                min_bytes: 1 << 24,
1375                have_bytes: fixtures::RGB_HUGE_DIMS.len() as u64,
1376            }
1377        );
1378    }
1379
1380    /// [`fixtures::RGB_2X2`] with its SOF0 `Y` and `X` fields set to the
1381    /// given geometry, so a ceiling can be probed without encoding it.
1382    fn rgb_with_sof_dims(width: u16, height: u16) -> Vec<u8> {
1383        let mut bytes = fixtures::RGB_2X2.to_vec();
1384        let sof = bytes
1385            .windows(2)
1386            .position(|w| w == [0xFF, 0xC0])
1387            .expect("RGB_2X2 is baseline");
1388        bytes[sof + 5..sof + 7].copy_from_slice(&height.to_be_bytes());
1389        bytes[sof + 7..sof + 9].copy_from_slice(&width.to_be_bytes());
1390        bytes
1391    }
1392
1393    #[test]
1394    fn the_codec_checks_the_budget_against_the_codestream_geometry() {
1395        // The dictionary says 2 x 2, so the pre-filter check admits it;
1396        // the SOF says 11586^2, which only the codec sees. Padded past EOI
1397        // so the evidence bound (1449^2 blocks x 2 bits) is met.
1398        let mut bytes = rgb_with_sof_dims(11586, 11586);
1399        bytes.resize(bytes.len() + 1449 * 1449 / 4 + 1, 0);
1400        let mut notes = CodecNotes::default();
1401        let doc = empty_document();
1402        let err = dct::decode(
1403            &doc.view(),
1404            &bytes,
1405            None,
1406            &dct_dict(2, 2),
1407            &DecodeOptions::default().with_limits(peak::DecodeLimits::new(1 << 28)),
1408            &mut notes,
1409            &|| false,
1410        )
1411        .unwrap_err();
1412        assert!(is_budget_refusal(&err), "{err:?}");
1413    }
1414
1415    #[test]
1416    fn corrupt_codestream_errs_never_returns_plausible_samples() {
1417        // The fail-clean contract, at the codec layer.
1418        let mut truncated = fixtures::RGB_2X2.to_vec();
1419        truncated.truncate(truncated.len() / 2);
1420        assert!(matches!(
1421            decode_fixture(&truncated, &dct_dict(2, 2)),
1422            Err(ImageCodecError::Corrupt { .. })
1423        ));
1424        assert!(matches!(
1425            decode_fixture(b"not a jpeg", &dct_dict(2, 2)),
1426            Err(ImageCodecError::Corrupt { .. })
1427        ));
1428    }
1429
1430    #[test]
1431    fn an_ascii85_prefix_is_run_before_the_codec() {
1432        // `/Filter [/ASCII85Decode /DCTDecode]` — a real, legal shape.
1433        // The byte-stream prefix must run first and the codec must see
1434        // the decoded codestream.
1435        let armoured = ascii85(fixtures::RGB_2X2);
1436        let mut dict = dct_dict(2, 2);
1437        dict.insert(
1438            Name::from(b"Filter"),
1439            Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
1440        );
1441        let img = decode_fixture(armoured.as_bytes(), &dict).unwrap();
1442        assert_eq!(img.codec, Some(Codec::Dct));
1443        assert_rgb_primaries(&img.samples);
1444    }
1445
1446    /// Minimal ASCII85 encoder — test-only, for the chained-filter case.
1447    fn ascii85(data: &[u8]) -> String {
1448        let mut out = String::new();
1449        for chunk in data.chunks(4) {
1450            let mut word = [0u8; 4];
1451            word[..chunk.len()].copy_from_slice(chunk);
1452            let mut value = u32::from_be_bytes(word);
1453            let mut group = [0u8; 5];
1454            for slot in group.iter_mut().rev() {
1455                *slot = b'!' + (value % 85) as u8;
1456                value /= 85;
1457            }
1458            out.extend(group[..chunk.len() + 1].iter().map(|&b| b as char));
1459        }
1460        out.push_str("~>");
1461        out
1462    }
1463
1464    #[test]
1465    fn a_chain_with_no_codec_yields_an_unspecified_coded_image() {
1466        // One entry point for every image: a Flate-only image still
1467        // comes back as a `CodedImage`, just with nothing declared.
1468        let dict = dict_with(vec![
1469            (b"Width", Object::Integer(4)),
1470            (b"Height", Object::Integer(2)),
1471            (b"BitsPerComponent", Object::Integer(8)),
1472        ]);
1473        let img = decode_fixture(b"rawsamples", &dict).unwrap();
1474        assert_eq!(img.codec, None);
1475        assert_eq!(img.color_model, CodecColorModel::Unspecified);
1476        assert_eq!((img.width, img.height), (4, 2));
1477        assert_eq!(img.components, 0, "no codec declared a component count");
1478        assert_eq!(img.samples, b"rawsamples");
1479    }
1480
1481    #[test]
1482    fn every_recognized_codec_is_now_implemented() {
1483        // `ImageCodecError::Unsupported` is retained after Pass 2.3 so a
1484        // regression stays visible (decision 005 §6.4), but no codec
1485        // should reach it any more. Each of the four is fed bytes that
1486        // are certainly not a valid codestream: the failure must be
1487        // Corrupt/FeatureUnsupported — "these bytes are broken" — never
1488        // "this codec is not built".
1489        for filter in [
1490            &b"DCTDecode"[..],
1491            b"CCITTFaxDecode",
1492            b"JBIG2Decode",
1493            b"JPXDecode",
1494        ] {
1495            let dict = dict_with(vec![
1496                (b"Filter", name(filter)),
1497                (b"Width", Object::Integer(4)),
1498                (b"Height", Object::Integer(2)),
1499            ]);
1500            let err = decode_fixture(b"not a codestream", &dict).unwrap_err();
1501            assert!(
1502                !matches!(err, ImageCodecError::Unsupported { .. }),
1503                "{}: still reports the codec as unimplemented ({err})",
1504                String::from_utf8_lossy(filter),
1505            );
1506        }
1507    }
1508
1509    // -----------------------------------------------------------------
1510    // JPXDecode (§7.4.9, §8.9.5 Table 89) — Pass 2.3
1511    // -----------------------------------------------------------------
1512
1513    /// A JPX image dictionary. `entries` carries whatever Table 89 keys
1514    /// a given test is about; `/Filter` is added here.
1515    ///
1516    /// Note what is NOT added by default: `/ColorSpace` and
1517    /// `/BitsPerComponent`. Table 89 makes both optional for this
1518    /// filter, so the *bare* dictionary is the conformant baseline and
1519    /// every entry beyond `/Width`//`/Height` is something a specific
1520    /// test chose to say.
1521    #[cfg(feature = "jpx")]
1522    fn jpx_dict(entries: Vec<(&[u8], Object)>) -> Dict {
1523        let mut all: Vec<(&[u8], Object)> = vec![(b"Filter", name(b"JPXDecode"))];
1524        all.extend(entries);
1525        dict_with(all)
1526    }
1527
1528    /// The bare 16 x 4 grayscale dictionary the two container-shape
1529    /// fixtures share.
1530    #[cfg(feature = "jpx")]
1531    fn jpx_gray_dict() -> Dict {
1532        jpx_dict(vec![
1533            (b"Width", Object::Integer(16)),
1534            (b"Height", Object::Integer(4)),
1535        ])
1536    }
1537
1538    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1539    #[cfg(feature = "jpx")]
1540    #[test]
1541    fn jpx_decodes_a_jp2_container_to_the_expected_samples() {
1542        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &jpx_gray_dict()).unwrap();
1543        assert_eq!(img.codec, Some(Codec::Jpx));
1544        assert_eq!((img.width, img.height), (16, 4));
1545        assert_eq!(img.components, 1);
1546        assert_eq!(img.color_model, CodecColorModel::Gray);
1547        assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
1548        assert!(!img.notes.geometry_mismatch);
1549        assert_eq!(img.embedded_alpha, None);
1550        assert_eq!(img.icc_profile, None);
1551    }
1552
1553    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1554    #[cfg(feature = "jpx")]
1555    #[test]
1556    fn jpx_decodes_a_raw_codestream_identically_to_its_jp2_container() {
1557        // §7.4.9 says the filter "shall expect to read a full JPX file
1558        // structure", but real producers embed bare codestreams and
1559        // `hayro-jpeg2000` sniffs which it has. The two shapes carry the
1560        // same picture, so they must produce the same bytes — which is
1561        // what proves pdfcer reads geometry and colour from the
1562        // codestream rather than from the container.
1563        let boxed = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &jpx_gray_dict()).unwrap();
1564        let bare = decode_fixture(fixtures_jpx::JPX_GRAY_8_J2K, &jpx_gray_dict()).unwrap();
1565        assert_eq!(bare.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
1566        assert_eq!(bare.samples, boxed.samples);
1567        assert_eq!((bare.width, bare.height), (boxed.width, boxed.height));
1568        assert_eq!(bare.color_model, boxed.color_model);
1569    }
1570
1571    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1572    #[cfg(feature = "jpx")]
1573    #[test]
1574    fn jpx_interleaves_rgb_components_in_order() {
1575        let dict = jpx_dict(vec![
1576            (b"Width", Object::Integer(4)),
1577            (b"Height", Object::Integer(2)),
1578        ]);
1579        let img = decode_fixture(fixtures_jpx::JPX_RGB_8_JP2, &dict).unwrap();
1580        assert_eq!(img.components, 3);
1581        assert_eq!(img.color_model, CodecColorModel::Rgb);
1582        assert_eq!(img.samples, fixtures_jpx::JPX_RGB_8_SAMPLES);
1583    }
1584
1585    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1586    #[cfg(feature = "jpx")]
1587    #[test]
1588    fn jpx_reports_cmyk_from_enumerated_colour_space_twelve() {
1589        // §7.4.9 singles this value out: enumerated colour space 12
1590        // (CMYK) "is part of JPX but not JPX baseline" and "shall be
1591        // supported in a PDF" regardless.
1592        let dict = jpx_dict(vec![
1593            (b"Width", Object::Integer(4)),
1594            (b"Height", Object::Integer(2)),
1595        ]);
1596        let img = decode_fixture(fixtures_jpx::JPX_CMYK_8_JP2, &dict).unwrap();
1597        assert_eq!(img.components, 4);
1598        assert_eq!(img.color_model, CodecColorModel::Cmyk);
1599        assert_eq!(img.samples, fixtures_jpx::JPX_CMYK_8_SAMPLES);
1600    }
1601
1602    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1603    #[cfg(feature = "jpx")]
1604    #[test]
1605    fn jpx_absent_colour_space_is_conformant_and_the_codestream_supplies_it() {
1606        // THE Table 89 inversion, from the side that a conventional
1607        // reader gets wrong: `/ColorSpace` is "Required for images,
1608        // EXCEPT those that use the JPXDecode filter". A dictionary with
1609        // no `/ColorSpace` and no `/BitsPerComponent` is fully
1610        // conformant, and the codec must supply both.
1611        let dict = jpx_gray_dict();
1612        assert!(dict.get(b"ColorSpace").is_none());
1613        assert!(dict.get(b"BitsPerComponent").is_none());
1614        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
1615        assert_eq!(img.color_model, CodecColorModel::Gray);
1616        assert_eq!(img.bits_per_component, 8);
1617        assert!(
1618            !img.notes.geometry_mismatch,
1619            "absent optional entries are not a disagreement"
1620        );
1621    }
1622
1623    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1624    #[cfg(feature = "jpx")]
1625    #[test]
1626    fn jpx_bits_per_component_is_ignored_and_a_stated_value_is_counted() {
1627        // Table 89: "this entry is optional and shall be ignored if
1628        // present. The bit depth is determined by the conforming reader
1629        // in the process of decoding." So a 16-bit codestream whose
1630        // dictionary honestly says `/BitsPerComponent 16` still yields
1631        // 8-bit samples — and the entry's presence is still counted,
1632        // because it is the one entry a reader is told to ignore.
1633        let dict = jpx_dict(vec![
1634            (b"Width", Object::Integer(4)),
1635            (b"Height", Object::Integer(2)),
1636            (b"BitsPerComponent", Object::Integer(16)),
1637        ]);
1638        let img = decode_fixture(fixtures_jpx::JPX_GRAY_16_JP2, &dict).unwrap();
1639        assert_eq!(img.bits_per_component, 8);
1640        assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_16_SAMPLES);
1641        assert!(img.notes.geometry_mismatch);
1642    }
1643
1644    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1645    #[cfg(feature = "jpx")]
1646    #[test]
1647    fn jpx_scales_high_bit_depths_full_range_not_by_high_byte() {
1648        // The discriminator pixel is 0x00FF: full-range scaling gives 1,
1649        // a high-byte truncation gives 0. See `jpx`'s module docs.
1650        let dict = jpx_dict(vec![
1651            (b"Width", Object::Integer(4)),
1652            (b"Height", Object::Integer(2)),
1653        ]);
1654        let img = decode_fixture(fixtures_jpx::JPX_GRAY_16_JP2, &dict).unwrap();
1655        assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_16_SAMPLES);
1656        assert_eq!(img.samples.first().copied(), Some(0x00), "0 stays 0");
1657        assert_eq!(
1658            img.samples.get(1).copied(),
1659            Some(0xFF),
1660            "the white point 2^16-1 must land on exactly 255"
1661        );
1662        assert_eq!(
1663            img.samples.get(4).copied(),
1664            Some(0x01),
1665            "0x00FF must scale to 1, not truncate to 0"
1666        );
1667    }
1668
1669    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1670    #[cfg(feature = "jpx")]
1671    #[test]
1672    fn jpx_dictionary_geometry_disagreement_is_counted_and_the_codestream_reported() {
1673        // §7.4.9 requires `/Width`//`/Height` to match the codestream
1674        // but gives no conflict rule. pdfcer reports the codestream's
1675        // numbers and counts the divergence; the renderer keeps the
1676        // dictionary's for placement.
1677        let dict = jpx_dict(vec![
1678            (b"Width", Object::Integer(999)),
1679            (b"Height", Object::Integer(7)),
1680        ]);
1681        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
1682        assert_eq!((img.width, img.height), (16, 4));
1683        assert!(img.notes.geometry_mismatch);
1684    }
1685
1686    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1687    #[cfg(feature = "jpx")]
1688    #[test]
1689    fn jpx_colour_space_channel_count_disagreement_is_counted() {
1690        // §7.4.9: "The number of colour channels in the JPEG2000 data
1691        // shall match the number of components in the colour space."
1692        // A `/DeviceRGB` dictionary over a grayscale codestream does
1693        // not, and the spec gives no recovery rule — so it is counted,
1694        // not refused, and the codec still reports what it actually has.
1695        let dict = jpx_dict(vec![
1696            (b"Width", Object::Integer(16)),
1697            (b"Height", Object::Integer(4)),
1698            (b"ColorSpace", name(b"DeviceRGB")),
1699        ]);
1700        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
1701        assert_eq!(img.components, 1);
1702        assert_eq!(img.color_model, CodecColorModel::Gray);
1703        assert!(img.notes.geometry_mismatch);
1704    }
1705
1706    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1707    #[cfg(feature = "jpx")]
1708    #[test]
1709    fn jpx_matching_colour_space_is_not_a_disagreement() {
1710        let dict = jpx_dict(vec![
1711            (b"Width", Object::Integer(4)),
1712            (b"Height", Object::Integer(2)),
1713            (b"ColorSpace", name(b"DeviceRGB")),
1714        ]);
1715        let img = decode_fixture(fixtures_jpx::JPX_RGB_8_JP2, &dict).unwrap();
1716        assert!(!img.notes.geometry_mismatch);
1717        assert_eq!(img.samples, fixtures_jpx::JPX_RGB_8_SAMPLES);
1718    }
1719
1720    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1721    #[cfg(feature = "jpx")]
1722    #[test]
1723    fn jpx_smask_in_data_defaults_to_ignoring_the_opacity_channel() {
1724        // Table 89's default is 0: "If present, encoded soft-mask image
1725        // information shall be ignored." A decoder that always hands
1726        // back the alpha it found is wrong. The channel is still lifted
1727        // OUT of the colour samples — it is not a colour component.
1728        let dict = jpx_dict(vec![
1729            (b"Width", Object::Integer(4)),
1730            (b"Height", Object::Integer(2)),
1731        ]);
1732        let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
1733        assert_eq!(img.components, 3);
1734        assert_eq!(img.embedded_alpha, None, "/SMaskInData 0 means ignore");
1735        assert_eq!(
1736            img.samples,
1737            fixtures_jpx::JPX_RGBA_8_SAMPLES,
1738            "the opacity channel must not stay interleaved with the colours"
1739        );
1740        assert!(!img.notes.jpx_smask_in_data_preblended);
1741    }
1742
1743    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1744    #[cfg(feature = "jpx")]
1745    #[test]
1746    fn jpx_smask_in_data_one_exposes_the_opacity_channel() {
1747        let dict = jpx_dict(vec![
1748            (b"Width", Object::Integer(4)),
1749            (b"Height", Object::Integer(2)),
1750            (b"SMaskInData", Object::Integer(1)),
1751        ]);
1752        let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
1753        assert_eq!(img.components, 3);
1754        assert_eq!(img.samples, fixtures_jpx::JPX_RGBA_8_SAMPLES);
1755        assert_eq!(
1756            img.embedded_alpha.as_deref(),
1757            Some(fixtures_jpx::JPX_RGBA_8_ALPHA)
1758        );
1759        assert!(!img.notes.jpx_smask_in_data_preblended);
1760    }
1761
1762    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1763    #[cfg(feature = "jpx")]
1764    #[test]
1765    fn jpx_smask_in_data_two_is_deferred_by_name_and_never_applied() {
1766        // Value 2 means the colour channels were preblended with a
1767        // backdrop and the opacity channel would need a `Matte` entry
1768        // to undo. Recognized, counted, and NOT applied: the colours
1769        // come back as stored (a real picture over that backdrop) and
1770        // the alpha stays unexposed, because using it without
1771        // un-premultiplying would double-darken every soft pixel.
1772        let dict = jpx_dict(vec![
1773            (b"Width", Object::Integer(4)),
1774            (b"Height", Object::Integer(2)),
1775            (b"SMaskInData", Object::Integer(2)),
1776        ]);
1777        let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
1778        assert!(img.notes.jpx_smask_in_data_preblended);
1779        assert_eq!(img.embedded_alpha, None);
1780        assert_eq!(img.samples, fixtures_jpx::JPX_RGBA_8_SAMPLES);
1781    }
1782
1783    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1784    #[cfg(feature = "jpx")]
1785    #[test]
1786    fn jpx_smask_in_data_out_of_range_falls_back_to_the_default() {
1787        // 3 is undefined. Ignoring the codestream's alpha is the outcome
1788        // that cannot corrupt what is drawn; refusing the image over one
1789        // stray integer would be a total loss.
1790        for value in [-1, 3, 99] {
1791            let dict = jpx_dict(vec![
1792                (b"Width", Object::Integer(4)),
1793                (b"Height", Object::Integer(2)),
1794                (b"SMaskInData", Object::Integer(value)),
1795            ]);
1796            let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
1797            assert_eq!(img.embedded_alpha, None, "SMaskInData {value}");
1798            assert!(
1799                !img.notes.jpx_smask_in_data_preblended,
1800                "SMaskInData {value}"
1801            );
1802        }
1803    }
1804
1805    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1806    #[cfg(feature = "jpx")]
1807    #[test]
1808    fn jpx_smask_in_data_without_an_opacity_channel_is_a_disagreement() {
1809        // "If SMaskInData is nonzero, there shall be only one opacity
1810        // channel in the JPEG2000 data" presupposes one exists. It does
1811        // not here — counted, not refused, because nothing about the
1812        // colour samples is wrong.
1813        let dict = jpx_dict(vec![
1814            (b"Width", Object::Integer(16)),
1815            (b"Height", Object::Integer(4)),
1816            (b"SMaskInData", Object::Integer(1)),
1817        ]);
1818        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
1819        assert_eq!(img.embedded_alpha, None);
1820        assert!(img.notes.geometry_mismatch);
1821        assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
1822    }
1823
1824    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1825    #[cfg(feature = "jpx")]
1826    #[test]
1827    fn jpx_ignores_the_decode_array_entirely_at_this_layer() {
1828        // Table 89: "If the image uses the JPXDecode filter and
1829        // ImageMask is false, Decode shall be ignored by a conforming
1830        // reader." Rule R26 already forbids this layer from applying
1831        // one, so an inverting `/Decode` must change nothing here — and
1832        // `pdfcer-render` is where the suppression is enforced for real.
1833        let plain = jpx_dict(vec![
1834            (b"Width", Object::Integer(16)),
1835            (b"Height", Object::Integer(4)),
1836        ]);
1837        let inverted = jpx_dict(vec![
1838            (b"Width", Object::Integer(16)),
1839            (b"Height", Object::Integer(4)),
1840            (
1841                b"Decode",
1842                Object::Array(vec![Object::Integer(1), Object::Integer(0)]),
1843            ),
1844        ]);
1845        let a = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &plain).unwrap();
1846        let b = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &inverted).unwrap();
1847        assert_eq!(a.samples, b.samples);
1848    }
1849
1850    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1851    #[cfg(feature = "jpx")]
1852    #[test]
1853    fn jpx_corrupt_data_errs_and_never_returns_plausible_samples() {
1854        // Fail-clean (decision 001 §6.1.4): corrupt in, `Err` out. A
1855        // truncated codestream is the realistic shape.
1856        let mut truncated = fixtures_jpx::JPX_GRAY_8_JP2.to_vec();
1857        truncated.truncate(truncated.len() / 2);
1858        for data in [&b"not a codestream at all"[..], &truncated, &[]] {
1859            let err = decode_fixture(data, &jpx_gray_dict()).unwrap_err();
1860            assert!(
1861                matches!(
1862                    err,
1863                    ImageCodecError::Corrupt {
1864                        codec: Codec::Jpx,
1865                        ..
1866                    } | ImageCodecError::FeatureUnsupported { .. }
1867                ),
1868                "unexpected error for {} bytes: {err}",
1869                data.len()
1870            );
1871        }
1872    }
1873
1874    #[cfg(feature = "jpx")]
1875    #[test]
1876    fn a_jp2_box_length_near_usize_max_is_corrupt_not_a_panic() {
1877        // LBox = 1, XLBox = u64::MAX - 3 (ISO/IEC 15444-1 I.4): the box
1878        // walk steps to four bytes short of usize::MAX, where `pos + 4`
1879        // overflowed. Found by `image_codec_jpx` once the tile count ran
1880        // before `Image::new`.
1881        let mut data = vec![0, 0, 0, 1];
1882        data.extend_from_slice(b"jP  ");
1883        data.extend_from_slice(&(u64::MAX - 3).to_be_bytes());
1884        let err = decode_fixture(&data, &jpx_gray_dict()).unwrap_err();
1885        assert!(matches!(err, ImageCodecError::Corrupt { .. }), "{err:?}");
1886    }
1887
1888    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1889    #[cfg(feature = "jpx")]
1890    #[test]
1891    fn jpx_refuses_an_absurd_tile_grid_that_no_pixel_ceiling_can_see() {
1892        // A CPU-exhaustion vector the `image_codec_jpx` fuzz target
1893        // found in its first minute: T.800's tile grid is declared
1894        // independently of the image size, so `XTsiz`/`YTsiz` of 4 x 2
1895        // over a 512 x 1024 image is **65,536 tiles** from 310 bytes.
1896        // `hayro-jpeg2000` builds one structure per tile — 32 seconds
1897        // of work for half a megapixel of output.
1898        //
1899        // The memory budget cannot see this (512 Kpx); evidence does,
1900        // since each tile past MAX_TILES needs a 14-byte minimal tile-part.
1901        //
1902        // Built by rewriting the fixture's SIZ marker, so the rest of
1903        // the main header stays valid and the parse genuinely reaches
1904        // the tile check. Field offsets from SOC (T.800 A.5.1):
1905        //   8 Xsiz | 12 Ysiz | 24 XTsiz | 28 YTsiz
1906        let mut shredded = fixtures_jpx::JPX_GRAY_8_J2K.to_vec();
1907        for (offset, value) in [(8usize, 512u32), (12, 1024), (24, 4), (28, 2)] {
1908            let Some(slot) = shredded.get_mut(offset..offset + 4) else {
1909                panic!("fixture is shorter than a SIZ marker segment");
1910            };
1911            slot.copy_from_slice(&value.to_be_bytes());
1912        }
1913        assert_eq!(
1914            decode_fixture(&shredded, &jpx_gray_dict()).unwrap_err(),
1915            ImageCodecError::DeclaredGeometryExceedsData {
1916                codec: Codec::Jpx,
1917                declared: DeclaredGeometry::Tiles { count: 65_536 },
1918                min_bytes: 65_536 * 14,
1919                have_bytes: shredded.len() as u64,
1920            },
1921            "a 65,536-tile grid must be refused before any tile is built"
1922        );
1923    }
1924
1925    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1926    #[cfg(feature = "jpx")]
1927    #[test]
1928    fn jpx_accepts_a_tile_grid_within_the_ceiling() {
1929        // The other side of the guard, which is the half that catches an
1930        // over-tight ceiling: the ordinary single-tile fixture must
1931        // still decode. Every ceiling in this project gets this pair
1932        // after MAX_TOKEN_LEN and MAX_XOBJECT_DEPTH both shipped too
1933        // tight and rejected conformant files.
1934        let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_J2K, &jpx_gray_dict()).unwrap();
1935        assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
1936    }
1937
1938    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1939    #[cfg(feature = "jpx")]
1940    #[test]
1941    fn jpx_unsupported_enumerated_colour_space_is_a_named_diagnostic() {
1942        // §7.4.9 permits enumerated colour space **19 (CIEJab)**
1943        // explicitly ("limited to the JPX baseline set of features,
1944        // except for enumerated colour space 19"), and one veraPDF
1945        // corpus file uses it. `hayro-jpeg2000` does not implement it
1946        // and refuses during colour resolution, before any sample
1947        // exists — so pdfcer names the gap rather than reporting a
1948        // corrupt file (rule R27). See `jpx::map_error` for the
1949        // recorded divergence from §7.4.9's fallback ladder.
1950        //
1951        // Built by rewriting the RGB fixture's `colr` box from 16 (sRGB)
1952        // to 19: JP2 boxes are length-prefixed, so the edit is in place
1953        // and every other byte — including the codestream — stays valid.
1954        // The `colr` payload is METH u8, PREC u8, APPROX u8, then the
1955        // 4-byte enumerated value when METH is 1.
1956        let mut ciejab = fixtures_jpx::JPX_RGB_8_JP2.to_vec();
1957        let tag = ciejab
1958            .windows(4)
1959            .position(|w| w == b"colr")
1960            .expect("the fixture must carry a colr box");
1961        let at = tag + 4 + 3;
1962        let Some(slot) = ciejab.get_mut(at..at + 4) else {
1963            panic!("colr box is truncated");
1964        };
1965        assert_eq!(slot, &16u32.to_be_bytes(), "fixture should start as sRGB");
1966        slot.copy_from_slice(&19u32.to_be_bytes());
1967
1968        let dict = jpx_dict(vec![
1969            (b"Width", Object::Integer(4)),
1970            (b"Height", Object::Integer(2)),
1971        ]);
1972        assert_eq!(
1973            decode_fixture(&ciejab, &dict).unwrap_err(),
1974            ImageCodecError::FeatureUnsupported {
1975                feature: "JPX/enumerated-colour-space",
1976            }
1977        );
1978    }
1979
1980    // Needs the `jpx` codec compiled in; see the feature block in Cargo.toml.
1981    #[cfg(feature = "jpx")]
1982    #[test]
1983    fn jpx_refuses_a_geometry_past_the_pdfcer_ceiling_before_decoding() {
1984        // A SIZ marker claiming 60000 x 60000 (3.6 Gpx) is inside
1985        // `hayro-jpeg2000`'s own 60000-per-axis cap, which does not
1986        // bound the PRODUCT — so pdfcer's ceiling is the only thing
1987        // between a 40-byte header and a multi-gigabyte allocation
1988        // (rule R25), and it has to fire between `Image::new` (headers
1989        // only) and `Image::decode` (which allocates one f32 per sample
1990        // per component from exactly these numbers).
1991        //
1992        // Built by rewriting the *real* fixture's SIZ marker rather than
1993        // by hand-assembling a codestream: the rest of the main header
1994        // (COD, QCD) then stays valid, so the parse genuinely reaches
1995        // the dimension check instead of failing earlier for an
1996        // unrelated reason — which is how the first draft of this test
1997        // passed for the wrong cause.
1998        //
1999        // SIZ layout (T.800 A.5.1), byte offsets from SOC:
2000        //   0 SOC | 2 SIZ | 4 Lsiz | 6 Rsiz | 8 Xsiz | 12 Ysiz
2001        //   16 XOsiz | 20 YOsiz | 24 XTsiz | 28 YTsiz | ...
2002        // The tile size is enlarged alongside the image so the tile grid
2003        // stays 1 x 1 and the geometry remains self-consistent.
2004        let mut huge = fixtures_jpx::JPX_GRAY_8_J2K.to_vec();
2005        for offset in [8usize, 12, 24, 28] {
2006            let Some(slot) = huge.get_mut(offset..offset + 4) else {
2007                panic!("fixture is shorter than a SIZ marker segment");
2008            };
2009            slot.copy_from_slice(&60_000u32.to_be_bytes());
2010        }
2011        assert!(is_budget_refusal(
2012            &decode_fixture(&huge, &jpx_gray_dict()).unwrap_err()
2013        ));
2014        // The codec's own check, which a filter in front would leave as
2015        // the only one: a 3.6 Gpx codestream is refused before allocating.
2016        let doc = empty_document();
2017        let err = jpx::decode(
2018            &doc.view(),
2019            &huge,
2020            &jpx_gray_dict(),
2021            &peak::DecodeLimits::new(1 << 30),
2022            &mut CodecNotes::default(),
2023        )
2024        .unwrap_err();
2025        assert!(is_budget_refusal(&err), "{err:?}");
2026    }
2027
2028    // -----------------------------------------------------------------
2029    // CCITTFaxDecode (§7.4.6, Table 11) — Pass 2.2
2030    // -----------------------------------------------------------------
2031
2032    /// An image dictionary declaring `CCITTFaxDecode` over the 16 x 4
2033    /// fixture geometry, with the given `/DecodeParms` entries.
2034    fn ccitt_dict(parms: Vec<(&[u8], Object)>) -> Dict {
2035        dict_with(vec![
2036            (b"Filter", name(b"CCITTFaxDecode")),
2037            (b"Width", Object::Integer(16)),
2038            (b"Height", Object::Integer(4)),
2039            (b"BitsPerComponent", Object::Integer(1)),
2040            (b"DecodeParms", Object::Dict(dict_with(parms))),
2041        ])
2042    }
2043
2044    /// The three `K` cases, each with the fixture that matches it.
2045    fn ccitt_variants() -> [(&'static str, i64, &'static [u8]); 3] {
2046        [
2047            ("Group 4 (K < 0)", -1, fixtures_bilevel::CCITT_G4_16X4),
2048            ("Group 3 1-D (K = 0)", 0, fixtures_bilevel::CCITT_G3_1D_16X4),
2049            ("Group 3 2-D (K > 0)", 4, fixtures_bilevel::CCITT_G3_2D_16X4),
2050        ]
2051    }
2052
2053    #[test]
2054    fn every_k_variant_decodes_to_the_same_picture() {
2055        // The headline CCITT test. Three genuinely different bit
2056        // streams — 1-D run codes, 2-D mode codes, and the mixed form
2057        // with a per-line tag bit — must all produce the identical
2058        // sample bytes, because they encode the identical picture.
2059        for (label, k, data) in ccitt_variants() {
2060            let dict = ccitt_dict(vec![
2061                (b"K", Object::Integer(k)),
2062                (b"Columns", Object::Integer(16)),
2063                (b"Rows", Object::Integer(4)),
2064            ]);
2065            let img = decode_fixture(data, &dict).unwrap();
2066            assert_eq!(img.codec, Some(Codec::Ccitt), "{label}");
2067            assert_eq!((img.width, img.height), (16, 4), "{label}");
2068            assert_eq!(img.components, 1, "{label}");
2069            assert_eq!(img.bits_per_component, 1, "{label}");
2070            assert_eq!(img.color_model, CodecColorModel::Bilevel, "{label}");
2071            assert_eq!(
2072                img.samples,
2073                fixtures_bilevel::BILEVEL_16X4_SAMPLES,
2074                "{label}: samples must be PDF convention, 0 = black"
2075            );
2076            assert!(!img.notes.geometry_mismatch, "{label}");
2077        }
2078    }
2079
2080    #[test]
2081    fn ccitt_black_is_1_inverts_every_sample() {
2082        // Table 11: `/BlackIs1 true` means "1 bits shall be interpreted
2083        // as black pixels … the reverse of the normal PDF convention",
2084        // so the two decodes must be exact bitwise complements. This is
2085        // the polarity trap pinned from both sides: a decoder that wired
2086        // `invert_black` to `!BlackIs1` passes neither half.
2087        for (label, k, data) in ccitt_variants() {
2088            let dict = ccitt_dict(vec![
2089                (b"K", Object::Integer(k)),
2090                (b"Columns", Object::Integer(16)),
2091                (b"Rows", Object::Integer(4)),
2092                (b"BlackIs1", Object::Boolean(true)),
2093            ]);
2094            let img = decode_fixture(data, &dict).unwrap();
2095            assert_eq!(
2096                img.samples,
2097                fixtures_bilevel::BILEVEL_16X4_INK,
2098                "{label}: BlackIs1 true must emit 1 for black"
2099            );
2100            let complement: Vec<u8> = fixtures_bilevel::BILEVEL_16X4_SAMPLES
2101                .iter()
2102                .map(|b| !b)
2103                .collect();
2104            assert_eq!(img.samples, complement, "{label}");
2105        }
2106    }
2107
2108    #[test]
2109    fn ccitt_black_is_1_false_is_the_same_as_absent() {
2110        // The default is `false`, so stating it must change nothing.
2111        let with = ccitt_dict(vec![
2112            (b"K", Object::Integer(-1)),
2113            (b"Columns", Object::Integer(16)),
2114            (b"Rows", Object::Integer(4)),
2115            (b"BlackIs1", Object::Boolean(false)),
2116        ]);
2117        let without = ccitt_dict(vec![
2118            (b"K", Object::Integer(-1)),
2119            (b"Columns", Object::Integer(16)),
2120            (b"Rows", Object::Integer(4)),
2121        ]);
2122        let a = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &with).unwrap();
2123        let b = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &without).unwrap();
2124        assert_eq!(a.samples, b.samples);
2125    }
2126
2127    #[test]
2128    fn ccitt_positive_k_values_are_indistinguishable() {
2129        // Table 11: the filter "shall not distinguish between different
2130        // positive K values". 1, 4 and 40 must decode identically.
2131        let decode_with_k = |k: i64| {
2132            let dict = ccitt_dict(vec![
2133                (b"K", Object::Integer(k)),
2134                (b"Columns", Object::Integer(16)),
2135                (b"Rows", Object::Integer(4)),
2136            ]);
2137            decode_fixture(fixtures_bilevel::CCITT_G3_2D_16X4, &dict)
2138                .unwrap()
2139                .samples
2140        };
2141        assert_eq!(decode_with_k(1), decode_with_k(4));
2142        assert_eq!(decode_with_k(4), decode_with_k(40));
2143        assert_eq!(decode_with_k(4), fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2144    }
2145
2146    #[test]
2147    fn ccitt_rows_zero_falls_back_to_the_dictionary_height() {
2148        // Table 11: "If the value is 0 or absent, the image's height is
2149        // not predetermined". `hayro-ccitt` has no unknown-height mode —
2150        // passing 0 would decode ZERO rows — so the adapter must supply
2151        // the dictionary's `/Height` (decision 005 §1.2). Tested three
2152        // ways: absent, explicitly 0, and via the dictionary alone.
2153        for parms in [
2154            vec![
2155                (&b"K"[..], Object::Integer(-1)),
2156                (b"Columns", Object::Integer(16)),
2157            ],
2158            vec![
2159                (&b"K"[..], Object::Integer(-1)),
2160                (b"Columns", Object::Integer(16)),
2161                (b"Rows", Object::Integer(0)),
2162            ],
2163        ] {
2164            let img = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &ccitt_dict(parms)).unwrap();
2165            assert_eq!(img.height, 4, "the /Height fallback must supply the bound");
2166            assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2167        }
2168    }
2169
2170    #[test]
2171    fn ccitt_end_of_line_is_advisory_not_a_gate() {
2172        // Table 11: "The CCITTFaxDecode filter shall ALWAYS accept
2173        // end-of-line bit patterns." libtiff writes EOLs into the Group
2174        // 3 fixtures, so the same bytes must decode identically whether
2175        // the flag is absent, true, or false.
2176        let decode_with = |eol: Option<bool>| {
2177            let mut parms = vec![
2178                (&b"K"[..], Object::Integer(0)),
2179                (b"Columns", Object::Integer(16)),
2180                (b"Rows", Object::Integer(4)),
2181            ];
2182            if let Some(v) = eol {
2183                parms.push((b"EndOfLine", Object::Boolean(v)));
2184            }
2185            decode_fixture(fixtures_bilevel::CCITT_G3_1D_16X4, &ccitt_dict(parms))
2186                .unwrap()
2187                .samples
2188        };
2189        assert_eq!(decode_with(None), fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2190        assert_eq!(decode_with(Some(true)), decode_with(None));
2191        assert_eq!(decode_with(Some(false)), decode_with(None));
2192    }
2193
2194    #[test]
2195    fn ccitt_columns_defaults_to_1728_and_the_default_is_load_bearing() {
2196        // The verified Table 11 default is the ITU-T A4 scan width, NOT
2197        // the image's `/Width`. A 16-column stream decoded as 1728
2198        // columns cannot succeed — which is exactly the observable
2199        // consequence that proves the default is applied rather than
2200        // quietly replaced by `/Width`.
2201        let dict = dict_with(vec![
2202            (b"Filter", name(b"CCITTFaxDecode")),
2203            (b"Width", Object::Integer(16)),
2204            (b"Height", Object::Integer(4)),
2205            (b"DecodeParms", Object::Dict(dict_with(vec![]))),
2206        ]);
2207        assert!(matches!(
2208            decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict),
2209            Err(ImageCodecError::Corrupt { .. })
2210        ));
2211    }
2212
2213    #[test]
2214    fn ccitt_geometry_disagreement_is_counted() {
2215        // `/Columns` and `/Width` disagreeing is the most common
2216        // real-world fax defect, and it shears rather than fails.
2217        let mut dict = ccitt_dict(vec![
2218            (b"K", Object::Integer(-1)),
2219            (b"Columns", Object::Integer(16)),
2220            (b"Rows", Object::Integer(4)),
2221        ]);
2222        dict.insert(Name::from(b"Width"), Object::Integer(24));
2223        let img = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict).unwrap();
2224        assert_eq!(img.width, 16, "the filter's /Columns governs the samples");
2225        assert!(img.notes.geometry_mismatch);
2226    }
2227
2228    #[test]
2229    fn ccitt_refuses_declared_rows_past_the_budget() {
2230        // Rule R25: the declared geometry is checked against the budget
2231        // before a byte is decoded. The peak prediction reads the filter's
2232        // /Columns and /Rows, so it refuses ahead of the codec.
2233        let dict = ccitt_dict(vec![
2234            (b"K", Object::Integer(-1)),
2235            (b"Columns", Object::Integer(65535)),
2236            (b"Rows", Object::Integer(65535)),
2237        ]);
2238        // Padded so the 65535 rows have the 8192 bytes evidence asks for
2239        // and the 512 MiB packed page is what refuses them.
2240        let mut padded = fixtures_bilevel::CCITT_G4_16X4.to_vec();
2241        padded.resize(8192, 0);
2242        let options = DecodeOptions::default().with_limits(peak::DecodeLimits::new(1 << 28));
2243        let err = decode_image_view_with(&empty_document().view(), &dict, &padded, false, options)
2244            .unwrap_err();
2245        let ImageCodecError::LimitExceeded {
2246            limit: SizeLimit::MemoryBudget,
2247            needed,
2248            allowed: 268_435_456,
2249        } = err
2250        else {
2251            panic!("expected a memory-budget refusal, got {err:?}");
2252        };
2253        assert!(needed >= 8192 * 65535, "{needed}");
2254        // No width cap remains: a 70,000-column row is not a limit refusal.
2255        let wide = ccitt_dict(vec![
2256            (b"K", Object::Integer(-1)),
2257            (b"Columns", Object::Integer(70000)),
2258            (b"Rows", Object::Integer(1)),
2259        ]);
2260        let wide = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &wide);
2261        assert!(
2262            !matches!(wide, Err(ImageCodecError::LimitExceeded { .. })),
2263            "{wide:?}"
2264        );
2265    }
2266
2267    #[test]
2268    fn ccitt_nonsensical_columns_is_refused_not_defaulted() {
2269        // A zero or negative `/Columns` is malformed. Silently falling
2270        // back to 1728 would decode a *different image* from the one the
2271        // file describes, which is the "plausible garbage" the
2272        // fail-clean contract forbids.
2273        for bad in [Object::Integer(0), Object::Integer(-16)] {
2274            let dict = ccitt_dict(vec![(b"K", Object::Integer(-1)), (b"Columns", bad)]);
2275            assert!(matches!(
2276                decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict),
2277                Err(ImageCodecError::Corrupt { .. })
2278            ));
2279        }
2280    }
2281
2282    #[test]
2283    fn ccitt_corrupt_data_errs_and_never_returns_a_short_page() {
2284        // Fail-clean at the codec layer. `hayro-ccitt` documents that
2285        // some rows may already have been written when it errors; pdfcer
2286        // deliberately discards them rather than hand back a silently
2287        // truncated fax page.
2288        let dict = ccitt_dict(vec![
2289            (b"K", Object::Integer(-1)),
2290            (b"Columns", Object::Integer(16)),
2291            (b"Rows", Object::Integer(4)),
2292        ]);
2293        let mut truncated = fixtures_bilevel::CCITT_G4_16X4.to_vec();
2294        truncated.truncate(3);
2295        assert!(matches!(
2296            decode_fixture(&truncated, &dict),
2297            Err(ImageCodecError::Corrupt { .. })
2298        ));
2299        assert!(matches!(
2300            decode_fixture(&[0x00; 32], &dict),
2301            Err(ImageCodecError::Corrupt { .. })
2302        ));
2303        // NOTE, deliberately recorded rather than asserted away: T.4/T.6
2304        // carry no checksum and no framing beyond EOL/EOFB, so plenty of
2305        // arbitrary bytes ARE valid code sequences. `[0xFF; 32]` is a run
2306        // of V(0) vertical-mode codes and decodes to a real (if
2307        // meaningless) picture. "Fail-clean" means pdfcer never *invents*
2308        // samples; it cannot mean pdfcer detects a codec's own
2309        // undetectable garbage.
2310        let _ = decode_fixture(&[0xFF; 32], &dict);
2311    }
2312
2313    #[test]
2314    fn ccf_is_a_legal_inline_abbreviation() {
2315        // Table 94 gives `CCF` for CCITTFaxDecode; unlike JBIG2 and JPX,
2316        // it is permitted inline.
2317        let doc = empty_document();
2318        let mut dict = ccitt_dict(vec![
2319            (b"K", Object::Integer(-1)),
2320            (b"Columns", Object::Integer(16)),
2321            (b"Rows", Object::Integer(4)),
2322        ]);
2323        dict.insert(Name::from(b"Filter"), name(b"CCF"));
2324        let img = decode_image(&doc, &dict, fixtures_bilevel::CCITT_G4_16X4, true).unwrap();
2325        assert_eq!(img.codec, Some(Codec::Ccitt));
2326        assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2327    }
2328
2329    // -----------------------------------------------------------------
2330    // JBIG2Decode (§7.4.7, Table 12) — Pass 2.2
2331    // -----------------------------------------------------------------
2332
2333    /// An image dictionary declaring `JBIG2Decode` over the fixture
2334    /// geometry, with the given `/DecodeParms` entries.
2335    fn jbig2_dict(parms: Vec<(&[u8], Object)>) -> Dict {
2336        dict_with(vec![
2337            (b"Filter", name(b"JBIG2Decode")),
2338            (b"Width", Object::Integer(16)),
2339            (b"Height", Object::Integer(4)),
2340            (b"BitsPerComponent", Object::Integer(1)),
2341            (b"DecodeParms", Object::Dict(dict_with(parms))),
2342        ])
2343    }
2344
2345    /// A document whose object 3 is an unfiltered stream holding
2346    /// `globals` — the shape `/JBIG2Globals` points at.
2347    fn document_with_globals(globals: &[u8]) -> Document {
2348        let mut buf = b"%PDF-1.7\n".to_vec();
2349        let mut offsets = Vec::new();
2350        for (num, body) in [
2351            (1u32, "<< /Type /Catalog /Pages 2 0 R >>".to_owned()),
2352            (2, "<< /Type /Pages /Kids [] /Count 0 >>".to_owned()),
2353        ] {
2354            offsets.push(buf.len());
2355            buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
2356        }
2357        offsets.push(buf.len());
2358        buf.extend_from_slice(
2359            format!("3 0 obj\n<< /Length {} >>\nstream\n", globals.len()).as_bytes(),
2360        );
2361        buf.extend_from_slice(globals);
2362        buf.extend_from_slice(b"\nendstream\nendobj\n");
2363        let xref_at = buf.len();
2364        buf.extend_from_slice(b"xref\n0 4\n0000000000 65535 f\r\n");
2365        for off in offsets {
2366            buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
2367        }
2368        buf.extend_from_slice(
2369            format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
2370        );
2371        Document::from_bytes(buf).unwrap()
2372    }
2373
2374    #[test]
2375    fn jbig2_decodes_to_the_same_samples_as_ccitt() {
2376        // The cross-codec assertion. T.88 §6.2.6 fixes MMR black at
2377        // bitmap value 1; PDF's convention is the opposite and JBIG2 has
2378        // no polarity parameter to say so, so the adapter's inversion is
2379        // unconditional. Two completely different routes, one answer.
2380        let dict = jbig2_dict(vec![]);
2381        let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
2382        assert_eq!(img.codec, Some(Codec::Jbig2));
2383        assert_eq!((img.width, img.height), (16, 4));
2384        assert_eq!(img.components, 1);
2385        assert_eq!(img.bits_per_component, 1);
2386        assert_eq!(img.color_model, CodecColorModel::Bilevel);
2387        assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2388        assert!(!img.notes.geometry_mismatch);
2389    }
2390
2391    #[test]
2392    fn jbig2_globals_are_resolved_through_the_document() {
2393        // Table 12's `/JBIG2Globals`: a stream REFERENCE, which is one
2394        // of the two mechanical reasons the codec layer takes a
2395        // `&Document` at all (decision 005 §1.2). Split the very same
2396        // stream in two — page information in the globals, region in the
2397        // image — and it must still decode to the same picture.
2398        let doc = document_with_globals(fixtures_bilevel::JBIG2_MMR_16X4_GLOBALS);
2399        let dict = jbig2_dict(vec![(
2400            b"JBIG2Globals",
2401            Object::Reference(pdfcer_model::object::ObjId::new(3, 0)),
2402        )]);
2403        let img = decode_image(&doc, &dict, fixtures_bilevel::JBIG2_MMR_16X4_PAGE, false).unwrap();
2404        assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2405    }
2406
2407    #[test]
2408    fn jbig2_without_its_globals_fails_cleanly() {
2409        // The other half of the pair: the region segment alone carries
2410        // no page information, so a decoder that silently ignored
2411        // `/JBIG2Globals` would fail here rather than draw something
2412        // wrong. That is what makes the previous test meaningful.
2413        let dict = jbig2_dict(vec![]);
2414        assert!(matches!(
2415            decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4_PAGE, &dict),
2416            Err(ImageCodecError::Corrupt { .. })
2417        ));
2418    }
2419
2420    #[test]
2421    fn jbig2_globals_that_are_not_a_stream_are_treated_as_absent() {
2422        // A stray non-stream `/JBIG2Globals` carries no segments, so it
2423        // is ignored rather than turned into a blank page. The image
2424        // that needs no globals still decodes.
2425        let dict = jbig2_dict(vec![(b"JBIG2Globals", Object::Integer(7))]);
2426        let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
2427        assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
2428    }
2429
2430    #[test]
2431    fn jbig2_geometry_comes_from_the_page_information_segment() {
2432        // Unlike CCITT, JBIG2 carries its own geometry, so a dictionary
2433        // that disagrees is Table 89's "entries inconsistent with each
2434        // other" — counted, never acted on.
2435        let mut dict = jbig2_dict(vec![]);
2436        dict.insert(Name::from(b"Height"), Object::Integer(9));
2437        let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
2438        assert_eq!(img.height, 4, "the page information segment governs");
2439        assert!(img.notes.geometry_mismatch);
2440    }
2441
2442    #[test]
2443    fn jbig2_page_association_other_than_1_still_decodes() {
2444        // §7.4.7 says an embedded stream's segments SHOULD carry page
2445        // association 1; the decoder does not read the field, so any other
2446        // value decodes the same picture rather than a blank page. Pinned
2447        // because a decoder that filtered on page 1 would pass every other
2448        // test here and blank these files.
2449        let dict = jbig2_dict(vec![]);
2450        for page in [0u8, 2, 7] {
2451            let mut data = fixtures_bilevel::JBIG2_MMR_16X4.to_vec();
2452            // The one-byte page-association field of each segment header
2453            // (T.88 §7.2.6): segment 0 at offset 6, segment 1 at 30 + 6.
2454            assert_eq!((data[6], data[36]), (1, 1));
2455            data[6] = page;
2456            data[36] = page;
2457            let img = decode_fixture(&data, &dict).unwrap();
2458            assert_eq!(
2459                img.samples,
2460                fixtures_bilevel::BILEVEL_16X4_SAMPLES,
2461                "page {page}"
2462            );
2463        }
2464    }
2465
2466    /// `JBIG2_MMR_16X4` wrapped in a T.88 file header (D.4) with `flags`,
2467    /// segments laid out as `flags` bit 0 says: sequential keeps each
2468    /// header beside its data, random-access puts both headers first.
2469    fn jbig2_file(flags: u8) -> Vec<u8> {
2470        let seg = fixtures_bilevel::JBIG2_MMR_16X4;
2471        let mut out = vec![0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A, flags];
2472        if flags & 0x02 == 0 {
2473            out.extend_from_slice(&1u32.to_be_bytes());
2474        }
2475        if flags & 0x01 != 0 {
2476            out.extend_from_slice(seg);
2477        } else {
2478            // Segment 0: header 0..11, data 11..30; segment 1: header
2479            // 30..41, data 41..80. The header list ends at an end-of-file
2480            // segment (type 51, T.88 §7.4.11), the only thing marking where
2481            // the data part begins.
2482            for range in [0..11, 30..41] {
2483                out.extend_from_slice(&seg[range]);
2484            }
2485            out.extend_from_slice(&[0, 0, 0, 2, 0x33, 0x00, 0x01, 0, 0, 0, 0]);
2486            for range in [11..30, 41..80] {
2487                out.extend_from_slice(&seg[range]);
2488            }
2489        }
2490        out
2491    }
2492
2493    #[test]
2494    fn jbig2_with_a_file_header_decodes_in_either_organisation() {
2495        let dict = jbig2_dict(vec![]);
2496        for flags in [0x01, 0x03, 0x00, 0x02] {
2497            let img = decode_fixture(&jbig2_file(flags), &dict).unwrap();
2498            assert_eq!(
2499                img.samples,
2500                fixtures_bilevel::BILEVEL_16X4_SAMPLES,
2501                "flags {flags:#04x}"
2502            );
2503        }
2504    }
2505
2506    #[test]
2507    fn jbig2_file_header_with_globals_is_refused() {
2508        let doc = document_with_globals(fixtures_bilevel::JBIG2_MMR_16X4_GLOBALS);
2509        let dict = jbig2_dict(vec![(
2510            b"JBIG2Globals",
2511            Object::Reference(pdfcer_model::object::ObjId::new(3, 0)),
2512        )]);
2513        let err = decode_image(&doc, &dict, &jbig2_file(0x01), false).unwrap_err();
2514        assert!(
2515            matches!(&err, ImageCodecError::Corrupt { detail, .. } if detail.contains("file header")),
2516            "{err:?}"
2517        );
2518    }
2519
2520    #[test]
2521    fn jbig2_corrupt_segments_err() {
2522        let dict = jbig2_dict(vec![]);
2523        for bad in [&b""[..], b"not jbig2 at all", &[0xFF; 40]] {
2524            assert!(
2525                matches!(
2526                    decode_fixture(bad, &dict),
2527                    Err(ImageCodecError::Corrupt { .. })
2528                ),
2529                "{bad:?}"
2530            );
2531        }
2532        let mut truncated = fixtures_bilevel::JBIG2_MMR_16X4.to_vec();
2533        truncated.truncate(truncated.len() - 4);
2534        assert!(matches!(
2535            decode_fixture(&truncated, &dict),
2536            Err(ImageCodecError::Corrupt { .. })
2537        ));
2538    }
2539
2540    #[test]
2541    fn inline_images_reject_jbig2_and_jpx_but_allow_dct() {
2542        // §7.4.7 / §8.9.7. Checked before any bytes are touched.
2543        let doc = empty_document();
2544        for (spelling, codec) in [
2545            (&b"JBIG2Decode"[..], Codec::Jbig2),
2546            (b"JPXDecode", Codec::Jpx),
2547            (b"JXLDecode", Codec::Jxl),
2548        ] {
2549            let dict = dict_with(vec![(b"Filter", name(spelling))]);
2550            assert_eq!(
2551                decode_image(&doc, &dict, b"anything", true).unwrap_err(),
2552                ImageCodecError::NotAllowedInline { codec }
2553            );
2554        }
2555        // `DCT` is a legal inline abbreviation (Table 94).
2556        let mut inline = dct_dict(2, 2);
2557        inline.insert(Name::from(b"Filter"), name(b"DCT"));
2558        let img = decode_image(&doc, &inline, fixtures::RGB_2X2, true).unwrap();
2559        assert_eq!(img.codec, Some(Codec::Dct));
2560    }
2561
2562    #[test]
2563    fn a_codec_that_is_not_the_last_filter_is_refused() {
2564        // Nothing can be chained after a codec: it consumes a
2565        // codestream and produces samples, not bytes.
2566        let dict = dict_with(vec![(
2567            b"Filter",
2568            Object::Array(vec![name(b"DCTDecode"), name(b"FlateDecode")]),
2569        )]);
2570        assert_eq!(
2571            decode_fixture(fixtures::RGB_2X2, &dict).unwrap_err(),
2572            ImageCodecError::CodecNotTerminal
2573        );
2574    }
2575
2576    #[test]
2577    fn lzw_framing_anomalies_survive_into_the_codec_notes() {
2578        // An LZW-armoured image whose stream lacks a ClearCode still
2579        // decodes, and the anomaly reaches the renderer's diagnostics
2580        // through `CodedImage::notes` rather than being swallowed at the
2581        // filter boundary.
2582        let dict = dict_with(vec![
2583            (b"Filter", name(b"LZWDecode")),
2584            (b"Width", Object::Integer(1)),
2585            (b"Height", Object::Integer(1)),
2586        ]);
2587        let img = decode_fixture(&[0x20, 0xC0, 0x40], &dict).unwrap();
2588        assert_eq!(img.samples, b"A");
2589        assert_eq!(img.notes.lzw_framing_anomalies, 1);
2590    }
2591
2592    #[test]
2593    fn codec_parms_follows_table_5_positions() {
2594        let parms = dict_with(vec![(b"ColorTransform", Object::Integer(0))]);
2595        // Single filter → a lone dictionary applies to it.
2596        let single = dict_with(vec![
2597            (b"Filter", name(b"DCTDecode")),
2598            (b"DecodeParms", Object::Dict(parms.clone())),
2599        ]);
2600        assert!(codec_parms(&single, 1).is_some());
2601        // Two filters → the array position of the LAST one.
2602        let chained = dict_with(vec![
2603            (
2604                b"Filter",
2605                Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
2606            ),
2607            (
2608                b"DecodeParms",
2609                Object::Array(vec![Object::Null, Object::Dict(parms)]),
2610            ),
2611        ]);
2612        assert!(codec_parms(&chained, 2).is_some());
2613        assert!(codec_parms(&chained, 1).is_none());
2614    }
2615
2616    // -----------------------------------------------------------------
2617    // A JP2 palette and a PDF `/Indexed` space are the SAME lookup
2618    // -----------------------------------------------------------------
2619
2620    /// The one entry both tables would hold in a file built to catch the
2621    /// double-resolution bug. Arbitrary, but distinctive: no component is 0
2622    /// or 255, so an off-by-one or a dropped channel is visible in the
2623    /// assertion rather than coincidentally right.
2624    /// What palette entry `i` resolves to in
2625    /// [`fixtures_jpx::jpx_gray_8_jp2_with_palette`]. The constant `13` is a
2626    /// fingerprint: a resolved sample whose blue is not 13 did not come from
2627    /// the palette.
2628    #[cfg(feature = "jpx")]
2629    fn palette_entry(i: u8) -> [u8; 3] {
2630        [i, 255 - i, 13]
2631    }
2632
2633    /// WITHOUT a PDF `/Indexed` space, the palette is left to the codec and
2634    /// the disclosure flag stays clear.
2635    ///
2636    /// # What this asserts, and what it deliberately does not
2637    ///
2638    /// It pins the **decision**, not the decoder: that the flag follows the
2639    /// dictionary, and that a palette-bearing file still decodes. It does
2640    /// NOT assert a resolved component count.
2641    ///
2642    /// That restraint is deliberate and was arrived at by measurement. The
2643    /// first draft asserted "1 channel in, 3 out" — reasoned from the `cmap`
2644    /// box's three entries — and this fixture returns **1**. The behaviour is
2645    /// pre-existing and untouched by the change under test, so asserting a
2646    /// number derived from reasoning rather than from a measured run would
2647    /// pin an expectation, not a fact, and the next person would have to
2648    /// discover which it was.
2649    ///
2650    /// Whether a synthetic `pclr`/`cmap` pair drives the decoder's expansion
2651    /// identically to a real encoder's output is **unestablished**, and it is
2652    /// not what this Pass changed. The paired test below carries the claim
2653    /// that matters.
2654    #[cfg(feature = "jpx")]
2655    #[test]
2656    fn a_jp2_palette_is_left_to_the_codec_when_the_pdf_offers_no_indexed_space() {
2657        let jp2 = fixtures_jpx::jpx_gray_8_jp2_with_palette();
2658        let img = decode_fixture(&jp2, &jpx_gray_dict()).unwrap();
2659
2660        assert!(
2661            !img.notes.jpx_palette_left_to_pdf,
2662            "with no /Indexed space in the dictionary, the codec keeps the palette"
2663        );
2664        assert!(!img.samples.is_empty(), "the file still decodes");
2665    }
2666
2667    /// WITH a PDF `/Indexed` space, the palette is LEFT ALONE and the
2668    /// samples stay indices — because applying both tables is the only way
2669    /// to be wrong.
2670    ///
2671    /// ISO 32000-1 §8.9 Table 89: with `JPXDecode`, if `/ColorSpace` is
2672    /// present then "colour space specifications in the JPEG2000 data shall
2673    /// be ignored". A `pclr`/`cmap` pair is such a specification.
2674    ///
2675    /// The failure this pins is invisible in any counter. Resolve here and
2676    /// the samples become `114, 247, 13`; the renderer then reads component
2677    /// 0 as an index, asks a one-entry table for entry **114**, finds
2678    /// nothing, and paints **black**. Nothing reports an error — the picture
2679    /// is simply the wrong colour.
2680    #[cfg(feature = "jpx")]
2681    #[test]
2682    fn a_jp2_palette_is_left_to_the_pdf_when_the_dictionary_carries_indexed() {
2683        let jp2 = fixtures_jpx::jpx_gray_8_jp2_with_palette();
2684        let mut dict = jpx_gray_dict();
2685        // `[/Indexed /DeviceRGB 0 <lookup>]` — the shape a real file uses,
2686        // with hival 0 and a table holding the SAME bytes as the JP2's.
2687        dict.insert(
2688            Name::from(b"ColorSpace"),
2689            Object::Array(vec![
2690                Object::Name(Name::from(b"Indexed")),
2691                Object::Name(Name::from(b"DeviceRGB")),
2692                Object::Integer(0),
2693                Object::String(palette_entry(0).to_vec()),
2694            ]),
2695        );
2696
2697        let img = decode_fixture(&jp2, &dict).unwrap();
2698
2699        assert_eq!(
2700            img.components, 1,
2701            "the samples must remain a single INDEX channel"
2702        );
2703        assert!(
2704            img.notes.jpx_palette_left_to_pdf,
2705            "and the decision must be disclosed -- it is invisible in the output"
2706        );
2707        assert_eq!(
2708            &img.samples[..8],
2709            &fixtures_jpx::JPX_GRAY_8_SAMPLES[..8],
2710            "indices pass through untouched, identical to the palette-free fixture"
2711        );
2712        let first = fixtures_jpx::JPX_GRAY_8_SAMPLES[0];
2713        assert_ne!(
2714            &img.samples[..3],
2715            &palette_entry(first),
2716            "if these matched, the palette had been applied after all and the \
2717             renderer would apply it a SECOND time"
2718        );
2719    }
2720
2721    /// The decision point itself, as a truth table.
2722    ///
2723    /// Guards the one case the codec deliberately cannot see: a
2724    /// `/ColorSpace` written as a NAME resolves through the page's resource
2725    /// dictionary, which this layer does not have. It answers `false` and
2726    /// keeps the old behaviour rather than guessing — a named limit, not an
2727    /// oversight.
2728    #[cfg(feature = "jpx")]
2729    #[test]
2730    fn only_a_visible_indexed_array_suppresses_palette_resolution() {
2731        let doc = empty_document();
2732        let with = |cs: Option<Object>| {
2733            let mut d = Dict::new();
2734            if let Some(cs) = cs {
2735                d.insert(Name::from(b"ColorSpace"), cs);
2736            }
2737            super::jpx::dict_colorspace_is_indexed(&doc.view(), &d)
2738        };
2739        let arr = |first: &[u8]| {
2740            Object::Array(vec![
2741                Object::Name(Name::from(first)),
2742                Object::Name(Name::from(b"DeviceRGB")),
2743            ])
2744        };
2745
2746        assert!(with(Some(arr(b"Indexed"))), "the array form is decidable");
2747        assert!(!with(Some(arr(b"ICCBased"))));
2748        assert!(!with(Some(Object::Name(Name::from(b"DeviceRGB")))));
2749        assert!(
2750            !with(Some(Object::Name(Name::from(b"CS0")))),
2751            "a NAMED resource is not visible from the codec layer; answering \
2752             `false` keeps the pre-existing behaviour instead of guessing"
2753        );
2754        assert!(!with(None), "no /ColorSpace at all");
2755    }
2756
2757    #[cfg(feature = "jxl")]
2758    fn jxl_dict(w: i64, h: i64, extra: Vec<(&[u8], Object)>) -> Dict {
2759        let mut all: Vec<(&[u8], Object)> = vec![
2760            (b"Filter", name(b"JXLDecode")),
2761            (b"Width", Object::Integer(w)),
2762            (b"Height", Object::Integer(h)),
2763        ];
2764        all.extend(extra);
2765        dict_with(all)
2766    }
2767
2768    #[cfg(feature = "jxl")]
2769    #[test]
2770    fn jxl_bare_and_boxed_gray_decode_to_the_same_samples() {
2771        let dict = jxl_dict(4, 2, vec![]);
2772        let bare = decode_fixture(fixtures_jxl::JXL_GRAY_4X2, &dict).unwrap();
2773        let boxed = decode_fixture(fixtures_jxl::JXL_GRAY_4X2_BOXED, &dict).unwrap();
2774        assert_eq!(bare.codec, Some(Codec::Jxl));
2775        assert_eq!((bare.width, bare.height, bare.components), (4, 2, 1));
2776        assert_eq!(bare.color_model, CodecColorModel::Gray);
2777        assert_eq!(bare.samples, fixtures_jxl::JXL_GRAY_4X2_SAMPLES);
2778        assert_eq!(boxed.samples, bare.samples);
2779        assert!(bare.notes.jxl_nonstandard);
2780        assert!(!bare.notes.geometry_mismatch);
2781        assert!(bare.icc_profile.as_ref().is_some_and(|p| !p.is_empty()));
2782        assert_eq!(bare.embedded_alpha, None);
2783    }
2784
2785    #[cfg(feature = "jxl")]
2786    #[test]
2787    fn jxl_rgb_interleaves_in_order_and_counts_a_geometry_disagreement() {
2788        let img = decode_fixture(fixtures_jxl::JXL_RGB_2X2, &jxl_dict(2, 2, vec![])).unwrap();
2789        assert_eq!(img.color_model, CodecColorModel::Rgb);
2790        assert_eq!(img.samples, fixtures_jxl::JXL_RGB_2X2_SAMPLES);
2791        let wrong = decode_fixture(fixtures_jxl::JXL_RGB_2X2, &jxl_dict(3, 2, vec![])).unwrap();
2792        assert!(wrong.notes.geometry_mismatch);
2793        assert_eq!(wrong.width, 2, "the codestream's geometry wins");
2794    }
2795
2796    #[cfg(feature = "jxl")]
2797    #[test]
2798    fn jxl_alpha_follows_smaskindata_then_a_dictionary_smask() {
2799        let rgba = fixtures_jxl::JXL_RGBA_2X2_SAMPLES;
2800        let colour: Vec<u8> = rgba.chunks(4).flat_map(|p| p[..3].to_vec()).collect();
2801        let alpha: Vec<u8> = rgba.chunks(4).map(|p| p[3]).collect();
2802        let decode =
2803            |extra| decode_fixture(fixtures_jxl::JXL_RGBA_2X2, &jxl_dict(2, 2, extra)).unwrap();
2804        let absent = decode(vec![]);
2805        assert_eq!(absent.samples, colour);
2806        assert_eq!(absent.embedded_alpha.as_deref(), Some(&alpha[..]));
2807        assert_eq!(
2808            decode(vec![(b"SMaskInData", Object::Integer(0))]).embedded_alpha,
2809            None
2810        );
2811        let smask = vec![(
2812            &b"SMask"[..],
2813            Object::Reference(pdfcer_model::object::ObjId::new(9, 0)),
2814        )];
2815        assert_eq!(
2816            decode(smask).embedded_alpha,
2817            None,
2818            "the dictionary's /SMask wins"
2819        );
2820        let forced = vec![
2821            (
2822                &b"SMask"[..],
2823                Object::Reference(pdfcer_model::object::ObjId::new(9, 0)),
2824            ),
2825            (&b"SMaskInData"[..], Object::Integer(1)),
2826        ];
2827        assert!(decode(forced).embedded_alpha.is_some());
2828    }
2829
2830    #[cfg(feature = "jxl")]
2831    #[test]
2832    fn jxl_garbage_is_a_codec_error_with_the_note_set() {
2833        let err = decode_fixture(b"\xFF\x0Anot really", &jxl_dict(1, 1, vec![])).unwrap_err();
2834        assert!(
2835            matches!(
2836                err,
2837                ImageCodecError::Corrupt {
2838                    codec: Codec::Jxl,
2839                    ..
2840                }
2841            ),
2842            "{err:?}"
2843        );
2844    }
2845}