rust-j2k 0.5.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
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
//! Stage 1 — codestream parsing (ISO/IEC 15444-1 Annex A).
//!
//! Walks the marker segments of a raw J2K codestream: the main header
//! (SIZ / COD / QCD, plus optional COC / QCC / RGN / TLM / PLM / COM), then
//! the tile-parts (SOT, optional RGN / PLT / COM, SOD, data). Produces a
//! [`MainHeader`] of decode parameters and the byte ranges of each tile's
//! packet data — everything the later stages need, with no interpretation of
//! the entropy-coded bytes yet.
//!
//! The main header is located before it is judged: [`walk_main_header`] finds
//! every marker segment without caring what the decoder supports, and
//! [`parse_main_header`] then interprets them. That split is what lets a
//! codestream be traversed past a feature we cannot decode, and is what makes
//! the reserved segment-less markers and unknown segments handleable at all.

pub mod markers;

use std::borrow::Cow;
use std::cell::OnceCell;
use std::collections::{HashMap, HashSet};

use crate::report::ReportEntry;
use crate::{Error, Result};
use markers::{
    Ccap15, Cod, Coding, ComponentParams, Cpf, PocVolume, Progression, Qcd, QuantStyle, Siz,
    SizComponent, TlmEntry, Transform, marker,
};

/// Parsed main-header decode parameters. COD/QCD carry the codestream-wide
/// defaults; [`components`](Self::components) carries each component's effective
/// parameters after any COC/QCC override and any RGN maxshift — the main
/// header's, replaced by the tile-part header's where one appears (A.6.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MainHeader {
    pub siz: Siz,
    pub cod: Cod,
    pub qcd: Qcd,
    /// Effective coding and quantization parameters per component, in SIZ order:
    /// COD/QCD's defaults with any COC/QCC override already applied. Every stage
    /// past the header reads these rather than [`cod`](Self::cod) or
    /// [`qcd`](Self::qcd), which hold the codestream-wide defaults.
    pub components: Vec<ComponentParams>,
    /// The progression volumes of any `POC` marker, in order; empty when the
    /// codestream carries none, in which case the packet order is [`cod`]'s
    /// single progression over every axis (A.6.6). A `POC` in a tile's first
    /// tile-part replaces this for its tile, the same way a tile COD replaces
    /// the coding style.
    ///
    /// [`cod`]: Self::cod
    pub poc: Vec<PocVolume>,
    /// `(Xcrg, Ycrg)` sub-pixel registration offsets per component, in SIZ
    /// order, from a `CRG` marker; empty when the codestream carries none
    /// (A.9.1). Informational: the offsets say how a display should register the
    /// components against one another, in units of `1/65536` of the reference-grid
    /// step, and do not change the decoded samples — so they are recorded for a
    /// caller to act on, not resampled here (OpenJPEG likewise reads past them).
    pub crg: Vec<(u16, u16)>,
    /// The `Ccap15` word of a `CAP` marker that signals Part 15 (HTJ2K);
    /// `None` when the codestream carries no `CAP`, or one that signals no
    /// Part 15 capability. It is read for MULTIHT, which is refused, and does
    /// not decide the block coder: each component's code-block style does.
    pub ccap15: Option<Ccap15>,
    /// The `CPF` marker, when the codestream carries one (ISO/IEC 15444-15
    /// A.6). Informational.
    pub cpf: Option<Cpf>,
}

impl MainHeader {
    /// A header whose components all take the COD/QCD defaults — the shape of
    /// every codestream that carries no COC and no QCC.
    pub fn new(siz: Siz, cod: Cod, qcd: Qcd) -> Self {
        let components = vec![
            ComponentParams {
                coding: cod.coding.clone(),
                quant: qcd.clone(),
                roi_shift: 0,
            };
            siz.components.len()
        ];
        MainHeader {
            siz,
            cod,
            qcd,
            components,
            poc: Vec::new(),
            crg: Vec::new(),
            ccap15: None,
            cpf: None,
        }
    }
}

#[cfg(test)]
impl MainHeader {
    /// A single-component header for unit tests: a `width` x `height` image at
    /// the origin in one tile, unit sub-sampling, LRCP, one layer, 64 x 64
    /// code-blocks, no precincts, and the given depth, wavelet and `qcd`.
    pub(crate) fn single_component(
        size: (u32, u32),
        depth: (u8, bool),
        wavelet: (u8, Transform),
        qcd: Qcd,
    ) -> Self {
        MainHeader::single_component_blocks(size, depth, wavelet, 6, qcd)
    }

    /// [`single_component`](Self::single_component) with code-blocks of
    /// `1 << block_exp` samples square; the stored exponent is `block_exp - 2`.
    pub(crate) fn single_component_blocks(
        (width, height): (u32, u32),
        (bit_depth, signed): (u8, bool),
        (decomposition_levels, transform): (u8, Transform),
        block_exp: u8,
        qcd: Qcd,
    ) -> Self {
        MainHeader::new(
            Siz {
                x_size: width,
                y_size: height,
                x_offset: 0,
                y_offset: 0,
                tile_width: width,
                tile_height: height,
                tile_x_offset: 0,
                tile_y_offset: 0,
                components: vec![SizComponent {
                    bit_depth,
                    signed,
                    x_sampling: 1,
                    y_sampling: 1,
                }],
            },
            Cod {
                progression: Progression::Lrcp,
                layers: 1,
                use_sop: false,
                use_eph: false,
                multiple_component_transform: false,
                coding: Coding {
                    decomposition_levels,
                    code_block_width: block_exp - 2,
                    code_block_height: block_exp - 2,
                    code_block_style: 0,
                    transform,
                    precinct_sizes: vec![],
                },
            },
            qcd,
        )
    }
}

/// One tile of the image: its index in the tile grid, the decode parameters in
/// force inside it, and its packet data.
///
/// A tile can be split across several tile-parts, interleaved with other tiles'
/// (A.4.2). They are gathered here: `data` is every one of this tile's
/// tile-parts' packet bytes, concatenated in `TPsot` order. Concatenation is
/// exact, not an approximation — a tile-part holds a whole number of packets
/// (B.9), so no packet straddles the seam — and it is what OpenJPEG does
/// (`opj_j2k_read_sod` appends each tile-part into the tile's buffer). It stays
/// borrowed for the overwhelmingly common single-part tile, and only copies when
/// there is more than one part to join.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tile<'a> {
    pub index: u32,
    /// This tile's own tile-part-header markers, as parsed. Resolve them against
    /// the main header with [`Codestream::tile_header`] to get the parameters the
    /// tile decodes under.
    ///
    /// They are *not* resolved into a whole header here, because a header is
    /// sized by the component count and there can be tens of thousands of tiles:
    /// materializing one per tile would cost `tiles × components` in memory and
    /// in time, which a header under 50 KB can drive into gigabytes and minutes.
    /// Instead, [`parse_tiles_with`] checks each tile's markers against a summary of
    /// the main header, in time proportional to the tile's own markers. At
    /// decode, a tile with no markers runs under the main header itself,
    /// borrowed; a tile with markers is resolved in full, in time and memory
    /// proportional to the component count, and the decode then spends at least
    /// that much on the tile's components anyway: it builds every
    /// component's geometry before it reads a packet. That holds with
    /// `strict` off too, where the decode goes on past a tile whose data runs
    /// out: a tile with no tile-part at all is never resolved, and every
    /// tile that is resolved builds its geometry. A tile-component holds at
    /// least one sample (SIZ refuses an empty one), so the copies cost at most
    /// `tiles × components`, no more than the image's samples (under a window
    /// or a tile, the samples of the tiles read, as only those are resolved).
    pub header: TileHeader,
    pub data: Cow<'a, [u8]>,
    /// Where each tile-part's data ends in [`data`](Self::data), in `TPsot`
    /// order, so a report can name the tile-part a byte offset falls in.
    pub part_ends: Vec<usize>,
    /// The tile's packed packet headers (`PPT`), concatenated across its
    /// tile-parts; empty when the headers are inline with the bodies. When
    /// non-empty, Tier-2 reads every packet header from here and every packet
    /// body from [`data`](Self::data) (A.7.5).
    pub packed_headers: Vec<u8>,
}

/// A parsed codestream: the main header plus every tile, in tile-index order.
///
/// A strict walk refuses a codestream that lacks a tile, so it holds them
/// all. With `strict` off a missing tile is left out of `tiles` and reported
/// in `entries`, with whatever else the walk found missing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Codestream<'a> {
    pub header: MainHeader,
    pub tiles: Vec<Tile<'a>>,
    /// What a walk with `strict` off found missing; always empty when strict.
    pub entries: Vec<ReportEntry>,
}

impl Tile<'_> {
    /// The tile-part that byte `offset` of [`data`](Self::data) falls in, or
    /// the last one for an offset at or past the end.
    pub fn part_at(&self, offset: usize) -> u8 {
        let part = self.part_ends.partition_point(|&end| end <= offset);
        part.min(self.part_ends.len().saturating_sub(1)) as u8
    }
}

impl Codestream<'_> {
    /// The parameters tile `index` decodes under: the main header with that
    /// tile's tile-part-header markers resolved over it (A.6.1).
    ///
    /// Every stage past the codestream takes one of these, so nothing downstream
    /// has to know that a tile header exists — a tile is just a header, a
    /// rectangle, and some bytes. A tile with no tile-part-header markers of its
    /// own decodes under the main header itself, borrowed, not copied.
    pub fn tile_header(&self, index: usize) -> Result<Cow<'_, MainHeader>> {
        let tile = self
            .tiles
            .get(index)
            .ok_or_else(|| Error::inconsistent(format!("no tile {index}")))?;
        resolve_tile_header(&self.header, &tile.header)
    }
}

/// Parse a raw codestream (must start with SOC, end with EOC).
///
/// Rejects anything outside the decoded feature set, such as a mixed-mode
/// HTJ2K code-block style, Part 2 extensions or unknown markers, with
/// [`Error::Unsupported`]. A JP2 file is
/// unwrapped before it gets here (see `crate::jp2`).
///
/// [`Error::Unsupported`]: crate::Error::Unsupported
#[cfg(test)]
pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
    parse_tiles(bytes, parse_header(bytes)?)
}

/// A codestream's main header, parsed, with what the tile walk needs to carry
/// on from it. It reads nothing past the first `SOT` marker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedHeader {
    pub header: MainHeader,
    /// Offset of the first `SOT` marker, where the tile walk starts.
    sot_offset: usize,
    /// The main header's `PPM` packet headers, one chunk per tile-part.
    ppm: Vec<Vec<u8>>,
}

/// Parse a codestream's main header, from `SOC` up to the first `SOT` marker,
/// and stop there: no tile-part header or packet byte is read. `parse` is
/// this followed by `parse_tiles`.
pub fn parse_header(bytes: &[u8]) -> Result<ParsedHeader> {
    let (header, sot_offset, ppm) = parse_main_header(bytes)?;
    Ok(ParsedHeader {
        header,
        sot_offset,
        ppm,
    })
}

/// Walk the tile-parts of the codestream whose main header `parsed` holds, and
/// check every tile's header.
#[cfg(test)]
pub fn parse_tiles(bytes: &[u8], parsed: ParsedHeader) -> Result<Codestream<'_>> {
    parse_tiles_with(bytes, parsed, true)
}

/// `parse_tiles`, or with `strict` false, the walk that takes missing data
/// as missing rather than refusing it (see [`walk_tiles`]).
pub fn parse_tiles_with(
    bytes: &[u8],
    parsed: ParsedHeader,
    strict: bool,
) -> Result<Codestream<'_>> {
    let codestream = split_tiles_with(bytes, parsed, strict)?;

    // Check every tile's header once, here, so a malformed tile-part header is
    // a parse error rather than a surprise partway through a decode. A header is
    // sized by the component count and a codestream can declare tens of
    // thousands of tiles, so each tile's own markers are checked against a
    // summary of the main header instead of resolving a header per tile. Only
    // a tile found at fault is resolved in full, so that the fault is reported
    // in the full check's words.
    let main = &codestream.header;
    let summary = OnceCell::new();
    for (index, tile) in codestream.tiles.iter().enumerate() {
        if !tile_header_is_valid(main, &summary, &tile.header) {
            // The two checks agree, so the full one fails here. Were it ever
            // to pass, its verdict would stand.
            let full = check_tile_in_full(main, &tile.header, index);
            debug_assert!(
                full.is_err(),
                "tile {index}: the quick check refused a valid tile"
            );
            full?;
        }
    }

    Ok(codestream)
}

/// Resolve a tile's header in full and check it: every invariant
/// [`resolve_tile_header`] holds it to, then the wavelet rule below. This is
/// what a valid tile header is; [`tile_header_is_valid`] decides the same
/// without resolving one.
fn check_tile_in_full(main: &MainHeader, tile: &TileHeader, index: usize) -> Result<()> {
    let resolved = resolve_tile_header(main, tile)?;

    // Every tile writes into one buffer per component, and that buffer's
    // arithmetic follows the component's wavelet: 5/3 reconstructs exact
    // integers, 9/7 reals. A tile-part COD may legally give a component a
    // different wavelet than the main header does, which would ask one buffer
    // to hold both. Nothing in Part 4 encodes that and no real encoder emits
    // it, so it is rejected rather than given a widened container.
    let pairs = resolved.components.iter().zip(&main.components);
    for (component, (in_tile, in_main)) in pairs.enumerate() {
        if in_tile.coding.transform != in_main.coding.transform {
            return Err(Error::unsupported(format!(
                "tile {index} codes component {component} with the {:?} wavelet where the \
                 main header uses {:?}; tiles that disagree on a component's wavelet are \
                 not decoded",
                in_tile.coding.transform, in_main.coding.transform,
            )));
        }
    }
    Ok(())
}

