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
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
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
//! 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::geometry::ResolutionGeom;
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 signaled.
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,
        tile: 0,
    };
    // One scratch for every layer, as the walk keeps it across packets.
    let mut scratch = Scratch::default();
    for layer in 0..layers {
        parse_packet(
            &mut streams,
            &super::Visits::new(u64::MAX),
            layer,
            layer,
            delimiters,
            style,
            bands,
            0,
            &mut states,
            &mut scratch,
            None,
        )?;
    }
    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),
        part_ends: vec![data.len()],
        packed_headers: Vec::new(),
    }
}

fn single_block_band(kind: BandKind, width: usize, height: usize) -> BandGeom {
    // One code-block cell as large as the band, at the canvas origin.
    let exp = |side: usize| side.next_power_of_two().trailing_zeros();
    BandGeom {
        kind,
        origin: (0, 0),
        width,
        height,
        block_cols: 1,
        block_rows: 1,
        bounds: (0, width as i64, 0, height as i64),
        first_block: (0, 0),
        block_exp: (exp(width), exp(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,
        first: 0,
        stride: cols,
    }]
}

/// [`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;
    let mut block_budget = usize::MAX;
    resolution_geoms(header, tile, comp, &mut budget, &mut block_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));
    let blocks: Vec<_> = ll.block_rects().collect();
    assert_eq!(blocks.len(), 16);
    // First block is a full 32×32 cell at the origin.
    assert_eq!(blocks[0], (0, 0, 32, 32));
    // The last of the first row is clipped to 100 − 96 = 4 wide.
    assert_eq!(blocks[3], (96, 0, 4, 32));
    // The bottom-right block is clipped to 100 − 96 = 4 on each axis.
    assert_eq!(blocks[15], (96, 96, 4, 4));
}

/// On grids that do not start at the canvas origin, with precincts smaller
/// than the band, the code-blocks tile each band exactly, in raster order,
/// and the precincts split the band's blocks between them with each block in
/// exactly one, in raster order within the precinct. A tile one row high
/// gives bands with width but no height, which hold no blocks at all.
#[test]
fn blocks_tile_the_band_and_precincts_partition_them() {
    let mut flat_bands = 0;
    for (offset, levels, cb, precinct, height) in [
        (0, 2, 2, 4, 75),
        (3, 3, 2, 5, 75),
        (17, 2, 3, 6, 75),
        (5, 4, 2, 15, 75),
        (0, 2, 2, 4, 1),
    ] {
        let mut header = header(97, height, levels, cb);
        header.siz.x_offset = offset;
        header.siz.y_offset = offset / 2;
        header.siz.tile_x_offset = 0;
        header.siz.tile_y_offset = 0;
        header.siz.tile_width = 97 + offset;
        header.siz.tile_height = height + offset;
        header.components[0].coding.precinct_sizes =
            vec![(precinct, precinct); usize::from(levels) + 1];
        let geoms = geoms_of(&header, 0, 0).unwrap();
        for band in geoms.iter().flat_map(|r| &r.bands) {
            flat_bands += usize::from(band.height == 0 && band.block_cols > 0);
            let rects: Vec<_> = band.block_rects().collect();
            assert_eq!(rects.len(), band.block_count());
            let area: usize = rects.iter().map(|&(_, _, w, h)| w * h).sum();
            assert_eq!(area, band.width * band.height, "the blocks tile the band");
            for (index, &(x, y, w, h)) in rects.iter().enumerate() {
                assert!(w > 0 && h > 0 && x + w <= band.width && y + h <= band.height);
                // Raster order: same row as the block before, or a new row.
                if index % band.block_cols != 0 {
                    let (px, py, pw, _) = rects[index - 1];
                    assert_eq!((x, y), (px + pw, py));
                }
            }
            let mut owner = vec![0; band.block_count()];
            for precinct in &band.precincts {
                for y in 0..precinct.rows {
                    for x in 0..precinct.cols {
                        let index = precinct.block(x, y);
                        owner[index] += 1;
                        // The precinct's blocks form a rectangle of the grid.
                        let first = precinct.block(0, 0);
                        assert_eq!(index % band.block_cols, first % band.block_cols + x);
                        assert_eq!(index / band.block_cols, first / band.block_cols + y);
                    }
                }
            }
            assert!(owner.iter().all(|&n| n == 1), "each block in one precinct");
        }
    }
    assert!(flat_bands > 0, "a band with width and no height was built");
}

