rust-j2k 0.4.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C library.
Documentation
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
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
//! The robustness table in `docs/roadmap-phase3.md` ("Fuzz and robustness
//! plan"), one or more inputs per row, each pinned to its outcome: it decodes,
//! or which [`Error`] variant it is. A row that changes variant fails the
//! matrix. The messages are pinned by the tests nearer each check; this test
//! is about the variant. Every input is built in code or is a committed
//! synthetic fixture; the table records what OpenJPEG 2.5.0 does with each
//! shape, measured with `opj_decompress` (and, for the raw-channel rows, a
//! probe linked to `libopenjp2` 2.5.0 with its ignore flag set).

use super::after::{
    ONE_COMPONENT, after, decode_raw, identity_cdef, no_color_then, one_component,
    psot_zero_codestream, with_jp2c_length,
};
use super::channels::cdef_of as cdef;
use super::palette::{cmap_box, pclr_box};
use super::*;

/// What a decode gives, by variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
    Decodes,
    Codestream,
    FileFormat,
    Unsupported,
    Limit,
    Other,
}

fn outcome(result: crate::Result<Image>) -> Outcome {
    match result {
        Ok(_) => Outcome::Decodes,
        Err(Error::Codestream(_)) => Outcome::Codestream,
        Err(Error::FileFormat(_)) => Outcome::FileFormat,
        Err(Error::Unsupported(_)) => Outcome::Unsupported,
        Err(Error::Limit(_)) => Outcome::Limit,
        Err(_) => Outcome::Other,
    }
}

/// How a row is decoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    Default,
    Raw,
    Srgb,
}

const SUBSAMPLED_PALETTE: &[u8] =
    include_bytes!("../../../tests/fixtures/jp2_palette_subsampled_small_first.jp2");
const CLAMPED_PALETTE: &[u8] = include_bytes!("../../../tests/fixtures/jp2_palette_clamp.jp2");

/// A three-component file with these `jp2h` children after `ihdr` and `colr`.
fn children(extra: &[Vec<u8>]) -> Vec<u8> {
    let mut all = vec![good_ihdr(), colr()];
    all.extend_from_slice(extra);
    file(&[jp2_ftyp(), jp2h(&all), jp2c()])
}

/// A `uinf` box holding a `ulst` with these contents and an empty `url `.
fn uuid_info(ulst: &[u8]) -> Vec<u8> {
    bx(b"uinf", &[bx(b"ulst", ulst), bx(b"url ", &[0; 4])].concat())
}

/// A `cmap` box from `(CMP, MTYP, PCOL)` triples.
fn cmap(entries: &[(u16, u8, u8)]) -> Vec<u8> {
    let payload: Vec<u8> = entries
        .iter()
        .flat_map(|&(cmp, mtyp, pcol)| {
            let [c0, c1] = cmp.to_be_bytes();
            [c0, c1, mtyp, pcol]
        })
        .collect();
    bx(b"cmap", &payload)
}

/// A one-entry `pclr` box over columns with these `Bi` bytes, every entry
/// zero.
fn one_entry_pclr(bi: &[u8]) -> Vec<u8> {
    let mut payload = vec![0, 1, u8::try_from(bi.len()).unwrap()];
    payload.extend_from_slice(bi);
    for &b in bi {
        let bytes = (usize::from(b & 0x7F) + 1).div_ceil(8).min(4);
        payload.extend(std::iter::repeat_n(0, bytes));
    }
    bx(b"pclr", &payload)
}

/// A one-component 2048x2048 codestream header: the single-component fixture
/// with its image and tile grown, so its main header parses. Its tile data
/// is never reached.
fn big_one_component() -> Vec<u8> {
    let mut codestream = ONE_COMPONENT.to_vec();
    for at in [8, 12, 24, 28] {
        codestream[at..at + 4].copy_from_slice(&2048u32.to_be_bytes());
    }
    codestream
}

/// A file whose palette expands a 2048x2048 index plane into 255 channels:
/// 255 * 2^22 samples, over the 2^28 sample limit.
fn palette_over_budget() -> Vec<u8> {
    palette_255_over(&big_one_component())
}