/// The main header's components, sorted by what a tile COD or QCD can fall
/// short of. Either marker lands on every component the tile does not name in
/// a COC or QCC, so checking it a component at a time would cost the
/// component count per tile; against this it costs the tile's own markers.
struct ComponentSummary {
    /// `(step entries, component)` for each component whose quantization is
    /// not derived, fewest entries first. The first a tile does not name is
    /// the tightest test of a tile COD's decomposition levels.
    by_steps: Vec<(usize, usize)>,
    /// `(decomposition levels, component)` for every component, most first.
    /// The first a tile does not name is the tightest test of a tile QCD's
    /// step entries.
    by_levels: Vec<(u8, usize)>,
    /// How many components use the 9/7 wavelet.
    irreversible: usize,
}

impl ComponentSummary {
    fn of(main: &MainHeader) -> Self {
        let mut by_steps: Vec<(usize, usize)> = main
            .components
            .iter()
            .enumerate()
            .filter(|(_, params)| params.quant.style != QuantStyle::ScalarDerived)
            .map(|(index, params)| (params.quant.steps.len(), index))
            .collect();
        by_steps.sort_unstable();
        let mut by_levels: Vec<(u8, usize)> = main
            .components
            .iter()
            .enumerate()
            .map(|(index, params)| (params.coding.decomposition_levels, index))
            .collect();
        by_levels.sort_unstable_by(|a, b| b.cmp(a));
        let irreversible = main
            .components
            .iter()
            .filter(|params| params.coding.transform == Transform::Irreversible97)
            .count();
        ComponentSummary {
            by_steps,
            by_levels,
            irreversible,
        }
    }
}

/// Whether `quant` can quantize a component of `levels` decomposition levels
/// under `transform`: the per-component half of [`validate_resolved`].
fn quant_fits(levels: u8, transform: Transform, quant: &Qcd) -> bool {
    let needed = 3 * usize::from(levels) + 1;
    (quant.style == QuantStyle::ScalarDerived || quant.steps.len() >= needed)
        && !(transform == Transform::Irreversible97 && quant.style == QuantStyle::None)
}

/// Whether [`check_tile_in_full`] accepts `tile` over `main`, decided in time
/// proportional to the tile's own markers, not to the component count. `main`
/// must be a header [`parse_main_header`] accepted, so that the components a
/// tile leaves alone are valid already.
///
/// A component the tile names in a COC or QCC is resolved and checked on its
/// own. Every other one takes the tile COD's coding if there is one, else its
/// main-header coding, and likewise the tile QCD's quantization. So a tile COD
/// or QCD is checked once, against the extreme of the components it lands on:
/// the first entry of `summary` the tile does not name.
fn tile_header_is_valid(
    main: &MainHeader,
    summary: &OnceCell<ComponentSummary>,
    tile: &TileHeader,
) -> bool {
    if resolved_poc_len(main, tile) > MAX_POC_VOLUMES {
        return false;
    }
    let own = &tile.overrides;
    if !own.codes_or_quantizes() {
        // RGN and POC change no invariant checked here.
        return true;
    }

    // `OverrideReader` refused a second COC or QCC for one component,
    // and `decode_coc`/`decode_qcc` bounded each index by the component count.
    let coc: HashMap<usize, &Coding> = own.coc.iter().map(|(i, c)| (*i, c)).collect();
    let qcc: HashMap<usize, &Qcd> = own.qcc.iter().map(|(i, q)| (*i, q)).collect();
    let named = || {
        coc.keys()
            .chain(qcc.keys().filter(|index| !coc.contains_key(index)))
            .copied()
    };
    let is_named = |index: usize| coc.contains_key(&index) || qcc.contains_key(&index);
    let in_main = |index: usize| &main.components[index];
    // The decomposition levels and wavelet component `index` takes in the tile,
    // and its quantization.
    let coding = |index: usize| match (coc.get(&index), &own.cod) {
        (Some(coding), _) => (coding.decomposition_levels, coding.transform),
        (None, Some(cod)) => (cod.coding.decomposition_levels, cod.coding.transform),
        (None, None) => {
            let coding = &in_main(index).coding;
            (coding.decomposition_levels, coding.transform)
        }
    };
    let quant = |index: usize| match (qcc.get(&index), &own.qcd) {
        (Some(quant), _) => *quant,
        (None, Some(qcd)) => qcd,
        (None, None) => &in_main(index).quant,
    };

    // The components the tile names, each on its own.
    for index in named() {
        let (levels, transform) = coding(index);
        if !quant_fits(levels, transform, quant(index))
            || transform != in_main(index).coding.transform
        {
            return false;
        }
    }

    // The rest, if any, against the summary.
    let total = main.components.len();
    if named().count() < total {
        let summary = summary.get_or_init(|| ComponentSummary::of(main));
        match (&own.cod, &own.qcd) {
            (None, None) => {}
            (Some(cod), qcd) => {
                // Each keeps its main-header wavelet, so none may differ from
                // the tile COD's.
                let differ = match cod.coding.transform {
                    Transform::Irreversible97 => total - summary.irreversible,
                    Transform::Reversible53 => summary.irreversible,
                };
                let differ_named = named()
                    .filter(|&index| in_main(index).coding.transform != cod.coding.transform)
                    .count();
                if differ != differ_named {
                    return false;
                }
                match qcd {
                    Some(qcd) => {
                        if !quant_fits(cod.coding.decomposition_levels, cod.coding.transform, qcd) {
                            return false;
                        }
                    }
                    // Their own quantization under the tile COD's levels. Each
                    // has the tile COD's wavelet (checked above) and passed the
                    // main header's checks under it, so the 9/7 rule holds.
                    None => {
                        let needed = 3 * usize::from(cod.coding.decomposition_levels) + 1;
                        let fewest = summary.by_steps.iter().find(|&&(_, i)| !is_named(i));
                        if fewest.is_some_and(|&(steps, _)| steps < needed) {
                            return false;
                        }
                    }
                }
            }
            // Their own coding under the tile QCD.
            (None, Some(qcd)) => {
                if qcd.style != QuantStyle::ScalarDerived {
                    let most = summary.by_levels.iter().find(|&&(_, i)| !is_named(i));
                    if most
                        .is_some_and(|&(levels, _)| qcd.steps.len() < 3 * usize::from(levels) + 1)
                    {
                        return false;
                    }
                }
                if qcd.style == QuantStyle::None {
                    let irreversible_named = named()
                        .filter(|&index| {
                            in_main(index).coding.transform == Transform::Irreversible97
                        })
                        .count();
                    if summary.irreversible != irreversible_named {
                        return false;
                    }
                }
            }
        }
    }

    // The color transform, over the first three components (skipped on an
    // image of fewer, see `mct::applies`).
    let cod = own.cod.as_ref().unwrap_or(&main.cod);
    if crate::mct::applies(cod.multiple_component_transform, main.siz.components.len()) {
        if crate::mct::check_geometry(&main.siz.components).is_err() {
            return false;
        }
        let first = coding(0).1;
        if (1..3).any(|index| coding(index).1 != first) {
            return false;
        }
    }
    true
}

/// [`parse_tiles_with`] (strict) without resolving every tile's header, for a caller that
/// reads one tile and resolves just that one with [`Codestream::tile_header`].
/// Resolving them all costs `tiles × components`.
pub(crate) fn split_tiles(bytes: &[u8], parsed: ParsedHeader) -> Result<Codestream<'_>> {
    split_tiles_with(bytes, parsed, true)
}

/// [`split_tiles`], strict or not (see [`walk_tiles`]).
fn split_tiles_with(bytes: &[u8], parsed: ParsedHeader, strict: bool) -> Result<Codestream<'_>> {
    let ParsedHeader {
        header,
        sot_offset,
        ppm,
    } = parsed;
    let mut entries = Vec::new();
    let tiles = walk_tiles(bytes, sot_offset, &header, &ppm, strict, &mut entries)?;
    Ok(Codestream {
        header,
        tiles,
        entries,
    })
}

/// A tile-part header's own markers (A.4.2): the tile-level overrides of the
/// main header's coding parameters, and any progression volumes. Only the
/// *first* tile-part of a tile may carry the overrides, so one per tile is
/// enough however many parts the tile is split into. (A later tile-part that
/// restates a value already in force is accepted and dropped; see
/// [`check_restatement`].)
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct TileHeader {
    overrides: Overrides,
    /// A tile-part `POC`'s progression volumes; empty when the tile carries none,
    /// in which case the main header's `POC` (or its single COD order) governs.
    poc: Vec<PocVolume>,
    /// Whether the tile's first tile-part carries a `POC`. Only then do the
    /// tile's volumes replace the main header's (see `resolve_tile_header`).
    poc_in_first_part: bool,
}

/// The COD, QCD, COC, QCC and RGN markers of one header, main or tile-part:
/// a COD/QCD default and the per-component overrides that layer over it.
///
/// The per-component overrides are **sparse**: only the components a marker
/// actually names. Almost every tile carries none at all, and a dense vector per
/// tile would cost `tiles × components` for nothing.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct Overrides {
    cod: Option<Cod>,
    qcd: Option<Qcd>,
    coc: Vec<(usize, Coding)>,
    qcc: Vec<(usize, Qcd)>,
    rgn: Vec<(usize, u8)>,
}

impl Overrides {
    /// Whether the header carries a COD, QCD, COC or QCC. RGN is left out: it
    /// changes no coding or quantization parameter.
    fn codes_or_quantizes(&self) -> bool {
        self.cod.is_some() || self.qcd.is_some() || !self.coc.is_empty() || !self.qcc.is_empty()
    }

    /// Lay these markers over `components`, lowest precedence first: a COD or
    /// QCD lands on every component, then each COC, QCC and RGN on the one
    /// component it names, outranking the COD or QCD (A.6.1 to A.6.5).
    ///
    /// `decode_coc`, `decode_qcc` and `decode_rgn` bounded each index by the
    /// SIZ component count, and `components` holds one entry per SIZ
    /// component, so no index lands outside it.
    fn lay_over(&self, components: &mut [ComponentParams]) {
        if let Some(cod) = &self.cod {
            for params in components.iter_mut() {
                params.coding.clone_from(&cod.coding);
            }
        }
        if let Some(qcd) = &self.qcd {
            for params in components.iter_mut() {
                params.quant.clone_from(qcd);
            }
        }
        for (index, coding) in &self.coc {
            components[*index].coding.clone_from(coding);
        }
        for (index, quant) in &self.qcc {
            components[*index].quant.clone_from(quant);
        }
        for (index, shift) in &self.rgn {
            components[*index].roi_shift = *shift;
        }
    }
}

/// Which header an [`OverrideReader`] reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Place {
    Main,
    /// A tile-part header, and whether it is its tile's first tile-part.
    TilePart {
        first: bool,
    },
}

/// Reads the COD, QCD, COC, QCC and RGN markers of one header into
/// [`Overrides`], refusing a duplicate. The main header and every tile-part
/// header read them through this one routine, which is also where each
/// COD's and COC's block coder meets [`check_block_coder`].
///
/// A.6 allows one COD and one QCD per header, and one COC, QCC and RGN per
/// component per header. A second one is not a later-wins override; it is a
/// malformed header, and guessing which wins would decode an image the encoder
/// never described. OpenJPEG is silently last-wins here; rejecting is stricter,
/// and no conformant codestream carries two. Each header is tallied apart: a
/// tile-part marker over a main-header one for the same component is the legal
/// override, not a duplicate.
struct OverrideReader<'s> {
    siz: &'s Siz,
    place: Place,
    overrides: Overrides,
    /// The `(marker, component)` pairs met so far, so that a header naming
    /// every component is checked in time proportional to its markers.
    named: HashSet<(u16, usize)>,
    /// Whether the codestream's `CAP` says it holds no `RGN` (`Ccap15` bit
    /// 12 is 0), so that an `RGN` read here is refused.
    rgn_free: bool,
}

impl<'s> OverrideReader<'s> {
    fn new(siz: &'s Siz, place: Place) -> Self {
        OverrideReader {
            siz,
            place,
            overrides: Overrides::default(),
            named: HashSet::new(),
            rgn_free: false,
        }
    }

    /// Hold this header to a `CAP` that says the codestream holds no `RGN`
    /// (ISO/IEC 15444-15 A.3.4): refuse an `RGN` already read, and any read
    /// later. The main header can carry its `CAP` after an `RGN`, so the
    /// check runs at both reads.
    fn forbid_rgn(&mut self) -> Result<()> {
        self.rgn_free = true;
        match self.overrides.rgn.first() {
            Some(&(index, _)) => Err(rgn_without_cap_bit(index)),
            None => Ok(()),
        }
    }

    /// Read marker `code` if it is a COD, QCD, COC, QCC or RGN, and say
    /// whether it was. `body` yields the marker's segment body. It is called
    /// only for one of those markers, so for any other the caller's cursor is
    /// left where it was.
    fn read<'b>(&mut self, code: u16, body: impl FnOnce() -> Result<Cursor<'b>>) -> Result<bool> {
        let suffix = match self.place {
            Place::Main => "",
            Place::TilePart { .. } => " in the tile-part header",
        };
        let duplicate =
            |name: &str| Error::codestream(format!("duplicate `{name}` marker{suffix}"));
        match code {
            marker::COD => {
                let seen = self.overrides.cod.is_some();
                // The main header refuses a second COD before reading it; a
                // tile-part header reads it first, so a malformed second COD
                // reports its own fault there.
                if seen && self.place == Place::Main {
                    return Err(duplicate("COD"));
                }
                let cod = decode_cod(body()?)?;
                check_block_coder(&cod.coding, "`COD`")?;
                if seen {
                    return Err(duplicate("COD"));
                }
                self.overrides.cod = Some(cod);
            }
            marker::QCD => {
                // In the same order as COD.
                let seen = self.overrides.qcd.is_some();
                if seen && self.place == Place::Main {
                    return Err(duplicate("QCD"));
                }
                let qcd = decode_quant(body()?, "`QCD`")?;
                if seen {
                    return Err(duplicate("QCD"));
                }
                self.overrides.qcd = Some(qcd);
            }
            marker::COC => {
                let (index, coding) = decode_coc(body()?, self.siz)?;
                check_block_coder(&coding, "`COC`")?;
                self.first_for(code, "COC", index, suffix)?;
                self.overrides.coc.push((index, coding));
            }
            marker::QCC => {
                let (index, quant) = decode_qcc(body()?, self.siz)?;
                self.first_for(code, "QCC", index, suffix)?;
                self.overrides.qcc.push((index, quant));
            }
            marker::RGN => {
                // A later tile-part's COD, COC, QCD and QCC are read for the
                // caller to hold to the values in force (`check_restatement`);
                // its RGN is refused here, as a malformed codestream rather
                // than an unsupported one.
                if self.place == (Place::TilePart { first: false }) {
                    return Err(Error::codestream(format!(
                        "marker {code:#06X} appears in a tile-part header other than the first; \
                         the coding-parameter overrides belong to the first tile-part of a tile"
                    )));
                }
                let (index, shift) = decode_rgn(body()?, self.siz)?;
                self.first_for(code, "RGN", index, suffix)?;
                if self.rgn_free {
                    return Err(rgn_without_cap_bit(index));
                }
                self.overrides.rgn.push((index, shift));
            }
            _ => return Ok(false),
        }
        Ok(true)
    }

    /// Refuse a second `name` marker for component `index` in this header.
    fn first_for(&mut self, code: u16, name: &str, index: usize, suffix: &str) -> Result<()> {
        if self.named.insert((code, index)) {
            Ok(())
        } else {
            Err(Error::codestream(format!(
                "duplicate `{name}` marker for component {index}{suffix}"
            )))
        }
    }

    fn finish(self) -> Overrides {
        self.overrides
    }
}

