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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
//! JP2 box-layer tests: what decodes, and the typed error for every malformed
//! or unsupported box shape. Each test goes through the public [`decode`], so
//! the container sniffing and the glue are under test too.
//!
//! The codestream is a committed lossless fixture (24x16, three 8-bit
//! components); the boxes around it are built here byte by byte.

use super::SIGNATURE;
use crate::{
    Association, ChannelDefinition, ChannelType, ColorSpace, ColorSpecification, DecodeOptions,
    Error, FileType, Image, ImageHeader, Jp2Metadata, Ratio, Res, Resolution, UuidBox, XmlBox,
    decode, decode_with, read_header,
};

mod after;
mod channels;
mod matrix;
mod palette;
mod rreq;
mod uuid_info;

const CODESTREAM: &[u8] = include_bytes!("../../tests/fixtures/multicomponent_lossless.j2k");
const WIDTH: u32 = 24;
const HEIGHT: u32 = 16;
const COMPONENTS: u16 = 3;

/// A box with a 32-bit `LBox`.
fn bx(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let length = u32::try_from(8 + payload.len()).expect("test box fits LBox");
    let mut out = length.to_be_bytes().to_vec();
    out.extend_from_slice(kind);
    out.extend_from_slice(payload);
    out
}

/// A box with `LBox = 1` and a 64-bit `XLBox`.
fn xl_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let mut out = 1u32.to_be_bytes().to_vec();
    out.extend_from_slice(kind);
    out.extend_from_slice(&(16 + payload.len() as u64).to_be_bytes());
    out.extend_from_slice(payload);
    out
}

/// A box with `LBox = 0`: it runs to the end of the file.
fn open_box(kind: &[u8; 4], payload: &[u8]) -> Vec<u8> {
    let mut out = 0u32.to_be_bytes().to_vec();
    out.extend_from_slice(kind);
    out.extend_from_slice(payload);
    out
}

/// A box header claiming `lbox` bytes, with no contents after it.
fn header_only(lbox: u32, kind: &[u8; 4]) -> Vec<u8> {
    let mut out = lbox.to_be_bytes().to_vec();
    out.extend_from_slice(kind);
    out
}

/// A box header with `LBox = 1` and the given `XLBox`, with no contents.
fn xl_header_only(xlbox: u64, kind: &[u8; 4]) -> Vec<u8> {
    let mut out = header_only(1, kind);
    out.extend_from_slice(&xlbox.to_be_bytes());
    out
}

fn ftyp(brand: &[u8; 4], compatible: &[&[u8; 4]]) -> Vec<u8> {
    let mut payload = brand.to_vec();
    payload.extend_from_slice(&0u32.to_be_bytes()); // MinV
    for code in compatible {
        payload.extend_from_slice(*code);
    }
    bx(b"ftyp", &payload)
}

fn jp2_ftyp() -> Vec<u8> {
    ftyp(b"jp2 ", &[b"jp2 "])
}

fn ihdr(height: u32, width: u32, components: u16) -> Vec<u8> {
    let mut payload = height.to_be_bytes().to_vec();
    payload.extend_from_slice(&width.to_be_bytes());
    payload.extend_from_slice(&components.to_be_bytes());
    payload.extend_from_slice(&[7, 7, 0, 0]); // BPC 8-bit unsigned, C, UnkC, IPR
    bx(b"ihdr", &payload)
}

fn good_ihdr() -> Vec<u8> {
    ihdr(HEIGHT, WIDTH, COMPONENTS)
}

/// An enumerated sRGB color specification.
fn colr() -> Vec<u8> {
    bx(b"colr", &[1, 0, 0, 0, 0, 0, 16])
}

fn jp2h(children: &[Vec<u8>]) -> Vec<u8> {
    bx(b"jp2h", &children.concat())
}

fn good_jp2h() -> Vec<u8> {
    jp2h(&[good_ihdr(), colr()])
}

fn jp2c() -> Vec<u8> {
    bx(b"jp2c", CODESTREAM)
}

/// The signature box followed by `boxes`.
fn file(boxes: &[Vec<u8>]) -> Vec<u8> {
    let mut out = SIGNATURE.to_vec();
    out.extend_from_slice(&boxes.concat());
    out
}

/// The smallest JP2 file: signature, `ftyp`, `jp2h` with `ihdr` + `colr`,
/// `jp2c`.
fn minimal() -> Vec<u8> {
    file(&[jp2_ftyp(), good_jp2h(), jp2c()])
}

/// What `decode` gives for the bare codestream.
fn raw() -> Image {
    decode(CODESTREAM).expect("the fixture codestream decodes")
}

/// Assert `bytes` decode to the bare codestream's components, with the
/// metadata a JP2 file carries today.
#[track_caller]
fn assert_decodes_like_raw(bytes: &[u8]) {
    let image = decode(bytes).unwrap_or_else(|e| panic!("JP2 decode failed: {e}"));
    let raw = raw();
    assert_eq!((image.width, image.height), (raw.width, raw.height));
    assert_eq!(image.components, raw.components);
    assert!(image.jp2.is_some(), "a JP2 file carries metadata");
}

#[track_caller]
fn file_format(bytes: &[u8], fragment: &str) {
    match decode(bytes) {
        Err(Error::FileFormat(message)) => assert!(
            message.contains(fragment),
            "expected a FileFormat error mentioning {fragment:?}, got {message:?}"
        ),
        other => panic!("expected FileFormat mentioning {fragment:?}, got {other:?}"),
    }
}

#[track_caller]
fn unsupported(bytes: &[u8], fragment: &str) {
    match decode(bytes) {
        Err(Error::Unsupported(message)) => assert!(
            message.contains(fragment),
            "expected an Unsupported error mentioning {fragment:?}, got {message:?}"
        ),
        other => panic!("expected Unsupported mentioning {fragment:?}, got {other:?}"),
    }
}

/// The payloads of a file's `xml ` boxes, in order.
fn xml_payloads(metadata: &Jp2Metadata) -> Vec<&[u8]> {
    metadata.xml.iter().map(|x| x.payload.as_slice()).collect()
}

#[test]
fn the_fixture_is_what_the_tests_assume() {
    let raw = raw();
    assert_eq!((raw.width, raw.height), (WIDTH, HEIGHT));
    assert_eq!(raw.components.len(), usize::from(COMPONENTS));
    assert_eq!(raw.jp2, None, "a raw codestream carries no JP2 metadata");
}