/// A tile of one sample at an odd origin has a precinct at its finest
/// resolution alone. The geometry builds no band for the 32 others, yet
/// `decode_packets` still hands each its empty subbands at their own origins
/// (ISO B.5, Eq. B-15), which the inverse DWT reads.
#[test]
fn empty_resolutions_build_no_band_geometry() {
    let mut header = header(2, 2, 32, 6);
    header.siz.x_offset = 1;
    header.siz.y_offset = 1;
    header.siz.tile_x_offset = 1;
    header.siz.tile_y_offset = 1;
    header.siz.tile_width = 1;
    header.siz.tile_height = 1;
    let geoms = geoms_of(&header, 0, 0).unwrap();
    assert_eq!(geoms.len(), 33);
    for geom in &geoms[..32] {
        assert_eq!(geom.precinct_count(), 0);
        assert!(geom.bands.is_empty());
    }
    assert_eq!(geoms[32].precinct_count(), 1);
    assert_eq!(geoms[32].bands.len(), 3);

    // One empty packet, for the finest resolution's precinct.
    let data = [0u8];
    let tile = tile(&data);
    let coded = decode_packets(&header, &tile, &mut decode_visits(0), u64::MAX, 0).unwrap();
    let resolutions = &coded.components[0].resolutions;
    assert_eq!(resolutions.len(), 33);
    type Band = (BandKind, (u32, u32), usize, usize, usize);
    let bands = |r: usize| -> Vec<Band> {
        resolutions[r]
            .subbands
            .iter()
            .map(|b| (b.kind, b.origin, b.width, b.height, b.blocks.len()))
            .collect()
    };
    // NLLL at level 32: [ceil(1 / 2^32), ceil(2 / 2^32)) = [1, 1) both ways.
    assert_eq!(bands(0), [(BandKind::Ll, (1, 1), 0, 0, 0)]);
    // Level 2, at resolution 31: HL is [0, 0) x [1, 1), LH [1, 1) x [0, 0).
    assert_eq!(
        bands(31),
        [
            (BandKind::Hl, (0, 1), 0, 0, 0),
            (BandKind::Lh, (1, 0), 0, 0, 0),
            (BandKind::Hh, (0, 0), 0, 0, 0),
        ]
    );
    // Level 1 holds the one sample, in HH.
    assert_eq!(
        bands(32),
        [
            (BandKind::Hl, (0, 1), 1, 0, 0),
            (BandKind::Lh, (1, 0), 0, 1, 0),
            (BandKind::Hh, (0, 0), 1, 1, 1),
        ]
    );
}

/// 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 mut block_budget = super::MAX_CODE_BLOCKS;
    let start = Instant::now();
    let result = resolution_geoms(&header, 0, 0, &mut budget, &mut block_budget);
    let elapsed = start.elapsed();

    assert!(
        matches!(result, Err(crate::Error::Limit(_))),
        "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 mut block_budget = super::MAX_CODE_BLOCKS;
    let first = resolution_geoms(&header, 0, 0, &mut budget, &mut block_budget);
    let second = resolution_geoms(&header, 0, 1, &mut budget, &mut block_budget);
    assert!(
        first.is_err() || matches!(second, Err(crate::Error::Limit(_))),
        "two components sharing the budget must not both allocate their precincts"
    );
}

