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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! # CCITTFaxDecode (ISO 32000-1 §7.4.6, Table 11; ITU-T T.4/T.6) — the fax adapter
//!
//! Spec source: `filters/filter__ccitt.md` in the PDF-spec RAG, whose
//! Table 11 quotation was **verified against the source PDF on
//! 2026-07-30** (printed pp. 30–31) — including the three defaults that
//! decision 005 §4.3 held as a *blocking prerequisite* for this Pass
//! because they had been recalled rather than read (`Columns` 1728,
//! `EndOfBlock` true, `BlackIs1` false; all three turned out correct,
//! but they are now sourced). The codec itself is delegated by ISO
//! 32000-1 to ITU-T T.4 and T.6 — §7.4.6 NOTE 2, verbatim: "The
//! encoding algorithm is not described in detail in this standard but
//! can be found in ITU Recommendations T.4 and T.6."
//!
//! Crate choice is decision 005 §4.3: **`hayro-ccitt`**, with `fax` as
//! the named fallback.
//!
//! The writer side is [`encode_g4`], pdfcer's own Group 4 encoder
//! (decision 193); it is checked against this decoder, not against itself.
//!
//! ## What this module is, and is not
//!
//! An **adapter**. `hayro-ccitt` does the Huffman run-length decoding,
//! the 2-D vertical/pass/horizontal mode machine, the EOL/EOFB/RTC
//! scanning and the reference-line bookkeeping. Everything here is
//! Table 11 → [`DecodeSettings`] translation, resource ceilings and
//! geometry reconciliation — which is precisely where pdfcer's own bugs
//! would live, and therefore where the doc comments, the tests and the
//! `image_codec_ccitt` fuzz target aim (decision 005 §6.5).
//!
//! ## Table 11 → `DecodeSettings`, one row at a time
//!
//! The mapping is deliberately 1:1 — that property is *why* decision 005
//! §3.5 chose this crate over `fax`, whose TIFF-shaped API would have
//! left the trichotomy, the byte alignment and the polarity as pdfcer
//! glue rather than as fuzzed vendor code.
//!
//! | Table 11 key | Default | `DecodeSettings` field | Note |
//! |---|---|---|---|
//! | `K` | 0 | `encoding` | trichotomy — see below |
//! | `EndOfLine` | false | `end_of_line` | advisory; the filter "shall always accept" EOL patterns |
//! | `EncodedByteAlign` | false | `rows_are_byte_aligned` | |
//! | `Columns` | **1728** | `columns` | the ITU-T A4 scan width, *not* `/Width` |
//! | `Rows` | 0 | `rows` | 0 ⇒ fall back to the image dictionary's `/Height` |
//! | `EndOfBlock` | **true** | `end_of_block` | overrides `Rows` |
//! | `BlackIs1` | **false** | `invert_black` | the polarity trap — see below |
//! | `DamagedRowsBeforeError` | 0 | *(none)* | unimplemented; named diagnostic (R27) |
//!
//! ### `K` is trichotomous, and only trichotomous
//!
//! Table 11, verbatim: "The filter shall **distinguish among negative,
//! zero, and positive values of K** to determine how to interpret the
//! encoded data; however, it **shall not distinguish between different
//! positive K values**." So `K = 4` and `K = 40` select the same decoder
//! path, and building a per-`K` table would be a bug dressed as
//! thoroughness. `encoding_mode` is that rule and nothing else.
//!
//! ### `BlackIs1` is the polarity trap
//!
//! Table 11 describes the flag as "whether **1 bits shall be interpreted
//! as black pixels and 0 bits as white pixels, the reverse of the normal
//! PDF convention for image data**", default **false**. Two consequences
//! that compound:
//!
//! 1. The *normal* PDF convention is therefore `0 = black` — which is
//! what the DeviceGray default `Decode [0 1]` produces at 1 bit per
//! component (sample 0 → grey 0.0). So with `BlackIs1` absent, this
//! filter must emit **0 for a black pixel**.
//! 2. T.4/T.6 speak in "white runs" and "black runs", not in bit values.
//! `hayro-ccitt` reports each pixel through its sink as a `white`
//! flag, already XORed with its `invert_black` setting. pdfcer's
//! `BilevelSink` writes a `1` bit for white. Composing those two
//! facts gives the mapping this module uses:
//! **`invert_black = BlackIs1`** — the direct assignment, not the
//! negation.
//!
//! Getting this backwards renders every fax image as its own negative,
//! which looks deliberate rather than broken. It is the single most
//! likely correctness bug in this filter, so it is pinned from both
//! sides by `mod.rs`'s `ccitt_black_is_1_inverts_every_sample` test:
//! the same codestream is decoded with `/BlackIs1` false and true, and
//! the two results must be exact bitwise complements.
//!
//! `/BlackIs1` is also the **one named exception** to rule R26 ("the
//! codec layer never decides colour"): it is a Table 11 *filter
//! parameter*, so it belongs to the adapter, unlike `/Decode`, which
//! stays `pdfcer-render`'s alone.
//!
//! ## Where `Rows` comes from when it is absent
//!
//! Table 11: "**If the value is 0 or absent, the image's height is not
//! predetermined**, and the encoded data shall be terminated by an
//! end-of-block bit pattern or by the end of the filter's data."
//!
//! `hayro-ccitt` has no "unknown height" mode — its Group 4 loop
//! terminates on `decoded_rows == settings.rows`, so passing `0` would
//! decode **zero rows**. pdfcer therefore supplies a bound, in the order
//! decision 005 §1.2 named as one of the reasons this codec needs the
//! image dictionary at all:
//!
//! 1. `/Rows`, when positive;
//! 2. otherwise the image dictionary's `/Height`, which is Required by
//! Table 89 and is what the image actually is;
//! 3. otherwise the most rows the data could code (evidence, decision
//! 227), never an invented "sensible" number (rule R25); the memory
//! budget bounds what those rows may cost.
//!
//! In every case the decoder still stops early on EOFB/RTC or on
//! exhausted input, so the bound is a ceiling and not an assertion. The
//! rows actually produced are what [`CodedImage::height`] reports.
//!
//! ## Resource ceilings are pdfcer's (rule R25)
//!
//! `hayro-ccitt` has **no** ceilings of its own: it allocates strictly
//! from the `columns`/`rows` it is handed, which puts the whole burden
//! here. A declared row count is checked against the data (evidence,
//! decision 227) and its packed size against the memory budget *before*
//! decoding; `BilevelSink` enforces the budget *during* decoding, so an
//! EOFB-less stream with no declared rows cannot allocate past it.
use ;
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 ObjectGraph;
use ;
use DocumentView;
pub use encode_g4;
/// Table 11's parameters, resolved against their verified defaults.
///
/// A struct rather than eight locals so [`settings`] can be unit-tested
/// against the table directly, and so a reviewer can compare the
/// defaults with `filter__ccitt.md` in one place.
/// Decode a `CCITTFaxDecode` codestream.
///
/// `data` is the codestream *after* any byte-stream filter prefix;
/// `parms` is the codec's own `/DecodeParms` entry; `dict` is the image
/// dictionary, consulted for the `/Rows` → `/Height` fallback and for
/// geometry reconciliation; `notes` accumulates the honesty counters.
///
/// # Errors
///
/// [`ImageCodecError::DeclaredGeometryExceedsData`] when `Rows` exceeds
/// what the data could code at one bit per row;
/// [`ImageCodecError::LimitExceeded`] when the declared rows' packed
/// samples, or the rows actually decoded, cross `limits.memory_budget`;
/// [`ImageCodecError::FeatureUnsupported`] with the key
/// `"CCITT/damaged-rows"` when the stream is damaged *and* the file
/// asked for damage tolerance pdfcer does not implement (rule R27);
/// [`ImageCodecError::Corrupt`] for a malformed codestream or a
/// nonsensical `/Columns`.
pub
// ---------------------------------------------------------------------------
// Table 11 → DecodeSettings
// ---------------------------------------------------------------------------
/// Read Table 11's eight parameters, applying the verified defaults.
///
/// Values of the wrong COS type are treated as absent rather than as
/// errors: Table 11's preamble makes these parameters *assertions about
/// how the data was encoded* ("all values supplied to the decoding
/// filter by any of these parameters shall match those used when the
/// data was encoded"), so a producer that wrote `/Columns /Foo` has
/// written a malformed file whose only recoverable reading is the
/// default. Refusing the image outright would lose more than it
/// protects, and the decode still fails cleanly if the default is wrong
/// for the data.
/// Table 11's `K` trichotomy, and only the trichotomy.
///
/// - `K < 0` — "Pure two-dimensional encoding (Group 4)"
/// - `K = 0` — "Pure one-dimensional encoding (Group 3, 1-D)"
/// - `K > 0` — "Mixed one- and two-dimensional encoding (Group 3, 2-D)"
///
/// The positive `k` is carried into [`EncodingMode::Group3_2D`] because
/// the crate's API asks for it, but the spec forbids *distinguishing*
/// between positive values, and `hayro-ccitt`'s Group 3 2-D loop indeed
/// reads the per-line tag bit rather than counting against `k` — so the
/// value is inert on both sides of the boundary. It is clamped rather
/// than truncated so a `K` of `i64::MAX` cannot wrap to something small.
const
/// Build the vendor settings from Table 11's parameters.
///
/// Split out from [`decode`] so the mapping can be asserted field by
/// field against the table without a codestream in hand.
/// `/Columns` and the declared row count exactly as [`decode`] reads them,
/// for the peak predictor (decision 227).
pub
/// The row count Table 11 lets pdfcer know in advance, if any.
///
/// `/Rows` first ("the height of the image in scan lines"), then the
/// image dictionary's `/Height` — the fallback decision 005 §1.2 named
/// as one of the two mechanical reasons this codec needs `&Document` at
/// all. `None` means neither is usable and the caller falls back to
/// what the data can code.
// ---------------------------------------------------------------------------
// Error mapping
// ---------------------------------------------------------------------------
/// Map a `hayro-ccitt` failure to a structured pdfcer error.
///
/// One case is a **named feature gap** rather than corruption
/// (rule R27). Table 11's `DamagedRowsBeforeError` — "the number of
/// damaged rows of data that shall be tolerated before an error occurs",
/// applying "only if `EndOfLine` is true and `K` is non-negative" —
/// describes a resynchronization behaviour (find the next `EndOfLine`
/// pattern, then substitute the previous row or a white scan line) that
/// `hayro-ccitt` does not implement and pdfcer does not add. When a file
/// asked for that tolerance and the stream then failed, saying
/// "corrupt" would be true but useless: the operator's actual question
/// is *which* missing capability would have saved it. So the diagnostic
/// names the feature, and it is counted by name in the renderer.
///
/// Every other failure is [`ImageCodecError::Corrupt`] — the fail-clean
/// contract (decision 001 §6.1.4): corrupt in, `Err` out, never
/// plausible-looking garbage. `hayro-ccitt` documents that some rows may
/// already have been written when it errors; pdfcer deliberately does
/// **not** return that partial image, because a silently short fax page
/// is exactly the "looks deliberate" failure this project refuses.
/// A corrupt-codestream error raised by pdfcer's own parameter checks.
/// Does the image dictionary disagree with what the filter produced?
///
/// Unlike DCT — where the codestream carries its own geometry — CCITT
/// has none: `Columns` and `Rows` are `/DecodeParms` entries, so a
/// disagreement here is a disagreement *between two parts of the same
/// dictionary*. It is still worth counting, because the two most common
/// real-world fax defects both show up as one:
///
/// - `/Columns` omitted on a non-1728-wide scan, so the 1728 default
/// governs the decoder's line length while `/Width` governs the image
/// — which shears the picture rather than failing;
/// - a stream that ran out of data before `/Height` rows, which yields
/// fewer rows than the dictionary promises.
///
/// `/BitsPerComponent` is included for the same reason as in the DCT
/// adapter: Table 89 makes an entry inconsistent with the filter an
/// error, and this filter "shall always deliver 1-bit samples". An
/// **absent** `/BitsPerComponent` is not a disagreement — image masks
/// routinely omit it, and §8.9.6.2 fixes it at 1 for them anyway.
/// The vendor sink impl.
///
/// `hayro-ccitt` has **already** applied `invert_black` by the time it
/// calls the sink (`push_pixels` computes
/// `color.is_white() ^ invert_black`), so the flag it hands over is
/// exactly pdfcer's notion of "white" and needs no further translation.
/// That is the composition the module docs derive: `BlackIs1` goes into
/// `invert_black` unchanged, and the sink writes a `1` bit for white.