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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
//! # JPXDecode (ISO 32000-1 §7.4.9, §8.9.5 Table 89; ITU-T T.800) — the JPEG 2000 adapter
//!
//! Spec source: `filters/filter__jpx.md` in the PDF-spec RAG, VERIFIED
//! 2026-07-30 against the staged `PDF32000_2008.pdf` (printed pp. 35–37
//! for §7.4.9, pp. 206–208 for Table 89). The codec itself is ITU-T
//! T.800 (published identically as ISO/IEC 15444-1); the PDF clause
//! defines only the *embedding*.
//!
//! Crate choice is decision 005 §4.5: **`hayro-jpeg2000`**, with
//! `simd` off (it pulls `fearless_simd`, which is where the crate's only
//! unsafe would live) and `image` off (it pulls the `image` crate and
//! `moxcms`, neither of which belongs in `pdfcer-core`). It is the only
//! credible pure-Rust JPEG 2000 decoder — 550k downloads against ~1.9k
//! for the nearest pure-Rust rival, with everything else in the space
//! wrapping OpenJPEG in C. That mattered: a C binding would have
//! triggered both a `LEGAL.md` §6.2 licence review of the underlying
//! library *and* reopened the single-static-binary packaging question
//! (`ARCHITECTURE.md` §6), and the mature JPEG 2000 implementations are
//! GPL.
//!
//! ## This filter INVERTS the usual dictionary rules — the whole point
//!
//! For every other image filter the image dictionary is authoritative
//! and the codestream must agree with it. Table 89 turns that around,
//! and §7.4.9 states the same rules a second time from the filter's
//! side. Both citations are valid; §7.4.9 is the fuller statement.
//!
//! | Entry | Ordinary image | **JPXDecode** |
//! |---|---|---|
//! | `/ColorSpace` | Required | **Optional.** Present → it wins and "the colour space specifications in the JPEG2000 data shall be ignored". Absent → "the colour space information in the JPEG2000 data shall be used". |
//! | `/BitsPerComponent` | Required | **"Optional and shall be ignored if present. The bit depth is determined by the conforming reader in the process of decoding."** |
//! | `/Decode` | Applied (§8.9.5.2) | **"Shall be ignored, except in the case where the image is treated as a mask; that is, when `ImageMask` is true."** |
//! | `/Width`, `/Height` | Authoritative | "shall **match** … the JPEG2000 data" — with **no** conflict-resolution rule given. |
//! | `/SMaskInData` | meaningless | Selects whether the codestream's own opacity channel is used at all. Default **0** = ignore it. |
//!
//! Two consequences are easy to get backwards and both are load-bearing:
//!
//! 1. **A present `/ColorSpace` WINS.** The trap is to read "the
//! codestream is authoritative for JPX" as a blanket rule and let the
//! codestream override a stated `/ColorSpace`. It does not. The
//! codestream wins only where the dictionary is *silent* (colour) or
//! *disqualified* (bit depth, `Decode`). Applying it the other way
//! round produces wrong colour on exactly the files a producer took
//! the trouble to tag.
//! 2. **A present `/BitsPerComponent` is WRONG to honour.** It is not
//! merely optional; a reader that uses it "will get the wrong depth,
//! because it shall be ignored if present". This module reports the
//! depth of the samples it actually delivers and the renderer takes
//! that in preference to the dictionary (see
//! `pdfcer_render::image`).
//!
//! This module owns half of that: it produces the samples, the
//! codestream-declared geometry, the codestream-declared colour model
//! and any embedded ICC profile. `pdfcer-render` owns the other half —
//! choosing between dictionary and codestream, and suppressing
//! `/Decode`.
//!
//! ## Bit depth: pdfcer delivers 8, range-scaled — a decision, documented
//!
//! §7.4.9 allows "any value from 1 to 38" bits per component, and
//! permits **different components to use different depths**. The
//! [`CodedImage`] contract has one uniform `bits_per_component`, because
//! §8.9.3's sample layout — which `pdfcer-render`'s unpacking path
//! implements — has no way to express a per-component depth.
//!
//! Table 89 resolves the tension for us in one clause: "the bit depth is
//! determined by the **conforming reader** in the process of decoding."
//! pdfcer determines **8**, and scales each component from its own
//! declared depth:
//!
//! ```text
//! out = round(sample / (2^d − 1) × 255) clamped to 0..=255
//! ```
//!
//! **Full-range scaling, not high-byte truncation.** The distinction is
//! real: a 16-bit sample of `0x00FF` scales to 1 and truncates to 0, and
//! more importantly the codestream's white point `2^d − 1` maps onto
//! exactly 255 for *every* depth under scaling, while truncation only
//! gets that right when `d` is a multiple of 8. `fixtures_jpx.rs`'s
//! 16-bit fixture carries a `0x00FF` pixel precisely to pin this.
//!
//! Per-component depths are handled naturally because each component is
//! scaled by its own `bit_depth()` on the way into the interleave. This
//! is also the reason the adapter does its own interleaving rather than
//! calling `hayro-jpeg2000`'s `DecodedImage::data_u8()`: that helper
//! interleaves the opacity channel *into* the colour samples, which
//! `/SMaskInData` requires us to keep separate, and its scaling path
//! computes `1 << bit_depth` on a depth that a JP2 palette box may
//! legally declare as large as 128 — a shift overflow. pdfcer's own loop
//! rejects any depth outside 1..=31 by name (rule R27) and never
//! performs that shift.
//!
//! ## `/SMaskInData` (Table 89, VERIFIED): 0 ignore, 1 opacity, 2 preblended
//!
//! - **0 (the default)** — "If present, encoded soft-mask image
//! information **shall be ignored**." So a decoder that always hands
//! back the alpha it found is *wrong*. The opacity channel is still
//! removed from the colour samples (it is not a colour component),
//! but it is not exposed.
//! - **1** — "The image's data stream includes encoded soft-mask
//! values." This is §7.4.9's *ordinary opacity* channel type. The
//! channel is lifted out into [`CodedImage::embedded_alpha`], one
//! 8-bit sample per pixel.
//! - **2** — "the image's data stream includes colour channels that have
//! been **preblended with a background**; the image data also includes
//! an opacity channel," and a reader "may create a soft-mask image
//! **with a `Matte` entry**". This is §7.4.9's *premultiplied
//! opacity* channel type.
//!
//! **Value 2 is recognize-and-defer, deliberately.** Reconstructing the
//! unblended colour needs the `Matte` backdrop and clause 11's
//! un-premultiplication, and clause 11 is out of scope for this Pass —
//! decision 005 §7 assigns `/SMask`, `/Mask` and colour-key masking to
//! `ROADMAP.md` Pass 1.1 item 6.3, and the spec RAG marks the `Matte`
//! interaction a GAP (clause 11 not yet ingested). So pdfcer:
//!
//! - decodes and returns the colour channels **as stored**, i.e.
//! preblended — which is what the picture genuinely looks like
//! composited over that backdrop, and therefore a recognizable image
//! rather than a grey box;
//! - does **not** expose the opacity channel, because using it without
//! un-premultiplying would double-darken every partially transparent
//! pixel;
//! - sets [`CodecNotes::jpx_smask_in_data_preblended`], which the
//! renderer and both front ends surface by name.
//!
//! That is the `fuzzy, never sneaky` shape (CLAUDE.md rule 4): visible,
//! counted, and not silently approximated. There is also a hard limit
//! underneath it — `hayro-jpeg2000`'s `cdef` parser accepts only channel
//! types 0 (colour) and 1 (opacity), so a file that declares a genuine
//! *premultiplied* channel type fails at parse with an invalid-box
//! error rather than reaching this branch at all.
//!
//! A nonzero `/SMaskInData` on an image whose codestream carries no
//! opacity channel is a malformed dictionary — "there shall be only one
//! opacity channel in the JPEG2000 data and it shall apply to all
//! colour channels" presupposes one exists. It is counted as a geometry
//! disagreement rather than refused: nothing about the colour samples is
//! wrong.
//!
//! Note the exclusion rule this module does **not** enforce: "If this
//! entry has a nonzero value, `SMask` shall not be specified." That is a
//! validation rule about the image dictionary, and `pdfcer-render` is
//! where image-dictionary consistency is judged.
//!
//! ## Colour: the §7.4.9 fallback ladder, and where ICC stops
//!
//! §7.4.9 specifies a *ladder*, not a lookup, for the `/ColorSpace`-absent
//! case: the codestream's own specification, preferring "the one with
//! the highest precedence and best approximation value"; on an
//! unsupported ICC profile "the next lower colour space … shall be
//! used"; and finally "**if no supported colour space is found, the
//! colour space used shall be `DeviceGray`, `DeviceRGB`, or
//! `DeviceCMYK`, depending on … whether the number of channels in the
//! JPEG2000 data is 1, 3, or 4**". A decoder that errors out on an
//! unsupported ICC profile is non-conformant.
//!
//! `hayro-jpeg2000` walks the top of that ladder itself and hands back
//! `ColorSpace::{Gray, RGB, CMYK, Icc{profile, n}, Unknown{n}}`. This
//! module walks the rest:
//!
//! | Vendor `ColorSpace` | [`CodecColorModel`] | `icc_profile` |
//! |---|---|---|
//! | `Gray` | `Gray` | none |
//! | `RGB` | `Rgb` | none |
//! | `CMYK` | `Cmyk` | none |
//! | `Icc { profile, n }` | by the profile's own **data colour space** signature, else by `n` | the profile, verbatim |
//! | `Unknown { n }` | `Unknown { n }` | none |
//!
//! The ICC row is the interesting one and the reason a four-byte header
//! read earns its place. pdfcer applies no colour management: the
//! renderer's `ICCBased` path already uses the spec's own
//! `N`-component fallback, treating an ICC RGB profile as `DeviceRGB`.
//! That approximation is fine for `GRAY`/`RGB `/`CMYK` profiles and
//! **wrong** for a `Lab ` profile, whose samples are not device
//! components at all — and `hayro-jpeg2000` returns exactly that shape
//! for a JPX enumerated CIELab image (it substitutes a bundled LAB
//! profile and leaves the samples as scaled Lab). Mapping such a
//! profile by channel count would paint L\*a\*b\* as if it were RGB:
//! plausible-looking, entirely wrong colour. So a profile whose data
//! colour space is not one pdfcer can approximate becomes
//! [`CodecColorModel::Unknown`], and the renderer refuses the image
//! rather than inventing colour for it.
//!
//! Note what is *not* here: this module never picks a PDF colour space,
//! never applies `/Decode`, and never applies an ICC transform
//! (rule R26). It reports what the samples are; the renderer decides
//! what they mean.
//!
//! ## Forbidden in inline images
//!
//! §7.4.9: "This filter shall only be applied to image XObjects, and not
//! to inline images." §8.9.7 says it 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." 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.
//!
//! ## No `/DecodeParms` (Table 6, VERIFIED)
//!
//! `JPXDecode` is one of the four `no`-parameter filters in Table 6
//! (with `ASCIIHexDecode`, `ASCII85Decode` and `RunLengthDecode`), which
//! is why `decode` takes no parameter dictionary at all — a difference
//! from the other three codecs that is worth seeing in the signature.
//! Everything configurable lives in the codestream or in the *image*
//! dictionary.
//!
//! ## Resource ceilings are pdfcer's, never the vendor's (rule R25)
//!
//! `hayro-jpeg2000` caps dimensions at 60,000 and does not bound the
//! *product*, so its own guards permit a 60,000 × 60,000 image — 3.6
//! Gpx. Worse, its `DecoderContext` allocates one `f32` per sample per
//! component **from the codestream's declared geometry, before any
//! entropy decoding**, so a few hundred header bytes can ask for
//! arbitrary memory. The ceilings below are therefore applied between
//! `Image::new` (which parses headers only) and `Image::decode` (which
//! allocates), which is the one place they can work.
//!
//! ### The tile-count ceiling, and the fuzz finding behind it
//!
//! Pixels and bytes are not the only unbounded quantity a SIZ marker
//! can declare. The **tile grid** is independent of them: T.800's
//! `XTsiz`//`YTsiz` may be as small as 1, so a 512 × 1024 image tiled at
//! 4 × 2 declares **65,536 tiles**, and a decoder that materializes and
//! walks one structure per tile does 65,536 tiles' worth of setup for
//! half a megapixel of output.
//!
//! That is not hypothetical. `fuzz_targets/image_codec_jpx.rs` produced
//! exactly that codestream — **310 bytes, 32 seconds** — within the
//! first minute of its first campaign. It is a CPU-exhaustion vector,
//! not a memory one, so neither [`MAX_IMAGE_PIXELS`] nor
//! `MAX_WORKING_BYTES` sees it: 512 Kpx is two orders of magnitude
//! inside both. The guard that sees it is evidence (decision 227): past
//! `MAX_TILES`, each tile must be backed by the 14 bytes its minimal
//! tile-part takes, and 310 bytes cannot back 65,536 tiles.
//!
//! ## Upstream's admitted gaps become named diagnostics (rule R27)
//!
//! `hayro-jpeg2000`'s own documentation states it has "some missing
//! pieces for some 'obscure' features, like for example support for
//! progression order changes in tile-parts". Mechanically, an unhandled
//! marker segment is a single `MarkerError::Unsupported` from either the
//! main-header or the tile-part-header parser, with no indication of
//! *which* marker. A bare "decode failed" there would be exactly the
//! grey box rule R27 forbids, so `decode` runs a bounded marker walk
//! **on the error path only** and reports
//! `"JPX/progression-order-change"` when a `POC` marker (T.800 Table
//! A.2, code `0xFF5F`) is present and `"JPX/unsupported-marker"`
//! otherwise. The walk never influences accept/reject — only the name of
//! the diagnostic — so it cannot drift into a second, disagreeing
//! parser.
use ;
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;
/// Ceiling on `hayro-jpeg2000`'s internal working set, in bytes.
///
/// The decoder holds one `f32` per sample per component — four bytes for
/// every one byte that reaches [`CodedImage::samples`] — and allocates
/// all of it up front from the codestream's declared geometry. It is the
/// shared [`MAX_DECODER_WORKING_BYTES`], so it is **tighter** than
/// [`MAX_IMAGE_PIXELS`]: a four-component JPX above 2^25 px, or a
/// three-component one above about 44.7 Mpx, is refused here. It is the
/// number the fuzz target's `-rss_limit_mb` is reasoned against.
const MAX_WORKING_BYTES: u64 = MAX_DECODER_WORKING_BYTES;
/// Tile count up to which no evidence is asked for; past it each tile
/// needs a minimal tile-part's bytes (`crate::evidence::jpx_tiles`).
///
/// A tile grid is declared independently of the image size (`XTsiz` and
/// `YTsiz` may each be as small as 1), and `hayro-jpeg2000` builds and
/// walks one structure per tile, so the tile count — not the pixel
/// count — is what bounds the decode's *work*. A 310-byte codestream
/// declaring 65,536 tiles over a 512 × 1024 image took **32 seconds**
/// when the fuzz target found it; see the module docs.
///
/// 4,096 is set from what real encoders emit rather than from a round
/// number. OpenJPEG's default is a single tile; Kakadu's is
/// 1024 × 1024, which is 30 tiles at pdfcer's 32 Mpx ceiling; the most
/// aggressive tiling seen in practice is 256 × 256, which is 512. So
/// this admits eight times the most aggressive real tiling, and lets a
/// full 32 Mpx image be tiled as finely as 91 × 91 — while bounding the
/// pathological case at roughly half a second instead of eight.
///
/// Like every ceiling in this module it is pdfcer's own number, not a
/// vendor default (rule R25).
const MAX_TILES: u64 = 4096;
/// Highest per-component bit depth pdfcer will scale from.
///
/// §7.4.9 allows 1..=38. `hayro-jpeg2000` refuses anything above 31 in
/// the SIZ marker (its bit-plane coder is `u32`-based), so for ordinary
/// components this is never the binding limit — but a JP2 **palette**
/// box may declare a column depth up to 128, and after palette
/// resolution that depth becomes the component's. Scaling from it would
/// mean evaluating `1 << 128`. Refused by name instead.
const MAX_COMPONENT_BIT_DEPTH: u8 = 31;
/// Table 89's `/SMaskInData` code, as an exhaustive three-way choice.
///
/// Modelled as an enum rather than an integer so that every use site has
/// to say what it does about the preblended case; the whole risk in this
/// entry is that value 2 gets quietly handled like value 1.
/// Decode a `JPXDecode` codestream (§7.4.9).
///
/// `data` is the JP2/JPX file structure — or a bare T.800 codestream;
/// `hayro-jpeg2000` sniffs which — after any byte-stream filter prefix.
/// `dict` is the image dictionary, read **only** for `/SMaskInData` and
/// for the geometry-disagreement counters; nothing in it changes how the
/// samples are produced. There is no `parms` argument because Table 6
/// gives this filter no parameters.
///
/// # Errors
///
/// - [`ImageCodecError::DeclaredGeometryExceedsData`] when the SIZ tile
/// grid is past [`MAX_TILES`] and the data is too short to hold a
/// minimal tile-part per tile;
/// - [`ImageCodecError::TooLarge`] when the codestream's declared
/// geometry crosses [`MAX_IMAGE_PIXELS`], [`MAX_IMAGE_DIMENSION`],
/// [`MAX_IMAGE_SAMPLE_BYTES`] or [`MAX_WORKING_BYTES`];
/// - [`ImageCodecError::FeatureUnsupported`] for the two named gaps —
/// an unhandled marker segment (`"JPX/progression-order-change"` /
/// `"JPX/unsupported-marker"`) and a component bit depth pdfcer will
/// not scale from (`"JPX/bit-depth"`);
/// - [`ImageCodecError::Corrupt`] for everything else, carrying the
/// vendor's own `Display` text so the detail names the actual fault.
///
/// Nothing here can panic: every fallible step is checked, every slice
/// access is bounds-checked, and the `image_codec_jpx` fuzz target
/// asserts it over arbitrary bytes.
pub
/// Scale one planar component to 8 bits and write it into an interleaved
/// buffer at `index`, striding by `stride` components per pixel.
///
/// The scale is the module docs' `round(v / (2^d − 1) × 255)`, clamped:
/// the inverse wavelet transform can legitimately produce values a
/// little outside `0..=2^d − 1` at sharp edges (T.800 Annex F's lifting
/// steps are not range-preserving), and §8.9.5.2's own instruction for
/// an out-of-range value is to adjust it "to the nearest allowed value".
///
/// `bit_depth` is guaranteed in `1..=31` by the caller's check, so the
/// shift cannot overflow and the divisor cannot be zero.
/// Read `/SMaskInData` (Table 89), defaulting to `0`.
///
/// Values outside 0..=2 are undefined by the spec. They are treated as
/// the default — "shall be ignored" — rather than guessed at: the two
/// alternatives are to refuse the image (a total loss over one stray
/// integer) or to pick one of the defined meanings (inventing a rule the
/// spec does not have). Ignoring the codestream's alpha is the outcome
/// that cannot corrupt what is drawn.
/// Map the vendor's colour space onto pdfcer's codec-level colour model,
/// carrying any embedded ICC profile out untouched.
///
/// The ICC branch walks the tail of §7.4.9's fallback ladder; see the
/// module docs for why the profile's own data-colour-space signature is
/// consulted rather than the channel count alone.
/// The four-character *data colour space* signature of an ICC profile.
///
/// ICC.1 fixes the profile header at 128 bytes with the data colour
/// space at offset 16 — `'GRAY'`, `'RGB '`, `'CMYK'`, `'Lab '` and so
/// on. Reading four bytes at a fixed offset is the whole of the parse;
/// pdfcer does not otherwise interpret ICC profiles, and this is used
/// only to decide whether the device-space approximation is honest.
/// Returns `None` for anything too short to carry a header.
/// Does the image dictionary disagree with the codestream?
///
/// §7.4.9 requires `/Width` and `/Height` to "match the corresponding
/// width and height values in the JPEG2000 data" but gives **no**
/// conflict-resolution rule, and Table 89 makes `/BitsPerComponent`
/// "optional and … ignored if present". So all three are compared and
/// none is acted on here: the divergence is counted, and
/// `pdfcer-render` keeps the dictionary's numbers for placement and the
/// codestream's for reading, which is the only split that neither
/// shears the picture nor moves it.
///
/// `/BitsPerComponent` counts as a disagreement whenever it is present
/// and is not the 8 pdfcer delivers — including the common, superficially
/// harmless case of a producer writing `16` for a 16-bit codestream.
/// That is not pedantry: it is the one entry a reader is actively told
/// to ignore, so a file carrying it is a file whose other entries
/// deserve a second look.
///
/// An **absent** entry is never a disagreement — Table 89 makes
/// `/ColorSpace` and `/BitsPerComponent` optional for this filter, which
/// is the entire point of the audit that preceded this Pass.
/// Whether the image dictionary's `/ColorSpace` is an `/Indexed` array.
///
/// # Why this is a separate question from the component count
///
/// `dict_colorspace_components` answers *"how many channels does the PDF
/// expect?"*, which for `/Indexed` is always 1 and says nothing about who
/// owns the palette. This answers *"does the PDF carry its own lookup
/// table?"* — and that decides whether the JPEG 2000 decoder should resolve
/// the codestream's own palette or leave the samples as indices.
///
/// # What it deliberately cannot see
///
/// A `/ColorSpace` written as a **name** (`/CS0`) resolves through the page's
/// resource dictionary, which the codec layer does not have and should not
/// acquire — the codec's job is bytes, not page structure. Such a name
/// returns `false`, keeping the pre-existing behaviour rather than guessing.
///
/// That is a real, named limit rather than an oversight: a JPX image with a
/// palette AND a named `/Indexed` resource would still double-resolve. No
/// such file is known, the shape is checkable if one turns up, and the
/// alternative — plumbing resources into the codec to catch a hypothetical —
/// costs more than it protects.
pub
/// The component count implied by a `/ColorSpace` given as a device
/// name, or `None` when the entry is absent or is any other shape.
///
/// Deliberately narrow. Resolving `[/ICCBased …]`, `[/Indexed …]` or a
/// named resource needs the page's resource dictionary, which the codec
/// layer does not have and should not acquire — `pdfcer-render` already
/// performs the full comparison once it has resolved the space. This
/// covers the case a JPX image actually hits in practice (a bare
/// `/DeviceRGB` beside a grayscale codestream) without duplicating the
/// colour-space resolver.
// ---------------------------------------------------------------------------
// Error mapping
// ---------------------------------------------------------------------------
/// Wrap a `hayro-jpeg2000` failure as a structured pdfcer error, naming
/// the one class of failure that is a *missing feature* rather than a
/// broken file.
///
/// `MarkerError::Unsupported` is raised by both the main-header and the
/// tile-part-header parsers for any marker segment the decoder does not
/// handle, and it carries no marker code. Upstream names progression
/// order changes in tile-parts as its known gap, and `POC` (T.800 Table
/// A.2, `0xFF5F`) is precisely the marker that expresses one — so the
/// codestream is walked once, here, to turn "unsupported marker" into
/// the name an operator can act on (rule R27).
///
/// Every other variant is a genuine corrupt/invalid-input report and
/// keeps the vendor's own `Display` text, which names the actual fault
/// (`"missing COD marker"`, `"invalid tile offsets"`, …) rather than
/// collapsing to "decode failed".
/// A corrupt-stream error raised by pdfcer's own checks.
/// T.800 Table A.2 marker code for a progression order change.
const MARKER_POC: u8 = 0x5F;
/// Start of tile-part.
const MARKER_SOT: u8 = 0x90;
/// Start of data — after this the tile-part carries entropy-coded
/// packets, not marker segments.
const MARKER_SOD: u8 = 0x93;
/// End of codestream.
const MARKER_EOC: u8 = 0xD9;
/// Start of codestream.
const MARKER_SOC: u8 = 0x4F;
/// Upper bound on marker segments walked while naming a diagnostic.
///
/// The walk is a diagnostic refinement on an already-failing path, so it
/// must be cheap and unconditionally terminating. Every step either
/// advances by at least two bytes or stops, which already bounds it by
/// the input length; this second bound keeps a pathological
/// many-tiny-segments codestream from turning an error report into a
/// measurable cost.
const MAX_MARKERS_WALKED: usize = 4096;
/// Name the missing feature behind a `MarkerError::Unsupported`.
///
/// Walks the codestream's **header** marker segments — the main header
/// up to the first `SOT`, then each tile-part header up to its `SOD` —
/// looking for `POC`. Entropy-coded packet data is skipped using the
/// tile-part length `Psot` from each `SOT` segment (T.800 A.4.2), so no
/// packet byte is ever mistaken for a marker.
///
/// Returns `"JPX/progression-order-change"` when a `POC` marker is
/// found and `"JPX/unsupported-marker"` otherwise, which is also the
/// answer for a JP2 box container whose codestream cannot be located or
/// for a walk that runs off the end. It never changes whether an image
/// is accepted — only what the refusal is called — so a disagreement
/// with the vendor's parser costs a less precise diagnostic and nothing
/// else.
/// The number of tiles the SIZ marker declares, per T.800 equation B-5.
///
/// ```text
/// numXtiles = ceil((Xsiz − XTOsiz) / XTsiz)
/// numYtiles = ceil((Ysiz − YTOsiz) / YTsiz)
/// ```
///
/// Re-read from the codestream because `hayro-jpeg2000` keeps its
/// `Header` private and exposes only the image dimensions — and because
/// the tile count is the quantity that bounds *decode work*, which no
/// pixel or byte ceiling can see (see [`MAX_TILES`]).
///
/// It runs before `Image::new`, so it is total on unvalidated bytes: SIZ
/// is at a known position (T.800 A.5.1) and every field is a fixed-width
/// big-endian integer.
///
/// ```text
/// +0 SOC | +2 SIZ | +4 Lsiz | +6 Rsiz | +8 Xsiz | +12 Ysiz
/// +16 XOsiz | +20 YOsiz | +24 XTsiz | +28 YTsiz | +32 XTOsiz | +36 YTOsiz
/// ```
///
/// Returns `None` when the codestream cannot be located, the segment is
/// short or a tile size is zero; the caller treats that as "no opinion"
/// and leaves the refusal to `Image::new`.
/// Locate the `SOC` marker that starts the T.800 codestream.
///
/// Two shapes reach here. A **bare codestream** starts with
/// `FF 4F FF 51` at offset 0. A **JP2 container** wraps it in a
/// `jp2c` box, so the box list is walked to find it — the same walk
/// `hayro-jpeg2000` does, but tolerating any failure by returning
/// `None`, because this is only ever refining a diagnostic.
/// `data[at..at + len]`, `None` when out of range or `at + len` overflows.