/// The refusal of an `RGN` for component `index` in a codestream whose
/// `Ccap15` bit 12 says it holds none (ISO/IEC 15444-15 A.3.4).
fn rgn_without_cap_bit(index: usize) -> Error {
    Error::codestream(format!(
        "`RGN` marker for component {index}, but `CAP` says the codestream has none \
         (`Ccap15` bit 12 is 0)"
    ))
}

/// What has been seen of one tile so far while the tile-parts are walked.
#[derive(Debug)]
struct TileParts<'a> {
    /// Each tile-part's packet data, in `TPsot` order (which is the order they
    /// must appear in, enforced below).
    parts: Vec<&'a [u8]>,
    /// `TNsot` from whichever tile-part stated it, plus one once the
    /// `TPsot == TNsot` correction is on (see [`count_is_one_short`]); `None`
    /// while every part so far left it 0 ("not yet known", A.4.2).
    declared_parts: Option<u16>,
    /// The tile's own header, from its first tile-part.
    header: TileHeader,
    /// What a later tile-part may restate (see [`check_restatement`]), built
    /// the first time one does.
    restated: Option<Restated>,
    /// The tile's packed packet headers from any `PPT` markers, concatenated
    /// across its tile-parts in `TPsot` order (and within a tile-part in `Zppt`
    /// order). Empty when the tile carries none, in which case the packet headers
    /// are inline with the bodies (A.7.5).
    packed_headers: Vec<u8>,
}

/// Walk every tile-part from the first `SOT` to the closing `EOC` (A.4.2,
/// A.4.4) and gather them into one [`Tile`] per tile index.
///
/// Tile-parts of different tiles may interleave freely, so this accumulates by
/// `Isot` and joins each tile's parts at the end. Within one tile they must
/// arrive in `TPsot` order, and every tile of the grid must be present: a
/// codestream that skips one describes an image it does not carry, which is a
/// truncation, not a feature to decode around.
///
/// A `Psot` overrun, an out-of-range or out-of-order `TPsot`, a `TNsot` that
/// disagrees with the parts that arrive, a missing tile, or a missing `EOC` all
/// reject with [`Error::Codestream`].
///
/// With `strict` false, missing data is taken as missing and recorded in
/// `entries`, and only that: the input may end anywhere after the first
/// `SOT` (inside a tile-part, its header or the next `SOT`), with or without
/// an `EOC`; a tile with no tile-part is left out; and `TNsot` is advisory, so
/// a tile may carry fewer or more tile-parts than it declares. Every other
/// fault is refused as in a strict walk, including a `TPsot` out of order or
/// with a gap, since the packets after a gap cannot be placed.
fn walk_tiles<'a>(
    bytes: &'a [u8],
    sot_offset: usize,
    main: &MainHeader,
    ppm: &[Vec<u8>],
    strict: bool,
    entries: &mut Vec<ReportEntry>,
) -> Result<Vec<Tile<'a>>> {
    let tile_count = main.siz.num_tiles() as usize;
    // `PPM` (main header) supplies one packet-header chunk per tile-part in
    // codestream order; this counter walks them as the tile-parts are read.
    let mut ppm_seq = 0usize;
    let mut tiles: Vec<TileParts<'a>> = (0..tile_count)
        .map(|_| TileParts {
            parts: Vec::new(),
            declared_parts: None,
            header: TileHeader::default(),
            restated: None,
            packed_headers: Vec::new(),
        })
        .collect();
    // OpenJPEG's `TPsot == TNsot` correction (see `count_is_one_short`): looked
    // for once, when the first tile has all its declared parts, and from then
    // on added to every `TNsot`.
    let mut count_checked = false;
    let mut count_correction = 0u16;
    // Whether every main-header component codes and quantizes as the main
    // COD and QCD say, for `check_restatement`; worked out on first use.
    let uniform = OnceCell::new();

    let mut part_offset = sot_offset;
    loop {
        // Not strict: input that ends inside the `SOT` marker segment ends the
        // codestream there. `SOT` is always 12 bytes (Lsot = 10).
        if !strict && bytes.len().saturating_sub(part_offset) < 12 {
            entries.push(ReportEntry::MissingEoc);
            break;
        }
        let mut cur = Cursor::at(bytes, part_offset);
        // `parse_main_header` stopped on the first SOT and the loop below only
        // continues when it has just read one, so this is always present.
        if cur.u16()? != marker::SOT {
            return Err(Error::codestream("tile-part does not start with `SOT`"));
        }
        let sot = decode_sot(segment(&mut cur)?)?;

        let index = usize::from(sot.tile_index);
        let tile = tiles.get_mut(index).ok_or_else(|| {
            Error::codestream(format!(
                "tile-part names tile {index}, but the grid holds {tile_count} tiles"
            ))
        })?;

        // A tile's parts are numbered from 0 and shall appear in order (A.4.2),
        // so TPsot is exactly how many of this tile's parts have already been
        // seen. That single equality catches a duplicate, a gap, and a
        // reordering at once.
        if usize::from(sot.tile_part_index) != tile.parts.len() {
            return Err(Error::codestream(format!(
                "tile {index} tile-part index is {}, but {} of its tile-parts have been read",
                sot.tile_part_index,
                tile.parts.len(),
            )));
        }
        // TNsot is 0 in a tile-part that does not yet know the count; any part
        // that does state one must agree with every other that does.
        if sot.num_tile_parts != 0 {
            let stated = u16::from(sot.num_tile_parts) + count_correction;
            // Not strict, the count is advisory: a part past it is read, and
            // the difference reported once the walk ends.
            if strict && u16::from(sot.tile_part_index) >= stated {
                return Err(Error::codestream(format!(
                    "tile {index} tile-part {} of a declared {stated} tile-parts",
                    sot.tile_part_index,
                )));
            }
            match tile.declared_parts {
                Some(declared) if declared != stated => {
                    return Err(Error::codestream(format!(
                        "tile {index} declares {stated} tile-parts in one `SOT` and {declared} in another",
                    )));
                }
                _ => tile.declared_parts = Some(stated),
            }
        }

        let first_part = sot.tile_part_index == 0;
        // Not strict, a tile-part the input ends inside (its `Psot` runs past
        // the end, or it has none) may end inside its header too. Then the
        // codestream ends at this tile-part, and none of it is read.
        let cut = !strict
            && (sot.psot == 0
                || part_offset
                    .checked_add(sot.psot as usize)
                    .is_none_or(|end| end > bytes.len()));
        let (tile_header, packed) = match read_tile_part_header(&mut cur, main, first_part) {
            Ok(read) => read,
            Err(_) if cut => {
                if sot.psot != 0 {
                    entries.push(ReportEntry::TruncatedTilePart {
                        tile: u32::from(sot.tile_index),
                        tile_part: sot.tile_part_index,
                        declared: u64::from(sot.psot),
                        present: (bytes.len() - part_offset) as u64,
                    });
                }
                entries.push(ReportEntry::MissingEoc);
                break;
            }
            Err(error) => return Err(error),
        };
        if first_part {
            tile.header = tile_header;
        } else {
            // A later tile-part may restate the coding-style values already in
            // force, which changes nothing; one that differs is refused here.
            // Its POC volumes are legal and append to the tile's, so the
            // progression can be split across the tile's parts (A.6.6). Each
            // part's list is capped, so the accumulation across parts must be
            // re-checked.
            check_restatement(main, &uniform, tile, &tile_header, index)?;
            check_poc_budget(tile.header.poc.len() + tile_header.poc.len())?;
            tile.header.poc.extend(tile_header.poc);
        }
        // Packed packet headers append across the tile's parts in TPsot order
        // (which is arrival order, enforced above), matching the body order.
        // They come from `PPT` (this tile-part's own markers) or `PPM` (the main
        // header, one chunk per tile-part in codestream order) — never both for
        // the same packets, so a codestream carrying each is out of subset.
        if ppm.is_empty() {
            tile.packed_headers.extend(packed);
        } else {
            if !packed.is_empty() {
                return Err(Error::unsupported(
                    "a codestream carrying both `PPM` and `PPT` packed headers is not decoded",
                ));
            }
            let chunk = ppm.get(ppm_seq).ok_or_else(|| {
                Error::codestream(
                    "`PPM` carries fewer packet-header chunks than the codestream has tile-parts",
                )
            })?;
            ppm_seq += 1;
            tile.packed_headers.extend_from_slice(chunk);
        }
        let data_start = cur.pos;

        // Psot counts from the SOT marker's first byte to the end of the
        // tile-part. Psot == 0 marks the *last* tile-part (A.4.2). Like
        // OpenJPEG, give it everything up to the last two bytes of the buffer,
        // the room for an EOC, without checking that those bytes are FF D9. A
        // stream with no EOC therefore loses its last two data bytes, as it
        // does in OpenJPEG, and fails later when the tile's packets run short.
        // Scanning for the first FF D9 instead would be unsound: bit stuffing
        // keeps packet data and headers clear of it, but an SOP segment's Nsop
        // counter is two raw bytes and can spell FF D9 (packet 65497, or a 0xFF
        // low byte abutting 0xD9), which would silently truncate a valid tile.
        // The asymmetry with the Psot != 0 arm (which ignores bytes after its
        // EOC) is therefore deliberate: with no declared length there is nothing
        // else to anchor to.
        let data_end = if sot.psot == 0 {
            match bytes.len().checked_sub(2).filter(|&end| end >= data_start) {
                Some(end) => end,
                // Not strict, the codestream ends within two bytes of the
                // header: the tile-part has no data, and its packets are
                // missing.
                None if !strict => data_start,
                None => {
                    return Err(Error::codestream(format!(
                        "tile {} tile-part {} has `Psot` 0 and fewer than two bytes after its \
                         header",
                        sot.tile_index, sot.tile_part_index
                    )));
                }
            }
        } else {
            let end = match part_offset
                .checked_add(sot.psot as usize)
                .filter(|&end| end <= bytes.len())
            {
                Some(end) => end,
                // Not strict, a tile-part cut short is read as far as it goes,
                // and the codestream ends there.
                None if !strict => {
                    entries.push(ReportEntry::TruncatedTilePart {
                        tile: u32::from(sot.tile_index),
                        tile_part: sot.tile_part_index,
                        declared: u64::from(sot.psot),
                        present: (bytes.len() - part_offset) as u64,
                    });
                    bytes.len()
                }
                None => {
                    return Err(Error::codestream(format!(
                        "tile {} tile-part {} declares `Psot` {}, but only {} bytes are left in \
                         the codestream",
                        sot.tile_index,
                        sot.tile_part_index,
                        sot.psot,
                        bytes.len() - part_offset
                    )));
                }
            };
            if end < data_start {
                return Err(Error::codestream(format!(
                    "tile {} tile-part {} declares `Psot` {}, shorter than its {}-byte header",
                    sot.tile_index,
                    sot.tile_part_index,
                    sot.psot,
                    data_start - part_offset
                )));
            }
            end
        };
        let tile = &mut tiles[index];
        tile.parts.push(&bytes[data_start..data_end]);

        // The first time a tile has every part it declares, look ahead for one
        // more part of it, as OpenJPEG does (`count_is_one_short`). If there is
        // one, every count is one short: raise each one stated so far, and
        // each one stated from here on.
        if !count_checked && tile.declared_parts == Some(u16::from(sot.tile_part_index) + 1) {
            count_checked = true;
            if sot.psot != 0 && count_is_one_short(bytes, data_end, sot.tile_index) {
                count_correction = 1;
                for tile in &mut tiles {
                    if let Some(declared) = &mut tile.declared_parts {
                        *declared += 1;
                    }
                }
            }
        }

        // A Psot = 0 tile-part is the last one: the walk ends there, whatever
        // the two bytes after its data are.
        if sot.psot == 0 {
            break;
        }
        // Not strict, a tile-part cut short ends the codestream.
        if data_end == bytes.len() && !strict {
            entries.push(ReportEntry::MissingEoc);
            break;
        }

        // Another SOT continues the walk; EOC ends it. Anything else — or
        // nothing at all — means the tile-part chain does not close.
        match read_u16(bytes, data_end) {
            Some(marker::EOC) => break,
            Some(marker::SOT) => part_offset = data_end,
            Some(other) => {
                return Err(Error::codestream(format!(
                    "expected `SOT` or `EOC` after a tile-part, found {other:#06X}"
                )));
            }
            // Not strict, the input may end after any tile-part.
            None if !strict => {
                entries.push(ReportEntry::MissingEoc);
                break;
            }
            None => {
                return Err(Error::codestream("missing `EOC` after the tile-part"));
            }
        }
    }

    // Every PPM chunk maps to one tile-part; leftover chunks mean the main header
    // packed headers for tile-parts the codestream never carried. Not strict,
    // a codestream that ends early may not reach the last of them.
    let ended_early = entries.last() == Some(&ReportEntry::MissingEoc);
    if ppm_seq != ppm.len() && !(ended_early && ppm_seq < ppm.len()) {
        return Err(Error::codestream(format!(
            "`PPM` carries {} packet-header chunk(s) but the codestream has {ppm_seq} tile-part(s)",
            ppm.len(),
        )));
    }

    let mut found = Vec::with_capacity(tiles.len());
    // Not strict: the run of missing tiles being gathered, as (first, end).
    let mut missing: Option<(u32, u32)> = None;
    for (index, tile) in tiles.into_iter().enumerate() {
        if tile.parts.is_empty() {
            if strict {
                return Err(Error::codestream(format!(
                    "the codestream carries no tile-part for tile {index}"
                )));
            }
            let index = index as u32;
            missing = Some(missing.map_or((index, index + 1), |(first, _)| (first, index + 1)));
            continue;
        }
        if let Some((first, end)) = missing.take() {
            entries.push(ReportEntry::MissingTiles { tiles: first..end });
        }
        if let Some(declared) = tile.declared_parts {
            if usize::from(declared) != tile.parts.len() {
                if strict {
                    return Err(Error::codestream(format!(
                        "tile {index} declares {declared} tile-parts but carries {}",
                        tile.parts.len()
                    )));
                }
                entries.push(ReportEntry::TilePartCountMismatch {
                    tile: index as u32,
                    declared,
                    found: tile.parts.len() as u16,
                });
            }
        }
        found.push((index, tile));
    }
    if let Some((first, end)) = missing {
        entries.push(ReportEntry::MissingTiles { tiles: first..end });
    }

    found
        .into_iter()
        .map(|(index, tile)| {
            // One part: borrow it. Several: join them, which is exact — a
            // tile-part holds a whole number of packets (B.9), so nothing
            // straddles the seam.
            let data = match <[&[u8]; 1]>::try_from(tile.parts.as_slice()) {
                Ok([only]) => Cow::Borrowed(only),
                Err(_) => Cow::Owned(tile.parts.concat()),
            };
            let part_ends = tile
                .parts
                .iter()
                .scan(0, |end, part| {
                    *end += part.len();
                    Some(*end)
                })
                .collect();
            Ok(Tile {
                index: index as u32,
                header: tile.header,
                data,
                part_ends,
                packed_headers: tile.packed_headers,
            })
        })
        .collect()
}