#[test]
fn a_minimal_jp2_decodes_to_its_codestream() {
    assert_decodes_like_raw(&minimal());
}

/// The skeleton every JP2 decode carries without `cdef` or `pclr`: the color
/// space from `colr`, one color channel per component, no palette.
#[test]
fn a_jp2_decode_carries_the_metadata_skeleton() {
    let image = decode(&minimal()).expect("decodes");
    let color = |n| ChannelDefinition {
        kind: ChannelType::Color,
        association: Association::Color(n),
    };
    assert_eq!(
        image.jp2,
        Some(Jp2Metadata {
            color: ColorSpace::Srgb,
            channels: vec![color(1), color(2), color(3)],
            palette_applied: false,
            palette: None,
            channel_mapping: None,
            channel_definitions: None,
            resolution: Resolution::default(),
            xml: Vec::new(),
            uuid: Vec::new(),
            ipr: Vec::new(),
            uuid_info: Vec::new(),
            image_header: ImageHeader {
                compression: 7,
                unknown_color_space: 0,
                ipr_flag: 0,
            },
            color_specifications: vec![ColorSpecification {
                method: 1,
                precedence: 0,
                approximation: 0,
                payload: vec![0, 0, 0, 16],
            }],
            file_type: FileType {
                brand: *b"jp2 ",
                minor_version: 0,
                compatibility: vec![*b"jp2 "],
            },
            reader_requirements: None,
        })
    );
}

#[test]
fn a_jp2c_with_a_64_bit_length_decodes() {
    assert_decodes_like_raw(&file(&[
        jp2_ftyp(),
        good_jp2h(),
        xl_box(b"jp2c", CODESTREAM),
    ]));
}

/// `ihdr` is checked against the full-resolution image area, so a reduced
/// decode of a JP2 file works and equals the reduced codestream decode.
#[test]
fn a_reduced_decode_of_a_jp2_matches_its_codestream() {
    let options = DecodeOptions::default().with_resolution_reduction(1);
    let file = decode_with(&minimal(), &options).expect("reduced JP2 decode");
    let raw = decode_with(CODESTREAM, &options).expect("reduced codestream decode");
    assert_eq!((file.width, file.height), (raw.width, raw.height));
    assert_eq!((file.width, file.height), (WIDTH / 2, HEIGHT / 2));
    assert_eq!(file.components, raw.components);
    assert!(file.jp2.is_some());
}

#[test]
fn a_last_jp2c_with_length_zero_decodes() {
    assert_decodes_like_raw(&file(&[
        jp2_ftyp(),
        good_jp2h(),
        open_box(b"jp2c", CODESTREAM),
    ]));
}

/// Unknown boxes are skipped at the top level and inside `jp2h`, a 64-bit
/// length on another box is read, and a second `ihdr` is ignored.
#[test]
fn unknown_and_repeated_boxes_are_skipped() {
    assert_decodes_like_raw(&file(&[
        jp2_ftyp(),
        bx(b"xml ", b"<a/>"),
        xl_box(b"uuid", &[0; 20]),
        jp2h(&[good_ihdr(), bx(b"zzzz", b"unknown"), colr(), ihdr(1, 1, 1)]),
        bx(b"xml ", b"<b/>"),
        jp2c(),
    ]));
}

/// Only the first `jp2c` is the codestream (I.5.4). OpenJPEG then walks what
/// follows it and accepts anything it cannot follow, so these all decode
/// (each measured with `opj_decompress` 2.5.0, which warns at most).
#[test]
fn bytes_after_the_codestream_that_openjpeg_accepts_decode() {
    let tails: Vec<(&str, Vec<u8>)> = vec![
        ("a second jp2c", bx(b"jp2c", b"not a codestream")),
        (
            "a bad length after a second jp2c, which ends the walk",
            [bx(b"jp2c", b"zz"), header_only(3, b"junk")].concat(),
        ),
        ("a box past the end of the file", header_only(100, b"junk")),
        (
            "a bad length after a box past the end",
            [header_only(100, b"junk"), header_only(3, b"junk")].concat(),
        ),
        ("ASCII text", b"hello, trailing text\n".to_vec()),
        ("three bytes", b"abc".to_vec()),
        ("seven zero bytes", vec![0; 7]),
        ("sixteen zero bytes (LBox 0)", vec![0; 16]),
        ("LBox 0", [header_only(0, b"junk"), b"zz".to_vec()].concat()),
        (
            "a truncated XLBox field",
            [header_only(1, b"junk"), vec![0; 3]].concat(),
        ),
        ("a well-formed box", bx(b"xml ", b"<after/>")),
    ];
    for (what, tail) in tails {
        let mut bytes = minimal();
        bytes.extend_from_slice(&tail);
        let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
        assert_eq!(image.components, raw().components, "{what}");
    }
}

/// The two faults OpenJPEG does reject after the codestream: a box whose
/// `LBox` is 2..=7, or whose `XLBox` is below 16, wherever the walk reaches it.
#[test]
fn a_short_box_length_after_the_codestream_is_rejected() {
    for lbox in 2..=7 {
        let mut bytes = minimal();
        bytes.extend_from_slice(&header_only(lbox, b"junk"));
        file_format(&bytes, "after the codestream has length");
    }
    for xlbox in [0, 8, 15] {
        let mut bytes = minimal();
        bytes.extend_from_slice(&xl_header_only(xlbox, b"junk"));
        file_format(&bytes, "after the codestream has `XLBox`");
    }
    // Reached after well-formed boxes of both length forms.
    let mut bytes = minimal();
    bytes.extend_from_slice(&bx(b"xml ", b"<a/>"));
    bytes.extend_from_slice(&xl_box(b"uuid", &[0; 8]));
    bytes.extend_from_slice(&header_only(3, b"junk"));
    file_format(&bytes, "after the codestream has length 3");
}

/// A JPX-branded file that lists `jp2 ` as compatible is read; so is a `jp2 `
/// brand with an empty compatibility list.
#[test]
fn jp2_compatibility_in_brand_or_list_is_enough() {
    assert_decodes_like_raw(&file(&[
        ftyp(b"jpx ", &[b"jpx ", b"jp2 "]),
        good_jp2h(),
        jp2c(),
    ]));
    assert_decodes_like_raw(&file(&[ftyp(b"jp2 ", &[]), good_jp2h(), jp2c()]));
}

