rust-j2k 0.3.0

Pure-Rust JPEG 2000 (ISO/IEC 15444) codec, built GRIB2-decode-first toward OpenJPEG-level coverage.
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
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
//! Tier-2 packet-decoding tests.
//!
//! Two oracles, both dependency-free: hand-built packet headers (every field
//! crafted, so a misread is caught directly) and the seed codestream, where the
//! parse self-check — packets must tile the tile-part exactly — proves the whole
//! header walk against a real OpenJPEG-produced bitstream.

use std::collections::BTreeSet;

use super::*;

/// Every byte of a code-block, across all its codeword segments.
fn all_bytes(block: &CodeBlock<'_>) -> Vec<u8> {
    block.segments.iter().flat_map(|s| s.bytes()).collect()
}

/// The byte chunks of a block's single codeword segment (the default style).
fn only_segment<'a, 'b>(block: &'a CodeBlock<'b>) -> &'a CodedSegment<'b> {
    assert_eq!(block.segments.len(), 1, "the default style has one segment");
    &block.segments[0]
}

/// Parse `data` as a one-layer packet over `bands`, returning the subbands and
/// the next byte offset — the shape `parse_packet` had before quality layers.
fn parse_one_packet<'a>(data: &'a [u8], bands: &[BandGeom]) -> Result<(Vec<Subband<'a>>, usize)> {
    let (subbands, next) = parse_layers(data, bands, 1)?;
    Ok((subbands, next))
}

/// Parse `layers` consecutive packets over `bands`, carrying the precinct state
/// across them the way `decode_packets` does. No packet delimiters.
fn parse_layers<'a>(
    data: &'a [u8],
    bands: &[BandGeom],
    layers: u32,
) -> Result<(Vec<Subband<'a>>, usize)> {
    parse_layers_with(
        data,
        bands,
        layers,
        Delimiters {
            sop: false,
            eph: false,
        },
    )
}

/// As [`parse_layers`], with `COD`'s packet delimiters signalled.
fn parse_layers_with<'a>(
    data: &'a [u8],
    bands: &[BandGeom],
    layers: u32,
    delimiters: Delimiters,
) -> Result<(Vec<Subband<'a>>, usize)> {
    parse_layers_styled(data, bands, layers, delimiters, 0)
}

/// As [`parse_layers`], with a code-block style — `restart` splits a block's
/// passes across codeword segments.
fn parse_layers_styled<'a>(
    data: &'a [u8],
    bands: &[BandGeom],
    layers: u32,
    delimiters: Delimiters,
    style: u8,
) -> Result<(Vec<Subband<'a>>, usize)> {
    let mut states: Vec<BandState<'a>> = bands.iter().map(BandState::new).collect();
    let mut streams = PacketStreams {
        header: data,
        header_pos: 0,
        data,
        body_pos: 0,
        packed: false,
    };
    for layer in 0..layers {
        parse_packet(
            &mut streams,
            layer,
            layer,
            delimiters,
            style,
            bands,
            0,
            &mut states,
        )?;
    }
    Ok((build_subbands(bands, states)?, streams.body_pos))
}
use crate::codestream::markers::{
    Cod, PocVolume, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform,
};
use crate::codestream::{MainHeader, Tile, TileHeader};
use crate::tier2::bio::BitReader;

/// The encode side of [`BitReader`]: MSB-first packing with the Annex B.10.1
/// `0xFF` bit-stuffing and the matching flush, so a crafted header round-trips
/// through the decoder exactly (the inverse of `align`).
struct PackedHeader {
    out: Vec<u8>,
    buf: u32,
    ct: i32,
}

impl PackedHeader {
    fn new() -> Self {
        PackedHeader {
            out: Vec::new(),
            buf: 0,
            ct: 8,
        }
    }

    fn byteout(&mut self) {
        self.ct = if self.buf == 0xFF { 7 } else { 8 };
        self.out.push(self.buf as u8);
        self.buf = 0;
    }

    fn bit(&mut self, b: u32) {
        if self.ct == 0 {
            self.byteout();
        }
        self.ct -= 1;
        self.buf |= (b & 1) << self.ct;
    }

    fn bits(&mut self, value: u32, n: u32) {
        for i in (0..n).rev() {
            self.bit((value >> i) & 1);
        }
    }

    /// Flush the partial byte and the trailing stuff byte (Annex B.10.1), the
    /// mirror of `BitReader::align`, and return the header bytes.
    fn finish(mut self) -> Vec<u8> {
        self.byteout();
        if self.ct == 7 {
            self.byteout();
        }
        self.out
    }
}

fn header(x_size: u32, y_size: u32, levels: u8, cblk_exp: u8) -> MainHeader {
    MainHeader::new(
        Siz {
            x_size,
            y_size,
            x_offset: 0,
            y_offset: 0,
            tile_width: x_size,
            tile_height: y_size,
            tile_x_offset: 0,
            tile_y_offset: 0,
            components: vec![SizComponent {
                bit_depth: 8,
                signed: false,
                x_sampling: 1,
                y_sampling: 1,
            }],
        },
        Cod {
            progression: Progression::Lrcp,
            layers: 1,
            decomposition_levels: levels,
            code_block_width: cblk_exp - 2,
            code_block_height: cblk_exp - 2,
            code_block_style: 0,
            use_sop: false,
            use_eph: false,
            multiple_component_transform: false,
            transform: Transform::Reversible53,
            precinct_sizes: Vec::new(),
        },
        Qcd {
            style: QuantStyle::None,
            guard_bits: 2,
            steps: vec![(8, 0)],
        },
    )
}

/// Tile 0, carrying `data`. A tile keeps only its own tile-part-header markers —
/// none, here — so the header `decode_packets` decodes under is passed alongside.
fn tile(data: &[u8]) -> Tile<'_> {
    Tile {
        index: 0,
        header: TileHeader::default(),
        data: std::borrow::Cow::Borrowed(data),
        packed_headers: Vec::new(),
    }
}

fn single_block_band(kind: BandKind, width: usize, height: usize) -> BandGeom {
    BandGeom {
        kind,
        origin: (0, 0),
        width,
        height,
        block_cols: 1,
        block_rows: 1,
        blocks: vec![(0, 0, width, height)],
        precincts: one_precinct(1, 1),
    }
}

/// The single maximal precinct that owns a band's whole `cols × rows` block
/// grid — what every hand-built band below has, since these tests craft packet
/// *headers* and the precinct partition is exercised against the oracle instead.
fn one_precinct(cols: usize, rows: usize) -> Vec<PrecinctGeom> {
    vec![PrecinctGeom {
        cols,
        rows,
        blocks: (0..cols * rows).collect(),
    }]
}

/// [`resolution_geoms`] with a full precinct budget — the budget is a
/// DoS guard, exercised separately, and irrelevant to the geometry these tests
/// check.
fn geoms_of(header: &MainHeader, tile: u32, comp: usize) -> Result<Vec<ResolutionGeom>> {
    let mut budget = usize::MAX;
    resolution_geoms(header, tile, comp, &mut budget)
}

// ---- Geometry (ISO Eq. B-15, code-block grid B.7) ----