/// Whether the tile-part chain from `from` holds another part of tile `tile`
/// whose `TPsot` equals its `TNsot`, so that every `TNsot` in the codestream
/// is one short of the parts it carries.
///
/// Some encoders (Adobe Photoshop's plug-in is one) number a tile's parts
/// 0 to N and declare N of them. OpenJPEG 2.5.0 corrects this on purpose
/// (`opj_j2k_need_nb_tile_parts_correction`, its issue 254: "Non conformant
/// codestream TPsot==TNsot"), and this copies its test. Once, when the first
/// tile has every part it declares, it walks the `SOT` chain onward, stepping
/// over other tiles' parts by `Psot`, to the next part of the same tile. If
/// that part has `TPsot == TNsot`, every tile's count is raised by one. The
/// walk gives up, finding nothing, at anything other than an `SOT`, at a
/// `Psot` below 14 (`0` included) on another tile's part, or at a `Psot` past
/// the end, as OpenJPEG's does.
///
/// The raised counts are held to the parts that arrive, as any count is, and
/// the parts are still read in `TPsot` order.
fn count_is_one_short(bytes: &[u8], from: usize, tile: u16) -> bool {
    let mut at = from;
    loop {
        if read_u16(bytes, at) != Some(marker::SOT) {
            return false;
        }
        // A malformed SOT ends the look-ahead; the walk reaches the same SOT
        // and refuses it there.
        let mut cur = Cursor::at(bytes, at + 2);
        let Ok(sot) = segment(&mut cur).and_then(decode_sot) else {
            return false;
        };
        if sot.tile_index == tile {
            return sot.tile_part_index == sot.num_tile_parts;
        }
        if sot.psot < 14 {
            return false;
        }
        match at.checked_add(sot.psot as usize) {
            Some(next) if next <= bytes.len() => at = next,
            _ => return false,
        }
    }
}

/// Whether every main-header component codes and quantizes as the main COD and
/// QCD say, so that no main COC or QCC changes anything.
#[derive(Debug, Clone, Copy)]
struct Uniform {
    coding: bool,
    quant: bool,
}

impl Uniform {
    fn of(main: &MainHeader) -> Self {
        Uniform {
            coding: main.components.iter().all(|p| p.coding == main.cod.coding),
            quant: main.components.iter().all(|p| p.quant == main.qcd),
        }
    }
}

/// What [`check_restatement`] knows about one tile: where its own COC and QCC
/// markers are, by component, and the COD and QCD a later part has already
/// been found to restate.
#[derive(Debug, Default)]
struct Restated {
    coc: HashMap<usize, usize>,
    qcc: HashMap<usize, usize>,
    cod: Option<Cod>,
    qcd: Option<Qcd>,
}

/// Accept a later tile-part's COD, COC, QCD and QCC only when each restates
/// the value already in force for the tile; refuse one that differs.
///
/// A.4.2 puts these markers in a tile's first tile-part. Some encoders (BAP
/// Image Systems is one) repeat the main header's COD and QCD in every
/// tile-part. OpenJPEG 2.5.0 reads a COD or QCD in any tile-part header
/// (`J2K_STATE_TPH` in its marker table) and applies it to the whole tile; it
/// dropped its "one COD per tile" check on purpose so that files like these
/// decode (`opj_j2k_read_cod`, its issue 1043, a BAP bulk-scanner file).
///
/// Here a restatement must change nothing, in this decoder's reading or in
/// OpenJPEG's, and it is then dropped. OpenJPEG writes a COD over every
/// component of the tile, and a QCD likewise, so a COD is accepted only when
/// it equals the tile's COD in force and every component of the tile already
/// codes as it says, and a QCD the same way. A COC or QCC must equal what its
/// component already has. Anything else is refused: the tile's earlier parts
/// are read under one set of values and its later parts would name another,
/// and which one the encoder meant is not in the file.
///
/// The cost is bounded by the markers read: a tile's COC and QCC are indexed
/// once, a COD or QCD found to restate is remembered, and whether the main
/// header's components are uniform is worked out once per codestream.
fn check_restatement(
    main: &MainHeader,
    uniform: &OnceCell<Uniform>,
    tile: &mut TileParts<'_>,
    later: &TileHeader,
    index: usize,
) -> Result<()> {
    let later = &later.overrides;
    if !later.codes_or_quantizes() {
        return Ok(());
    }
    let own = &tile.header.overrides;
    let restated = tile.restated.get_or_insert_with(|| Restated {
        coc: own
            .coc
            .iter()
            .enumerate()
            .map(|(at, (c, _))| (*c, at))
            .collect(),
        qcc: own
            .qcc
            .iter()
            .enumerate()
            .map(|(at, (c, _))| (*c, at))
            .collect(),
        ..Restated::default()
    });
    let differs = |what: String| {
        Error::codestream(format!(
            "a later tile-part of tile {index} carries a {what} that differs from the one \
             in force; the coding-parameter overrides belong to the first tile-part of a tile"
        ))
    };

    if let Some(cod) = &later.cod {
        if restated.cod.as_ref() != Some(cod) {
            let coding = &cod.coding;
            let same = cod == own.cod.as_ref().unwrap_or(&main.cod)
                && own.coc.iter().all(|(_, c)| c == coding)
                && (own.cod.is_some() || uniform.get_or_init(|| Uniform::of(main)).coding);
            if !same {
                return Err(differs("`COD`".into()));
            }
            restated.cod = Some(cod.clone());
        }
    }
    if let Some(qcd) = &later.qcd {
        if restated.qcd.as_ref() != Some(qcd) {
            let same = qcd == own.qcd.as_ref().unwrap_or(&main.qcd)
                && own.qcc.iter().all(|(_, q)| q == qcd)
                && (own.qcd.is_some() || uniform.get_or_init(|| Uniform::of(main)).quant);
            if !same {
                return Err(differs("`QCD`".into()));
            }
            restated.qcd = Some(qcd.clone());
        }
    }
    for (component, coding) in &later.coc {
        let same = match (restated.coc.get(component), &own.cod) {
            (Some(&at), _) => own.coc[at].1 == *coding,
            (None, Some(cod)) => cod.coding == *coding,
            (None, None) => main.components[*component].coding == *coding,
        };
        if !same {
            return Err(differs(format!("`COC` for component {component}")));
        }
    }
    for (component, quant) in &later.qcc {
        let same = match (restated.qcc.get(component), &own.qcd) {
            (Some(&at), _) => own.qcc[at].1 == *quant,
            (None, Some(qcd)) => qcd == quant,
            (None, None) => main.components[*component].quant == *quant,
        };
        if !same {
            return Err(differs(format!("`QCC` for component {component}")));
        }
    }
    Ok(())
}

/// Read one tile-part header: the markers between its `SOT` segment and its
/// `SOD` (A.4.2). The cursor is left on the first byte of the packet data.
///
/// Only the *first* tile-part of a tile may carry the coding-parameter overrides
/// (COD/COC/QCD/QCC/RGN): they say how to read the tile's packets. A later
/// part's COD, COC, QCD and QCC are returned for the caller to hold to the
/// values in force ([`check_restatement`]); [`OverrideReader`] refuses a later
/// RGN, as a malformed codestream rather than an unsupported one.
fn read_tile_part_header(
    cur: &mut Cursor<'_>,
    main: &MainHeader,
    first_part: bool,
) -> Result<(TileHeader, Vec<u8>)> {
    let siz = &main.siz;
    let mut tile = TileHeader::default();
    let mut overrides = OverrideReader::new(siz, Place::TilePart { first: first_part });
    if main.ccap15.is_some_and(|c| !c.rgn()) {
        // Nothing is read yet, so this cannot fail.
        overrides.forbid_rgn()?;
    }
    // `PPT` packet headers for this tile-part, collected as `(Zppt, bytes)` and
    // concatenated in `Zppt` order below.
    let mut ppt: Vec<(u8, Vec<u8>)> = Vec::new();

    loop {
        let m = cur.u16()?;
        if overrides.read(m, || segment(cur))? {
            continue;
        }
        match m {
            marker::SOD => break,
            marker::COM => {
                segment(cur)?;
            }
            // Packet lengths (A.7.3): informational, so the structure is
            // validated and the lengths discarded — the packets are read from
            // the data itself, and decoding must not depend on the hint.
            marker::PLT => {
                decode_plt(segment(cur)?)?;
            }
            // A tile-part POC sets the progression for this tile, replacing the
            // main header's (see `resolve_tile_header`). Unlike the coding-style
            // overrides, it is legal in *any* tile-part, not just the first
            // (B.12.3, OpenJPEG's `J2K_STATE_TPH`), and volumes accumulate
            // across every one of the tile's parts — so a later tile-part may
            // carry one.
            marker::POC => {
                decode_poc(segment(cur)?, siz, &mut tile.poc)?;
            }
            // Packed packet headers (A.7.5): this tile-part's packet headers,
            // moved out of the bitstream into the marker. `Zppt` orders the
            // markers of one tile-part; the bytes after it are `Ippt`. Legal in
            // any tile-part (the headers span all of them). Collected here and
            // stitched into the tile's packed buffer by the caller; a decoder
            // that ignored them would read packet headers off the packet bodies
            // and decode garbage.
            marker::PPT => {
                let mut body = segment(cur)?;
                let zppt = body.u8()?;
                if ppt.iter().any(|&(z, _)| z == zppt) {
                    return Err(Error::codestream(format!(
                        "duplicate `PPT` index `Zppt` {zppt} in one tile-part header"
                    )));
                }
                let ippt = body.take(body.remaining())?;
                ppt.push((zppt, ippt.to_vec()));
            }
            // These are legal markers, but not here: TLM and PLM are
            // main-header-only (A.7.1, A.7.2), and SOP/EPH delimit packets
            // after SOD. In a tile-part header they are a malformed
            // codestream, not a missing feature.
            marker::TLM | marker::PLM | marker::SOP | marker::EPH => {
                return Err(Error::codestream(format!(
                    "marker {m:#06X} is not permitted in a tile-part header"
                )));
            }
            // CAP and CPF describe the whole codestream, so they belong in the
            // main header only (ISO/IEC 15444-1 A.5.2, ISO/IEC 15444-15 A.6);
            // OpenJPEG reads both there only. Here, like a misplaced TLM, they
            // are a malformed codestream.
            marker::CAP | marker::CPF => {
                return Err(Error::codestream(format!(
                    "{} is a main-header marker; it is not permitted in a tile-part header",
                    marker::describe(m)
                )));
            }
            other => {
                return Err(Error::codestream(format!(
                    "unexpected marker {other:#06X} in tile-part header"
                )));
            }
        }
    }
    // Stitch this tile-part's PPT markers into one buffer, ordered by Zppt.
    ppt.sort_by_key(|&(z, _)| z);
    let packed = ppt.into_iter().flat_map(|(_, bytes)| bytes).collect();
    tile.overrides = overrides.finish();
    // `parse_tiles` reads this flag from the first tile-part only; the
    // `first_part` test is defensive.
    tile.poc_in_first_part = first_part && !tile.poc.is_empty();
    Ok((tile, packed))
}

