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