/// At a resolution reduction, the code-blocks of the resolutions it drops
/// are charged to the decode's work bound, one visit each, before any packet
/// is read; nothing else of the geometry is. A 256 x 256 tile of two levels in
/// 16 x 16 code-blocks has 16, 48 and 192 code-blocks at resolutions 0, 1 and
/// 2, so a reduction of 1 drops 192 and a reduction of 2 drops 240.
#[test]
fn the_dropped_resolutions_code_blocks_are_charged_to_the_work_bound() {
    let mut header = header(256, 256, 2, 4);
    header.components[0].coding.precinct_sizes = vec![(15, 15), (6, 6), (6, 6)];
    let geoms = geoms_of(&header, 0, 0).unwrap();
    let blocks: Vec<usize> = geoms
        .iter()
        .map(|r| r.bands.iter().map(BandGeom::block_count).sum())
        .collect();
    assert_eq!(blocks, [16, 48, 192]);
    let precincts: usize = geoms.iter().map(ResolutionGeom::precinct_count).sum();
    // One empty packet for each precinct.
    let data = vec![0u8; precincts];
    let tile = tile(&data);
    let walk = |visits: u64, reduction: u8| {
        let mut budget = Budget {
            reduction,
            ..Budget::decode(visits, u64::MAX)
        };
        let result = decode_packets_within(&header, &tile, &mut budget).map(|_| ());
        (result, budget.visits)
    };

    let spent = |reduction| {
        let (result, left) = walk(u64::MAX, reduction);
        result.expect("the packets end at the end");
        u64::MAX - left
    };
    let full = spent(0);
    assert_eq!(spent(1) - full, 192);
    assert_eq!(spent(2) - full, 240);

    // The charge comes before the walk: one visit short, the geometry is
    // refused and nothing is spent; with exactly enough, the walk fails at its
    // first packet with nothing left.
    for (visits, left) in [(239, 239), (240, 0)] {
        let (result, after) = walk(visits, 2);
        assert!(matches!(result, Err(crate::Error::Limit(_))), "{visits}");
        assert_eq!(after, left, "with {visits} visits");
    }
}

/// 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,
        bounds: (0, 16, 0, 8),
        first_block: (0, 0),
        block_exp: (3, 3),
        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], &mut decode_visits(0), u64::MAX, 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, &mut decode_visits(0), u64::MAX, 0);
    }
}

/// 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, &mut decode_visits(0), u64::MAX, 0)
        .map_err(Error::from)
        .expect_err("guard fires before any packet parse");
    assert!(matches!(err, crate::Error::Limit(_)), "{err}");
}

/// The block budget bites while the geometry is built, not after summing it:
/// an 8192×8192 single-band tile-component under 4×4 blocks is ~2^22 blocks,
/// and materializing per-block state for that grid first is the ~160 MiB /
/// multi-second cost an after-the-fact check pays. With the guard enforced
/// inside the geometry walk this returns in microseconds.
#[test]
fn block_count_guard_rejects_before_allocating() {
    use std::time::Instant;
    // nl = 0 → one resolution, one LL band covering the whole tile-component;
    // 8192/4 = 2048 blocks each way, ~2^22 in the single band.
    let header = header(8192, 8192, 0, 2);

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

    assert!(
        matches!(result, Err(crate::Error::Limit(_))),
        "an 8192×8192 single-band tile-component under 4×4 blocks must be rejected"
    );
    assert!(
        elapsed.as_millis() < 100,
        "the guard must fire while the geometry is built, not after ({elapsed:?})"
    );
}

// ---- 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_honor_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 desynchronize 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 signaled. A decoder that
/// reset it would read the wrong number of bits and desynchronize.
#[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 desynchronize.
#[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 may take coding passes and no bytes from every layer: B.10.7 sets
/// no lower bound on a contribution's length, and Tier-1 decodes the passes
/// from the `0xFF` fill (D.4.1), as OpenJPEG does. The passes still count and
/// the one segment holds them both, with no chunk.
#[test]
fn a_block_with_passes_and_no_bytes_at_all_is_accepted() {
    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)];
    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!(block.segments.len(), 1);
    assert_eq!(block.segments[0].passes, 2);
    assert!(
        block.segments[0].chunks.is_empty(),
        "a zero length files no chunk"
    );
    assert_eq!(next, data.len());
}