/// Resolve one tile's effective parameters: the main header with the tile-part
/// header's markers laid over it, in the standard's precedence order (A.6.1).
///
/// For each component the winner is the first of
///
/// ```text
/// tile COC  >  tile COD  >  main COC  >  main COD
/// ```
///
/// and likewise QCC > QCD down the same two levels. The middle two are the trap:
/// a **tile COD outranks a main-header COC**. So it is not enough to lay the
/// tile's markers over the main header's resolved components — the main COC
/// would win a contest it lost, and the tile would decode on a pyramid no marker
/// described.
///
/// The ladder falls out instead: the main header's resolved components already
/// encode `main COC > main COD`, so a tile COD overwrites *every* component's
/// coding (beating any main COC), and a tile COC then overwrites the one
/// component it names (beating the tile COD). An RGN in a tile-part header
/// likewise *replaces* the main header's for that component (A.6.3).
///
/// A tile with no markers of its own decodes under the main header unchanged,
/// so that is returned borrowed: the main header already passed every check
/// below. Any other tile is a copy, sized by the component count.
fn resolve_tile_header<'m>(main: &'m MainHeader, tile: &TileHeader) -> Result<Cow<'m, MainHeader>> {
    if *tile == TileHeader::default() {
        return Ok(Cow::Borrowed(main));
    }
    let mut header = main.clone();

    // A tile COD/QCD is the tile's new default: it displaces the main header's
    // COD/QCD *and* any main-header COC/QCC, so `lay_over` lands it on every
    // component, then lays the tile's own per-component markers over that.
    let overrides = &tile.overrides;
    if let Some(cod) = &overrides.cod {
        header.cod.clone_from(cod);
    }
    if let Some(qcd) = &overrides.qcd {
        header.qcd.clone_from(qcd);
    }
    overrides.lay_over(&mut header.components);

    // A tile-part POC *overrides* the main header's for this tile (A.6.6:
    // "Tile-part POC > Main POC > Tile-part COD > Main COD", the greater
    // overriding the lesser; B.12.3 likewise). A.6.6 also requires that POC to
    // be in the tile's first tile-part. So a tile whose first tile-part has a
    // POC walks only its own volumes, accumulated across its tile-parts in
    // order. OpenJPEG 2.5.0 instead seeds each tile from the main header, POC
    // included, and `opj_j2k_read_poc` appends the tile-part's volumes after
    // it, so a file carrying both decodes wrong there (docs/openjpeg-departures.md).
    //
    // A tile whose first POC is in a later tile-part breaks A.6.6. Its first
    // packets can only follow the main header's order, so it is read as
    // OpenJPEG reads it: the main volumes, then the tile's. A tile with no POC
    // keeps the main header's from `main.clone()` above.
    check_poc_budget(resolved_poc_len(main, tile))?;
    if tile.poc_in_first_part {
        header.poc.clone_from(&tile.poc);
    } else {
        header.poc.extend(tile.poc.iter().copied());
    }

    // The tile's resolved parameters must hold every invariant the main header's
    // do: a tile COD/QCD pair can break one the main header kept.
    validate_resolved(&header)?;
    Ok(Cow::Owned(header))
}

/// SOT fields (A.4.2): the tile index, tile-part length, part index, and part
/// count. The packet-data extent is derived from `psot` by the caller.
struct Sot {
    tile_index: u16,
    psot: u32,
    tile_part_index: u8,
    num_tile_parts: u8,
}

/// Decode the SOT marker segment body (everything after `Lsot`): Isot, Psot,
/// TPsot, TNsot. `expect_consumed` enforces the fixed `Lsot == 10` layout.
fn decode_sot(mut b: Cursor<'_>) -> Result<Sot> {
    let tile_index = b.u16()?;
    let psot = b.u32()?;
    let tile_part_index = b.u8()?;
    let num_tile_parts = b.u8()?;
    b.expect_consumed("`SOT`")?;
    Ok(Sot {
        tile_index,
        psot,
        tile_part_index,
        num_tile_parts,
    })
}

/// Read a big-endian `u16` marker at `pos`, or `None` if it would run past the
/// end. Used to peek the marker that follows a tile-part without disturbing the
/// segment cursor.
fn read_u16(bytes: &[u8], pos: usize) -> Option<u16> {
    let hi = *bytes.get(pos)?;
    let lo = *bytes.get(pos + 1)?;
    Some(u16::from_be_bytes([hi, lo]))
}

/// One marker segment located by the structural walk: its code and its body
/// (empty for the segment-less markers).
struct Segment<'a> {
    code: u16,
    body: &'a [u8],
}

/// Upper bound on the marker segments a main header may carry.
///
/// A segment-less marker costs two input bytes but one `Segment` record, so a
/// run of them would grow the located-segment list several times faster than the
/// input it came from. The largest conformant header is far smaller than this:
/// `Csiz` tops out at 16384, and even a COC *and* a QCC per component is 32768
/// segments, so this bound cannot reject a real codestream.
const MAX_MAIN_HEADER_SEGMENTS: usize = 1 << 16;

/// Walk the main header's marker segments from just after `SOC` to the first
/// `SOT`, without judging any of them (A.6).
///
/// This is deliberately subset-agnostic: it establishes *where every segment
/// is*, and leaves "can we decode this?" to the caller. Running the whole walk
/// before any segment is interpreted is what lets a codestream carrying an
/// out-of-subset feature still be traversed end to end — which is the only way
/// a marker sitting *after* the offending one gets exercised at all.
///
/// Two shapes a naive walker gets wrong, both present in the corpus:
///
/// - the reserved range `0xFF30..=0xFF3F` carries **no** length field; reading
///   one consumes the bytes that follow (`p0_02` has `0xFF30` after its `COM`);
/// - a marker this decoder does not recognize still has a length, so the walk
///   can step over it. Whether the *decoder* may proceed past it is a different
///   question, and `parse_main_header` answers it with `Unsupported`.
///
/// Returns the segments in codestream order and the offset of the `SOT` that
/// ended the header. When the input ends after `SOC` and before the first
/// `SOT` marker is whole, the offset is [`Error::Incomplete`] instead and the
/// segments are those the input holds in full, so the caller can judge them
/// before it reports the cut: the walk reads only marker codes and lengths
/// here, so running out of input means the input was cut short (or a length
/// was damaged to reach past it, which looks the same). A non-marker where a
/// marker must be, a length below 2, and `SOD`/`EOC` before any tile-part are
/// [`Error::Codestream`].
fn walk_main_header(bytes: &[u8]) -> Result<(Vec<Segment<'_>>, Result<usize>)> {
    let mut cur = Cursor::new(bytes);

    // 0 bytes, or `FF` alone, may still become `SOC`.
    if bytes.len() < 2 && marker::SOC.to_be_bytes().starts_with(bytes) {
        return Err(Error::incomplete(
            "the input ends before the codestream's `SOC` marker is whole",
        ));
    }
    if cur.u16().ok() != Some(marker::SOC) {
        return Err(Error::codestream("does not start with the `SOC` marker"));
    }

    let mut segments = Vec::new();
    let sot_offset = loop {
        let Ok(code) = cur.u16() else {
            break Err(cut_short("before its first `SOT` marker"));
        };
        match code {
            // The first SOT ends the main header; point the offset back at it.
            marker::SOT => break Ok(cur.pos - 2),

            // A second SOC, or a delimiter that belongs to a tile-part, means
            // the header is malformed rather than merely unfamiliar.
            marker::SOC | marker::SOD | marker::EOC => {
                return Err(Error::codestream(format!(
                    "unexpected marker {code:#06X} before any tile-part"
                )));
            }

            _ if !marker::is_marker(code) => {
                return Err(Error::codestream(format!(
                    "expected a marker in the main header, found {code:#06X}"
                )));
            }

            // Everything else is located, not interpreted.
            _ => {
                // A segment-less marker advances only two bytes, so a run of
                // them would grow `segments` at ~12x the input. Bound it: no
                // conformant main header comes close, and the cap keeps a hostile
                // input's allocation proportional to nothing but this constant.
                if segments.len() == MAX_MAIN_HEADER_SEGMENTS {
                    return Err(Error::codestream(format!(
                        "main header has more than {MAX_MAIN_HEADER_SEGMENTS} marker segments"
                    )));
                }
                let body = if marker::has_segment(code) {
                    match main_header_segment(&mut cur)? {
                        Some(body) => body,
                        None => {
                            break Err(cut_short(&format!(
                                "in its {} segment",
                                marker::describe(code)
                            )));
                        }
                    }
                } else {
                    &[][..]
                };
                segments.push(Segment { code, body });
            }
        }
    };

    Ok((segments, sot_offset))
}

/// The body of the main-header segment whose marker the walk just read, as
/// [`segment`] reads it, or `None` when the input ends inside its length or
/// its body: a cut, not a malformed segment.
fn main_header_segment<'a>(cur: &mut Cursor<'a>) -> Result<Option<&'a [u8]>> {
    let Ok(len) = cur.u16() else {
        return Ok(None);
    };
    if len < 2 {
        return Err(Error::codestream("marker segment length below 2"));
    }
    Ok(cur.take(usize::from(len) - 2).ok())
}

/// The input ends inside the main header, at `place`.
fn cut_short(place: &str) -> Error {
    Error::incomplete(format!("the input ends inside the main header, {place}"))
}

/// Parse the main header up to (but not into) the first `SOT`.
///
/// Returns the decoded [`MainHeader`] and the byte offset of that `SOT` marker,
/// which is where tile-part walking (issue #6) begins. Stops before any
/// entropy-coded data, so it never touches packet bytes.
///
/// The header is walked in full by [`walk_main_header`] first, then each
/// located segment is interpreted in codestream order.
fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize, Vec<Vec<u8>>)> {
    // A cut header is judged on the segments the input holds in full, in the
    // order a whole one is, so a damaged segment before the cut is reported
    // as it would be in the whole file; `end` reports the cut only once those
    // all pass.
    let (segments, end) = walk_main_header(bytes)?;

    // SIZ shall be the first marker segment after SOC (A.6).
    let Some(first) = segments.first() else {
        end?;
        return Err(Error::codestream("main header has no marker segments"));
    };
    if first.code != marker::SIZ {
        return Err(Error::codestream(
            "`SIZ` must be the first marker after `SOC`",
        ));
    }
    let siz = decode_siz(Cursor::new(first.body))?;

    // Judge the image before its coding parameters, so a codestream outside the
    // subset reports the *image* feature that blocks it (an origin, a tile grid)
    // rather than whichever coding-style bit COD happens to trip on first. Both
    // are `Unsupported`; this is about which reason is useful to read.
    validate_geometry(&siz)?;
    check_sample_container(&siz)?;

    let mut overrides = OverrideReader::new(&siz, Place::Main);
    // TLM entries met so far, which is the tile index an `ST = 0` entry
    // implies.
    let mut tlm_entries = 0usize;
    let mut poc: Vec<PocVolume> = Vec::new();
    let mut crg: Option<Vec<(u16, u16)>> = None;
    // `CAP` and `CPF`, each at most once: `Some(ccap15)` once a CAP is read.
    let mut cap: Option<Option<Ccap15>> = None;
    let mut cpf: Option<Cpf> = None;
    // Packed packet headers (A.7.4), collected as `(Zppm, Ippm)` and split into
    // per-tile-part chunks after the walk by `decode_ppm_chunks`.
    let mut ppm: Vec<(u8, Vec<u8>)> = Vec::new();

    for seg in &segments[1..] {
        let body = || Cursor::new(seg.body);
        if overrides.read(seg.code, || Ok(body()))? {
            continue;
        }
        match seg.code {
            marker::SIZ => {
                return Err(Error::codestream("duplicate `SIZ` marker"));
            }
            // Comment: recognized, carries nothing the decoder needs.
            marker::COM => {}

            // Length markers (A.7): pointers into the codestream, not decode
            // parameters — the packet and tile-part structures they describe
            // are read from the codestream itself, so decoding is identical
            // with them present or absent. TLM's entries are validated and
            // dropped, since no decode step reads them and a header can hold
            // millions; PLM's packet lengths are skipped as OpenJPEG skips
            // them (`opj_j2k_read_plm` reads nothing past `Zplm`).
            marker::TLM => decode_tlm(body(), &siz, &mut tlm_entries, |_| {})?,
            marker::PLM => decode_plm(body())?,

            // Progression-order change (A.6.6): a sequence of progression volumes
            // that replaces COD's single order for the whole codestream. Volumes
            // accumulate across markers.
            marker::POC => decode_poc(body(), &siz, &mut poc)?,

            // Component registration (A.9.1): sub-pixel display offsets, recorded
            // but not applied. One CRG per codestream (main-header only).
            marker::CRG => {
                if crg.replace(decode_crg(body(), &siz)?).is_some() {
                    return Err(Error::codestream("duplicate `CRG` marker"));
                }
            }

            // PLT is the tile-part-header form of PLM (A.7.3); in the main
            // header it is a malformed codestream, not a missing feature.
            marker::PLT => {
                return Err(Error::codestream(
                    "`PLT` is a tile-part-header marker; it is not permitted in the main header",
                ));
            }

            // Packed packet headers in the main header (A.7.4): `Zppm` orders
            // this marker among the header's PPM markers, and the rest is `Ippm`.
            // Collected here and split per tile-part after the walk; a tile-part
            // then sources its packet headers from its chunk (see `walk_tiles`).
            marker::PPM => {
                let mut b = body();
                let zppm = b.u8()?;
                let ippm = b.take(b.remaining())?;
                ppm.push((zppm, ippm.to_vec()));
            }

            // Extended capabilities (ISO/IEC 15444-1 A.5.2) and the
            // corresponding profile (ISO/IEC 15444-15 A.6): one of each per
            // codestream.
            marker::CAP => {
                let ccap15 = decode_cap(body())?;
                if cap.replace(ccap15).is_some() {
                    return Err(Error::codestream("duplicate `CAP` marker"));
                }
                if ccap15.is_some_and(|c| !c.rgn()) {
                    overrides.forbid_rgn()?;
                }
            }
            marker::CPF => {
                if cpf.replace(decode_cpf(body())?).is_some() {
                    return Err(Error::codestream("duplicate `CPF` marker"));
                }
            }

            // Valid markers the decoded subset does not yet cover. Rejected
            // rather than skipped: each one changes how the codestream is
            // interpreted, so ignoring it would silently decode the wrong
            // image. PPT/SOP/EPH belong after SOD or in a tile-part header,
            // not the main one.
            marker::PPT | marker::SOP | marker::EPH => {
                return Err(Error::unsupported(format!(
                    "marker {} is outside the decoded subset",
                    marker::describe(seg.code)
                )));
            }

            // A JPEG 2000 Part 2 codestream marker (ISO/IEC 15444-2). Named so
            // the rejection says which Part 2 feature blocks the decode —
            // multiple-component transforms, non-linearity, extra bit depths —
            // rather than reading as a bare unknown code.
            code if marker::PART2.contains(&code) => {
                return Err(Error::unsupported(format!(
                    "{} is a JPEG 2000 Part 2 marker, outside the Part 1 subset",
                    marker::describe(seg.code)
                )));
            }

            // The reserved segment-less range is *defined* to carry nothing, so
            // it is the one thing that can be passed over safely.
            code if marker::RESERVED_NO_SEGMENT.contains(&code) => {}

            // Any other marker this decoder does not know. The walk stepped over
            // its segment — that is what lets the header be traversed at all —
            // but we will not decode past it: every marker code is allocated by
            // some part of the standard, and an unknown one may well change what
            // the packet data means. Guessing that it is ignorable would trade
            // a clean rejection for a silently wrong image.
            other => {
                return Err(Error::unsupported(format!(
                    "unrecognized marker {other:#06X} in the main header"
                )));
            }
        }
    }

    // Every segment the input holds is valid. What is left needs the whole
    // header: whether COD and QCD are there, the resolved components (a later
    // COC can change a component's levels, and so the subbands its
    // quantization must cover), and the PPM chunk order.
    let sot_offset = end?;
    let mut overrides = overrides.finish();
    let cod =
        (overrides.cod.take()).ok_or_else(|| Error::codestream("missing required `COD` marker"))?;
    let qcd =
        (overrides.qcd.take()).ok_or_else(|| Error::codestream("missing required `QCD` marker"))?;

    // Start from COD/QCD's defaults, then lay each override over its component.
    // That is the whole of A.6.2's and A.6.5's resolution rule at the main
    // header's level; `resolve_tile_header` continues the ladder for a tile.
    let mut header = MainHeader::new(siz, cod, qcd);
    header.poc = poc;
    header.crg = crg.unwrap_or_default();
    header.ccap15 = cap.flatten();
    header.cpf = cpf;
    overrides.lay_over(&mut header.components);

    validate_resolved(&header)?;
    let ppm_chunks = decode_ppm_chunks(ppm)?;
    Ok((header, sot_offset, ppm_chunks))
}