/// A JP2 file around this 2048x2048 one-component codestream, with a palette
/// of 255 columns mapped to 255 channels.
fn palette_255_over(codestream: &[u8]) -> Vec<u8> {
    let columns: Vec<u8> = (0..=254).collect();
    let mapping: Vec<(u16, u8, u8)> = columns.iter().map(|&i| (0, 1, i)).collect();
    file(&[
        jp2_ftyp(),
        jp2h(&[
            ihdr(2048, 2048, 1),
            colr(),
            one_entry_pclr(&[7; 255]),
            cmap(&mapping),
        ]),
        bx(b"jp2c", codestream),
    ])
}

/// `count` empty boxes of an unknown type.
fn unknown_boxes(count: usize) -> Vec<u8> {
    header_only(8, b"zzzz").repeat(count)
}

/// The fixture codestream split into two tile-parts, the last with
/// `Psot = 0`, still ending in `EOC`.
fn two_parts_last_open() -> Vec<u8> {
    let sot = CODESTREAM
        .windows(2)
        .position(|w| w == [0xFF, 0x90])
        .expect("the fixture has a tile-part");
    let data = &CODESTREAM[sot + 14..CODESTREAM.len() - 2];
    let (first, second) = data.split_at(data.len() / 2);
    let part = |index: u8, data: &[u8], psot: u32| {
        let mut out = vec![0xFF, 0x90, 0, 10, 0, 0];
        out.extend_from_slice(&psot.to_be_bytes());
        out.extend_from_slice(&[index, 2, 0xFF, 0x93]);
        out.extend_from_slice(data);
        out
    };
    let first_psot = u32::try_from(14 + first.len()).unwrap();
    [
        &CODESTREAM[..sot],
        &part(0, first, first_psot),
        &part(1, second, 0),
        &[0xFF, 0xD9][..],
    ]
    .concat()
}

/// A `Psot = 0` last tile-part followed by more bytes in the slice it runs
/// to: the `jp2c` box does not end at its `EOC` (`LBox` 0, or a length that
/// ends inside the codestream). OpenJPEG 2.5.0 decodes each, ignoring the
/// bytes past the last packet; the codestream parser rejects them.
fn open_last_part_then_more() -> Vec<(&'static str, Vec<u8>)> {
    open_last_part_shapes().split_off(1)
}

/// The shapes of [`open_last_part_then_more`], led by one whose `jp2c`
/// length is right but whose codestream has no `EOC`, then an `xml ` box.
/// That box ends where its codestream does, so it decodes, as in
/// OpenJPEG 2.5.0.
fn open_last_part_shapes() -> Vec<(&'static str, Vec<u8>)> {
    let with_eoc = psot_zero_codestream();
    let without_eoc = &with_eoc[..with_eoc.len() - 2];
    let xml = bx(b"xml ", b"<a>hello</a>");
    let bad_colr = bx(b"colr", &[1, 0]);
    let prefix = file(&[jp2_ftyp(), good_jp2h()]);
    let short = |lbox: u32, codestream: &[u8], tail: &[u8]| {
        [&prefix[..], &header_only(lbox, b"jp2c"), codestream, tail].concat()
    };
    vec![
        (
            "no EOC, then an xml box",
            [&prefix[..], &bx(b"jp2c", without_eoc), &xml].concat(),
        ),
        ("LBox 108, then an xml box", short(108, &with_eoc, &xml)),
        (
            "LBox 108, then a short colr",
            short(108, &with_eoc, &bad_colr),
        ),
        (
            "two tile-parts, LBox 200, then a short colr",
            short(200, &two_parts_last_open(), &bad_colr),
        ),
        (
            "LBox 0 holding the codestream and an xml box",
            [
                &prefix[..],
                &open_box(b"jp2c", &[&with_eoc[..], &xml].concat()),
            ]
            .concat(),
        ),
    ]
}

