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