/// Under `bypass` a zero-length contribution still fills its codeword
/// segments, so the next layer's passes and lengths go to the right ones. Layer
/// 0 adds 11 passes: segment 0 (ten MQ passes) and one pass of segment 1 (raw,
/// two passes), both with a length of zero. Layer 1 adds 2 passes: the second
/// of segment 1, with its bytes, then segment 2 (one MQ pass).
#[test]
fn a_zero_length_bypass_contribution_keeps_the_segments_in_step() {
    use crate::codestream::markers::code_block_style::LAZY;
    let mut l0 = PackedHeader::new();
    l0.bit(1);
    l0.bit(1); // included
    l0.bit(1); // zero-bitplane 0
    l0.bits(0b1111, 4);
    l0.bits(11 - 6, 5); // 11 passes
    l0.bit(0); // Lblock 3
    l0.bits(0, 3 + 3); // segment 0: ten passes, floor(log2 10) = 3, length 0
    l0.bits(0, 3); // segment 1: one pass, length 0

    let mut l1 = PackedHeader::new();
    l1.bit(1);
    l1.bit(1); // contributes
    l1.bits(0b10, 2); // 2 passes
    l1.bit(0); // Lblock 3
    l1.bits(2, 3); // segment 1: one more pass, 2 bytes
    l1.bits(1, 3); // segment 2: one pass, 1 byte

    let data = packets(&[(l0.finish(), vec![]), (l1.finish(), vec![0x11, 0x22, 0x33])]);
    let bands = [single_block_band(BandKind::Ll, 8, 8)];
    let delimiters = Delimiters {
        sop: false,
        eph: false,
    };
    let (subbands, next) = parse_layers_styled(&data, &bands, 2, delimiters, LAZY).unwrap();

    let block = &subbands[0].blocks[0];
    assert_eq!(block.num_passes, 13);
    let shape: Vec<(u32, Vec<u8>)> = block
        .segments
        .iter()
        .map(|s| (s.passes, s.bytes()))
        .collect();
    assert_eq!(
        shape,
        vec![(10, vec![]), (2, vec![0x11, 0x22]), (1, vec![0x33])]
    );
    assert_eq!(next, data.len());
}

/// 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,
        &super::Visits::new(u64::MAX),
        u64::MAX,
        true,
        |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 desynchronizes
/// 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",
    );
}

/// `header`'s packets, walked with every visit to spare and its `POC`
/// sequence's packets held in a bitmap only when they are at most
/// `dense_bits`, as [`super::progression::for_each_packet`] holds
/// them.
fn order_holding(header: &MainHeader, dense_bits: u64) -> 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();
    super::progression::for_each_packet(
        header,
        &walk,
        &super::Visits::new(u64::MAX),
        dense_bits,
        true,
        |l, r, c, p| {
            seen.push((l, r, c, p));
            Ok(())
        },
    )
    .unwrap();
    seen
}

/// Three components, two sub-sampled differently, two levels, 4x4 precincts
/// at every resolution and four layers, under five `POC` volumes that overlap
/// in part and in full, in all five orders. The last two cover the whole tile.
fn overlapping_volumes() -> MainHeader {
    let mut layout = Layout::plain((32, 32), 2).components(3).precincts(2, 2);
    layout.sampling = vec![(1, 1), (2, 2), (1, 2)];
    let mut header = layout.header();
    header.cod.layers = 4;
    let volume = |res: (u8, u8), comp: (u16, u16), layer_end: u16, progression| PocVolume {
        res_start: res.0,
        res_end: res.1,
        comp_start: comp.0,
        comp_end: comp.1,
        layer_end,
        progression,
    };
    header.poc = vec![
        volume((0, 2), (0, 2), 2, Progression::Lrcp),
        volume((1, 3), (1, 3), 3, Progression::Rpcl),
        volume((0, 3), (0, 3), 1, Progression::Pcrl),
        volume((0, 3), (0, 3), 4, Progression::Cprl),
        volume((0, 3), (0, 3), 4, Progression::Rlcp),
    ];
    header
}