/// `depth` `asoc` superboxes nested in one another.
fn nested_asoc(depth: usize) -> Vec<u8> {
    (0..depth).fold(bx(b"xml ", b"<deep/>"), |inner, _| bx(b"asoc", &inner))
}

/// A `colr` payload (`METH` 2) whose ICC profile LittleCMS refuses to open:
/// a header with the `acsp` signature, version 5.1, and no tags.
fn unopenable_profile() -> Vec<u8> {
    let mut icc = vec![0u8; 132];
    icc[..4].copy_from_slice(&132u32.to_be_bytes());
    icc[8..12].copy_from_slice(&0x0510_0000u32.to_be_bytes());
    icc[12..24].copy_from_slice(b"scnrRGB XYZ ");
    icc[36..40].copy_from_slice(b"acsp");
    [vec![2, 0, 0], icc].concat()
}

#[test]
fn every_robustness_table_row_has_its_outcome() {
    use crate::{ColorOutput, DecodeOptions, decode_with};
    use Mode::{Default, Raw, Srgb};
    use Outcome::*;

    let ihdr_payload = good_ihdr()[8..].to_vec();
    let truncated = &CODESTREAM[..CODESTREAM.len() - 40];
    let rows: Vec<(&str, Vec<u8>, Mode, Outcome)> = vec![
        (
            "neither magic",
            b"not a codestream".to_vec(),
            Default,
            Codestream,
        ),
        (
            "signature box wrong payload",
            {
                let mut bytes = minimal();
                bytes[11] = 0x0B;
                bytes
            },
            Default,
            FileFormat,
        ),
        (
            "signature box wrong length",
            [
                bx(b"jP  ", &[0x0D, 0x0A, 0x87, 0x0A, 0]),
                jp2_ftyp(),
                good_jp2h(),
                jp2c(),
            ]
            .concat(),
            Default,
            FileFormat,
        ),
        (
            "ftyp missing",
            file(&[good_jp2h(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "ftyp not second",
            file(&[good_jp2h(), jp2_ftyp(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "no jp2 in brand or compatibility list",
            file(&[ftyp(b"jpx ", &[b"jpx "]), good_jp2h(), jp2c()]),
            Default,
            Unsupported,
        ),
        (
            "box length < 8",
            file(&[jp2_ftyp(), header_only(5, b"zzzz"), good_jp2h(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "XLBox < 16",
            file(&[jp2_ftyp(), xl_header_only(15, b"zzzz"), good_jp2h(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "box runs past its parent",
            file(&[
                jp2_ftyp(),
                bx(b"jp2h", &[good_ihdr(), header_only(100, b"colr")].concat()),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "box runs past the file",
            [file(&[jp2_ftyp(), good_jp2h()]), header_only(100, b"xml ")].concat(),
            Default,
            FileFormat,
        ),
        (
            "jp2c runs past the end of the file",
            [
                file(&[jp2_ftyp(), good_jp2h()]),
                header_only(u32::try_from(CODESTREAM.len() + 100).unwrap(), b"jp2c"),
                CODESTREAM.to_vec(),
            ]
            .concat(),
            Default,
            Decodes,
        ),
        (
            "jp2c with LBox 2..7",
            with_jp2c_length(3, &[]),
            Default,
            Decodes,
        ),
        (
            "jp2c with XLBox < 16",
            [
                file(&[jp2_ftyp(), good_jp2h()]),
                xl_header_only(8, b"jp2c"),
                CODESTREAM.to_vec(),
            ]
            .concat(),
            Default,
            Decodes,
        ),
        (
            "jp2c with LBox >= 8 but shorter than its codestream",
            with_jp2c_length(108, &[]),
            Default,
            Decodes,
        ),
        (
            "LBox = 0 on a box that is not last",
            file(&[jp2_ftyp(), open_box(b"xml ", b""), good_jp2h(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "LBox = 0 on the last box, jp2c",
            file(&[jp2_ftyp(), good_jp2h(), open_box(b"jp2c", CODESTREAM)]),
            Default,
            Decodes,
        ),
        (
            "XLBox >= 2^32 on a box other than jp2c",
            [
                file(&[jp2_ftyp(), good_jp2h()]),
                xl_header_only(1 << 40, b"xml "),
            ]
            .concat(),
            Default,
            FileFormat,
        ),
        (
            "XLBox >= 2^32 on jp2c",
            [
                file(&[jp2_ftyp(), good_jp2h()]),
                xl_header_only(1 << 40, b"jp2c"),
                CODESTREAM.to_vec(),
            ]
            .concat(),
            Default,
            Decodes,
        ),
        (
            "jp2h missing",
            file(&[jp2_ftyp(), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "second jp2h before jp2c",
            file(&[jp2_ftyp(), good_jp2h(), jp2h(&[good_ihdr()]), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "jp2c before jp2h",
            file(&[jp2_ftyp(), jp2c(), good_jp2h()]),
            Default,
            FileFormat,
        ),
        (
            "ihdr missing",
            file(&[jp2_ftyp(), jp2h(&[colr()]), jp2c()]),
            Default,
            FileFormat,
        ),
        (
            "ihdr not 14 bytes",
            file(&[
                jp2_ftyp(),
                jp2h(&[bx(b"ihdr", &ihdr_payload[..13]), colr()]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "ihdr not first in jp2h",
            file(&[jp2_ftyp(), jp2h(&[colr(), good_ihdr()]), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "ihdr W/H != SIZ image area",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, WIDTH + 1, COMPONENTS), colr()]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "ihdr.NC != Csiz",
            file(&[jp2_ftyp(), jp2h(&[ihdr(HEIGHT, WIDTH, 2), colr()]), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "ihdr width of 0",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, 0, COMPONENTS), colr()]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "ihdr NC > 16384",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, WIDTH, 16385), colr()]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "ihdr.BPC or bpcc disagree with SIZ depth",
            children(&[bx(b"bpcc", &[15, 15, 15])]),
            Default,
            Decodes,
        ),
        (
            "second ihdr",
            children(&[bx(b"ihdr", &[0])]),
            Default,
            Decodes,
        ),
        (
            "second colr",
            children(&[bx(b"colr", &[1, 0, 0, 0, 0, 0, 17])]),
            Default,
            Decodes,
        ),
        (
            "colr METH other than 1 or 2",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[3, 0, 0]), colr()]),
                jp2c(),
            ]),
            Default,
            Decodes,
        ),
        (
            "colr under 3 bytes",
            children(&[bx(b"colr", &[1, 0])]),
            Default,
            FileFormat,
        ),
        (
            "colr METH 1 under 7 bytes",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[1, 0, 0, 0])]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "colr METH 2 with no profile",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[2, 0, 0])]),
                jp2c(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "colr METH 1 with bytes past EnumCS",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[1, 0, 0, 0, 0, 0, 16, 9])]),
                jp2c(),
            ]),
            Default,
            Decodes,
        ),
        (
            "bpcc not NC bytes",
            children(&[bx(b"bpcc", &[7, 7])]),
            Default,
            FileFormat,
        ),
        (
            "ihdr.UnkC = 1 with a colr",
            file(&[
                jp2_ftyp(),
                jp2h(&[
                    bx(b"ihdr", &[ihdr_payload[..12].to_vec(), vec![1, 0]].concat()),
                    colr(),
                ]),
                jp2c(),
            ]),
            Default,
            Decodes,
        ),
        (
            "no colr at all",
            file(&[jp2_ftyp(), jp2h(&[good_ihdr()]), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "colr METH 2 with too few bytes for a profile header",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[2, 0, 0, 1, 2, 3])]),
                jp2c(),
            ]),
            Default,
            Decodes,
        ),
        (
            "colr METH 2 with too few bytes for a profile header, sRGB output",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &[2, 0, 0, 1, 2, 3])]),
                jp2c(),
            ]),
            Srgb,
            Decodes,
        ),
        (
            "an ICC profile lcms will not open, sRGB output",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), bx(b"colr", &unopenable_profile())]),
                jp2c(),
            ]),
            Srgb,
            Decodes,
        ),
        (
            "pclr NE = 0",
            children(&[bx(b"pclr", &[0, 0, 3, 7, 7, 7]), cmap_box()]),
            Default,
            FileFormat,
        ),
        (
            "pclr claiming 1024 x 255 entries in a 40-byte box",
            children(&[
                bx(b"pclr", &[[4, 0, 255].as_slice(), &[7; 37]].concat()),
                cmap_box(),
            ]),
            Default,
            FileFormat,
        ),
        (
            "cmap without pclr",
            children(&[cmap_box()]),
            Default,
            FileFormat,
        ),
        (
            "cmap before pclr",
            children(&[cmap_box(), pclr_box()]),
            Default,
            FileFormat,
        ),
        (
            "cmap shorter than 4 * NPC bytes",
            children(&[pclr_box(), cmap(&[(0, 1, 0), (0, 1, 1)])]),
            Default,
            FileFormat,
        ),
        (
            "cmap longer than 4 * NPC bytes",
            children(&[pclr_box(), [cmap_box(), vec![0; 4]].concat()]),
            Default,
            FileFormat,
        ),
        (
            "pclr without cmap",
            children(&[pclr_box()]),
            Default,
            Decodes,
        ),
        (
            "cmap CMP >= Csiz",
            children(&[pclr_box(), cmap(&[(0, 1, 0), (0, 1, 1), (3, 1, 2)])]),
            Default,
            FileFormat,
        ),
        (
            "cmap palette column mapped twice",
            children(&[pclr_box(), cmap(&[(0, 1, 0), (0, 1, 0), (0, 1, 2)])]),
            Default,
            FileFormat,
        ),
        (
            "cmap with MTYP 1 && PCOL != i",
            children(&[pclr_box(), cmap(&[(0, 1, 1), (0, 1, 0), (0, 1, 2)])]),
            Default,
            Unsupported,
        ),
        (
            "one component, cmap leaves a column unused",
            one_component(&[pclr_box(), cmap(&[(0, 1, 0), (0, 0, 0), (0, 1, 2)])], &[]),
            Default,
            Decodes,
        ),
        (
            "direct channel i",
            children(&[pclr_box(), cmap(&[(0, 1, 0), (1, 0, 0), (0, 1, 2)])]),
            Default,
            Decodes,
        ),
        (
            "palette column deeper than the i32 container",
            children(&[one_entry_pclr(&[31, 7, 7]), cmap_box()]),
            Default,
            Unsupported,
        ),
        (
            "palette column deeper than the i32 container, raw channels",
            children(&[one_entry_pclr(&[31, 7, 7]), cmap_box()]),
            Raw,
            Decodes,
        ),
        (
            "palette and direct channels of different sub-sampling",
            SUBSAMPLED_PALETTE.to_vec(),
            Default,
            Decodes,
        ),
        (
            "signed palette column",
            children(&[one_entry_pclr(&[0x87, 7, 7]), cmap_box()]),
            Default,
            Decodes,
        ),
        (
            "palette index out of range",
            CLAMPED_PALETTE.to_vec(),
            Default,
            Decodes,
        ),
        (
            "second pclr",
            children(&[pclr_box(), pclr_box(), cmap_box()]),
            Default,
            FileFormat,
        ),
        (
            "second cdef",
            children(&[identity_cdef(), identity_cdef()]),
            Default,
            FileFormat,
        ),
        (
            "cdef N = 0",
            children(&[bx(b"cdef", &[0, 0])]),
            Default,
            FileFormat,
        ),
        (
            "cdef indices at 65535",
            children(&[cdef(&[(65535, 0, 65535), (1, 0, 2), (2, 0, 3)])]),
            Default,
            FileFormat,
        ),
        (
            "cdef indices at 65535, raw channels (layout only)",
            children(&[cdef(&[(65535, 0, 65535), (1, 0, 2), (2, 0, 3)])]),
            Raw,
            Decodes,
        ),
        (
            "cdef incomplete list",
            children(&[cdef(&[(0, 0, 1), (1, 0, 2)])]),
            Default,
            FileFormat,
        ),
        (
            "cdef names a channel twice, every channel named",
            children(&[cdef(&[(0, 0, 1), (1, 0, 2), (2, 0, 3), (0, 1, 0)])]),
            Default,
            Decodes,
        ),
        (
            "cdef color entry not at Asoc - 1",
            children(&[cdef(&[(0, 0, 3), (1, 0, 2), (2, 0, 1)])]),
            Default,
            Decodes,
        ),
        (
            "cdef Typ not 0/1/2/65535",
            children(&[cdef(&[(0, 0, 1), (1, 0, 2), (2, 7, 0)])]),
            Default,
            Decodes,
        ),
        (
            "unknown box anywhere",
            file(&[
                jp2_ftyp(),
                bx(b"zzzz", b"?"),
                jp2h(&[good_ihdr(), bx(b"zzzz", b"?"), colr()]),
                jp2c(),
                bx(b"zzzz", b"?"),
            ]),
            Default,
            Decodes,
        ),
        (
            "10 000 unknown boxes before jp2h and after jp2c",
            file(&[
                jp2_ftyp(),
                unknown_boxes(10_000),
                good_jp2h(),
                jp2c(),
                unknown_boxes(10_000),
            ]),
            Default,
            Decodes,
        ),
        (
            "res malformed",
            children(&[bx(
                b"res ",
                &[header_only(3, b"resc"), vec![0; 10]].concat(),
            )]),
            Default,
            Decodes,
        ),
        (
            "resc with a zero denominator",
            children(&[bx(b"res ", &bx(b"resc", &[0, 1, 0, 0, 0, 1, 0, 0, 0, 0]))]),
            Default,
            Decodes,
        ),
        (
            "uuid shorter than its identifier",
            file(&[jp2_ftyp(), bx(b"uuid", b"short"), good_jp2h(), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "xml/uuid after jp2c",
            after(&[bx(b"xml ", b"<a/>"), bx(b"uuid", &[0; 20])]),
            Default,
            Decodes,
        ),
        (
            "jp2i and uinf before and after jp2c",
            file(&[
                jp2_ftyp(),
                bx(b"jp2i", b"rights"),
                good_jp2h(),
                uuid_info(&[0, 0]),
                jp2c(),
                bx(b"jp2i", b""),
                uuid_info(&[0, 1, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]),
            ]),
            Default,
            Decodes,
        ),
        (
            "uinf malformed: not one ulst and one url, NU not the ulst length, url under 4 bytes, a bad child box",
            file(&[jp2_ftyp(), good_jp2h(), uuid_info(&[0, 1]), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "malformed uinf after jp2c (skipped)",
            after(&[bx(b"uinf", &bx(b"url ", &[0; 4]))]),
            Default,
            Decodes,
        ),
        (
            "ihdr W/H wrong and the codestream truncated",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, WIDTH + 1, COMPONENTS), colr()]),
                bx(b"jp2c", truncated),
            ]),
            Default,
            FileFormat,
        ),
        (
            "header boxes at the top level after jp2h",
            file(&[jp2_ftyp(), good_jp2h(), identity_cdef(), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "the same boxes at the top level before jp2h",
            file(&[jp2_ftyp(), bx(b"cdef", &[0, 0]), good_jp2h(), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "boxes after jp2c: LBox 2..7",
            after(&[header_only(5, b"junk")]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: XLBox < 16",
            after(&[xl_header_only(15, b"junk")]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: fewer than 8 bytes, LBox 0, a box past the end",
            after(&[open_box(b"junk", b"?")]),
            Default,
            Decodes,
        ),
        (
            "boxes after jp2c: a known header box past the end of the file",
            after(&[header_only(100, b"cdef")]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a second signature",
            after(&[SIGNATURE.to_vec()]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: an empty jp2h",
            after(&[jp2h(&[])]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a short colr",
            after(&[bx(b"colr", &[1])]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a wrong-length bpcc",
            after(&[bx(b"bpcc", &[7])]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a short METH 1 with no usable colr before it",
            no_color_then(&[bx(b"colr", &[1, 0, 0])]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a cmap without pclr",
            after(&[cmap_box()]),
            Default,
            FileFormat,
        ),
        (
            "boxes after jp2c: a second cdef, raw channels",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), colr(), identity_cdef()]),
                jp2c(),
                identity_cdef(),
            ]),
            Raw,
            FileFormat,
        ),
        (
            "boxes after jp2c: a second cdef after an applied one",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), colr(), identity_cdef()]),
                jp2c(),
                identity_cdef(),
            ]),
            Default,
            Decodes,
        ),
        (
            "boxes after jp2c: anything after a Psot = 0 codestream",
            [
                file(&[
                    jp2_ftyp(),
                    good_jp2h(),
                    bx(b"jp2c", &psot_zero_codestream()),
                ]),
                header_only(3, b"junk"),
            ]
            .concat(),
            Default,
            Decodes,
        ),
        (
            "second jp2c",
            after(&[bx(b"jp2c", b"not a codestream")]),
            Default,
            Decodes,
        ),
        (
            "deeply nested superboxes",
            file(&[jp2_ftyp(), nested_asoc(2_000), good_jp2h(), jp2c()]),
            Default,
            Decodes,
        ),
        (
            "palette expansion over the sample budget",
            palette_over_budget(),
            Default,
            Limit,
        ),
    ];
    let rows: Vec<(String, Vec<u8>, Mode, Outcome)> = rows
        .into_iter()
        .map(|(what, bytes, mode, want)| (what.to_string(), bytes, mode, want))
        .chain(
            open_last_part_shapes()
                .into_iter()
                .enumerate()
                .map(|(index, (what, bytes))| {
                    let what = format!("Psot = 0 then more bytes: {what}");
                    let want = if index == 0 { Decodes } else { Codestream };
                    (what, bytes, Default, want)
                }),
        )
        .collect();
    let mut wrong = Vec::new();
    for (what, bytes, mode, want) in &rows {
        let got = outcome(match mode {
            Mode::Default => decode(bytes),
            Mode::Raw => decode_raw(bytes),
            Mode::Srgb => decode_with(
                bytes,
                &DecodeOptions::default().with_color(ColorOutput::Srgb),
            ),
        });
        if got != *want {
            wrong.push(format!("{what} ({mode:?}): expected {want:?}, got {got:?}"));
        }
    }
    assert!(
        wrong.is_empty(),
        "rows off the table:\n{}",
        wrong.join("\n")
    );
}