/// A small image with 2^6 code-blocks gives one block per subband, and the
/// subband dimensions follow the standard's half-resolution split.
#[test]
fn geometry_single_block_per_subband() {
    let geoms = geoms_of(&header(100, 100, 2, 6), 0, 0).unwrap();
    assert_eq!(geoms.len(), 3); // NL = 2 → resolutions 0,1,2

    // Resolution 0: the NLLL band at level 2, ceil(100/4) = 25 square.
    let ll = &geoms[0].bands[0];
    assert_eq!(ll.kind, BandKind::Ll);
    assert_eq!((ll.width, ll.height), (25, 25));
    assert_eq!((ll.block_cols, ll.block_rows), (1, 1));

    // Resolution 1 detail bands sit at level 2 as well: 25 square.
    assert_eq!(geoms[1].bands.len(), 3);
    assert_eq!(geoms[1].bands[0].kind, BandKind::Hl);
    for b in &geoms[1].bands {
        assert_eq!((b.width, b.height), (25, 25));
    }

    // Resolution 2 detail bands at level 1: ceil(99/2) = 50 square.
    for b in &geoms[2].bands {
        assert_eq!((b.width, b.height), (50, 50));
    }
}

/// A band wider than the code-block tiles into a grid; the trailing row/column
/// blocks are clipped to the band edge.
#[test]
fn geometry_multi_block_grid() {
    // 200×200, one level, 2^5 = 32 blocks. LL is ceil(200/2) = 100 square.
    let geoms = geoms_of(&header(200, 200, 1, 5), 0, 0).unwrap();
    let ll = &geoms[0].bands[0];
    assert_eq!((ll.width, ll.height), (100, 100));
    // ceil(100/32) = 4 blocks each way.
    assert_eq!((ll.block_cols, ll.block_rows), (4, 4));
    // First block is a full 32×32 cell at the origin.
    assert_eq!(ll.blocks[0], (0, 0, 32, 32));
    // The bottom-right block is clipped to 100 − 96 = 4 on each axis.
    let last = ll.blocks[ll.block_cols * ll.block_rows - 1];
    assert_eq!(last, (96, 96, 4, 4));
}

/// The maximum decomposition depth builds without overflowing the grid shifts
/// and yields one resolution per level plus the base.
#[test]
fn geometry_max_decomposition_levels() {
    let geoms = geoms_of(&header(2, 2, 32, 6), 0, 0).unwrap();
    assert_eq!(geoms.len(), 33);
    // The coarsest LL collapses to a single sample; nothing panics on the way.
    assert_eq!((geoms[0].bands[0].width, geoms[0].bands[0].height), (1, 1));
}

/// A tile-component larger than one maximal precinct (2^15 on either axis) now
/// splits into two — before #61 this was the case the decoder had to reject,
/// because the packet walk visited a single precinct per resolution and would
/// have desynchronized (Eq. B-16).
#[test]
fn geometry_splits_past_the_maximal_precinct_extent() {
    let wide = geoms_of(&header(32769, 16, 1, 6), 0, 0).unwrap();
    assert_eq!(
        (wide[1].precincts_wide, wide[1].precincts_high),
        (2, 1),
        "the finest resolution spans two maximal precincts across"
    );
    let tall = geoms_of(&header(16, 32769, 1, 6), 0, 0).unwrap();
    assert_eq!((tall[1].precincts_wide, tall[1].precincts_high), (1, 2));
}

/// Exactly 2^15 still fits in the single maximal precinct.
#[test]
fn geometry_accepts_full_precinct_extent() {
    let geoms = geoms_of(&header(32768, 16, 1, 6), 0, 0).unwrap();
    assert_eq!(geoms[1].bands[0].width, 16384);
}

/// A hostile geometry — a tall, thin tile-component under a 2^1 precinct — has
/// ~one precinct per two rows, tens of millions of them, each its own
/// allocation. The budget stops it *before* the precincts are built, not after:
/// with the guard enforced inside the geometry walk this returns in microseconds,
/// where the after-the-fact check it replaced spent seconds and gigabytes first.
#[test]
fn geometry_rejects_a_precinct_bomb_before_allocating() {
    use std::time::Instant;
    let mut header = header(1, 1 << 24, 1, 6);
    header.components[0].coding.precinct_sizes = vec![(1, 1), (1, 1)];

    let mut budget = super::MAX_PRECINCTS;
    let start = Instant::now();
    let result = resolution_geoms(&header, 0, 0, &mut budget);
    let elapsed = start.elapsed();

    assert!(
        matches!(result, Err(crate::Error::Unsupported(_))),
        "a 1×2^24 tile-component at a 2^1 precinct must be rejected"
    );
    assert!(
        elapsed.as_millis() < 100,
        "the guard must fire before the precincts are built, not after ({elapsed:?})"
    );
}

/// The budget is the tile's, not a component's: two components each individually
/// under the cap but together over it are still rejected, because
/// `resolution_geoms` spends one running total across them.
#[test]
fn the_precinct_budget_is_shared_across_components() {
    // A 1024×1024 tile-component under a 2^1 precinct is ~512×512 = 2^18
    // precincts at the finest resolution, right at the cap. Give the header two
    // such components; the shared budget must not admit both.
    let mut header = header(1024, 1024, 1, 6);
    header.siz.components.push(header.siz.components[0]);
    header.components.push(header.components[0].clone());
    for comp in &mut header.components {
        comp.coding.precinct_sizes = vec![(1, 1), (1, 1)];
    }

    let mut budget = super::MAX_PRECINCTS;
    let first = resolution_geoms(&header, 0, 0, &mut budget);
    let second = resolution_geoms(&header, 0, 1, &mut budget);
    assert!(
        first.is_err() || matches!(second, Err(crate::Error::Unsupported(_))),
        "two components sharing the budget must not both allocate their precincts"
    );
}

/// A code-block size past the standard's 2^10 / xcb+ycb≤12 limit is rejected,
/// not silently clamped (which would also keep the grid shifts well-defined).
#[test]
fn geometry_rejects_oversized_code_block() {
    // code_block_width field 9 → exponent 11 (> 10).
    let err = geoms_of(&header(64, 64, 1, 13), 0, 0);
    assert!(matches!(err, Err(crate::Error::Marker(_))));
}

// ---- Number-of-passes prefix code (ISO Table B.4) ----

#[test]
fn num_passes_table() {
    // (passes, the exact bits the encoder writes for that count).
    let cases: &[(u32, &[u32])] = &[
        (1, &[0]),
        (2, &[1, 0]),
        (3, &[1, 1, 0, 0]),
        (5, &[1, 1, 1, 0]),
        (6, &[1, 1, 1, 1, 0, 0, 0, 0, 0]),
        (36, &[1, 1, 1, 1, 1, 1, 1, 1, 0]),
        (37, &[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]),
        (164, &[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]),
    ];
    for (passes, pattern) in cases {
        let mut w = PackedHeader::new();
        for &b in *pattern {
            w.bit(b);
        }
        let bytes = w.finish();
        let mut bio = BitReader::new(&bytes);
        assert_eq!(read_num_passes(&mut bio), *passes, "passes={passes}");
    }
}

// ---- Hand-built packets ----

