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