#[test]
fn a_jpx_without_jp2_compatibility_is_unsupported() {
    unsupported(
        &file(&[ftyp(b"jpx ", &[b"jpx ", b"jpxb"]), good_jp2h(), jp2c()]),
        "without `jp2 ` compatibility",
    );
}

/// A palette in `jp2h` is applied: one channel per `cmap` entry.
#[test]
fn a_palette_box_decodes() {
    let image = decode(&file(&[
        jp2_ftyp(),
        jp2h(&[
            good_ihdr(),
            palette::pclr_box(),
            colr(),
            palette::cmap_box(),
        ]),
        jp2c(),
    ]))
    .expect("a palettized file decodes");
    palette::assert_palette_applied(&image);
}

/// A `pclr` without a `cmap` is ignored (I.5.3.4: both or neither), as
/// OpenJPEG does.
#[test]
fn a_palette_box_without_a_component_mapping_box_is_ignored() {
    let bytes = file(&[
        jp2_ftyp(),
        jp2h(&[good_ihdr(), colr(), palette::pclr_box()]),
        jp2c(),
    ]);
    assert_decodes_like_raw(&bytes);
    assert!(!decode(&bytes).unwrap().jp2.unwrap().palette_applied);
}

/// A channel definition box is applied: file2's layout (components 0, 1, 2
/// are colors 3, 2, 1) comes out in color order.
#[test]
fn a_channel_definition_box_is_applied() {
    let bytes = file(&[
        jp2_ftyp(),
        jp2h(&[good_ihdr(), colr(), channels::reversed()]),
        jp2c(),
    ]);
    channels::assert_reversed(&decode(&bytes).expect("decodes"));
}

/// A box whose length is shorter than its own 8-byte header, for every such
/// length.
#[test]
fn a_box_length_of_1_to_7_is_rejected() {
    for lbox in 2..=7 {
        let bytes = file(&[jp2_ftyp(), header_only(lbox, b"zzzz"), good_jp2h(), jp2c()]);
        file_format(&bytes, "shorter than its 8-byte header");
    }
    // `LBox = 1` announces an `XLBox`; with the file ending first, the field is
    // truncated.
    let mut truncated = file(&[jp2_ftyp(), good_jp2h()]);
    truncated.extend_from_slice(&header_only(1, b"jp2c"));
    truncated.extend_from_slice(&[0, 0, 0]);
    file_format(&truncated, "`XLBox` field is truncated");
}

#[test]
fn an_xlbox_of_zero_or_past_the_end_is_rejected() {
    for xlbox in [0, 8, 15] {
        let bytes = file(&[
            jp2_ftyp(),
            xl_header_only(xlbox, b"zzzz"),
            good_jp2h(),
            jp2c(),
        ]);
        file_format(&bytes, "shorter than its 16-byte header");
    }
    // One byte longer than the file, and far past it: both are truncation
    // for any box but the codestream, and nothing is allocated from the length.
    for xlbox in [16 + 4 + 1, 1 << 40, u64::MAX] {
        let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
        bytes.extend_from_slice(&xl_header_only(xlbox, b"xml "));
        bytes.extend_from_slice(b"<a/>");
        file_format(&bytes, "remain in the file");
    }
}

#[test]
fn a_child_box_overrunning_its_superbox_is_rejected() {
    // The `colr` child claims 100 bytes; `jp2h` holds 22 + 15.
    let mut children = good_ihdr();
    children.extend_from_slice(&header_only(100, b"colr"));
    children.extend_from_slice(&colr()[8..]);
    file_format(
        &file(&[jp2_ftyp(), bx(b"jp2h", &children), jp2c()]),
        "remain in the `jp2h` box",
    );
}

/// OpenJPEG reads a codestream to its end whatever its box length says, so a
/// `jp2c` whose `LBox` or `XLBox` runs past the end of the file is clamped to
/// it and decodes.
#[test]
fn a_jp2c_overrunning_the_file_is_clamped_and_decodes() {
    let claimed = u32::try_from(8 + CODESTREAM.len() + 100).unwrap();
    let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
    bytes.extend_from_slice(&header_only(claimed, b"jp2c"));
    bytes.extend_from_slice(CODESTREAM);
    assert_decodes_like_raw(&bytes);

    for xlbox in [16 + CODESTREAM.len() as u64 + 1, 1 << 40, u64::MAX] {
        let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
        bytes.extend_from_slice(&xl_header_only(xlbox, b"jp2c"));
        bytes.extend_from_slice(CODESTREAM);
        assert_decodes_like_raw(&bytes);
    }
}

/// Clamping does not rescue a codestream that is actually cut short: the
/// codestream parser still rejects it.
#[test]
fn a_clamped_jp2c_with_a_truncated_codestream_is_still_rejected() {
    let cut = &CODESTREAM[..CODESTREAM.len() - 40];
    let mut bytes = file(&[jp2_ftyp(), good_jp2h()]);
    bytes.extend_from_slice(&header_only(
        u32::try_from(8 + CODESTREAM.len()).unwrap(),
        b"jp2c",
    ));
    bytes.extend_from_slice(cut);
    assert!(
        matches!(decode(&bytes), Err(Error::Codestream(_))),
        "{:?}",
        decode(&bytes)
    );
}

/// `ihdr` may come anywhere in `jp2h`, as OpenJPEG reads it.
#[test]
fn an_ihdr_after_other_header_boxes_decodes() {
    assert_decodes_like_raw(&file(&[
        jp2_ftyp(),
        jp2h(&[colr(), bx(b"zzzz", b"?"), good_ihdr()]),
        jp2c(),
    ]));
}

/// A second `jp2h` before the codestream is merged into the first, as
/// OpenJPEG does: its `ihdr` is ignored (here it disagrees with SIZ) and its
/// other children are added to the first box's.
#[test]
fn a_second_jp2h_is_merged_into_the_first() {
    let bytes = file(&[
        jp2_ftyp(),
        good_jp2h(),
        jp2h(&[ihdr(1, 1, 1), bx(b"colr", &[1, 0, 0, 0, 0, 0, 17])]),
        jp2c(),
    ]);
    assert_decodes_like_raw(&bytes);
    let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
    assert_eq!(parsed.header.ihdr.width, WIDTH, "the first ihdr wins");
    assert_eq!(parsed.header.colr().len(), 2, "both colr boxes, in order");
    assert_eq!(parsed.header.colr()[0], &colr()[8..]);
}