/// An included single block: inclusion, zero-bitplane run, pass count, Lblock,
/// and length all decode, and the body slice is the bytes after the header.
#[test]
fn packet_one_included_block() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // inclusion tag tree (1×1): value 0 → included at layer 0
    w.bits(0b001, 3); // zero-bitplane tag tree: value 2 (two 0s then a 1)
    w.bit(0); // num_passes = 1
    w.bit(0); // Lblock stays 3
    w.bits(5, 3); // length: Lblock(3) + floor(log2 1)=0 → 3 bits, value 5
    let mut data = w.finish();
    let header_len = data.len();
    let body = [0xDE, 0xAD, 0xBE, 0xEF, 0x42];
    data.extend_from_slice(&body);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_one_packet(&data, &bands).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 1);
    assert_eq!(block.zero_bit_planes, 2);
    assert_eq!(all_bytes(block), body);
    assert_eq!(next, header_len + body.len());
}

/// Zero bit-planes count against the raised `Kmax = Mb + SPrgn` (ISO H.2), so
/// under a maxshift a background-only block can signal far more of them than
/// any band has magnitude planes — up to 292 (`Mb` ≤ 37, `SPrgn` ≤ 255). A
/// count in that range must parse; only a run past it is a malformed header.
#[test]
fn packet_zero_bitplane_count_can_exceed_the_magnitude_planes() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included at layer 0
    for _ in 0..292 {
        w.bit(0); // zero-bitplane tag tree: 292 zeros...
    }
    w.bit(1); // ...then the terminating 1: value 292, the largest possible
    w.bit(0); // num_passes = 1
    w.bit(0); // Lblock stays 3
    w.bits(5, 3); // length: 3 bits, value 5
    let mut data = w.finish();
    let body = [0xDE, 0xAD, 0xBE, 0xEF, 0x42];
    data.extend_from_slice(&body);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, _next) = parse_one_packet(&data, &bands).unwrap();
    assert_eq!(subbands[0].blocks[0].zero_bit_planes, 292);
}

/// A run of zero bits past every value a conformant stream can signal is a
/// malformed header, rejected rather than walked to the end of the buffer.
#[test]
fn packet_zero_bitplane_run_past_the_limit_is_rejected() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included at layer 0
    for _ in 0..400 {
        w.bit(0); // a zero run that never resolves inside the limit
    }
    let data = w.finish();

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let err = parse_one_packet(&data, &bands).expect_err("should reject");
    assert!(matches!(err, Error::Codestream(_)), "{err:?}");
}

/// A larger pass count widens the length field by floor(log2 passes).
#[test]
fn packet_length_field_width_tracks_passes() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included
    w.bit(1); // zero-bitplane value 0
    // num_passes = 5 → bits 1110; floor(log2 5) = 2, so length is Lblock+2 = 5 bits.
    w.bits(0b1110, 4);
    w.bit(0); // Lblock stays 3
    w.bits(20, 5); // length = 20
    let mut data = w.finish();
    let body = vec![7u8; 20];
    data.extend_from_slice(&body);

    let bands = [single_block_band(BandKind::Hh, 16, 16)];
    let (subbands, _next) = parse_one_packet(&data, &bands).unwrap();
    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 5);
    assert_eq!(block.zero_bit_planes, 0);
    assert_eq!(all_bytes(block).len(), 20);
}

/// The Lblock unary run widens the length field one bit per `1`.
#[test]
fn packet_lblock_increment() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included
    w.bit(1); // zero-bitplane value 0
    w.bit(0); // num_passes = 1
    w.bits(0b110, 3); // Lblock += 2 (two 1s then a 0) → Lblock = 5
    w.bits(9, 5); // length = 5 bits, value 9
    let mut data = w.finish();
    let body = vec![1u8; 9];
    data.extend_from_slice(&body);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, _next) = parse_one_packet(&data, &bands).unwrap();
    assert_eq!(all_bytes(&subbands[0].blocks[0]).len(), 9);
}

/// An empty packet (present bit 0) contributes nothing and is one byte long.
#[test]
fn packet_empty() {
    let mut w = PackedHeader::new();
    w.bit(0); // not present
    let data = w.finish();
    assert_eq!(data.len(), 1);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_one_packet(&data, &bands).unwrap();
    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 0);
    assert!(block.segments.is_empty());
    assert_eq!(next, 1);
}

/// A present packet whose single block is not included in the one layer: the
/// inclusion tag tree never resolves below the layer-0 threshold.
#[test]
fn packet_block_not_included() {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(0); // inclusion value ≥ 1 → not included at layer 0
    let data = w.finish();

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_one_packet(&data, &bands).unwrap();
    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 0);
    assert!(block.segments.is_empty());
    assert_eq!(next, data.len());
}

/// Two blocks in one band, only the second included: the body byte belongs to
/// the second block, the first stays empty. Exercises the shared-root tag tree
/// and per-block body assignment.
#[test]
fn packet_two_blocks_partial_inclusion() {
    // 2×1 inclusion tag tree, values L0=1 (not included at layer 0), L1=0.
    // Root min 0. Reading block 0 at threshold 1: root `1` (min 0), node0 `0`
    // (raise to 1) → not below 1 → not included. Reading block 1: node1 `1`
    // (value 0) → included.
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // inclusion root resolves to min 0
    w.bit(0); // block 0 node: value ≥ 1 → not included
    w.bit(1); // block 1 node: value 0 → included
    // Block 1's zero-bitplane tag tree is also 2×1, so reading its leaf first
    // resolves the (fresh) root: root `1` then leaf `1` for value 0.
    w.bit(1); // zero-bitplane root → min 0
    w.bit(1); // zero-bitplane leaf → value 0
    w.bit(0); // block 1 num_passes = 1
    w.bit(0); // Lblock stays 3
    w.bits(2, 3); // block 1 length = 2
    let mut data = w.finish();
    let body = [0xAA, 0xBB];
    data.extend_from_slice(&body);

    let band = BandGeom {
        kind: BandKind::Ll,
        origin: (0, 0),
        width: 16,
        height: 8,
        block_cols: 2,
        block_rows: 1,
        blocks: vec![(0, 0, 8, 8), (8, 0, 8, 8)],
        precincts: one_precinct(2, 1),
    };
    let (subbands, _next) = parse_one_packet(&data, &[band]).unwrap();
    let blocks = &subbands[0].blocks;
    assert_eq!(blocks[0].num_passes, 0);
    assert!(all_bytes(&blocks[0]).is_empty());
    assert_eq!(blocks[1].num_passes, 1);
    assert_eq!(all_bytes(&blocks[1]), &body);
}

// ---- Seed codestream (the real-bitstream oracle) ----

