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