/// A `cdef` is applied wherever OpenJPEG applies it: in a second `jp2h`, or
/// misplaced at the top level after the first `jp2h` (both measured with
/// `opj_decompress` 2.5.0: the channels come out reversed).
#[test]
fn a_cdef_in_a_second_jp2h_or_after_jp2h_is_applied() {
    let cdef = channels::reversed();
    let in_second_jp2h = file(&[
        jp2_ftyp(),
        good_jp2h(),
        jp2h(&[good_ihdr(), cdef.clone()]),
        jp2c(),
    ]);
    channels::assert_reversed(&decode(&in_second_jp2h).expect("decodes"));
    let after_jp2h = file(&[jp2_ftyp(), good_jp2h(), cdef, jp2c()]);
    channels::assert_reversed(&decode(&after_jp2h).expect("decodes"));
}

/// The palette boxes are applied wherever OpenJPEG applies them: in a second
/// `jp2h`, or misplaced at the top level after the first `jp2h` (each shape
/// measured with `opj_decompress` 2.5.0).
#[test]
fn palette_boxes_in_a_second_jp2h_or_after_jp2h_are_applied() {
    let (pclr, cmap) = (palette::pclr_box(), palette::cmap_box());
    let shapes = [
        (
            "both in a second jp2h",
            file(&[
                jp2_ftyp(),
                good_jp2h(),
                jp2h(&[good_ihdr(), pclr.clone(), cmap.clone()]),
                jp2c(),
            ]),
        ),
        (
            "pclr in jp2h, cmap in a second jp2h",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), colr(), pclr.clone()]),
                jp2h(&[good_ihdr(), cmap.clone()]),
                jp2c(),
            ]),
        ),
        (
            "both after jp2h",
            file(&[jp2_ftyp(), good_jp2h(), pclr.clone(), cmap.clone(), jp2c()]),
        ),
        (
            "pclr in jp2h, cmap after it",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), colr(), pclr.clone()]),
                cmap.clone(),
                jp2c(),
            ]),
        ),
    ];
    for (what, bytes) in shapes {
        let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
        palette::assert_palette_applied(&image);
    }
}

/// Before `jp2h`, OpenJPEG ignores a misplaced header box ("JPEG2000 Header
/// box not read yet ... will be ignored"), so the file decodes as coded.
#[test]
fn header_boxes_misplaced_before_jp2h_are_ignored() {
    let bytes = file(&[
        jp2_ftyp(),
        bx(b"cdef", &[0, 0]),
        bx(b"pclr", &[0; 8]),
        bx(b"cmap", &[0; 4]),
        bx(b"colr", &[1, 0, 0, 0, 0, 0, 17]),
        good_jp2h(),
        jp2c(),
    ]);
    assert_decodes_like_raw(&bytes);
    let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
    assert_eq!(parsed.header.colr(), vec![&colr()[8..]]);
    assert_eq!(parsed.other.len(), 4);
}

/// `color_specifications` holds every `colr` the header reads, in file
/// order: an ignored `METH` 3 box, the first usable one (which alone sets
/// `color`), one in a second `jp2h` and one misplaced after `jp2h`. A `colr`
/// before `jp2h` or after the codestream is not a header box and is left out.
#[test]
fn every_header_colr_is_reported_in_file_order() {
    let colr_with = |head: [u8; 3], data: &[u8]| bx(b"colr", &[&head[..], data].concat());
    let bytes = file(&[
        jp2_ftyp(),
        colr_with([1, 9, 9], &[0, 0, 0, 18]),
        jp2h(&[
            colr_with([3, 1, 2], &[0xAB]),
            good_ihdr(),
            colr_with([1, 0, 0], &[0, 0, 0, 17]),
        ]),
        jp2h(&[good_ihdr(), colr_with([2, 4, 5], b"icc")]),
        colr_with([1, 6, 7], &[0, 0, 0, 21, 0xFF]),
        jp2c(),
        colr_with([1, 8, 8], &[0, 0, 0, 16]),
    ]);
    assert_decodes_like_raw(&bytes);
    let jp2 = decode(&bytes).unwrap().jp2.unwrap();
    assert_eq!(read_header(&bytes).unwrap().jp2.as_ref(), Some(&jp2));
    assert_eq!(jp2.color, ColorSpace::Grayscale);
    let spec = |[method, precedence, approximation]: [u8; 3], payload: &[u8]| ColorSpecification {
        method,
        precedence,
        approximation,
        payload: payload.to_vec(),
    };
    assert_eq!(
        jp2.color_specifications,
        [
            spec([3, 1, 2], &[0xAB]),
            spec([1, 0, 0], &[0, 0, 0, 17]),
            spec([2, 4, 5], b"icc"),
            spec([1, 6, 7], &[0, 0, 0, 21, 0xFF]),
        ]
    );
}

/// A file with a header or codestream fault and a malformed `cdef` reports
/// the first fault: the `cdef` is read after the codestream's main header.
#[test]
fn a_structural_fault_wins_over_a_malformed_cdef() {
    let with_cdef = |ihdr_box: Vec<u8>, stream: &[u8]| {
        file(&[
            jp2_ftyp(),
            jp2h(&[ihdr_box, colr(), bx(b"cdef", &[0, 0])]),
            bx(b"jp2c", stream),
        ])
    };
    file_format(
        &with_cdef(ihdr(1, 1, 1), CODESTREAM),
        "`ihdr` declares a 1x1 image",
    );
    assert!(matches!(
        decode(&with_cdef(good_ihdr(), b"not a codestream")),
        Err(Error::Codestream(_))
    ));
}