/// Volumes that overlap, in part and in full and in every order, emit each
/// packet once, where the first volume to reach it puts it, whether the
/// sequence's packets are held in a bitmap or in a set. The reference walks
/// each volume on its own (one volume takes no dedup) and keeps the first
/// time each packet comes.
#[test]
fn overlapping_poc_volumes_emit_each_packet_once_in_order() {
    let header = overlapping_volumes();
    let mut first = Vec::new();
    let mut reached = std::collections::HashSet::new();
    for volume in &header.poc {
        let mut alone = header.clone();
        alone.poc = vec![*volume];
        first.extend(
            order_of_header(&alone)
                .into_iter()
                .filter(|&packet| reached.insert(packet)),
        );
    }
    // The last volumes cover the whole tile: every packet of the plain order.
    let mut plain = header.clone();
    plain.poc.clear();
    let all: BTreeSet<_> = order_of_header(&plain).into_iter().collect();
    assert_eq!(first.iter().copied().collect::<BTreeSet<_>>(), all);
    assert!(first.len() > 100, "{} packets", first.len());

    assert_eq!(order_of_header(&header), first, "bitmap");
    assert_eq!(order_holding(&header, u64::MAX), first, "bitmap");
    assert_eq!(order_holding(&header, 0), first, "set");
}

/// When the volumes reach more packets than the walk has visits left and
/// every volume is a layer order, which reads every precinct it reaches, the
/// walk cannot finish: it is refused before a packet is read. With exactly
/// as many visits as packets it starts.
#[test]
fn layer_order_volumes_past_the_visits_left_are_refused_at_once() {
    let mut header = Layout::plain((32, 32), 2).header();
    header.cod.layers = 4;
    let full = PocVolume {
        res_start: 0,
        res_end: 3,
        comp_start: 0,
        comp_end: 1,
        layer_end: 4,
        progression: Progression::Lrcp,
    };
    header.poc = vec![
        full,
        PocVolume {
            progression: Progression::Rlcp,
            ..full
        },
    ];
    let geoms: Vec<Vec<ResolutionGeom>> = vec![geoms_of(&header, 0, 0).expect("geometry")];
    let walk = PacketWalk {
        siz: &header.siz,
        tile: header.siz.tile_rect(0).expect("tile 0"),
        geoms: &geoms,
    };
    // 4 layers x 3 resolutions x 1 precinct.
    let walk_with = |header: &MainHeader, visits: u64, poc_bitmap: Option<u64>| {
        let mut read = 0;
        let result = for_each_packet(
            header,
            &walk,
            &super::Visits::new(visits),
            poc_bitmap.unwrap_or(visits),
            poc_bitmap.is_none(),
            |_, _, _, _| {
                read += 1;
                Ok(())
            },
        );
        (result, read)
    };
    let (result, read) = walk_with(&header, 11, None);
    match result {
        Err(Error::Limit(m)) => assert!(m.contains("work bound") && m.contains("12"), "{m}"),
        other => panic!("expected the work bound, got {other:?}"),
    }
    assert_eq!(read, 0);
    let (_, read) = walk_with(&header, 12, None);
    assert!(read > 0);
    // A bitmap cap above the visits left does not save it.
    let (result, read) = walk_with(&header, 11, Some(u64::MAX));
    assert!(matches!(result, Err(Error::Limit(_))), "{result:?}");
    assert_eq!(read, 0);

    // A positional volume may pass over precincts, so it is walked, unless
    // the walk keeps no set, as `read_header`'s does not, and the packets
    // are more than its bitmap may hold.
    header.poc[1].progression = Progression::Rpcl;
    let (result, read) = walk_with(&header, 11, None);
    assert!(read > 0, "{result:?}");
    let (result, read) = walk_with(&header, 11, Some(11));
    assert!(matches!(result, Err(Error::Limit(_))), "{result:?}");
    assert_eq!(read, 0);
    let (result, read) = walk_with(&header, 11, Some(12));
    assert!(read > 0, "{result:?}");
}