/// Check the invariants that only hold once a header's per-component parameters
/// are resolved — whichever header level resolved them. A tile-part COD/QCD pair
/// can break one the main header kept, so this runs for every tile header too,
/// not just the main one.
fn validate_resolved(header: &MainHeader) -> Result<()> {
    // A `CAP` that says each tile-component holds one kind of code-block
    // (HTDECLARED, ISO/IEC 15444-15 A.3.2) rules out a MIXED style. The
    // style is per tile-component and `CAP` may follow COD or COC in the
    // main header, so this is checked on the resolved parameters.
    if header.ccap15.is_some_and(|c| c.ht_declared()) {
        use markers::code_block_style::HT_MIXED;
        if let Some(index) = header
            .components
            .iter()
            .position(|p| p.coding.code_block_style & HT_MIXED != 0)
        {
            return Err(Error::codestream(format!(
                "component {index} has a MIXED code-block style, but `CAP` says each \
                 tile-component holds one kind of code-block (`Ccap15` bits 15-14 are 10)"
            )));
        }
    }
    // A quantization default or override must cover every subband its
    // component decomposes into: 3·NL + 1 entries for the none/expounded
    // styles (derived's single entry is enforced in `decode_quant`, and excess
    // entries are ignored, as OpenJPEG does). NL is only known here, after the
    // overrides are resolved; discovering the shortfall per subband at decode
    // time would misreport a malformed marker as a geometry inconsistency.
    for (index, params) in header.components.iter().enumerate() {
        let needed = 3 * usize::from(params.coding.decomposition_levels) + 1;
        if params.quant.style != QuantStyle::ScalarDerived && params.quant.steps.len() < needed {
            return Err(Error::marker(format!(
                "component {index} carries {} quantization step entries but its {} \
                 decomposition levels need {needed}",
                params.quant.steps.len(),
                params.coding.decomposition_levels
            )));
        }
        // The wavelet constrains the quantization style (E.1 ties reversible
        // to no quantization, irreversible to scalar). OpenJPEG decodes both
        // non-conformant pairings: style-0 entries still carry exponents, so
        // it derives 9/7 steps with mantissa 0 and reconstructs. This crate
        // accepts the 5/3-with-scalar direction to match the oracle (the
        // reversible path ignores the mantissas — same output) but rejects
        // 9/7-with-none rather than adopt the oracle's zero-mantissa
        // interpretation of a stream the standard forbids — a documented
        // stricter-than-oracle call (docs/openjpeg-departures.md), relaxed if a real
        // file ever trips it.
        if params.coding.transform == Transform::Irreversible97
            && params.quant.style == QuantStyle::None
        {
            return Err(Error::marker(format!(
                "component {index} pairs the 9/7 wavelet with the no-quantization style"
            )));
        }
    }

    // The color transform is signaled by COD but constrains SIZ, so it can
    // only be checked once both are read. On an image of fewer than three
    // components it is skipped, as OpenJPEG skips it (`mct::applies`).
    if crate::mct::applies(
        header.cod.multiple_component_transform,
        header.siz.components.len(),
    ) {
        crate::mct::check_geometry(&header.siz.components)?;
        // Which color transform applies follows from the wavelet, and the
        // wavelet is per component once COC is in play: 5/3 is RCT (integers),
        // 9/7 is ICT (floats). The three components must share it — a mix
        // reconstructs some as integers and some as floats and describes a
        // transform that does not exist. OpenJPEG reads the type off component 0.
        let transform = header.components[0].coding.transform;
        for (index, params) in header.components.iter().take(3).enumerate() {
            if params.coding.transform != transform {
                return Err(Error::unsupported(format!(
                    "`COD` signals the color transform but component {index} uses a different \
                     wavelet than component 0; the transform is undefined over a mix"
                )));
            }
        }
    }

    Ok(())
}

/// Refuse a component whose sample range does not fit the `i32` container
/// (unsigned 32 bits, or more than 32), from SIZ alone. It is a header fault,
/// so it is found before any tile is read. OpenJPEG 2.5.0 is stricter: it
/// refuses every depth over 31 bits at SIZ, signed 32 included. This decoder
/// accepts signed 32 on purpose, since it fits `i32` (a deliberate
/// deviation, #167; see `docs/openjpeg-departures.md`); unsigned 32 and anything above 32
/// are refused. `image::assemble` repeats the check for headers built by hand.
fn check_sample_container(siz: &Siz) -> Result<()> {
    for (index, comp) in siz.components.iter().enumerate() {
        let fits = if comp.signed {
            comp.bit_depth <= 32
        } else {
            comp.bit_depth <= 31
        };
        if !fits {
            return Err(Error::unsupported(format!(
                "component {index} depth {} ({}) exceeds the i32 sample container",
                comp.bit_depth,
                if comp.signed { "signed" } else { "unsigned" }
            )));
        }
    }
    Ok(())
}

/// Enforce the decoded geometry subset on the SIZ fields: a well-formed image
/// and tile grid, bounded in tile count. The image and tile origins may be
/// non-zero (Annex B's reference grid), so this checks the Table A-9
/// constraints that a non-zero origin makes load-bearing, then bounds the tile
/// count before it reaches the buffer allocations. The image area is held to
/// the caller's sample limit later, once the options are known
/// (`samples::check_codestream`).
fn validate_geometry(siz: &Siz) -> Result<()> {
    if siz.x_size == 0 || siz.y_size == 0 {
        return Err(Error::marker("`SIZ` declares a zero-size image"));
    }
    // Table A-9: `0 <= XOsiz < Xsiz`. An origin at or past the far edge encloses
    // no image, so it is a malformed field, not an undecoded feature.
    if siz.x_offset >= siz.x_size || siz.y_offset >= siz.y_size {
        return Err(Error::marker(format!(
            "image offset ({}, {}) is not inside the image {}x{}",
            siz.x_offset, siz.y_offset, siz.x_size, siz.y_size
        )));
    }
    if siz.tile_width == 0 || siz.tile_height == 0 {
        return Err(Error::marker("`SIZ` declares a zero-size tile"));
    }
    // Table A-9: `XTOsiz <= XOsiz` and `XTOsiz + XTsiz > XOsiz`. The first keeps
    // the tile grid from starting to the right of the image; the second keeps
    // the first tile column non-empty (its rect clips to `[XOsiz, …)`), without
    // which `tile_rect` would hand `resolution_geoms` an empty leading tile.
    if siz.tile_x_offset > siz.x_offset || siz.tile_y_offset > siz.y_offset {
        return Err(Error::marker(format!(
            "tile offset ({}, {}) is past the image offset ({}, {})",
            siz.tile_x_offset, siz.tile_y_offset, siz.x_offset, siz.y_offset
        )));
    }
    if u64::from(siz.tile_x_offset) + u64::from(siz.tile_width) <= u64::from(siz.x_offset)
        || u64::from(siz.tile_y_offset) + u64::from(siz.tile_height) <= u64::from(siz.y_offset)
    {
        return Err(Error::marker(format!(
            "tile ({}x{} at offset ({}, {})) does not reach the image offset ({}, {})",
            siz.tile_width,
            siz.tile_height,
            siz.tile_x_offset,
            siz.tile_y_offset,
            siz.x_offset,
            siz.y_offset,
        )));
    }
    // `Isot` is a `u16` running 0..=65534 (Table A-10), so a grid finer than
    // that has tiles no tile-part can name. The bound also caps the per-tile
    // bookkeeping — one resolved header and one geometry walk each — that the
    // sample budget alone does not: a 1×1 tile costs a header but almost no
    // samples.
    const MAX_TILES: u32 = 65535;
    let tiles = siz.num_tiles();
    if tiles > MAX_TILES {
        return Err(Error::marker(format!(
            "tile grid is {}x{} = {tiles} tiles, past the {MAX_TILES}-tile limit on `Isot`",
            siz.tile_grid().0,
            siz.tile_grid().1,
        )));
    }
    Ok(())
}

/// Decode SIZ — image and tile geometry plus every component's depth, sign, and
/// sub-sampling (A.5.1).
///
/// Parses all `Csiz` components. Whether the decoder can *reconstruct* them is
/// a separate question, enforced by [`validate_geometry`] once the whole main
/// header is read, and by the sample limit after it, so a
/// multi-component codestream still parses cleanly here.
///
/// `Ssiz` is a depth-minus-one in the low 7 bits with the sign in bit 7, so the
/// declared depth is `1..=128`; the standard caps it at 38 (Table A-11) and
/// anything above that is a malformed field, not an unsupported feature.
fn decode_siz(mut b: Cursor<'_>) -> Result<Siz> {
    let _rsiz = b.u16()?; // capabilities / profile — not needed by the decoder
    let x_size = b.u32()?;
    let y_size = b.u32()?;
    let x_offset = b.u32()?;
    let y_offset = b.u32()?;
    let tile_width = b.u32()?;
    let tile_height = b.u32()?;
    let tile_x_offset = b.u32()?;
    let tile_y_offset = b.u32()?;
    let csiz = b.u16()?;

    if csiz == 0 {
        return Err(Error::marker("`SIZ` declares zero components"));
    }
    if csiz > markers::MAX_COMPONENTS {
        return Err(Error::marker(format!(
            "`SIZ` declares {csiz} components, above the limit of {}",
            markers::MAX_COMPONENTS
        )));
    }
    // Each component record is 3 bytes. Check the segment can actually hold them
    // before reserving, so a lying `Csiz` cannot steer the allocation.
    if b.remaining() != 3 * csiz as usize {
        return Err(Error::codestream(format!(
            "`SIZ` has {} bytes for {csiz} component records, expected {}",
            b.remaining(),
            3 * csiz as usize,
        )));
    }

    let mut components = Vec::with_capacity(csiz as usize);
    for index in 0..csiz {
        let ssiz = b.u8()?;
        let x_sampling = b.u8()?;
        let y_sampling = b.u8()?;
        let bit_depth = (ssiz & 0x7F) + 1;
        if bit_depth > 38 {
            return Err(Error::marker(format!(
                "component {index} declares bit depth {bit_depth}, above the limit of 38"
            )));
        }
        if x_sampling == 0 || y_sampling == 0 {
            return Err(Error::marker(format!(
                "component {index} declares a zero sub-sampling factor ({x_sampling}, {y_sampling})"
            )));
        }
        components.push(SizComponent {
            bit_depth,
            signed: ssiz & 0x80 != 0,
            x_sampling,
            y_sampling,
        });
    }
    b.expect_consumed("`SIZ`")?;

    let siz = Siz {
        x_size,
        y_size,
        x_offset,
        y_offset,
        tile_width,
        tile_height,
        tile_x_offset,
        tile_y_offset,
        components,
    };
    // Geometry legality (`validate_geometry`) and the sample limit
    // (`samples::check_codestream`) are the callers' to apply, in that order,
    // so this function stays a pure reader of the marker segment.
    Ok(siz)
}