/// The JP2 box layer's reject matrix: every malformed box shape, mapped to
/// its typed error and the check that raised it.
#[test]
fn reject_matrix_maps_every_malformed_box_shape_to_its_typed_error() {
    let ihdr_payload = good_ihdr()[8..].to_vec();
    let rows: Vec<(&str, Vec<u8>, &str)> = vec![
        (
            "signature box with the wrong contents",
            {
                let mut bytes = minimal();
                bytes[11] = 0x0B;
                bytes
            },
            "signature box",
        ),
        (
            "signature box one byte too long",
            [
                bx(b"jP  ", &[0x0D, 0x0A, 0x87, 0x0A, 0x00]),
                jp2_ftyp(),
                good_jp2h(),
                jp2c(),
            ]
            .concat(),
            "signature box",
        ),
        (
            "signature box alone",
            SIGNATURE.to_vec(),
            "ends after the signature",
        ),
        (
            "ftyp not second",
            file(&[good_jp2h(), jp2_ftyp(), jp2c()]),
            "`ftyp` box must follow the signature, not `jp2h`",
        ),
        (
            "ftyp too short",
            file(&[bx(b"ftyp", b"jp2 "), good_jp2h(), jp2c()]),
            "`ftyp` box holds 4 bytes",
        ),
        (
            "ftyp with a partial compatibility code",
            file(&[bx(b"ftyp", b"jp2 \0\0\0\0jp2 xx"), good_jp2h(), jp2c()]),
            "`ftyp` box holds 14 bytes",
        ),
        (
            "no jp2h (signature, ftyp, jp2c)",
            file(&[jp2_ftyp(), jp2c()]),
            "no `jp2h` header box before its `jp2c`",
        ),
        (
            "jp2c before jp2h",
            file(&[jp2_ftyp(), jp2c(), good_jp2h()]),
            "no `jp2h` header box before its `jp2c`",
        ),
        ("no jp2c", file(&[jp2_ftyp(), good_jp2h()]), "no `jp2c`"),
        (
            "neither jp2h nor jp2c",
            file(&[jp2_ftyp()]),
            "no `jp2h` header box and no `jp2c`",
        ),
        (
            "empty jp2h",
            file(&[jp2_ftyp(), jp2h(&[]), jp2c()]),
            "`jp2h` box has no `ihdr`",
        ),
        (
            "jp2h without ihdr",
            file(&[jp2_ftyp(), jp2h(&[colr()]), jp2c()]),
            "`jp2h` box has no `ihdr`",
        ),
        (
            "a second jp2h without ihdr",
            file(&[jp2_ftyp(), good_jp2h(), jp2h(&[colr()]), jp2c()]),
            "`jp2h` box has no `ihdr`",
        ),
        (
            "ihdr of 13 bytes",
            file(&[
                jp2_ftyp(),
                jp2h(&[bx(b"ihdr", &ihdr_payload[..13]), colr()]),
                jp2c(),
            ]),
            "`ihdr` box holds 13 bytes",
        ),
        (
            "ihdr of 15 bytes",
            file(&[
                jp2_ftyp(),
                jp2h(&[
                    bx(b"ihdr", &[ihdr_payload.as_slice(), &[0]].concat()),
                    colr(),
                ]),
                jp2c(),
            ]),
            "`ihdr` box holds 15 bytes",
        ),
        (
            "ihdr width differs from SIZ",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, WIDTH + 1, COMPONENTS), colr()]),
                jp2c(),
            ]),
            "`ihdr` declares a 25x16 image",
        ),
        (
            "ihdr height differs from SIZ",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT - 1, WIDTH, COMPONENTS), colr()]),
                jp2c(),
            ]),
            "`ihdr` declares a 24x15 image",
        ),
        (
            "ihdr NC of 0",
            file(&[jp2_ftyp(), jp2h(&[ihdr(HEIGHT, WIDTH, 0), colr()]), jp2c()]),
            "none may be 0",
        ),
        (
            "ihdr width of 0",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, 0, COMPONENTS), colr()]),
                jp2c(),
            ]),
            "none may be 0",
        ),
        (
            "ihdr height of 0",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(0, WIDTH, COMPONENTS), colr()]),
                jp2c(),
            ]),
            "none may be 0",
        ),
        (
            "ihdr NC over 16384",
            file(&[
                jp2_ftyp(),
                jp2h(&[ihdr(HEIGHT, WIDTH, 16385), colr()]),
                jp2c(),
            ]),
            "declares 16385 components",
        ),
        (
            "LBox 0 inside jp2h",
            file(&[
                jp2_ftyp(),
                jp2h(&[good_ihdr(), open_box(b"colr", &colr()[8..])]),
                jp2c(),
            ]),
            "has length 0",
        ),
        (
            "LBox 0 on a box that is not last",
            file(&[jp2_ftyp(), open_box(b"xml ", b""), good_jp2h(), jp2c()]),
            "a box of length 0 (to the end of the file) swallowed the rest",
        ),
        (
            "LBox 2..7 after the codestream",
            [minimal(), header_only(5, b"junk")].concat(),
            "after the codestream has length 5",
        ),
        (
            "XLBox below 16 after the codestream",
            [minimal(), xl_header_only(15, b"junk")].concat(),
            "after the codestream has `XLBox` 15",
        ),
        (
            "a box header cut short before jp2c",
            [file(&[jp2_ftyp(), good_jp2h()]), vec![0, 0, 0]].concat(),
            "a box header needs 8 bytes but 3 remain in the file",
        ),
        (
            "a jp2h child header cut short",
            file(&[jp2_ftyp(), jp2h(&[good_ihdr(), vec![0, 0, 0, 9]]), jp2c()]),
            "a box header needs 8 bytes but 4 remain in the `jp2h` box",
        ),
    ];
    for (what, bytes, fragment) in rows {
        match decode(&bytes) {
            Err(Error::FileFormat(message)) => assert!(
                message.contains(fragment),
                "{what}: expected a message mentioning {fragment:?}, got {message:?}"
            ),
            other => panic!("{what}: expected FileFormat, got {other:?}"),
        }
    }
}

/// Input with neither magic is still the codestream parser's to reject.
#[test]
fn input_with_neither_magic_is_a_codestream_error() {
    for bytes in [&b""[..], b"not a codestream", b"\x00\x00\x00\x0cjP"] {
        assert!(
            matches!(decode(bytes), Err(Error::Codestream(_))),
            "{bytes:?}"
        );
    }
}

/// Every prefix of a valid file, and every single-byte corruption of its box
/// headers, is a typed result: never a panic.
#[test]
fn truncations_and_header_corruptions_never_panic() {
    let bytes = minimal();
    let codestream_at = bytes.len() - CODESTREAM.len();
    for end in 0..bytes.len() {
        let _ = decode(&bytes[..end]);
    }
    for at in 0..codestream_at {
        for value in [0x00, 0x01, 0x07, 0x0F, 0x80, 0xFF] {
            let mut corrupt = bytes.clone();
            corrupt[at] = value;
            let _ = decode(&corrupt);
        }
    }
}