/// A packet skipped from the set is charged `SET_SKIP_VISITS` (12) visits,
/// one skipped from the bitmap none: two identical RPCL volumes spend 12
/// visits more per packet read when the packets are held in a set.
#[test]
fn only_a_skip_from_the_set_is_charged() {
    let mut header = overlapping_volumes();
    let full = PocVolume {
        res_start: 0,
        res_end: 3,
        comp_start: 0,
        comp_end: 3,
        layer_end: 4,
        progression: Progression::Rpcl,
    };
    header.poc = vec![full, full];
    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 spent = |dense_bits: u64| {
        let visits = super::Visits::new(u64::MAX);
        let mut read = 0u64;
        super::progression::for_each_packet(
            &header,
            &walk,
            &visits,
            dense_bits,
            true,
            |_, _, _, _| {
                read += 1;
                Ok(())
            },
        )
        .unwrap();
        (u64::MAX - visits.get(), read)
    };
    let (bitmap, read) = spent(u64::MAX);
    let (set, read_from_set) = spent(0);
    assert_eq!(read, read_from_set);
    assert!(read > 100, "{read} packets");
    assert_eq!(set - bitmap, 12 * read);
}

// ---- POC coverage (issue #260) ----

/// `check_poc_coverage` on `header`'s own geometry.
fn coverage(header: &MainHeader) -> Result<()> {
    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,
    };
    super::progression::check_poc_coverage(header, &walk, 0)
}

fn poc(res: (u8, u8), comp: (u16, u16), layer_end: u16, progression: Progression) -> PocVolume {
    PocVolume {
        res_start: res.0,
        res_end: res.1,
        comp_start: comp.0,
        comp_end: comp.1,
        layer_end,
        progression,
    }
}

/// Three components, three resolutions, three layers.
fn coverage_header(volumes: Vec<PocVolume>) -> MainHeader {
    let mut header = Layout::plain((32, 32), 2).components(3).header();
    header.cod.layers = 3;
    header.poc = volumes;
    header
}

/// Volumes that together reach every layer, resolution and component pass;
/// volumes that leave out the first or the last of any axis, or a gap where
/// two volumes meet, are `Codestream`, naming the first packet left out.
#[test]
fn poc_volumes_must_cover_every_packet_of_the_tile() {
    use Progression::{Cprl, Lrcp, Pcrl, Rlcp, Rpcl};
    let pass = |volumes: Vec<PocVolume>| coverage(&coverage_header(volumes));
    let fail = |volumes: Vec<PocVolume>, comp: usize, res: usize, layer: u16| match pass(
        volumes.clone(),
    ) {
        Err(Error::Codestream(m)) => assert!(
            m.contains(&format!(
                "component {comp}, resolution {res}, from layer {layer} of 3"
            )),
            "{volumes:?}: {m}"
        ),
        other => panic!("{volumes:?}: expected a codestream error, got {other:?}"),
    };

    // One volume over everything, in each order, and past the axes' ends.
    for order in [Lrcp, Rlcp, Rpcl, Pcrl, Cprl] {
        pass(vec![poc((0, 3), (0, 3), 3, order)]).unwrap();
    }
    pass(vec![poc((0, 33), (0, 255), 255, Rpcl)]).unwrap();
    // Each axis split between two volumes that meet.
    pass(vec![
        poc((0, 1), (0, 3), 3, Lrcp),
        poc((1, 3), (0, 3), 3, Cprl),
    ])
    .unwrap();
    pass(vec![
        poc((0, 3), (0, 2), 3, Lrcp),
        poc((0, 3), (2, 3), 3, Rpcl),
    ])
    .unwrap();
    // Layers: a later volume over every layer completes an earlier one.
    pass(vec![
        poc((0, 3), (0, 3), 1, Lrcp),
        poc((0, 3), (0, 3), 3, Pcrl),
    ])
    .unwrap();

    // The last of each axis left out.
    fail(vec![poc((0, 3), (0, 3), 2, Lrcp)], 0, 0, 2);
    fail(vec![poc((0, 2), (0, 3), 3, Lrcp)], 0, 2, 0);
    fail(vec![poc((0, 3), (0, 2), 3, Lrcp)], 2, 0, 0);
    // The first of each axis left out (layers always start at 0).
    fail(vec![poc((1, 3), (0, 3), 3, Rlcp)], 0, 0, 0);
    fail(vec![poc((0, 3), (1, 3), 3, Cprl)], 0, 0, 0);
    // A gap between two volumes.
    fail(
        vec![poc((0, 1), (0, 3), 3, Lrcp), poc((2, 3), (0, 3), 3, Lrcp)],
        0,
        1,
        0,
    );
    fail(
        vec![poc((0, 3), (0, 1), 3, Lrcp), poc((0, 3), (2, 3), 3, Lrcp)],
        1,
        0,
        0,
    );
    // Layers split over different resolutions do not add up: resolution 1
    // has layers 0..1 from the first volume only.
    fail(
        vec![
            poc((0, 2), (0, 3), 1, Lrcp),
            poc((0, 1), (0, 3), 3, Lrcp),
            poc((2, 3), (0, 3), 3, Lrcp),
        ],
        0,
        1,
        1,
    );
    // Without a POC there is nothing to check.
    pass(Vec::new()).unwrap();
}