/// The seed fixture parses end to end: the right packet count, every subband
/// present, and — implicitly, via `decode_packets`' self-check — the packets
/// tiling the tile-part data exactly. A field misread would leave trailing
/// bytes and error out here.
#[test]
fn seed_codestream_parses() {
    let bytes = include_bytes!("../../tests/fixtures/jpeg2000_regular_latlon.j2k");
    let cs = crate::codestream::parse(bytes).unwrap();
    let coded = decode_packets(&cs.header, &cs.tiles[0]).unwrap();

    // opj_dump reports numresolutions = 5 (NL = 4): one LL packet + four detail
    // levels.
    assert_eq!(coded.components[0].resolutions.len(), 5);
    assert_eq!(coded.components[0].resolutions[0].subbands.len(), 1);
    assert_eq!(
        coded.components[0].resolutions[0].subbands[0].kind,
        BandKind::Ll
    );
    for res in &coded.components[0].resolutions[1..] {
        assert_eq!(res.subbands.len(), 3);
    }

    let total_blocks: usize = coded.components[0]
        .resolutions
        .iter()
        .flat_map(|r| &r.subbands)
        .map(|s| s.blocks.len())
        .sum();
    assert_eq!(total_blocks, 13); // 1 + 4×3, one block per subband at this size

    // At least one block actually carries coded data.
    let included = coded.components[0]
        .resolutions
        .iter()
        .flat_map(|r| &r.subbands)
        .flat_map(|s| &s.blocks)
        .any(|b| b.num_passes > 0 && !all_bytes(b).is_empty());
    assert!(included, "expected some included code-block");
}

/// Garbage tile-part data must resolve to an `Ok`/`Err` result, never a panic —
/// every shift, slice, and loop is bounded. (Full fuzzing is issue #18.)
#[test]
fn malformed_tile_data_never_panics() {
    let cases: [Vec<u8>; 5] = [
        Vec::new(),
        vec![0xFF; 64],
        vec![0x00; 64],
        (0..=255u8).cycle().take(300).collect(),
        vec![0x80, 0x01, 0xFF, 0xFE, 0x00, 0x7F],
    ];
    let h = header(32, 32, 3, 6);
    for data in &cases {
        let t = tile(data);
        // The result is allowed to be either Ok or Err; only a panic would fail.
        let _ = decode_packets(&h, &t);
    }
}

/// A header pairing a large image with tiny legal 4×4 code-blocks would drive
/// millions of per-block states and tag trees before a single tile-part byte
/// is read; the block-count guard rejects it up front instead.
#[test]
fn block_count_guard_rejects_metadata_bomb() {
    // 4096×4096 with 4×4 blocks: ~1.4M blocks across the ladder, over the 2^19 cap.
    let h = header(4096, 4096, 1, 2);
    let t = tile(&[]);
    let err = decode_packets(&h, &t).expect_err("guard fires before any packet parse");
    assert!(matches!(err, crate::Error::Unsupported(_)), "{err}");
}

// ---- Per-component geometry (issue #57) ----

/// Each component's subbands derive from *its own* sub-sampling, so components
/// of one image can have different band sizes at the same resolution.
///
/// Mixed per-component sub-sampling has no end-to-end oracle yet: OpenJPEG's raw
/// encoder cannot produce one (see `scripts/gen-multicomponent-fixtures.py`) and
/// every conformance entry that carries it also needs a progression or layer
/// feature that is not decoded. So it is pinned here, at the geometry, where a
/// decoder that reused component 0's factors for every component would show up.
#[test]
fn resolution_geoms_honour_each_components_sub_sampling() {
    let mut h = header(64, 64, 1, 6);
    h.siz.components = vec![
        SizComponent {
            bit_depth: 8,
            signed: false,
            x_sampling: 1,
            y_sampling: 1,
        },
        SizComponent {
            bit_depth: 8,
            signed: false,
            x_sampling: 2,
            y_sampling: 1,
        },
        SizComponent {
            bit_depth: 8,
            signed: false,
            x_sampling: 1,
            y_sampling: 2,
        },
        SizComponent {
            bit_depth: 8,
            signed: false,
            x_sampling: 2,
            y_sampling: 2,
        },
    ];

    // Re-resolve the per-component parameters against the widened SIZ: they are
    // derived from the component count, not stored beside it.
    let h = MainHeader::new(h.siz, h.cod, h.qcd);

    // One decomposition level, so resolution 0 is the LL at half the
    // tile-component extent in each axis.
    let expected_ll = [(32, 32), (16, 32), (32, 16), (16, 16)];
    for (component, (want_width, want_height)) in expected_ll.into_iter().enumerate() {
        let geoms = geoms_of(&h, 0, component).unwrap();
        let ll = &geoms[0].bands[0];
        assert_eq!(ll.kind, BandKind::Ll);
        assert_eq!(
            (ll.width, ll.height),
            (want_width, want_height),
            "component {component} LL band",
        );
    }

    // A component index past the SIZ list is an internal inconsistency, not a
    // silent fall back to component 0.
    assert!(geoms_of(&h, 0, 4).is_err());
}

// ---- Quality layers (issue #64) ----

/// Assemble `(header, body)` pairs into a tile-part. Each packet's header is a
/// whole number of bytes and its body follows immediately, so the layers cannot
/// share one bit-writer.
fn packets(parts: &[(Vec<u8>, Vec<u8>)]) -> Vec<u8> {
    let mut data = Vec::new();
    for (header, body) in parts {
        data.extend_from_slice(header);
        data.extend_from_slice(body);
    }
    data
}