/// The walk keeps what the later header code reads: the `jp2h` children as raw
/// slices in file order, the other top-level boxes before the codestream, and
/// the unread bytes after it.
#[test]
fn the_walk_records_header_boxes_and_the_bytes_around_the_codestream() {
    let trailing = bx(b"xml ", b"<after/>");
    let bytes = file(&[
        jp2_ftyp(),
        bx(b"xml ", b"<before/>"),
        jp2h(&[
            good_ihdr(),
            colr(),
            bx(b"colr", &[3, 0, 0]),
            bx(b"bpcc", &[7, 7, 7]),
            bx(b"res ", &[1, 2]),
            bx(b"zzzz", b"?"),
        ]),
        jp2c(),
        trailing.clone(),
    ]);
    let parsed = super::parse(&bytes, &crate::WorkLimit::Default).expect("parses");
    let header = &parsed.header;
    assert_eq!(
        (
            header.ihdr.height,
            header.ihdr.width,
            header.ihdr.components
        ),
        (HEIGHT, WIDTH, COMPONENTS)
    );
    let first_colr = colr();
    assert_eq!(header.colr(), vec![&first_colr[8..], &[3, 0, 0][..]]);
    assert_eq!(header.bpcc(), vec![&[7, 7, 7][..]]);
    assert_eq!(header.res(), vec![&[1, 2][..]]);
    assert!(header.pclr().is_empty() && header.cmap().is_empty() && header.cdef().is_empty());
    assert_eq!(header.unknown().len(), 1);
    assert_eq!(&header.unknown()[0].kind, b"zzzz");
    assert_eq!(parsed.codestream, CODESTREAM);
    assert_eq!(parsed.other.len(), 1);
    assert_eq!(parsed.other[0].payload, b"<before/>");
    assert_eq!(parsed.after_codestream.len(), 1);
    assert_eq!(&parsed.after_codestream[0].kind, b"xml ");
    assert_eq!(parsed.after_codestream[0].payload, b"<after/>");
}

/// `ihdr.NC` is not held to `Csiz`: the codestream decides the image, as in
/// OpenJPEG 2.5.0 (#164, 2026-11-01). Measured: `opj_decompress`
/// decodes a one-component codestream under an `ihdr` with `NC` 2 or 9. A
/// `bpcc` is still held to `NC`, so it must hold `NC` bytes, not `Csiz`.
#[test]
fn an_ihdr_component_count_unlike_csiz_decodes() {
    for nc in [1, 2, 4, 9, 16384] {
        let bytes = file(&[jp2_ftyp(), jp2h(&[ihdr(HEIGHT, WIDTH, nc), colr()]), jp2c()]);
        assert_decodes_like_raw(&bytes);
        let header = read_header(&bytes).unwrap_or_else(|e| panic!("NC {nc}: {e}"));
        assert_eq!(header.components.len(), usize::from(COMPONENTS), "NC {nc}");
    }
    let with_bpcc = |nc: u16, bytes: usize| {
        file(&[
            jp2_ftyp(),
            jp2h(&[
                ihdr(HEIGHT, WIDTH, nc),
                bx(b"bpcc", &vec![7; bytes]),
                colr(),
            ]),
            jp2c(),
        ])
    };
    assert_decodes_like_raw(&with_bpcc(4, 4));
    file_format(&with_bpcc(4, 3), "a `bpcc` box holds 3 bytes");
}

/// A file with a wrong `ihdr` width and a truncated codestream reports the
/// box fault: `ihdr` is held to SIZ before any tile-part is read, as
/// OpenJPEG does ("Error with SIZ marker: IHDR w(769) h(512) vs. SIZ w(768)
/// h(512)" on file1 cut to 20000 bytes). Header faults found by the channel
/// plans come before tile faults too.
#[test]
fn a_header_fault_wins_over_a_truncated_codestream() {
    let truncated = &CODESTREAM[..CODESTREAM.len() - 40];
    assert!(matches!(decode(truncated), Err(Error::Codestream(_))));
    let with = |children: &[Vec<u8>], wide: bool| {
        let width = if wide { WIDTH + 1 } else { WIDTH };
        let mut all = vec![ihdr(HEIGHT, width, COMPONENTS), colr()];
        all.extend_from_slice(children);
        file(&[jp2_ftyp(), jp2h(&all), bx(b"jp2c", truncated)])
    };
    file_format(&with(&[], true), "`ihdr` declares a 25x16 image");
    file_format(
        &with(&[bx(b"cmap", &[0, 0, 1, 0])], false),
        "a `cmap` box but no `pclr` box",
    );
    file_format(
        &with(&[bx(b"cdef", &[0, 0])], false),
        "declares 0 channel definitions",
    );
    // With no header fault, the truncation is what is reported.
    assert!(matches!(
        decode(&with(&[], false)),
        Err(Error::Codestream(_))
    ));
}

fn res_box(children: &[Vec<u8>]) -> Vec<u8> {
    bx(b"res ", &children.concat())
}

fn res_payload(v: (u16, u16, i8), h: (u16, u16, i8)) -> Vec<u8> {
    let mut out = Vec::new();
    for value in [v.0, v.1, h.0, h.1] {
        out.extend_from_slice(&value.to_be_bytes());
    }
    out.extend_from_slice(&[v.2 as u8, h.2 as u8]);
    out
}

fn ratio(numerator: u16, denominator: u16, exponent: i8) -> Ratio {
    Ratio {
        numerator,
        denominator,
        exponent,
    }
}