/// The `Psot = 0` rows fail on the bytes past the last packet, and without
/// the trailing bytes the split codestream decodes. So does the codestream
/// with no `EOC` in a right-sized box.
#[test]
fn an_open_last_tile_part_fails_only_on_the_bytes_after_its_packets() {
    for (what, bytes) in open_last_part_then_more() {
        match decode(&bytes) {
            Err(Error::Codestream(message)) => assert!(
                message.contains("left after the last packet"),
                "{what}: {message}"
            ),
            other => panic!("{what}: expected Codestream, got {other:?}"),
        }
    }
    let two_parts = file(&[jp2_ftyp(), good_jp2h(), bx(b"jp2c", &two_parts_last_open())]);
    assert_eq!(
        decode(&two_parts).expect("decodes").components,
        raw().components
    );
    // A right-sized box: the codestream ends at its end, and the `xml ` box
    // after it is reported by both calls.
    let (what, right_sized) = open_last_part_shapes().swap_remove(0);
    let image = decode(&right_sized).unwrap_or_else(|e| panic!("{what}: {e}"));
    assert_eq!(image.components, raw().components, "{what}");
    let metadata = image.jp2.expect("a JP2 file");
    assert_eq!(xml_payloads(&metadata), [b"<a>hello</a>"], "{what}");
    assert_eq!(
        read_header(&right_sized).unwrap().jp2,
        Some(metadata),
        "{what}"
    );
}