/// A block included in layer 0 signals its later contributions with a single
/// bit, not another inclusion tag-tree read, and its coding passes accumulate.
#[test]
fn layers_accumulate_passes_and_segments() {
    let mut l0 = PackedHeader::new();
    l0.bit(1); // present
    l0.bit(1); // inclusion tag tree (1x1): value 0
    l0.bits(0b001, 3); // zero-bitplane value 2
    l0.bit(0); // num_passes = 1
    l0.bit(0); // Lblock stays 3
    l0.bits(3, 3); // length 3

    let mut l1 = PackedHeader::new();
    l1.bit(1); // present
    l1.bit(1); // already included, so one bit: contributes
    l1.bit(0); // num_passes = 1
    l1.bit(0); // Lblock stays 3
    l1.bits(2, 3); // length 2

    let data = packets(&[(l0.finish(), vec![1, 2, 3]), (l1.finish(), vec![4, 5])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 2, "passes accumulate across layers");
    assert_eq!(block.zero_bit_planes, 2, "read once, on first inclusion");
    assert_eq!(only_segment(block).chunks.len(), 2, "one chunk per layer");
    // The MQ codeword is the concatenation, in layer order.
    assert_eq!(all_bytes(block), vec![1, 2, 3, 4, 5]);
    assert_eq!(next, data.len());
}

/// A block absent from layer 0 is resolved by the inclusion tag tree at a rising
/// threshold: the tree keeps its partial decode between packets. Rebuilding it
/// per packet would re-read the same bit and desynchronise the header.
#[test]
fn a_block_first_included_in_a_later_layer() {
    let mut l0 = PackedHeader::new();
    l0.bit(1); // present
    l0.bit(0); // inclusion: not yet (raises the tree's bound to 1)

    let mut l1 = PackedHeader::new();
    l1.bit(1); // present
    l1.bit(1); // inclusion resolves: value 1 <= layer 1
    l1.bit(1); // zero-bitplane value 0
    l1.bit(0); // num_passes = 1
    l1.bit(0); // Lblock stays 3
    l1.bits(2, 3); // length 2

    let data = packets(&[(l0.finish(), vec![]), (l1.finish(), vec![0xAA, 0xBB])]);
    let bands = [single_block_band(BandKind::Hl, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 1);
    assert_eq!(block.zero_bit_planes, 0);
    assert_eq!(all_bytes(block), vec![0xAA, 0xBB]);
    assert_eq!(next, data.len());
}

/// An included block that contributes nothing to a layer costs one zero bit and
/// leaves its accumulated state alone.
#[test]
fn an_included_block_may_skip_a_layer() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(0); // Lblock 3
    l0.bits(2, 3); // length 2

    let mut l1 = PackedHeader::new();
    l1.bit(1); // present
    l1.bit(0); // included, but no contribution this layer

    let data = packets(&[(l0.finish(), vec![9, 9]), (l1.finish(), vec![])]);
    let bands = [single_block_band(BandKind::Lh, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 1);
    assert_eq!(all_bytes(block), vec![9, 9]);
    assert_eq!(next, data.len());
}

/// `Lblock` grows by a unary run and carries into later layers: the width of the
/// length field in layer 1 depends on what layer 0 signalled. A decoder that
/// reset it would read the wrong number of bits and desynchronise.
#[test]
fn lblock_persists_across_layers() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(1); // Lblock 3 -> 4
    l0.bit(0); // end of the unary run
    l0.bits(2, 4); // the length field is now 4 bits wide

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bit(0); // 1 pass
    l1.bit(0); // no further Lblock growth
    l1.bits(3, 4); // still 4 bits, because Lblock persisted

    let data = packets(&[(l0.finish(), vec![1, 2]), (l1.finish(), vec![3, 4, 5])]);
    let bands = [single_block_band(BandKind::Hh, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 2);
    assert_eq!(all_bytes(block), vec![1, 2, 3, 4, 5]);
    assert_eq!(next, data.len());
}

/// The length field's width is `Lblock + floor(log2(passes))` for the passes of
/// *this* contribution, not the running total. Layer 1 adds 3 passes to a block
/// that already has 3: a decoder that used the accumulated 6 would read a 5-bit
/// length where 4 were written, and desynchronise.
#[test]
fn length_field_width_uses_this_layers_passes_not_the_total() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bits(0b1100, 4); // num_passes = 3
    l0.bit(0); // Lblock stays 3
    l0.bits(2, 4); // length 2, in 3 + floor(log2 3) = 4 bits

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bits(0b1100, 4); // num_passes = 3 again (total becomes 6)
    l1.bit(0); // Lblock stays 3
    l1.bits(3, 4); // still 4 bits: floor(log2 3) = 1, not floor(log2 6) = 2

    let data = packets(&[(l0.finish(), vec![1, 2]), (l1.finish(), vec![3, 4, 5])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 6, "the total still accumulates");
    assert_eq!(all_bytes(block), vec![1, 2, 3, 4, 5]);
    assert_eq!(next, data.len());
}

/// An empty packet costs its layer a single bit and touches no state, so the
/// inclusion tree still resolves at value 0 in the next layer.
#[test]
fn an_empty_packet_leaves_the_tag_trees_alone() {
    let mut l0 = PackedHeader::new();
    l0.bit(0); // empty packet

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // inclusion resolves at value 0 — the tree was never advanced
    l1.bit(1); // zero-bitplane 0
    l1.bit(0); // 1 pass
    l1.bit(0); // Lblock 3
    l1.bits(1, 3); // length 1

    let data = packets(&[(l0.finish(), vec![]), (l1.finish(), vec![0x7F])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 1);
    assert_eq!(all_bytes(block), vec![0x7F]);
    assert_eq!(next, data.len());
}

/// A layer may add coding passes and no bytes. The MQ codeword is continuous
/// across layers, so the encoder's rate split can put a block's passes in one
/// layer and the bytes carrying them in the next. OpenJPEG reads such a length
/// without complaint, and so must this: rejecting it would false-reject a valid
/// codestream.
#[test]
fn a_layer_may_contribute_passes_without_bytes() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(0); // Lblock 3
    l0.bits(0, 3); // length 0 — no bytes this layer

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bit(0); // 1 pass
    l1.bit(0); // Lblock 3
    l1.bits(2, 3); // length 2 — the bytes arrive now

    let data = packets(&[(l0.finish(), vec![]), (l1.finish(), vec![0xC0, 0xDE])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 2).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 2, "both layers' passes count");
    assert_eq!(all_bytes(block), vec![0xC0, 0xDE]);
    assert_eq!(next, data.len());
}

/// A block that takes coding passes but no bytes from *any* layer would hand
/// Tier-1 an empty MQ stream. That is the case worth rejecting.
#[test]
fn a_block_with_passes_and_no_bytes_at_all_is_codestream() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(0); // Lblock 3
    l0.bits(0, 3); // length 0

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bit(0); // 1 pass
    l1.bit(0); // Lblock 3
    l1.bits(0, 3); // length 0 again — no bytes ever arrive

    let data = packets(&[(l0.finish(), vec![]), (l1.finish(), vec![])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    assert!(matches!(
        parse_layers(&data, &bands, 2),
        Err(Error::Codestream(_))
    ));
}

/// A tile-part that ends before its declared layers are read is truncation, not
/// a silently short decode.
#[test]
fn a_tile_part_shorter_than_its_layers_is_codestream() {
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(0); // Lblock 3
    l0.bits(1, 3); // length 1

    let data = packets(&[(l0.finish(), vec![0x01])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    assert!(matches!(
        parse_layers(&data, &bands, 2),
        Err(Error::Codestream(_))
    ));
}

// ---- Progression orders (issue #62) and the precinct partition (#61) ----

const ORDERS: [Progression; 5] = [
    Progression::Lrcp,
    Progression::Rlcp,
    Progression::Rpcl,
    Progression::Pcrl,
    Progression::Cprl,
];

/// The knobs the packet walk actually reads: how big the tile-component grids
/// are, how deep the pyramid is, and how the precincts cut it up. The positional
/// orders derive their sweep from all three, so a progression test that fixes an
/// axis count instead of a geometry cannot exercise them.
struct Layout {
    size: (u32, u32),
    /// One `(XRsiz, YRsiz)` per component.
    sampling: Vec<(u8, u8)>,
    levels: u8,
    /// `(PPx, PPy)` per resolution, coarsest first. Empty = maximal.
    precincts: Vec<(u8, u8)>,
}

impl Layout {
    /// One component, no sub-sampling, maximal precincts.
    fn plain(size: (u32, u32), levels: u8) -> Self {
        Layout {
            size,
            sampling: vec![(1, 1)],
            levels,
            precincts: Vec::new(),
        }
    }

    fn components(mut self, count: usize) -> Self {
        self.sampling = vec![(1, 1); count];
        self
    }

    /// The same precinct exponent at every resolution.
    fn precincts(mut self, ppx: u8, ppy: u8) -> Self {
        self.precincts = vec![(ppx, ppy); usize::from(self.levels) + 1];
        self
    }

    fn header(&self) -> MainHeader {
        MainHeader::new(
            Siz {
                x_size: self.size.0,
                y_size: self.size.1,
                x_offset: 0,
                y_offset: 0,
                tile_width: self.size.0,
                tile_height: self.size.1,
                tile_x_offset: 0,
                tile_y_offset: 0,
                components: self
                    .sampling
                    .iter()
                    .map(|&(x_sampling, y_sampling)| SizComponent {
                        bit_depth: 8,
                        signed: false,
                        x_sampling,
                        y_sampling,
                    })
                    .collect(),
            },
            Cod {
                progression: Progression::Lrcp,
                layers: 1,
                decomposition_levels: self.levels,
                code_block_width: 4, // 2^6
                code_block_height: 4,
                code_block_style: 0,
                use_sop: false,
                use_eph: false,
                multiple_component_transform: false,
                transform: Transform::Reversible53,
                precinct_sizes: self.precincts.clone(),
            },
            Qcd {
                style: QuantStyle::None,
                guard_bits: 2,
                steps: vec![(8, 0); 3 * usize::from(self.levels) + 1],
            },
        )
    }
}

/// The `(layer, resolution, component, precinct)` sequence one order visits over
/// a real tile geometry.
fn order_of(
    layout: &Layout,
    progression: Progression,
    layers: u32,
) -> Vec<(u32, usize, usize, usize)> {
    let mut header = layout.header();
    header.cod.progression = progression;
    header.cod.layers = layers as u16;
    order_of_header(&header)
}

/// [`order_of`] driven by an already-built header, so a test can set a `POC`.
fn order_of_header(header: &MainHeader) -> Vec<(u32, usize, usize, usize)> {
    let geoms: Vec<Vec<ResolutionGeom>> = (0..header.siz.components.len())
        .map(|c| geoms_of(header, 0, c).expect("geometry"))
        .collect();
    let walk = PacketWalk {
        siz: &header.siz,
        tile: header.siz.tile_rect(0).expect("tile 0"),
        geoms: &geoms,
    };
    let mut seen = Vec::new();
    for_each_packet(header, &walk, |l, r, c, p| {
        seen.push((l, r, c, p));
        Ok(())
    })
    .unwrap();
    seen
}

/// Each order is a distinct permutation of the layer / resolution / component
/// nesting (ISO B.12.1). With one precinct per resolution the position axis has a
/// single value and drops out, which is the shape every pre-#61 codestream had.
#[test]
fn each_progression_nests_its_axes_in_the_right_order() {
    // Two resolutions, two components, two layers, and a single precinct each.
    let layout = Layout::plain((32, 32), 1).components(2);
    let first_four = |p| {
        order_of(&layout, p, 2)[..4]
            .iter()
            .map(|&(l, r, c, _)| (l, r, c))
            .collect::<Vec<_>>()
    };

    assert_eq!(
        first_four(Progression::Lrcp),
        [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
    );
    assert_eq!(
        first_four(Progression::Rlcp),
        [(0, 0, 0), (0, 0, 1), (1, 0, 0), (1, 0, 1)]
    );
    assert_eq!(
        first_four(Progression::Rpcl),
        [(0, 0, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1)]
    );
    assert_eq!(
        first_four(Progression::Pcrl),
        [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0)]
    );
}

/// The five orders are permutations of one set, not five different selections of
/// packets. This is the invariant that pins the positional sweeps down: they
/// enumerate precincts by walking the reference grid rather than by counting, so
/// a wrong step, a wrong lattice test, or a wrong `precno` shows up here as a
/// packet visited twice or not at all — even though the *counting* orders next to
/// them cannot go wrong that way.
#[test]
fn every_order_visits_the_same_packets() {
    // Sub-sampled components and precincts smaller than the resolution, so the
    // components' precinct lattices genuinely differ and the sweep has to
    // interleave them.
    let layout = Layout {
        size: (64, 48),
        sampling: vec![(1, 1), (2, 1), (2, 2)],
        levels: 2,
        precincts: vec![(3, 3), (4, 4), (4, 5)],
    };
    let expected: BTreeSet<_> = order_of(&layout, Progression::Lrcp, 3)
        .into_iter()
        .collect();
    assert!(expected.len() > 60, "the layout must be worth walking");

    for progression in ORDERS {
        let seen = order_of(&layout, progression, 3);
        assert_eq!(
            seen.len(),
            expected.len(),
            "{progression:?} visits {} packets, LRCP visits {}",
            seen.len(),
            expected.len(),
        );
        assert_eq!(
            seen.iter().copied().collect::<BTreeSet<_>>(),
            expected,
            "{progression:?} visits a different set of packets than LRCP",
        );
    }
}

/// A deep pyramid pushes a coarse resolution's precinct span past 2^32 reference
/// grid units — with maximal precincts that happens at `NL >= 17`. OpenJPEG scales
/// that span in 64-bit arithmetic and still emits the packet; the positional
/// sweep must do the same, or it silently drops the resolution and desynchronises
/// the tile. The counting orders (LRCP/RLCP) never touch the span, so they are the
/// oracle here: every order must still visit the same set.
#[test]
fn positional_orders_do_not_drop_deep_resolutions() {
    // NL = 17: resolution 0 has span 2^(15+17) = 2^32, one past what a 32-bit
    // shift holds. The low resolutions collapse to 1×1 at the origin, each its own
    // single-precinct packet.
    let layout = Layout::plain((8, 8), 17);
    let expected: BTreeSet<_> = order_of(&layout, Progression::Lrcp, 1)
        .into_iter()
        .collect();

    for progression in ORDERS {
        let seen: BTreeSet<_> = order_of(&layout, progression, 1).into_iter().collect();
        assert_eq!(
            seen, expected,
            "{progression:?} dropped a deep-resolution packet",
        );
    }
}

/// With one precinct per resolution, PCRL and CPRL genuinely enumerate the same
/// sequence — their position loops both degenerate. That was true of every
/// codestream this crate could decode before #61, and it is why OpenJPEG's own
/// output for the two differed in exactly one byte: the COD progression code.
#[test]
fn pcrl_and_cprl_coincide_with_one_precinct() {
    let layout = Layout::plain((32, 32), 2).components(3);
    assert_eq!(
        order_of(&layout, Progression::Pcrl, 3),
        order_of(&layout, Progression::Cprl, 3),
    );
}

/// …and part company as soon as there is more than one precinct to position.
/// PCRL sweeps the canvas once and interleaves the components at each point;
/// CPRL finishes a component's whole sweep before starting the next. This is the
/// distinction no fixture in the corpus could draw until now.
#[test]
fn pcrl_and_cprl_diverge_once_precincts_exist() {
    let layout = Layout::plain((64, 64), 2).components(3).precincts(4, 4);
    let pcrl = order_of(&layout, Progression::Pcrl, 1);
    let cprl = order_of(&layout, Progression::Cprl, 1);

    assert_eq!(pcrl.len(), cprl.len());
    assert_ne!(pcrl, cprl, "the two orders must not coincide");
    // CPRL's first packets all belong to component 0; PCRL's do not.
    assert!(cprl[..cprl.len() / 3].iter().all(|&(_, _, c, _)| c == 0));
    assert!(pcrl[..4].iter().any(|&(_, _, c, _)| c != 0));
}

/// The orders are distinct only when more than one of the axes is. A single
/// component, a single layer and a single precinct collapse all five onto `r`,
/// which is why the conformance entry `p0_01` cannot test any of them.
#[test]
fn the_orders_coincide_when_only_resolution_varies() {
    let layout = Layout::plain((32, 32), 3);
    let first = order_of(&layout, ORDERS[0], 1);
    for progression in ORDERS {
        assert_eq!(order_of(&layout, progression, 1), first, "{progression:?}");
    }
    // Add a second layer and LRCP parts company with RLCP.
    let layered = Layout::plain((32, 32), 1);
    assert_ne!(
        order_of(&layered, Progression::Lrcp, 2),
        order_of(&layered, Progression::Rlcp, 2),
    );
}

// ---- POC: progression-order change (issue #63) ----

/// A `POC` splits the packet stream into progression volumes, each an order over
/// its own sub-range. This one runs resolution 0 in LRCP, then resolutions 1–2
/// in RLCP, over three layers — the packet order across the boundary must be the
/// first volume's sequence followed by the second's, which is hand-built here.
#[test]
fn poc_switches_order_at_the_volume_boundary() {
    // Two resolutions of detail (NL = 2 → resolutions 0,1,2), three layers, one
    // component, one precinct each — so a packet is `(layer, resolution)`.
    let mut header = Layout::plain((32, 32), 2).header();
    header.cod.layers = 3;
    header.poc = vec![
        PocVolume {
            res_start: 0,
            res_end: 1,
            comp_start: 0,
            comp_end: 1,
            layer_end: 3,
            progression: Progression::Lrcp,
        },
        PocVolume {
            res_start: 1,
            res_end: 3,
            comp_start: 0,
            comp_end: 1,
            layer_end: 3,
            progression: Progression::Rlcp,
        },
    ];
    let seq: Vec<(u32, usize)> = order_of_header(&header)
        .into_iter()
        .map(|(l, r, _, _)| (l, r))
        .collect();

    // Volume 0 — resolution 0 only, LRCP (layer outer): (0,0),(1,0),(2,0).
    // Volume 1 — resolutions 1,2, RLCP (resolution outer): all layers of res 1,
    // then all of res 2.
    assert_eq!(
        seq,
        vec![
            (0, 0),
            (1, 0),
            (2, 0),
            (0, 1),
            (1, 1),
            (2, 1),
            (0, 2),
            (1, 2),
            (2, 2),
        ],
    );
}

/// The `POC` volumes may overlap; a packet reached by more than one is emitted
/// once, by the first volume — OpenJPEG's shared `include` array. Here volume 1
/// re-covers everything volume 0 already emitted, so the second volume must add
/// nothing, and the whole stream must still be exactly the tile's packet set.
#[test]
fn poc_emits_each_packet_once_across_overlapping_volumes() {
    let mut header = Layout::plain((32, 32), 2).header();
    header.cod.layers = 2;
    let full = PocVolume {
        res_start: 0,
        res_end: 3,
        comp_start: 0,
        comp_end: 1,
        layer_end: 2,
        progression: Progression::Lrcp,
    };
    // Volume 0 covers everything; volume 1 covers everything again in a different
    // order.
    header.poc = vec![
        full,
        PocVolume {
            progression: Progression::Rlcp,
            ..full
        },
    ];
    let with_overlap = order_of_header(&header);

    // The reference: the same geometry with no POC, plain LRCP over two layers.
    let mut plain = Layout::plain((32, 32), 2).header();
    plain.cod.layers = 2;
    let no_poc = order_of_header(&plain);

    let seen: BTreeSet<_> = with_overlap.iter().copied().collect();
    assert_eq!(
        with_overlap.len(),
        seen.len(),
        "a packet was emitted twice across the overlapping volumes",
    );
    assert_eq!(
        seen,
        no_poc.into_iter().collect::<BTreeSet<_>>(),
        "the overlapping volumes must cover exactly the tile's packet set",
    );
}

// ---- Packet delimiters: SOP / EPH (issue #73) ----

const SOP: Delimiters = Delimiters {
    sop: true,
    eph: false,
};
const EPH: Delimiters = Delimiters {
    sop: false,
    eph: true,
};

/// A six-byte SOP marker segment: `FF91 0004 Nsop`.
fn sop_marker(nsop: u16) -> Vec<u8> {
    let mut v = vec![0xFF, 0x91, 0x00, 0x04];
    v.extend_from_slice(&nsop.to_be_bytes());
    v
}

/// One included block: a header with `zero_bit_planes = 0`, one pass, length 2.
fn one_block_header() -> Vec<u8> {
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included
    w.bit(1); // zero-bitplane 0
    w.bit(0); // 1 pass
    w.bit(0); // Lblock stays 3
    w.bits(2, 3); // length 2
    w.finish()
}

/// SOP precedes the packet header and is consumed; its `Nsop` must match the
/// packet's index within the tile.
#[test]
fn sop_is_consumed_and_its_sequence_number_checked() {
    let mut data = sop_marker(0);
    data.extend_from_slice(&one_block_header());
    data.extend_from_slice(&[0xAB, 0xCD]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_with(&data, &bands, 1, SOP).unwrap();
    assert_eq!(all_bytes(&subbands[0].blocks[0]), vec![0xAB, 0xCD]);
    assert_eq!(next, data.len());
}

/// SOP is optional even when `Scod` signals it (A.8.1). OpenJPEG warns and
/// carries on; rejecting its absence would false-reject a valid codestream.
#[test]
fn a_missing_sop_is_tolerated() {
    let mut data = one_block_header();
    data.extend_from_slice(&[1, 2]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_with(&data, &bands, 1, SOP).unwrap();
    assert_eq!(all_bytes(&subbands[0].blocks[0]), vec![1, 2]);
    assert_eq!(next, data.len());
}

/// A wrong `Nsop` means the packet boundary is not where the codestream says.
/// That is what the marker exists to detect, so it is an error even though
/// OpenJPEG leaves it unchecked (`/* TODO : check the Nsop value */`).
#[test]
fn a_wrong_sop_sequence_number_is_codestream() {
    let mut data = sop_marker(7); // packet 0 claims to be packet 7
    data.extend_from_slice(&one_block_header());
    data.extend_from_slice(&[1, 2]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let e = parse_layers_with(&data, &bands, 1, SOP).unwrap_err();
    assert!(
        matches!(&e, Error::Codestream(m) if m.contains("sequence number")),
        "got {e:?}"
    );
}

#[test]
fn a_malformed_sop_segment_is_codestream() {
    let bands = [single_block_band(BandKind::Ll, 8, 8)];

    // Lsop must be 4.
    let mut data = vec![0xFF, 0x91, 0x00, 0x06, 0x00, 0x00];
    data.extend_from_slice(&one_block_header());
    data.extend_from_slice(&[1, 2]);
    let e = parse_layers_with(&data, &bands, 1, SOP).unwrap_err();
    assert!(
        matches!(&e, Error::Codestream(m) if m.contains("Lsop")),
        "got {e:?}"
    );

    // Truncated before Nsop.
    let data = vec![0xFF, 0x91, 0x00, 0x04, 0x00];
    let e = parse_layers_with(&data, &bands, 1, SOP).unwrap_err();
    assert!(matches!(e, Error::Codestream(_)), "got {e:?}");
}

/// `Nsop` is 16 bits and wraps. Packet 65536 carries `Nsop = 0` again.
#[test]
fn the_sop_sequence_number_wraps_at_65536() {
    let mut data = sop_marker(0);
    data.extend_from_slice(&one_block_header());
    data.extend_from_slice(&[1, 2]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let mut states: Vec<BandState<'_>> = bands.iter().map(BandState::new).collect();
    let mut streams = PacketStreams {
        header: &data,
        header_pos: 0,
        data: &data,
        body_pos: 0,
        packed: false,
    };
    // Packet index 65536 expects Nsop 0, not 65536 (which does not fit).
    parse_packet(&mut streams, 0, 65536, SOP, 0, &bands, 0, &mut states).expect("wraps to zero");
}

/// EPH sits between the packet header and its body, and `Scod` makes it
/// mandatory rather than optional (A.8.2).
#[test]
fn eph_is_consumed_after_the_packet_header() {
    let mut data = one_block_header();
    data.extend_from_slice(&[0xFF, 0x92]);
    data.extend_from_slice(&[3, 4]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_with(&data, &bands, 1, EPH).unwrap();
    assert_eq!(all_bytes(&subbands[0].blocks[0]), vec![3, 4]);
    assert_eq!(next, data.len());
}

#[test]
fn a_missing_eph_is_codestream() {
    let mut data = one_block_header();
    data.extend_from_slice(&[1, 2]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let e = parse_layers_with(&data, &bands, 1, EPH).unwrap_err();
    assert!(
        matches!(&e, Error::Codestream(m) if m.contains("EPH")),
        "got {e:?}"
    );
}

/// An empty packet still carries its EPH: the marker follows the header, and an
/// empty packet has one.
#[test]
fn an_empty_packet_still_carries_its_eph() {
    let mut w = PackedHeader::new();
    w.bit(0); // empty packet
    let mut data = w.finish();
    data.extend_from_slice(&[0xFF, 0x92]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_with(&data, &bands, 1, EPH).unwrap();
    assert_eq!(subbands[0].blocks[0].num_passes, 0);
    assert_eq!(next, data.len());
}

// ---- Code-block style: restart / termall (issue #67) ----

/// Under `restart` each coding pass is a terminated codeword segment of its own,
/// so one contribution carries a length field per pass, not one per contribution.
#[test]
fn restart_splits_a_contribution_into_one_segment_per_pass() {
    const RESTART: u8 = 0x04;
    let mut w = PackedHeader::new();
    w.bit(1); // present
    w.bit(1); // included
    w.bit(1); // zero-bitplane 0
    w.bits(0b1100, 4); // num_passes = 3
    w.bit(0); // Lblock stays 3
    // Three length fields, one per pass. Each is `Lblock + floor(log2 1)` = 3
    // bits wide, because each segment takes exactly one pass.
    w.bits(1, 3);
    w.bits(2, 3);
    w.bits(3, 3);
    let mut data = w.finish();
    data.extend_from_slice(&[0xA1]); // pass 0
    data.extend_from_slice(&[0xB1, 0xB2]); // pass 1
    data.extend_from_slice(&[0xC1, 0xC2, 0xC3]); // pass 2

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_styled(
        &data,
        &bands,
        1,
        Delimiters {
            sop: false,
            eph: false,
        },
        RESTART,
    )
    .unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 3);
    assert_eq!(block.segments.len(), 3, "one segment per coding pass");
    for segment in &block.segments {
        assert_eq!(segment.passes, 1);
    }
    assert_eq!(block.segments[0].bytes(), vec![0xA1]);
    assert_eq!(block.segments[1].bytes(), vec![0xB1, 0xB2]);
    assert_eq!(block.segments[2].bytes(), vec![0xC1, 0xC2, 0xC3]);
    assert_eq!(next, data.len());
}

/// Without `restart` the same three passes share one segment and one length
/// field — the codeword is continuous.
#[test]
fn the_default_style_keeps_one_segment_for_every_pass() {
    let mut w = PackedHeader::new();
    w.bit(1);
    w.bit(1); // included
    w.bit(1); // zero-bitplane 0
    w.bits(0b1100, 4); // num_passes = 3
    w.bit(0); // Lblock stays 3
    // One length field, `Lblock + floor(log2 3)` = 4 bits wide.
    w.bits(6, 4);
    let mut data = w.finish();
    data.extend_from_slice(&[1, 2, 3, 4, 5, 6]);

    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers(&data, &bands, 1).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 3);
    assert_eq!(block.segments.len(), 1, "one continuous codeword");
    assert_eq!(block.segments[0].passes, 3);
    assert_eq!(next, data.len());
}

/// A segment never takes more passes than it may. Under `restart` a layer that
/// contributes several passes opens several segments inside one packet.
#[test]
fn restart_segments_fill_one_pass_at_a_time_across_layers() {
    const RESTART: u8 = 0x04;
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bit(0); // 1 pass
    l0.bit(0); // Lblock stays 3
    l0.bits(1, 3); // one length

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bit(0); // 1 pass — a *new* segment, since the first is full
    l1.bit(0); // Lblock stays 3
    l1.bits(2, 3);

    let data = packets(&[(l0.finish(), vec![7]), (l1.finish(), vec![8, 9])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let (subbands, next) = parse_layers_styled(
        &data,
        &bands,
        2,
        Delimiters {
            sop: false,
            eph: false,
        },
        RESTART,
    )
    .unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 2);
    assert_eq!(
        block.segments.len(),
        2,
        "a full segment does not take more passes"
    );
    assert_eq!(block.segments[0].bytes(), vec![7]);
    assert_eq!(block.segments[1].bytes(), vec![8, 9]);
    assert_eq!(next, data.len());
}

// ---- Code-block style: bypass / lazy (issue #66) ----

/// The lazy (`bypass`) split terminates at every raw/MQ boundary: the ten MQ
/// passes of the four most significant bit-planes come first, then each lower
/// plane splits into a two-pass raw segment (significance + refinement) and a
/// one-pass MQ segment (cleanup) — OpenJPEG's `opj_t2_init_seg` `10, 2, 1, 2,
/// 1, …`.
#[test]
fn lazy_segment_max_passes_follows_the_10_2_1_pattern() {
    const LAZY: u8 = 0x01;
    let mut segments: Vec<SegmentState<'_>> = Vec::new();
    let mut pattern = Vec::new();
    for _ in 0..7 {
        let max_passes = segment_max_passes(LAZY, &segments);
        pattern.push(max_passes);
        segments.push(SegmentState {
            passes: 0,
            max_passes,
            chunks: Vec::new(),
        });
    }
    assert_eq!(pattern, [10, 2, 1, 2, 1, 2, 1]);
}

/// `bypass` leaves the other split rules untouched: `termall` still terminates
/// every pass, and the default style takes a single 109-pass segment.
#[test]
fn non_lazy_segment_max_passes_is_unchanged() {
    const TERMALL: u8 = 0x04;
    assert_eq!(segment_max_passes(TERMALL, &[]), 1);
    assert_eq!(segment_max_passes(0, &[]), 109);
}