/// `resc` and `resd` are read from `res ` as four `u16` and two `i8`: the
/// vertical ratio first, the exponents last.
#[test]
fn the_resolution_box_is_read() {
    let resc = res_payload((10000, 254, 0), (3, 4, -2));
    let resd = res_payload((12901, 32768, 4), (1, 2, 127));
    let bytes = file(&[
        jp2_ftyp(),
        jp2h(&[
            good_ihdr(),
            colr(),
            res_box(&[bx(b"resc", &resc), bx(b"resd", &resd)]),
        ]),
        jp2c(),
    ]);
    assert_decodes_like_raw(&bytes);
    let want = Resolution {
        capture: Some(Res {
            vertical: ratio(10000, 254, 0),
            horizontal: ratio(3, 4, -2),
        }),
        display: Some(Res {
            vertical: ratio(12901, 32768, 4),
            horizontal: ratio(1, 2, 127),
        }),
    };
    assert_eq!(decode(&bytes).unwrap().jp2.unwrap().resolution, want);
    assert_eq!(read_header(&bytes).unwrap().jp2.unwrap().resolution, want);
}

#[test]
fn a_ratio_converts_to_grid_points_per_meter() {
    assert_eq!(ratio(3, 4, 2).grid_points_per_meter(), Some(75.0));
    assert_eq!(ratio(5, 1, -1).grid_points_per_meter(), Some(0.5));
    assert_eq!(ratio(1, 0, 0).grid_points_per_meter(), None);
}

/// OpenJPEG 2.5.0 does not read `res `, so no shape of it fails there: every
/// one below was built and decoded with `opj_decompress`. Here they decode
/// too, and a malformed `resc` or `resd` is reported as absent. The first
/// well-formed box of each kind counts.
#[test]
fn a_malformed_resolution_box_never_fails_a_decode() {
    let good = res_payload((10000, 254, 0), (10000, 254, 0));
    let capture = |v| {
        Some(Res {
            vertical: v,
            horizontal: v,
        })
    };
    let dpi = capture(ratio(10000, 254, 0));
    let cases: Vec<(&str, Vec<u8>, Resolution)> = vec![
        ("empty res", res_box(&[]), Resolution::default()),
        (
            "garbage in res",
            bx(b"res ", &[1, 2, 3]),
            Resolution::default(),
        ),
        (
            "resc of 9 bytes",
            res_box(&[bx(b"resc", &good[..9])]),
            Resolution::default(),
        ),
        (
            "resc of 11 bytes",
            res_box(&[bx(b"resc", &[good.as_slice(), &[0]].concat())]),
            Resolution::default(),
        ),
        (
            "empty resd",
            res_box(&[bx(b"resd", &[])]),
            Resolution::default(),
        ),
        (
            "a child with LBox 3",
            bx(b"res ", &[header_only(3, b"resc"), good.clone()].concat()),
            Resolution::default(),
        ),
        (
            "a child past the end of res",
            bx(b"res ", &[header_only(200, b"resc"), good.clone()].concat()),
            Resolution::default(),
        ),
        (
            "a zero denominator",
            res_box(&[bx(b"resc", &res_payload((1, 0, 0), (1, 0, 0)))]),
            Resolution {
                capture: capture(ratio(1, 0, 0)),
                display: None,
            },
        ),
        (
            "a good resc before a broken child",
            res_box(&[bx(b"resc", &good), header_only(3, b"resd")]),
            Resolution {
                capture: dpi,
                display: None,
            },
        ),
        (
            "a short resc, then a good one",
            res_box(&[bx(b"resc", &good[..4]), bx(b"resc", &good)]),
            Resolution {
                capture: dpi,
                display: None,
            },
        ),
        (
            "two good resc: the first counts",
            res_box(&[
                bx(b"resc", &good),
                bx(b"resc", &res_payload((1, 1, 1), (1, 1, 1))),
            ]),
            Resolution {
                capture: dpi,
                display: None,
            },
        ),
        (
            "an unknown child",
            res_box(&[bx(b"zzzz", b"?"), bx(b"resd", &good)]),
            Resolution {
                capture: None,
                display: dpi,
            },
        ),
    ];
    for (what, res, want) in cases {
        let bytes = file(&[jp2_ftyp(), jp2h(&[good_ihdr(), colr(), res]), jp2c()]);
        let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
        assert_eq!(image.jp2.unwrap().resolution, want, "{what}");
    }
}

/// A `res ` box outside `jp2h` is not read (I.5.3.7 puts it inside).
#[test]
fn a_resolution_box_at_the_top_level_is_not_read() {
    let res = res_box(&[bx(b"resc", &res_payload((10000, 254, 0), (10000, 254, 0)))]);
    let bytes = file(&[jp2_ftyp(), good_jp2h(), res, jp2c()]);
    assert_eq!(
        decode(&bytes).unwrap().jp2.unwrap().resolution,
        Resolution::default()
    );
}

/// Every top-level `xml ` and `uuid` box comes back verbatim in file order,
/// before and after the codestream. Ones nested in a skipped superbox
/// (`asoc`), or inside `jp2h`, are not top-level and are not collected. A
/// `uuid` shorter than its identifier is skipped (OpenJPEG decodes such a
/// file; measured with `opj_decompress`).
#[test]
fn xml_and_uuid_boxes_are_passed_through_in_file_order() {
    let id: [u8; 16] = core::array::from_fn(|i| i as u8);
    let other_id = [0xAB; 16];
    let bytes = file(&[
        jp2_ftyp(),
        bx(b"xml ", b"<one/>"),
        bx(b"uuid", &[id.as_slice(), b"first"].concat()),
        bx(b"uuid", b"too short"),
        bx(b"rreq", &[1, 0x80, 0, 0]),
        bx(b"asoc", &bx(b"xml ", b"<nested/>")),
        jp2h(&[good_ihdr(), colr(), bx(b"xml ", b"<in jp2h/>")]),
        xl_box(b"xml ", b"<two/>"),
        jp2c(),
        bx(b"uuid", &other_id),
        bx(b"xml ", b"<three/>"),
    ]);
    assert_decodes_like_raw(&bytes);
    let metadata = decode(&bytes).unwrap().jp2.unwrap();
    assert_eq!(
        metadata
            .xml
            .iter()
            .map(|x| x.payload.as_slice())
            .collect::<Vec<_>>(),
        [&b"<one/>"[..], b"<two/>", b"<three/>"]
    );
    assert_eq!(
        metadata.uuid,
        vec![
            UuidBox {
                id,
                payload: b"first".to_vec(),
            },
            UuidBox {
                id: other_id,
                payload: Vec::new(),
            },
        ]
    );
    assert_eq!(read_header(&bytes).unwrap().jp2, Some(metadata));
}