/// `read_header_with` fails exactly when `decode_with` does, under the same
/// options. Two shapes where the options decide (the #182 critique): a
/// palette channel that looks up another column is checked unless
/// `raw_channels` asks for the index plane, and a palette's expansion fits the
/// sample limit only once a resolution reduction shrinks the image.
#[test]
fn read_header_with_agrees_with_decode_with_under_the_same_options() {
    use crate::{DecodeOptions, read_header, read_header_with};

    // Palette channel 0 looks up column 1.
    let other_column = children(&[pclr_box(), cmap(&[(0, 1, 1), (0, 1, 0), (0, 1, 2)])]);
    let raw = DecodeOptions::default().with_raw_channels(true);
    assert!(matches!(
        read_header(&other_column),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(decode(&other_column), Err(Error::Unsupported(_))));
    let header = read_header_with(&other_column, &raw).expect("raw channels skips the mapping");
    let image = decode_with(&other_column, &raw).expect("decodes raw");
    assert_eq!((header.width, header.height), (image.width, image.height));
    assert_eq!(header.components.len(), image.components.len());
    assert_eq!(header.jp2, image.jp2);

    // A real 2048x2048 flat image behind a 255-column palette: 255 * 2^22
    // samples over the 2^28 limit, 255 * 2^18 under it at reduction 2.
    let flat = include_bytes!("../../../tests/fixtures/budget/flat_2048_lossless.j2k");
    let big = palette_255_over(flat);
    let reduced = DecodeOptions::default().with_resolution_reduction(2);
    assert!(matches!(read_header(&big), Err(Error::Limit(_))));
    assert!(matches!(decode(&big), Err(Error::Limit(_))));
    // 255 * 2^22 is 3.98 times 2^28, so `Raised(4)` admits the expansion
    // (`Raised(3)` does not); the header is all this test reads at full size.
    let raised = |n| DecodeOptions::default().with_sample_limit(crate::WorkLimit::Raised(n));
    assert!(matches!(
        read_header_with(&big, &raised(3)),
        Err(Error::Limit(_))
    ));
    let header = read_header_with(&big, &raised(4)).expect("fits a raised limit");
    assert_eq!(header.components.len(), 255);
    let header = read_header_with(&big, &reduced).expect("fits once reduced");
    assert_eq!((header.width, header.height), (512, 512));
    assert_eq!(header.components.len(), 255);
    let image = decode_with(&big, &reduced).expect("decodes reduced");
    assert_eq!((image.width, image.height), (512, 512));
    assert_eq!(image.components.len(), 255);
    assert_eq!(header.jp2, image.jp2);
}

/// Options that contradict each other, and an sRGB request on a raw
/// codestream with no color space, fail in `read_header_with` as in
/// `decode_with`.
#[test]
fn read_header_with_refuses_the_options_decode_with_refuses() {
    use crate::{ColorOutput, DecodeOptions, read_header_with};

    let both = DecodeOptions::default()
        .with_raw_channels(true)
        .with_color(ColorOutput::Srgb);
    let srgb = DecodeOptions::default().with_color(ColorOutput::Srgb);
    let three = include_bytes!("../../../tests/fixtures/multicomponent_lossless.j2k");
    for bytes in [&minimal(), &three[..]] {
        assert!(matches!(
            read_header_with(bytes, &both),
            Err(Error::InvalidOptions(_))
        ));
        assert!(matches!(
            decode_with(bytes, &both),
            Err(Error::InvalidOptions(_))
        ));
    }
    assert!(matches!(
        read_header_with(three, &srgb),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(
        decode_with(three, &srgb),
        Err(Error::Unsupported(_))
    ));
    // The refusal is a header fault, so a cut tile does not hide it (found by
    // the `header` fuzz target).
    let cut = &three[..three.len() - 40];
    assert!(matches!(
        read_header_with(cut, &srgb),
        Err(Error::Unsupported(_))
    ));
    assert!(matches!(
        decode_with(cut, &srgb),
        Err(Error::Unsupported(_))
    ));
}