/// A component with fewer decomposition levels (its own `COC`) has fewer
/// resolutions, and a volume need only cover those it has: here component 1
/// has two, and its volume stops at resolution 2. Its missing second
/// resolution is still refused.
#[test]
fn poc_coverage_counts_each_components_own_resolutions() {
    let mut header = coverage_header(vec![
        poc((0, 3), (0, 1), 3, Progression::Lrcp),
        poc((0, 2), (1, 2), 3, Progression::Rpcl),
        poc((0, 3), (2, 3), 3, Progression::Cprl),
    ]);
    header.components[1].coding.decomposition_levels = 1;
    coverage(&header).unwrap();

    header.poc[1].res_end = 1;
    match coverage(&header) {
        Err(Error::Codestream(m)) => assert!(m.contains("component 1, resolution 1,"), "{m}"),
        other => panic!("expected a codestream error, got {other:?}"),
    }
}

/// A resolution empty on the tile has no precincts and so no packets, and no
/// volume need cover it. A 2 x 1 tile at x = 1 has nothing at resolution 0 of
/// two levels: `ceil(1 / 4) = ceil(3 / 4)`.
#[test]
fn poc_coverage_does_not_need_an_empty_resolution() {
    let mut header = Layout::plain((3, 1), 2).header();
    header.siz.x_offset = 1;
    let geoms = geoms_of(&header, 0, 0).unwrap();
    assert_eq!(geoms[0].precinct_count(), 0);
    assert!(geoms[1].precinct_count() > 0);
    header.poc = vec![poc((1, 3), (0, 1), 1, Progression::Lrcp)];
    coverage(&header).unwrap();
    header.poc[0].res_start = 2;
    assert!(matches!(coverage(&header), Err(Error::Codestream(_))));
}

/// The refusal names the tile it is in: here the second of two 16 x 32
/// tiles, through the decode's own entry point.
#[test]
fn the_poc_coverage_error_names_the_tile() {
    let mut header = coverage_header(vec![poc((0, 2), (0, 3), 3, Progression::Lrcp)]);
    header.siz.tile_width = 16;
    let mut second = tile(&[]);
    second.index = 1;
    match decode_packets(&header, &second, &mut decode_visits(0), u64::MAX, 0).map_err(Error::from)
    {
        Err(Error::Codestream(m)) => assert!(
            m.contains("tile 1 leave out its packets of component 0, resolution 2,"),
            "{m}"
        ),
        Err(e) => panic!("expected a codestream error, got {e}"),
        Ok(_) => panic!("expected a codestream error, got coded data"),
    }
}

// ---- 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,
        tile: 0,
    };
    // Packet index 65536 expects Nsop 0, not 65536 (which does not fit).
    parse_packet(
        &mut streams,
        &super::Visits::new(u64::MAX),
        0,
        65536,
        SOP,
        0,
        &bands,
        0,
        &mut states,
        &mut Scratch::default(),
        None,
    )
    .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);
}