/// After the codestream, the boxes are collected as far as OpenJPEG's walk
/// there goes, and collecting them never fails a decode it accepts: a box
/// past the end of the file or a second `jp2c` ends the walk, and a box of
/// `LBox` 0 runs to the end of the file.
#[test]
fn boxes_after_the_codestream_are_collected_as_far_as_the_walk_goes() {
    let xml = |text: &[u8]| bx(b"xml ", text);
    let tails: Vec<(&str, Vec<u8>, usize)> = vec![
        ("two xml", [xml(b"<a/>"), xml(b"<b/>")].concat(), 2),
        (
            "an xml past the end of the file",
            [xml(b"<a/>"), header_only(100, b"xml ")].concat(),
            1,
        ),
        (
            "an open-ended xml",
            [xml(b"<a/>"), open_box(b"xml ", b"<b/>")].concat(),
            2,
        ),
        (
            "after a second jp2c",
            [xml(b"<a/>"), bx(b"jp2c", b"zz"), xml(b"<b/>")].concat(),
            1,
        ),
        (
            "three stray bytes",
            [xml(b"<a/>"), vec![0, 0, 0]].concat(),
            1,
        ),
    ];
    for (what, tail, count) in tails {
        let bytes = [minimal(), tail].concat();
        let image = decode(&bytes).unwrap_or_else(|e| panic!("{what}: {e}"));
        assert_eq!(image.jp2.unwrap().xml.len(), count, "{what}");
    }
}

/// `read_header` stops at the codestream's first `SOT` marker: a file cut
/// right after it has the same header as the whole file. Cut before the
/// marker, the main header is unterminated, which OpenJPEG also refuses
/// ("Stream too short").
#[test]
fn read_header_reads_no_tile_data() {
    let sot = CODESTREAM
        .windows(2)
        .position(|w| w == [0xFF, 0x90])
        .expect("the fixture has a tile-part");
    let whole = read_header(&minimal()).expect("header");
    let jp2c_at = minimal().len() - CODESTREAM.len();
    for cut in [sot + 2, sot + 6, sot + 20, CODESTREAM.len() - 1] {
        let bytes = file(&[jp2_ftyp(), good_jp2h(), bx(b"jp2c", &CODESTREAM[..cut])]);
        assert_eq!(read_header(&bytes).as_ref(), Ok(&whole), "cut at {cut}");
        assert!(decode(&bytes).is_err(), "cut at {cut}");
        // Clamped `jp2c` and raw codestream alike.
        let clamped = &minimal()[..jp2c_at + cut];
        assert_eq!(
            read_header(clamped).as_ref(),
            Ok(&whole),
            "clamped at {cut}"
        );
        let raw = read_header(&CODESTREAM[..cut]).expect("raw header");
        assert_eq!(
            (raw.width, raw.height, &raw.components),
            (whole.width, whole.height, &whole.components)
        );
    }
    assert!(matches!(
        read_header(&CODESTREAM[..sot]),
        Err(Error::Codestream(_))
    ));
}

/// Without a `cdef`, the first N channels are colors 1..=N, N from the
/// color space, and every channel past them is unspecified (I.5.3.6).
#[test]
fn default_labels_stop_at_the_color_spaces_count() {
    let icc = |space: &[u8; 4]| {
        let mut profile = vec![0u8; 128];
        profile[16..20].copy_from_slice(space);
        ColorSpace::RestrictedIcc(profile)
    };
    // Every enumerated value with a color count (ISO/IEC 15444-2 Table M.25),
    // so dropping one arm fails here; 16, 17 and 18 arrive as their own
    // `ColorSpace` variants.
    let enumerated = [
        (0, 1),
        (1, 3),
        (3, 3),
        (4, 3),
        (9, 3),
        (11, 3),
        (12, 4),
        (13, 4),
        (14, 3),
        (15, 1),
        (19, 3),
        (20, 3),
        (21, 3),
        (22, 3),
        (23, 3),
        (24, 3),
    ];
    let mut cases = vec![
        (ColorSpace::Srgb, 3),
        (ColorSpace::Sycc, 3),
        (ColorSpace::Grayscale, 1),
        (icc(b"GRAY"), 1),
        (icc(b"RGB "), 3),
        (icc(b"YCbr"), 3),
        (icc(b"CMYK"), 4),
        (icc(b"2CLR"), 2),
        (icc(b"5CLR"), 5),
        (icc(b"9CLR"), 9),
        (icc(b"ACLR"), 10),
        (icc(b"FCLR"), 15),
    ];
    cases.extend(
        enumerated
            .iter()
            .map(|&(value, n)| (ColorSpace::Enumerated(value), n)),
    );
    for (space, colors) in cases {
        let labels = super::color_channels(6, &space).unwrap();
        for (i, label) in labels.iter().enumerate() {
            let want = if i < colors {
                (ChannelType::Color, Association::Color(i as u16 + 1))
            } else {
                (ChannelType::Unspecified, Association::None)
            };
            assert_eq!(
                (label.kind, label.association),
                want,
                "{space:?} channel {i}"
            );
        }
    }
    // The counts themselves, where a count of six or more would look like
    // `None` through six labels.
    for (space, want) in [
        (icc(b"9CLR"), Some(9)),
        (icc(b"ACLR"), Some(10)),
        (icc(b"FCLR"), Some(15)),
        (icc(b"aCLR"), None),
        (icc(b"fCLR"), None),
        (icc(b"GCLR"), None),
        (icc(b"0CLR"), None),
        (icc(b"1CLR"), None),
    ] {
        assert_eq!(super::color_count(&space), want, "{space:?}");
    }
    // A space whose color count is not known keeps every channel a color.
    for space in [
        ColorSpace::Unknown,
        ColorSpace::Enumerated(2),
        ColorSpace::Enumerated(5),
        ColorSpace::Enumerated(10),
        ColorSpace::Enumerated(25),
        ColorSpace::Enumerated(99),
        ColorSpace::RestrictedIcc(Vec::new()),
        // `nCLR` is 2 to 15 colors, upper-case: these are not signatures.
        icc(b"0CLR"),
        icc(b"1CLR"),
        icc(b"aCLR"),
        icc(b"fCLR"),
        icc(b"GCLR"),
    ] {
        let labels = super::color_channels(6, &space).unwrap();
        assert!(
            labels.iter().all(|l| l.kind == ChannelType::Color),
            "{space:?}"
        );
    }
}