/// Decode COD — default coding style (A.6.1): transform, decomposition depth,
/// progression, layers, code-block size/style, precinct sizes. All six Part 1
/// style flags and both color transforms are accepted, and Part 2's array MCT
/// is rejected. The HTJ2K style bits are kept for [`check_block_coder`].
fn decode_cod(mut b: Cursor<'_>) -> Result<Cod> {
    // Scod bit 0: user-defined precincts in SPcod. Bit 1: SOP may precede each
    // packet. Bit 2: EPH follows each packet header. Bits 3-7 are reserved.
    let scod = b.u8()?;
    if scod & 0xF8 != 0 {
        return Err(Error::marker(format!(
            "`COD` sets reserved `Scod` bits {:#04X}",
            scod & 0xF8
        )));
    }
    let explicit_precincts = scod & 0x01 != 0;
    let use_sop = scod & 0x02 != 0;
    let use_eph = scod & 0x04 != 0;

    let code = b.u8()?;
    let progression = Progression::from_u8(code)
        .ok_or_else(|| Error::marker(format!("reserved progression order {code}")))?;

    // Every packet costs at least one byte, so a layer count is bounded by the
    // tile-part in practice; a declared zero is malformed (ISO Table A-16).
    let layers = b.u16()?;
    if layers == 0 {
        return Err(Error::marker("`COD` declares zero quality layers"));
    }

    // SGcod multiple-component transform: 0 = none, 1 = the Part 1 color
    // transform over the first three components. 2 selects Part 2's array MCT,
    // which is a different feature entirely.
    let mct = b.u8()?;
    let multiple_component_transform = match mct {
        0 => false,
        1 => true,
        other => {
            return Err(Error::unsupported(format!(
                "multiple-component transform type {other}; only the Part 1 color transform is decoded"
            )));
        }
    };

    // Maximal precincts (PPx=PPy=15) when Scod bit 0 is clear, signaled by an
    // empty list.
    let coding = decode_coding(&mut b, "`COD`", explicit_precincts)?;
    b.expect_consumed("`COD`")?;

    Ok(Cod {
        progression,
        layers,
        use_sop,
        use_eph,
        multiple_component_transform,
        coding,
    })
}

/// The most progression volumes a tile's walk will honor. This is a decode
/// guard one volume above OpenJPEG's limit: its `opj_tcp_t::pocs` array has
/// 32 entries, and `opj_j2k_read_poc` refuses ("Too many POCs") a count of 32
/// or more, so it reads at most 31. The standard sets
/// no limit, but each volume re-enumerates the packet space and a duplicate
/// emission consumes no bitstream bytes, so an uncapped list is a quadratic
/// work bomb: `V` volumes over `P` one-byte packets cost `V·P` dedup probes
/// while the input pays for `P + 7V` bytes. The cap is enforced wherever
/// volumes accumulate — per marker and across a tile's parts — and again on the
/// list a tile resolves to ([`resolved_poc_len`]).
const MAX_POC_VOLUMES: usize = 32;

/// How many progression volumes `tile` walks over `main`: its own when its
/// first tile-part has a POC, which replaces the main header's, and otherwise
/// the main header's followed by any from later tile-parts (see
/// `resolve_tile_header`).
fn resolved_poc_len(main: &MainHeader, tile: &TileHeader) -> usize {
    if tile.poc_in_first_part {
        tile.poc.len()
    } else {
        main.poc.len() + tile.poc.len()
    }
}

/// Reject a progression-volume count past [`MAX_POC_VOLUMES`].
fn check_poc_budget(volumes: usize) -> Result<()> {
    if volumes > MAX_POC_VOLUMES {
        return Err(Error::limit_fixed(
            crate::LimitKind::PocVolumes,
            format!(
                "the `POC` markers declare {volumes} progression volumes for a tile, over the \
             limit of {MAX_POC_VOLUMES}"
            ),
        ));
    }
    Ok(())
}

/// Decode a POC marker (A.6.6, Table A-32): a sequence of progression volumes.
///
/// Each volume is `RSpoc`(1) `CSpoc`(1 or 2) `LYEpoc`(2) `REpoc`(1) `CEpoc`(1 or
/// 2) `Ppoc`(1). The component fields are two bytes once the image has 257 or
/// more components (like `Ccoc`/`Cqcc`), so the whole volume is `7` or `9` bytes,
/// and the marker body must be a whole number of them. `CSpoc`/`CEpoc` are read
/// against the component count; `LYEpoc` is clamped to the layer count later,
/// where it is known for certain.
///
/// Volumes append to any already in `into`: several POC markers in one header,
/// or in the tile-parts of one tile, form one sequence, as in OpenJPEG's
/// `opj_j2k_read_poc`. A tile's sequence then replaces the main header's when
/// it starts in the tile's first tile-part (see `resolve_tile_header`).
fn decode_poc(mut b: Cursor<'_>, siz: &Siz, into: &mut Vec<PocVolume>) -> Result<()> {
    let comp_room = if siz.components.len() < 257 { 1 } else { 2 };
    let volume_size = 5 + 2 * comp_room;
    let body_len = b.remaining();
    if body_len == 0 || !body_len.is_multiple_of(volume_size) {
        return Err(Error::marker(format!(
            "`POC` body is {body_len} bytes, not a whole number of {volume_size}-byte volumes"
        )));
    }
    check_poc_budget(into.len() + body_len / volume_size)?;
    let read_comp = |b: &mut Cursor<'_>| -> Result<u16> {
        if comp_room == 1 {
            Ok(u16::from(b.u8()?))
        } else {
            b.u16()
        }
    };
    for _ in 0..body_len / volume_size {
        let res_start = b.u8()?;
        let comp_start = read_comp(&mut b)?;
        let layer_end = b.u16()?;
        let res_end = b.u8()?;
        let comp_end = read_comp(&mut b)?;
        let progression = Progression::from_u8(b.u8()?)
            .ok_or_else(|| Error::marker("`POC` volume sets a reserved progression order"))?;
        // A volume that encloses nothing would consume no packets and desync
        // nothing, but it is a malformed field, not a no-op the encoder meant.
        // `LYEpoc` shares the rule: Table A-33 gives it the range 1–65535, so a
        // zero-layer volume is a malformed field too, rejected here rather than
        // surfacing later as a less precise desync error.
        if res_end <= res_start || comp_end <= comp_start || layer_end == 0 {
            return Err(Error::marker(format!(
                "`POC` volume has an empty range: resolutions [{res_start}, {res_end}), \
                 components [{comp_start}, {comp_end}), layers [0, {layer_end})"
            )));
        }
        into.push(PocVolume {
            res_start,
            res_end,
            comp_start,
            comp_end,
            layer_end,
            progression,
        });
    }
    Ok(())
}

/// Decode the `SPcod`/`SPcoc` tail shared by COD and COC (Tables A-12, A-14):
/// decomposition levels, the two code-block exponents, the style byte, the
/// wavelet, and — when `explicit_precincts` — the per-resolution precinct sizes.
/// `origin` names the marker for error messages.
///
/// The precinct flag lives in `Scod`/`Scoc`, not here, so the caller reads it and
/// passes it down. When it is clear the partition is maximal and
/// `precinct_sizes` comes back empty.
fn decode_coding(b: &mut Cursor<'_>, origin: &str, explicit_precincts: bool) -> Result<Coding> {
    let decomposition_levels = b.u8()?;
    // Table A-15: 0–32 decomposition levels; 33–255 are reserved. A reserved
    // field encoding rejects at parse, like the wavelet and style bytes below.
    if decomposition_levels > 32 {
        return Err(Error::marker(format!(
            "{origin} sets reserved decomposition level count {decomposition_levels} (max 32)"
        )));
    }
    let code_block_width = b.u8()?;
    let code_block_height = b.u8()?;
    // Every bit is allocated (Table A-19, ISO/IEC 15444-15 A.4), so the byte
    // is kept whole; `check_block_coder` refuses the coders not yet decoded.
    let code_block_style = b.u8()?;
    let transform = match b.u8()? {
        0 => Transform::Irreversible97,
        1 => Transform::Reversible53,
        other => {
            return Err(Error::marker(format!(
                "{origin} sets reserved wavelet transform {other}"
            )));
        }
    };
    // One `SPcod` precinct byte per resolution — `NL + 1` of them, coarsest
    // first — each packing `PPx` in the low nibble and `PPy` in the high one
    // (Table A-21). They are exponents on that *resolution's* grid, so the same
    // byte means a different span at every level.
    let precinct_sizes = if explicit_precincts {
        let mut sizes = Vec::with_capacity(usize::from(decomposition_levels) + 1);
        for resolution in 0..=usize::from(decomposition_levels) {
            let byte = b.u8()?;
            let (ppx, ppy) = (byte & 0x0F, byte >> 4);
            // A 2^0 precinct is legal only at the coarsest resolution (Table
            // A-21). Above it the precinct is halved onto the subband grid, so a
            // zero exponent would ask for a 2^-1 code-block partition — the
            // geometry is not merely unusual, it does not exist.
            if resolution > 0 && (ppx == 0 || ppy == 0) {
                return Err(Error::marker(format!(
                    "{origin} sets precinct 2^{ppx} x 2^{ppy} at resolution {resolution}; \
                     a zero exponent is permitted only at resolution 0"
                )));
            }
            sizes.push((ppx, ppy));
        }
        sizes
    } else {
        Vec::new()
    };

    // The standard bounds each code-block exponent at 2^10 and their sum at
    // 2^12 (Table A-18). OpenJPEG refuses the field when it reads the header
    // ("Invalid cblkw/cblkh combination"), so a header-only read does too.
    let (xcb, ycb) = (
        u32::from(code_block_width) + 2,
        u32::from(code_block_height) + 2,
    );
    if xcb > 10 || ycb > 10 || xcb + ycb > 12 {
        return Err(Error::marker(format!(
            "code-block size 2^{xcb} x 2^{ycb} is over the 4096-sample limit"
        )));
    }

    Ok(Coding {
        decomposition_levels,
        code_block_width,
        code_block_height,
        code_block_style,
        transform,
        precinct_sizes,
    })
}

/// The component index a COC or QCC applies to (`Ccoc`, `Cqcc`). One byte while
/// `Csiz < 257`, two bytes otherwise (A.6.2, A.6.5) — the width depends on the
/// component count, so SIZ must already be parsed.
fn component_index(b: &mut Cursor<'_>, siz: &Siz, origin: &str) -> Result<usize> {
    let count = siz.components.len();
    let index = if count < 257 {
        usize::from(b.u8()?)
    } else {
        usize::from(b.u16()?)
    };
    if index >= count {
        return Err(Error::marker(format!(
            "{origin} targets component {index}, but `SIZ` declares {count}"
        )));
    }
    Ok(index)
}

/// Decode COC — a coding-style override for one component (A.6.2).
///
/// Returns the component index and the coding parameters that replace COD's for
/// it. `Scoc` carries only the precinct flag; every other bit is reserved.
fn decode_coc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Coding)> {
    let index = component_index(&mut b, siz, "`COC`")?;
    let scoc = b.u8()?;
    let explicit_precincts = scoc & 0x01 != 0;
    // Only bit 0 is defined in `Scoc` (Table A-21). SOP and EPH are signaled
    // once for the tile, in COD's `Scod`, and have no per-component form — so
    // unlike `Scod` there is nothing else here to read. OpenJPEG stores the byte
    // without validating it and consults only bit 0.
    if scoc & 0xFE != 0 {
        return Err(Error::marker(format!(
            "`COC` sets reserved `Scoc` bits {:#04X}",
            scoc & 0xFE
        )));
    }
    let coding = decode_coding(&mut b, "`COC`", explicit_precincts)?;
    b.expect_consumed("`COC`")?;
    Ok((index, coding))
}

/// Decode QCC — a quantization override for one component (A.6.5). The body
/// after `Cqcc` is a `QCD` body, byte for byte.
fn decode_qcc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Qcd)> {
    let index = component_index(&mut b, siz, "`QCC`")?;
    let quant = decode_quant(b, "`QCC`")?;
    Ok((index, quant))
}

/// Decode RGN — a region of interest for one component (A.6.3).
///
/// Returns the component index and its maxshift. `Srgn` selects the ROI style,
/// and `0` (implicit — the maxshift of Annex H) is the only style Part 1
/// defines. OpenJPEG reads the byte and never looks at it, so a codestream using
/// a Part 2 style decodes there as though it were maxshift.
fn decode_rgn(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, u8)> {
    let index = component_index(&mut b, siz, "`RGN`")?;
    let srgn = b.u8()?;
    if srgn != 0 {
        return Err(Error::unsupported(format!(
            "region-of-interest style {srgn}; only the implicit maxshift (`Srgn` = 0) is decoded"
        )));
    }
    let shift = b.u8()?;
    b.expect_consumed("`RGN`")?;
    Ok((index, shift))
}

/// Decode TLM — tile-part lengths (A.7.1) — appending onto `entries`.
///
/// `Stlm` packs two field widths: `ST` (bits 4–5) is the tile-index width in
/// bytes, where 0 means the index is implied by entry order across all TLM
/// markers, and `SP` (bit 6) selects 16- or 32-bit lengths. `ST = 3` and the
/// reserved bits (0–3 and 7) are illegal encodings; OpenJPEG warns and ignores
/// the whole TLM chain on `ST = 3` or a bad entry size and never looks at the
/// reserved bits, but as with `Scoc` rejecting is stricter and no conformant
/// codestream carries them.
///
/// An entry may only name a tile the grid actually holds. OpenJPEG makes the
/// same range check against its grid.
///
/// `seen` counts the entries of every TLM marker read so far, across markers;
/// each valid entry is handed to `entry`.
fn decode_tlm(
    mut b: Cursor<'_>,
    siz: &Siz,
    seen: &mut usize,
    mut entry: impl FnMut(TlmEntry),
) -> Result<()> {
    b.u8()?; // Ztlm: this marker's position among the TLMs
    let stlm = b.u8()?;
    if stlm & 0x8F != 0 {
        return Err(Error::marker(format!(
            "`TLM` sets reserved `Stlm` bits {:#04X}",
            stlm & 0x8F
        )));
    }
    let st = (stlm >> 4) & 0x3;
    if st == 3 {
        return Err(Error::marker(
            "`TLM` tile-index width `ST` = 3 is not defined",
        ));
    }
    let sp = (stlm >> 6) & 0x1;

    let entry_size = usize::from(st) + 2 * (usize::from(sp) + 1);
    if !b.remaining().is_multiple_of(entry_size) {
        return Err(Error::codestream(format!(
            "`TLM` carries {} entry bytes, not a multiple of its {entry_size}-byte entries",
            b.remaining()
        )));
    }

    while b.remaining() > 0 {
        let tile_index = match st {
            0 => u32::try_from(*seen).unwrap_or(u32::MAX),
            1 => u32::from(b.u8()?),
            _ => u32::from(b.u16()?),
        };
        if tile_index >= siz.num_tiles() {
            return Err(Error::marker(format!(
                "`TLM` names tile {tile_index}, but the grid holds {} tiles",
                siz.num_tiles()
            )));
        }
        let length = match sp {
            0 => u32::from(b.u16()?),
            _ => b.u32()?,
        };
        *seen += 1;
        entry(TlmEntry { tile_index, length });
    }
    Ok(())
}

