1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//! # JBIG2Decode (ISO 32000-1 §7.4.7, Table 12; ITU-T T.88) — the JBIG2 adapter
//!
//! Spec source: `filters/filter__jbig2.md` in the PDF-spec RAG. ISO
//! 32000-1 §7.4.7 defines only the **PDF embedding** — the
//! `/JBIG2Globals` parameter and the stream framing — and delegates the
//! codec itself to ITU-T T.88 (published identically as ISO/IEC 14492;
//! §7.4.7's own reference to "ISO/IEC 11544" is a defect in the source
//! text, verified against T.88 p. 3 and recorded in the RAG — do not
//! "correct" it back).
//!
//! Crate choice is decision 005 §4.4: **`hayro-jbig2`**. The alternatives
//! were all GPL-3.0 C FFI bindings to Artifex's `jbig2dec`, untouched
//! since 2020 — disqualified three times over (copyleft against
//! `LEGAL.md` §1, C FFI against the wasm32/portable
//! invariants, abandonment against `ARCHITECTURE.md` §10). `hayro-jbig2`
//! removes the question rather than posing it, and it is the reason no
//! `LEGAL.md` §6.2 escalation was needed for this Pass.
//!
//! **Amended 2026-08-07**: this said "an *undecided* `LEGAL.md` §1". The
//! licence was decided **MIT** on 2026-08-01, which makes the copyleft
//! disqualification **stronger, not weaker** — an MIT project cannot
//! link GPL-3.0 at all (`LEGAL.md` §6.1), so what was a risk pending a
//! decision is now a categorical bar. The choice made here needs no
//! revisiting; only its stated reason was out of date.
//!
//! ## `/JBIG2Globals` is why this codec needs `&Document`
//!
//! Table 12's single parameter is a **stream reference**: the JBIG2
//! global (page-0) segments — typically a symbol dictionary. Table 12's
//! second sentence makes the placement a `shall` keyed on **segment page
//! association == 0**, "even if only a single JBIG2 image XObject refers
//! to it" — sharing across images is a separate *permissive* statement
//! (§7.4.7 bullet 4), not what selects a segment into this stream.
//! Resolving the reference needs the document, which is one of the
//! two mechanical reasons decision 005 §1.2 gave for the two-tier filter
//! architecture — `(dict, raw)` cannot reach it.
//!
//! `hayro-jbig2`'s `Image::new_embedded(data, globals)` takes the globals
//! as a separate byte slice, which *is* the PDF embedding shape
//! (T.88 Annex D.3, the "embedded stream" organization with no file
//! header and no end-of-file segment). Decision 005 §3.5 records that no
//! general-purpose JBIG2 decoder exposes that split, and it is the
//! single largest reason this crate fits without glue.
//!
//! The globals stream is itself a PDF stream and is very often
//! `FlateDecode`d, so it goes through [`pdfcer_model::filters::decode_stream`]
//! before reaching the decoder. An **absent** `/JBIG2Globals` is normal
//! and not an error: an image whose segments are all inline needs none.
//!
//! ## Forbidden in inline images
//!
//! §7.4.7, verbatim: "the JBIG2Decode filter shall not be used with
//! inline images." §8.9.7 says the same from the other side —
//! `JBIG2Decode` and `JPXDecode` are absent from Table 94's
//! abbreviation list "because those filters shall not be used with
//! inline images." That rule is enforced *before* any bytes are touched,
//! in [`super::decode_image`] via [`super::Codec::allowed_inline`], so
//! this module is never reached from the inline path at all.
//!
//! ## Polarity: T.88 says 1 is black, PDF says 0 is black
//!
//! A JBIG2 bitmap stores `1` for a black pixel — the convention T.88
//! §6.2.6 states explicitly for the MMR path ("pixels decoded by the MMR
//! decoder having the value 'black' shall be treated as having the value
//! 1") and uses throughout. `hayro-jbig2` surfaces it faithfully: its
//! sink's flag is named `black`.
//!
//! PDF's convention for bilevel image data is the opposite, and §7.4.6
//! Table 11 is where the spec says so out loud, in `BlackIs1`'s
//! description: 1-means-black is "the reverse of the normal PDF
//! convention for image data". With the DeviceGray default
//! `Decode [0 1]` at 1 bit per component, sample 0 → grey 0.0 → black.
//!
//! Unlike CCITT, JBIG2Decode has **no polarity parameter** — Table 12
//! carries `/JBIG2Globals` and nothing else — so the inversion is
//! unconditional and belongs here, not to the file. This module
//! therefore pushes `!black` into `BilevelSink`, whose contract is
//! "true writes a 1 bit (white)". Every other shipping PDF engine does
//! the identical flip at the identical place.
//!
//! ## Resource ceilings are pdfcer's (rule R25)
//!
//! `Image::new_embedded` parses segment headers only — bounded by the
//! input length — and reports the page geometry through `width()` and
//! `height()` **before** anything is decoded. `decode()` then allocates
//! the full page bitmap from that geometry. So the budget check has
//! exactly one correct place, between those two calls: the packed page
//! against the memory budget. A page information segment claiming
//! 65535 × 65535 (512 MiB packed) is refused there under a smaller
//! budget rather than after the allocation.
//!
use Image;
use BilevelSink;
use ;
// decision 018: the codecs resolve indirect entries through a `DocumentView`
// rather than a `&Document`, so an image whose dictionary lives in an
// editing session decodes as the operator currently has it. `Document` is
// still named by the back-compat `decode_image` wrapper in `mod.rs`.
use filters;
use ObjectGraph;
use ;
use DocumentView;
pub use encode_generic;
/// Widest or tallest bitmap `hayro-jbig2` 0.3 will build (its
/// `bitmap::MAX_DIMENSION`, `u16::MAX`). T.88's page fields are 32-bit,
/// so this is the decoder's fact, not the format's; named here so a
/// larger page is refused as a limit rather than as corrupt data.
const MAX_BITMAP_SIDE: u32 = 65_535;
/// Decode a `JBIG2Decode` codestream.
///
/// `data` is the embedded JBIG2 stream (T.88 Annex D.3 organization)
/// after any byte-stream filter prefix, or a whole T.88 file (Annex D.1
/// or D.2, recognised by its header) that a producer embedded instead; `parms` is the codec's own
/// `/DecodeParms` entry, consulted for `/JBIG2Globals`; `dict` is the
/// image dictionary, used only for geometry reconciliation; `notes`
/// accumulates the honesty counters.
///
/// # Errors
///
/// [`ImageCodecError::LimitExceeded`] when the packed page crosses
/// `limits.memory_budget`; [`ImageCodecError::Corrupt`] when the globals stream cannot
/// be decoded, when the segment stream is malformed, or when decoding
/// fails. `hayro-jbig2` returns a structured error for every failure
/// mode, so the mapping is total and nothing here can panic.
pub
/// Refuse a page side `hayro-jbig2` cannot hold, then a packed page past
/// the memory budget.
/// Resolve and decode `/JBIG2Globals` (Table 12), if present.
///
/// The entry is "a stream containing the JBIG2 global (page 0)
/// segments", required there by Table 12 "even if only a single JBIG2
/// image XObject refers to it" (page-0 association, not sharing, is the
/// selector). Three things have to happen and all three can fail
/// differently:
///
/// 1. the entry resolves through the document (it is an indirect
/// reference in every real file — which also lets multiple XObjects
/// share one globals stream, the permissive case in §7.4.7);
/// 2. it is a **stream**, whose raw bytes come out of the retained
/// buffer by span;
/// 3. those bytes run through their own `/Filter` chain, because a
/// globals stream is ordinarily `FlateDecode`d like any other.
///
/// A `/JBIG2Globals` that resolves to something other than a stream is
/// treated as **absent** rather than as an error: many images need no
/// globals at all, a non-stream value carries none, and refusing the
/// image would turn a producer's stray entry into a blank page. If the
/// segments really were needed, `Image::new_embedded` fails immediately
/// afterwards with a structured error naming the missing reference —
/// which is the more useful diagnostic anyway.
///
/// # Errors
///
/// [`ImageCodecError::Filter`] if the globals stream exists but its own
/// filter chain fails. That one *is* an error: the file said the
/// segments are over there, and they cannot be read.
pub
// ---------------------------------------------------------------------------
// Error mapping
// ---------------------------------------------------------------------------
/// Wrap a `hayro-jbig2` failure as a structured pdfcer error.
///
/// The crate's `DecodeError` is an enum over parse/segment/region/
/// symbol/huffman/template/overflow faults and implements `Display`, so
/// the detail string names the actual fault rather than "decode
/// failed". No variant is mapped to
/// [`ImageCodecError::FeatureUnsupported`] today: unlike DCT, whose
/// unsupported *frame types* are a fixed, enumerable set that pdfcer
/// pre-sniffs, `hayro-jbig2` implements the whole of T.88's decoding
/// side (generic, refinement, symbol/text, halftone/pattern, MMR and
/// arithmetic), so there is no known sub-feature to name. If one turns
/// up, it becomes a named key here (rule R27) rather than an added
/// tolerance.
/// The JBIG2 file-header ID string (T.88 D.4.1). An embedded stream
/// starting with these bytes would need segment number `0x974A4232`, so the
/// match is not ambiguous in practice.
const FILE_HEADER_ID: = ;
/// A corrupt-stream error raised by pdfcer's own checks.
/// Does the image dictionary disagree with the page the segments
/// declared?
///
/// JBIG2 is the one bilevel codec that *does* carry its own geometry: a
/// page information segment (T.88 §7.4.8) states the page bitmap's width
/// and height independently of `/Width` and `/Height`. A disagreement is
/// a producer bug — Table 89's "entries inconsistent with each other" —
/// counted and reported, never acted on: `pdfcer-render` keeps the
/// dictionary's numbers for placement and the codestream's for the row
/// stride, which is the only combination that neither shears the picture
/// nor moves it.
///
/// `/BitsPerComponent` is included because Table 89 fixes it at 1 for
/// this filter. An **absent** entry is not a disagreement.
/// The vendor sink impl: T.88's `1 = black` becomes pdfcer's
/// `1 = white` (module docs).