/// Decode CRG — component registration (A.9.1): one `(Xcrg, Ycrg)` sub-pixel
/// offset per component, each a `u16` in units of `1/65536` of the reference-grid
/// step. The body is exactly `4 · Csiz` bytes.
///
/// The offsets are recorded, not applied. CRG is informational — it registers
/// the components for display, not for decoding — so the reconstructed samples
/// are the same with it present or absent, and the class-1 references are made
/// without resampling (issue #74). OpenJPEG reads past the body without keeping
/// the values at all; recording them is the one place this is deliberately more
/// than the oracle, so a caller that does care about registration can act on them.
fn decode_crg(mut b: Cursor<'_>, siz: &Siz) -> Result<Vec<(u16, u16)>> {
    let count = siz.components.len();
    if b.remaining() != count * 4 {
        return Err(Error::marker(format!(
            "`CRG` carries {} bytes, not the {} its {count} components need",
            b.remaining(),
            count * 4
        )));
    }
    let mut offsets = Vec::with_capacity(count);
    for _ in 0..count {
        let x = b.u16()?;
        let y = b.u16()?;
        offsets.push((x, y));
    }
    Ok(offsets)
}

/// `Pcap` bit 15, counted from the MSB: the codestream uses Part 15 (HTJ2K)
/// capabilities (ISO/IEC 15444-15 A.3.1).
const PCAP_PART15: u32 = 1 << (32 - 15);

/// Decode CAP — extended capabilities (ISO/IEC 15444-1 A.5.2): `Pcap`, then
/// one `Ccap` word for each bit `Pcap` sets, in bit order from the MSB. Bit
/// `i` (from 1 at the MSB) says the codestream uses capabilities of Part `i`.
///
/// Returns the Part 15 word when `Pcap` sets that bit. A capability of any
/// other part is `Unsupported`, as is MULTIHT (`Ccap15` bit 13), which no
/// conformance codestream sets. OpenJPEG reads no field of CAP.
fn decode_cap(mut b: Cursor<'_>) -> Result<Option<Ccap15>> {
    let len = b.remaining();
    let pcap = if len >= 4 { b.u32()? } else { 0 };
    let needed = 4 + 2 * pcap.count_ones() as usize;
    if len != needed {
        return Err(Error::marker(format!(
            "`CAP` carries {len} bytes, not the {needed} its `Pcap` needs"
        )));
    }
    if let Some(bit) = (1..=32).find(|&i| i != 15 && pcap & (1 << (32 - i)) != 0) {
        // Part 1 is the baseline and has no extended capabilities, and no
        // part past 17 exists. Such a bit names no capability this decoder
        // knows; it is still `Unsupported`, not `Marker`, since a later
        // edition may assign it.
        let message = if (2..=17).contains(&bit) {
            format!("`CAP` signals capabilities of ISO/IEC 15444-{bit}, outside the decoded subset")
        } else {
            format!(
                "`CAP` sets `Pcap` bit {bit}, counted from the MSB, which names no part \
                 of ISO/IEC 15444 with capabilities this decoder knows"
            )
        };
        return Err(Error::unsupported(message));
    }
    if pcap & PCAP_PART15 == 0 {
        return Ok(None);
    }
    // The `Ccap` words follow `Pcap`'s bits from the MSB, so `Ccap15` is the
    // first word only because every other part's bit was refused above. Once
    // a Part 2 capability is read, `Ccap2` comes before it.
    let ccap15 = Ccap15(b.u16()?);
    if ccap15.multiht() {
        return Err(Error::unsupported(
            "`CAP` signals more than one HT set per code-block (MULTIHT), outside the decoded subset",
        ));
    }
    Ok(Some(ccap15))
}

/// Decode CPF — the corresponding profile (ISO/IEC 15444-15 A.6): one or
/// more 16-bit `Pcpf` words. Kept, not checked against `Rsiz` or the
/// profile: it changes nothing about decoding, and OpenJPEG reads none of
/// it. A body that is not whole words is malformed.
fn decode_cpf(mut b: Cursor<'_>) -> Result<Cpf> {
    let len = b.remaining();
    if len == 0 || !len.is_multiple_of(2) {
        return Err(Error::marker(format!(
            "`CPF` carries {len} bytes, not one or more 16-bit `Pcpf` words"
        )));
    }
    let words = (0..len / 2).map(|_| b.u16()).collect::<Result<_>>()?;
    Ok(Cpf { words })
}

/// The one guard on which block coder a COD or COC selects, run as each is
/// read in the main header or a tile-part header ([`OverrideReader`]).
///
/// The style bits decide each tile-component's coder (ISO/IEC 15444-15
/// A.4); `CAP` does not override them. `0x40` alone selects the HT block
/// coder. `0x40` with `0x80` is MIXED: each code-block is an HT block or a
/// Part 1 block, which tier-2 tells apart. A.4 allows the Part 1 blocks
/// there neither bypass nor termination on each pass, so a MIXED style with
/// either bit is malformed. `0x80` without `0x40` is a Part 1 style with a
/// reserved bit set, and is refused as outside the decoded subset. Because it
/// runs per segment, a cut header that already holds such a COD or COC is
/// refused, not reported as incomplete.
fn check_block_coder(coding: &Coding, origin: &str) -> Result<()> {
    use markers::code_block_style::{HT, HT_MIXED, LAZY, TERMALL};
    let style = coding.code_block_style;
    if style & (HT | HT_MIXED) == HT_MIXED {
        return Err(Error::unsupported(format!(
            "{origin} code-block style ({}) is outside the decoded subset",
            markers::code_block_style::describe(HT_MIXED),
        )));
    }
    let terminating = style & (LAZY | TERMALL);
    if style & HT_MIXED != 0 && terminating != 0 {
        return Err(Error::marker(format!(
            "{origin} code-block style is MIXED with {}, which ISO/IEC 15444-15 A.4 \
             does not allow its Part 1 code-blocks",
            markers::code_block_style::describe(terminating),
        )));
    }
    Ok(())
}

/// Decode PLM — main-header packet lengths (A.7.2).
///
/// Validated for presence and otherwise skipped, exactly as OpenJPEG's
/// `opj_j2k_read_plm` does: an `Nplm`/`Iplm` chain may split across PLM
/// markers mid-entry, so per-marker structural validation would reject
/// codestreams the oracle accepts. The packets themselves are read from the
/// codestream, so nothing here is needed to decode.
fn decode_plm(mut b: Cursor<'_>) -> Result<()> {
    b.u8()?; // Zplm: this marker's position among the PLMs
    Ok(())
}

/// Decode PLT — tile-part packet lengths (A.7.3).
///
/// Each packet length is a base-128 chain of bytes, high bit meaning "another
/// byte follows". The lengths are informational and discarded; what is checked
/// is that the last chain is whole — a final byte with its continuation bit
/// set is a truncated entry. OpenJPEG rejects the same way unless every
/// payload bit of the dangling chain is zero (`opj_j2k_read_plt` tests the
/// accumulated *value* at segment end, and `0 << 7` stays 0); rejecting the
/// all-zero dangle too is stricter, the same documented stance as the TLM
/// encodings above.
fn decode_plt(mut b: Cursor<'_>) -> Result<()> {
    b.u8()?; // Zplt: this marker's position among the tile-part's PLTs
    // The chains are self-delimiting, so whole-ness is one property: the last
    // byte must not claim a continuation.
    let chains = b.take(b.remaining())?;
    if chains.last().is_some_and(|&last| last & 0x80 != 0) {
        return Err(Error::codestream(
            "`PLT` ends in the middle of a packet-length entry",
        ));
    }
    Ok(())
}

/// Split the main header's packed packet headers (`PPM`, A.7.4) into one chunk
/// per tile-part, in codestream order.
///
/// Each `PPM` marker carries `Zppm` (its position) and `Ippm` (payload). Joined
/// across every marker in `Zppm` order, the payload is a run of `(Nppm, bytes)`
/// records — `Nppm` a 4-byte length, `bytes` that tile-part's packet headers —
/// one record per tile-part. `Nppm` may straddle a marker boundary, so the
/// payloads are concatenated before the records are read, matching OpenJPEG's
/// `opj_j2k_merge_ppm`. Each returned chunk feeds a tile-part's packet-header
/// stream in [`walk_tiles`], the same role `PPT` plays for a single tile-part.
fn decode_ppm_chunks(mut markers: Vec<(u8, Vec<u8>)>) -> Result<Vec<Vec<u8>>> {
    if markers.is_empty() {
        return Ok(Vec::new());
    }
    // `Zppm` orders the markers; a repeated index is a malformed main header.
    markers.sort_by_key(|&(z, _)| z);
    if markers.windows(2).any(|w| w[0].0 == w[1].0) {
        return Err(Error::codestream(
            "duplicate `PPM` index `Zppm` in the main header",
        ));
    }
    let joined: Vec<u8> = markers.into_iter().flat_map(|(_, bytes)| bytes).collect();

    let mut cur = Cursor::new(&joined);
    let mut chunks = Vec::new();
    while cur.remaining() > 0 {
        // Nppm: the byte count of this tile-part's packet headers (may be 0).
        let nppm = cur.u32()? as usize;
        chunks.push(cur.take(nppm)?.to_vec());
    }
    Ok(chunks)
}

/// Decode the quantization body shared by QCD (A.6.4) and QCC (A.6.5): style,
/// guard bits, and the per-subband (exponent, mantissa) step parameters. QCC's
/// body after `Cqcc` is a QCD body byte for byte, so `origin` only names the
/// marker for error messages — a malformed override must not report as a fault
/// in the codestream-wide default.
fn decode_quant(mut b: Cursor<'_>, origin: &str) -> Result<Qcd> {
    let sqcd = b.u8()?;
    let guard_bits = sqcd >> 5;
    let style = match sqcd & 0x1F {
        0 => QuantStyle::None,
        1 => QuantStyle::ScalarDerived,
        2 => QuantStyle::ScalarExpounded,
        other => {
            return Err(Error::marker(format!(
                "{origin} sets reserved quantization style {other}"
            )));
        }
    };

    // A step table covers at most the 3·NL + 1 subbands of a 32-level
    // decomposition (A.6.4, with NL ≤ 32 per Table A-15), so 97 entries.
    // Entries past that are kept out of the table — but still consumed — the
    // way OpenJPEG caps at J2K_MAXBANDS and decodes (verified empirically:
    // a 120-entry QCD decodes without a warning). Dropping rather than
    // rejecting also keeps a hostile 65535-byte Lqcd from inflating the
    // per-component `Qcd` clones in [`MainHeader::new`].
    const MAX_STEP_ENTRIES: usize = 3 * 32 + 1;

    let mut steps = Vec::new();
    match style {
        // No quantization (reversible): one byte per subband, high 5 bits are
        // the exponent, mantissa is 0.
        QuantStyle::None => {
            if b.remaining() == 0 {
                return Err(Error::codestream(format!(
                    "{origin} carries no step entries"
                )));
            }
            while b.remaining() > 0 {
                let v = b.u8()?;
                if steps.len() < MAX_STEP_ENTRIES {
                    steps.push((v >> 3, 0));
                }
            }
        }
        // Scalar: 16-bit per entry, high 5 bits exponent, low 11 bits mantissa.
        // Derived signals one entry (LL); expounded one per subband.
        QuantStyle::ScalarDerived | QuantStyle::ScalarExpounded => {
            if b.remaining() == 0 || !b.remaining().is_multiple_of(2) {
                return Err(Error::codestream(format!(
                    "{origin} step table is truncated"
                )));
            }
            if style == QuantStyle::ScalarDerived && b.remaining() != 2 {
                return Err(Error::codestream(format!(
                    "derived {origin} must carry exactly one step entry"
                )));
            }
            while b.remaining() > 0 {
                let v = b.u16()?;
                if steps.len() < MAX_STEP_ENTRIES {
                    steps.push((((v >> 11) & 0x1F) as u8, v & 0x07FF));
                }
            }
        }
    }

    Ok(Qcd {
        style,
        guard_bits,
        steps,
    })
}

/// Read a marker segment's length field and return a [`Cursor`] over its body.
///
/// `Lmarker` (A.4) counts the two length bytes but not the two marker bytes, so
/// the body is `Lmarker - 2` bytes. A length below 2 or past the buffer end is a
/// malformed codestream.
fn segment<'a>(cur: &mut Cursor<'a>) -> Result<Cursor<'a>> {
    let len = cur.u16()? as usize;
    if len < 2 {
        return Err(Error::codestream("marker segment length below 2"));
    }
    let body = cur.take(len - 2)?;
    Ok(Cursor::new(body))
}

/// Bounds-checked big-endian byte cursor. Every read maps an overrun to
/// [`Error::Codestream`] so truncation is a typed error, never a panic.
struct Cursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// A cursor over `buf` starting at an absolute offset, for resuming a walk
    /// (e.g. tile-parts) from a position the main-header pass returned.
    fn at(buf: &'a [u8], pos: usize) -> Self {
        Self { buf, pos }
    }

    fn remaining(&self) -> usize {
        self.buf.len() - self.pos
    }

    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        if self.remaining() < n {
            return Err(Error::codestream("truncated marker segment"));
        }
        let slice = &self.buf[self.pos..self.pos + n];
        self.pos += n;
        Ok(slice)
    }

    fn u8(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }

    fn u16(&mut self) -> Result<u16> {
        let b = self.take(2)?;
        Ok(u16::from_be_bytes([b[0], b[1]]))
    }

    fn u32(&mut self) -> Result<u32> {
        let b = self.take(4)?;
        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
    }

    /// Assert the whole segment body was consumed; a trailing remainder means
    /// the declared length and the field layout disagree.
    fn expect_consumed(&self, marker: &str) -> Result<()> {
        if self.remaining() != 0 {
            return Err(Error::codestream(format!(
                "{marker} segment has {} unexpected trailing byte(s)",
                self.remaining()
            )));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests;