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
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
//! Unit tests for main-header parsing.
//!
//! Each header is assembled byte-for-byte from the Annex A field layout, so the
//! expected `MainHeader` is checked against the spec, not against our own
//! parser. On top of that,
//! [`siz_matches_opj_dump_across_the_conformance_corpus`] cross-checks the
//! parsed per-component geometry of all 23 conformance codestreams against the
//! `opj_dump` values recorded in the corpus manifest.

use super::markers::{Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform, marker};
use super::*;
use crate::Error;
use crate::synth;
use synth::seg;

fn be16(v: u16) -> [u8; 2] {
    v.to_be_bytes()
}

/// SIZ body (everything after `Lsiz`): 512x256 single tile, `csiz` components.
fn siz_body(csiz: u16, comps: &[(u8, u8, u8)]) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&be16(0)); // Rsiz
    b.extend_from_slice(&512u32.to_be_bytes()); // Xsiz
    b.extend_from_slice(&256u32.to_be_bytes()); // Ysiz
    b.extend_from_slice(&0u32.to_be_bytes()); // XOsiz
    b.extend_from_slice(&0u32.to_be_bytes()); // YOsiz
    b.extend_from_slice(&512u32.to_be_bytes()); // XTsiz
    b.extend_from_slice(&256u32.to_be_bytes()); // YTsiz
    b.extend_from_slice(&0u32.to_be_bytes()); // XTOsiz
    b.extend_from_slice(&0u32.to_be_bytes()); // YTOsiz
    b.extend_from_slice(&be16(csiz));
    for &(ssiz, xr, yr) in comps {
        b.extend_from_slice(&[ssiz, xr, yr]);
    }
    b
}

/// One unsigned 16-bit component (Ssiz = depth-1 = 15, sign bit clear).
fn one_component() -> Vec<u8> {
    siz_body(1, &[(15, 1, 1)])
}

#[allow(clippy::too_many_arguments)]
fn cod_body(
    scod: u8,
    prog: u8,
    layers: u16,
    mct: u8,
    nl: u8,
    xcb: u8,
    ycb: u8,
    style: u8,
    transform: u8,
) -> Vec<u8> {
    let mut b = vec![scod, prog];
    b.extend_from_slice(&be16(layers));
    b.push(mct);
    b.extend_from_slice(&[nl, xcb, ycb, style, transform]);
    b
}

/// Default valid COD: LRCP, single layer, 5 levels, 64x64 code-blocks.
fn cod_default(transform: u8) -> Vec<u8> {
    cod_body(0, 0, 1, 0, 5, 4, 4, 0, transform)
}

/// QCD body, no quantization (reversible): one exponent byte per subband.
fn qcd_none(guard: u8, exponents: &[u8]) -> Vec<u8> {
    let mut b = vec![guard << 5]; // style 0 (no quantization) in the low 5 bits
    for &e in exponents {
        b.push(e << 3);
    }
    b
}

/// QCD body, scalar expounded: a 16-bit (exponent, mantissa) per subband.
fn qcd_expounded(guard: u8, steps: &[(u8, u16)]) -> Vec<u8> {
    let mut b = vec![(guard << 5) | 2];
    for &(e, m) in steps {
        b.extend_from_slice(&be16((u16::from(e) << 11) | (m & 0x07FF)));
    }
    b
}

/// Assemble SOC + segments + a terminating SOT marker.
fn codestream(segments: &[Vec<u8>]) -> Vec<u8> {
    let mut h = Vec::new();
    h.extend_from_slice(&be16(marker::SOC));
    for s in segments {
        h.extend_from_slice(s);
    }
    h.extend_from_slice(&be16(marker::SOT));
    h
}

#[test]
fn valid_reversible_header_parses() {
    let exps = [8u8; 16]; // 3*5 + 1 subbands for 5 levels
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &exps)),
    ]);

    let (header, sot_offset, _) = parse_main_header(&bytes).expect("parse");

    assert_eq!(
        header,
        MainHeader::single_component(
            (512, 256),
            (16, false),
            (5, Transform::Reversible53),
            Qcd {
                style: QuantStyle::None,
                guard_bits: 2,
                steps: vec![(8, 0); 16],
            },
        )
    );
    // The offset points at the terminating SOT marker.
    assert_eq!(sot_offset, bytes.len() - 2);
    assert_eq!(&bytes[sot_offset..sot_offset + 2], &be16(marker::SOT));
}

#[test]
fn valid_irreversible_header_parses() {
    let steps = [(10u8, 1234u16); 16];
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_body(1, &[(0x80 | 11, 1, 1)])), // signed 12-bit
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &qcd_expounded(1, &steps)),
    ]);

    let (header, _, _) = parse_main_header(&bytes).expect("parse");

    assert_eq!(header.siz.components[0].bit_depth, 12);
    assert!(header.siz.components[0].signed);
    assert_eq!(header.cod.coding.transform, Transform::Irreversible97);
    assert_eq!(header.qcd.style, QuantStyle::ScalarExpounded);
    assert_eq!(header.qcd.guard_bits, 1);
    assert_eq!(header.qcd.steps, vec![(10, 1234); 16]);
}

#[test]
fn derived_quant_keeps_single_step() {
    let mut body = vec![(2u8 << 5) | 1]; // guard 2, derived
    body.extend_from_slice(&be16((9 << 11) | 42)); // one (exp, mantissa)
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &body),
    ]);

    let (header, _, _) = parse_main_header(&bytes).expect("parse");
    assert_eq!(header.qcd.style, QuantStyle::ScalarDerived);
    assert_eq!(header.qcd.steps, vec![(9, 42)]);
}

#[test]
fn comment_segment_is_skipped() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COM, &[0, 1, b'h', b'i']),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(parse_main_header(&bytes).is_ok());
}

// --- reject matrix -------------------------------------------------------

fn err(bytes: &[u8]) -> Error {
    parse_main_header(bytes).expect_err("should reject")
}

#[test]
fn missing_soc_is_codestream() {
    // Starts with SIZ instead of SOC.
    let bytes = seg(marker::SIZ, &one_component());
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn siz_not_first_is_codestream() {
    let bytes = codestream(&[seg(marker::COD, &cod_default(1))]);
    let e = err(&bytes);
    assert!(
        matches!(&e, Error::Codestream(m) if m.message().contains("first marker")),
        "{e:?}"
    );
}

/// A SIZ whose length promises more than the input holds: the input ends
/// inside the main header, so more bytes may still complete it.
#[test]
fn truncated_main_header_segment_is_incomplete() {
    let mut bytes = be16(marker::SOC).to_vec();
    bytes.extend_from_slice(&be16(marker::SIZ));
    bytes.extend_from_slice(&be16(100));
    bytes.extend_from_slice(&[0, 0, 0, 0]);
    assert!(matches!(err(&bytes), Error::Incomplete(_)));
}

/// A segment body too short for its own fields is all there, so it is
/// malformed, not cut short: the main-header walk read the whole of it.
#[test]
fn a_segment_too_short_for_its_fields_is_codestream() {
    let mut body = one_component();
    body.truncate(body.len() - 1);
    let e = err(&codestream(&[seg(marker::SIZ, &body)]));
    assert!(matches!(e, Error::Codestream(_)), "{e:?}");
}

#[test]
fn trailing_bytes_in_siz_is_codestream() {
    let mut body = one_component();
    body.push(0xAB); // one byte the layout does not account for
    let bytes = codestream(&[
        seg(marker::SIZ, &body),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn multiple_components_parse() {
    let bytes = codestream(&[
        seg(
            marker::SIZ,
            &siz_body(3, &[(15, 1, 1), (7, 2, 2), (7, 2, 2)]),
        ),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let (header, _, _) = parse_main_header(&bytes).expect("multi-component header parses");
    assert_eq!(header.siz.components.len(), 3);
    // Each component keeps its own depth and sub-sampling.
    assert_eq!(header.siz.component_extent(0), Some((512, 256)));
    assert_eq!(header.siz.component_extent(1), Some((256, 128)));
    assert_eq!(header.siz.components[1].bit_depth, 8);
}

#[test]
fn zero_components_is_marker() {
    let bytes = codestream(&[seg(marker::SIZ, &siz_body(0, &[]))]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// SIZ body with explicit geometry and one valid unsigned 15-bit component, so
/// the geometry-subset rejects (validated before the component list) can be
/// exercised one field at a time.
#[allow(clippy::too_many_arguments)]
fn siz_geom(x: u32, y: u32, xo: u32, yo: u32, xt: u32, yt: u32, xto: u32, yto: u32) -> Vec<u8> {
    let mut b = Vec::new();
    b.extend_from_slice(&be16(0)); // Rsiz
    for v in [x, y, xo, yo, xt, yt, xto, yto] {
        b.extend_from_slice(&v.to_be_bytes());
    }
    b.extend_from_slice(&be16(1)); // Csiz
    b.extend_from_slice(&[15, 1, 1]); // one unsigned 16-bit component
    b
}

#[test]
fn zero_size_image_is_marker() {
    let bytes = codestream(&[seg(marker::SIZ, &siz_geom(0, 256, 0, 0, 512, 256, 0, 0))]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn a_nonzero_image_and_tile_offset_is_accepted() {
    // A non-zero image origin with a tile origin at or before it (Table A-9) is
    // valid JPEG 2000 — the reference-grid geometry the conformance entries
    // p1_01 and p1_07 carry. `validate_geometry` must pass it.
    let mut siz = siz_of(1, &[(8, 1, 1)]);
    siz.x_size = 128;
    siz.y_size = 128;
    siz.x_offset = 5;
    siz.y_offset = 3;
    siz.tile_x_offset = 1;
    siz.tile_y_offset = 2;
    assert!(validate_geometry(&siz).is_ok());
}

#[test]
fn an_image_offset_at_or_past_the_far_edge_is_marker() {
    // Table A-9: `XOsiz < Xsiz`. An origin at the far edge encloses no image.
    let mut siz = siz_of(1, &[(8, 1, 1)]);
    siz.x_size = 64;
    siz.y_size = 64;
    siz.x_offset = 64;
    assert!(matches!(validate_geometry(&siz), Err(Error::Marker(_))));
}

#[test]
fn a_tile_offset_past_the_image_offset_is_marker() {
    // Table A-9: `XTOsiz <= XOsiz`. A tile grid starting right of the image
    // origin is malformed, not an undecoded feature.
    let mut siz = siz_of(1, &[(8, 1, 1)]);
    siz.x_size = 64;
    siz.y_size = 64;
    siz.x_offset = 2;
    siz.tile_x_offset = 3;
    assert!(matches!(validate_geometry(&siz), Err(Error::Marker(_))));
}

#[test]
fn a_first_tile_that_never_reaches_the_image_is_marker() {
    // Table A-9: `XTOsiz + XTsiz > XOsiz`. Otherwise the first tile column clips
    // to nothing and `tile_rect` hands `resolution_geoms` an empty leading tile.
    let mut siz = siz_of(1, &[(8, 1, 1)]);
    siz.x_size = 64;
    siz.y_size = 64;
    siz.x_offset = 10;
    siz.tile_x_offset = 0;
    siz.tile_width = 8; // 0 + 8 = 8 <= 10
    assert!(matches!(validate_geometry(&siz), Err(Error::Marker(_))));
}

#[test]
fn zero_size_tile_is_marker() {
    let bytes = codestream(&[seg(marker::SIZ, &siz_geom(512, 256, 0, 0, 0, 256, 0, 0))]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// A tile grid finer than `Isot` can name has tiles no tile-part can reach, so
/// SIZ is malformed rather than merely unsupported. `Isot` runs 0..=65534
/// (Table A-10), which caps the grid at 65535 tiles.
#[test]
fn a_tile_grid_past_the_isot_range_is_marker() {
    // 65536 one-pixel tiles across a 65536x1 image: one tile past the limit.
    let bytes = codestream(&[seg(marker::SIZ, &siz_geom(65536, 1, 0, 0, 1, 1, 0, 0))]);
    assert!(matches!(err(&bytes), Error::Marker(_)));

    // 65535 tiles is the largest grid that fits, and it parses.
    let bytes = codestream(&[seg(marker::SIZ, &siz_geom(65535, 1, 0, 0, 1, 1, 0, 0))]);
    assert!(
        matches!(err(&bytes), Error::Codestream(_)),
        "reaches the missing-COD check"
    );
}

/// The tile grid SIZ describes, and each tile's rectangle on the reference grid.
/// The right and bottom tiles of a grid that does not divide the image evenly are
/// clipped, which is what makes an edge tile partial.
#[test]
fn the_tile_grid_covers_the_image_with_clipped_edge_tiles() {
    let header = parsed(&[
        // 40x40 image in 16x16 tiles: a 3x3 grid whose last row and column are
        // 8 wide, not 16.
        seg(marker::SIZ, &siz_geom(40, 40, 0, 0, 16, 16, 0, 0)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let siz = &header.siz;
    assert_eq!(siz.tile_grid(), (3, 3));
    assert_eq!(siz.num_tiles(), 9);

    let rect = |i| siz.tile_rect(i).expect("tile in the grid");
    assert_eq!(
        (rect(0).x0, rect(0).y0, rect(0).x1, rect(0).y1),
        (0, 0, 16, 16)
    );
    assert_eq!(
        (rect(1).x0, rect(1).x1),
        (16, 32),
        "tiles are numbered in raster order"
    );
    assert_eq!(
        (rect(2).x0, rect(2).x1),
        (32, 40),
        "the last column is clipped to the image"
    );
    assert_eq!(
        (rect(8).x0, rect(8).y0, rect(8).x1, rect(8).y1),
        (32, 32, 40, 40)
    );
    assert!(siz.tile_rect(9).is_none(), "past the grid");

    // Every tile of the grid, laid side by side, is the image and nothing else.
    let area: u64 = (0..siz.num_tiles()).map(|i| rect(i).area()).sum();
    assert_eq!(area, 40 * 40);
}

#[cfg(target_pointer_width = "64")]
#[test]
fn oversize_image_area_is_a_limit() {
    // 32769×16384 is just past the 2^29 default sample limit. The parse
    // itself leaves the area to the limit, which knows the caller's options.
    let n = 16384;
    let siz = siz_of_geom(2 * n + 1, n);
    let cap = crate::samples::MAX_IMAGE_SAMPLES;
    let e = crate::samples::check_codestream(&siz, 0, cap).unwrap_err();
    assert!(
        matches!(&e, Error::Limit(m) if m.message().starts_with("image area 32769x16384 needs")),
        "got {e:?}"
    );
    // 32768×16384 is exactly the limit, and fits.
    assert!(crate::samples::check_codestream(&siz_of_geom(2 * n, n), 0, cap).is_ok());
    // One level down the area is a quarter, and fits.
    assert!(crate::samples::check_codestream(&siz, 1, cap).is_ok());
}

/// The SIZ of a `width` x `height` single-component image, one tile.
#[cfg(target_pointer_width = "64")]
fn siz_of_geom(width: u32, height: u32) -> Siz {
    decode_siz(Cursor::new(&siz_geom(
        width, height, 0, 0, width, height, 0, 0,
    )))
    .unwrap()
}

#[test]
fn tile_larger_than_image_is_accepted() {
    // A tile larger than the image (XTsiz > Xsiz) is legal — the tile clips to
    // the image and the grid is still single-tile — so it must parse, pinning
    // the `<` boundary in the multi-tile check against a future `!=` tightening.
    let exps = [8u8; 16];
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_geom(512, 256, 0, 0, 1024, 512, 0, 0)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &exps)),
    ]);
    assert!(parse_main_header(&bytes).is_ok());
}

#[test]
fn every_progression_order_parses() {
    for (code, want) in [
        (0, Progression::Lrcp),
        (1, Progression::Rlcp),
        (2, Progression::Rpcl),
        (3, Progression::Pcrl),
        (4, Progression::Cprl),
    ] {
        let bytes = codestream(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_body(0, code, 1, 0, 5, 4, 4, 0, 1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]);
        let (header, _, _) = parse_main_header(&bytes).unwrap_or_else(|e| panic!("{code}: {e:?}"));
        assert_eq!(header.cod.progression, want, "progression code {code}");
    }
}

#[test]
fn reserved_progression_order_is_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 5, 1, 0, 5, 4, 4, 0, 1)),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn reserved_progression_is_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 7, 1, 0, 5, 4, 4, 0, 1)),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn multiple_layers_parse() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 0, 5, 0, 5, 4, 4, 0, 1)), // 5 layers
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let (header, _, _) = parse_main_header(&bytes).expect("multi-layer header parses");
    assert_eq!(header.cod.layers, 5);
}

#[test]
fn zero_layers_is_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 0, 0, 0, 5, 4, 4, 0, 1)),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// A main header whose COD signals an explicit precinct partition (`Scod` bit 0)
/// with `sizes` as its `SPcod` tail, wrapped in a complete codestream. Two
/// decomposition levels, so a partition is three bytes.
fn with_precincts(sizes: &[u8]) -> Vec<u8> {
    let mut cod = cod_body(0x01, 0, 1, 0, 2, 4, 4, 0, 1);
    cod.extend_from_slice(sizes);
    let header = vec![
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod),
        seg(marker::QCD, &qcd_none(2, &[8; 7])),
    ];
    let data = [0xDE, 0xAD];
    assemble(&header, &synth::sot(0, psot_for(&data), 0, 1), &data, true)
}

/// `Scod` bit 0 adds one `SPcod` 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).
#[test]
fn explicit_precinct_sizes_parse_from_spcod() {
    // Three resolutions: 2^0 × 2^1, 2^6 × 2^5, 2^7 × 2^7.
    let bytes = with_precincts(&[0x10, 0x56, 0x77]);
    let cs = parse(&bytes).expect("explicit precincts parse");
    assert_eq!(
        cs.header.cod.coding.precinct_sizes,
        vec![(0, 1), (6, 5), (7, 7)],
        "PPx is the low nibble, PPy the high one"
    );
    let coding = &cs.header.components[0].coding;
    assert_eq!(coding.precinct(0), (0, 1));
    assert_eq!(coding.precinct(2), (7, 7));
}

/// A maximal partition — `Scod` bit 0 clear — carries no `SPcod` bytes and reads
/// back as `(15, 15)` everywhere, the single precinct that spans any
/// tile-component under 2^15 on a side.
#[test]
fn an_implicit_precinct_partition_is_maximal() {
    let data = [0xDE, 0xAD];
    let bytes = assemble(
        &default_header(),
        &synth::sot(0, psot_for(&data), 0, 1),
        &data,
        true,
    );
    let cs = parse(&bytes).expect("implicit precincts parse");
    assert!(cs.header.cod.coding.precinct_sizes.is_empty());
    assert_eq!(cs.header.components[0].coding.precinct(0), (15, 15));
    assert_eq!(cs.header.components[0].coding.precinct(5), (15, 15));
}

/// A 2^0 precinct is legal only at the coarsest resolution (Table A-21): above
/// it the precinct halves onto the subband grid, so a zero exponent would ask
/// for a partition that does not exist. That is an illegal field encoding, not a
/// missing feature.
#[test]
fn a_zero_precinct_exponent_above_resolution_zero_is_a_marker_error() {
    assert!(
        parse(&with_precincts(&[0x00, 0x55, 0x55])).is_ok(),
        "2^0 is legal at resolution 0"
    );
    for sizes in [[0x55, 0x50, 0x55], [0x55, 0x05, 0x55]] {
        assert!(
            matches!(perr(&with_precincts(&sizes)), Error::Marker(_)),
            "{sizes:02X?}"
        );
    }
}

#[test]
fn sop_and_eph_flags_parse_independently() {
    for (scod, sop, eph) in [
        (0x00, false, false),
        (0x02, true, false), // p0_12 signals SOP only
        (0x04, false, true), // p0_11 signals EPH only
        (0x06, true, true),
    ] {
        let bytes = codestream(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_body(scod, 0, 1, 0, 5, 4, 4, 0, 1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]);
        let (header, _, _) =
            parse_main_header(&bytes).unwrap_or_else(|e| panic!("{scod:#04X}: {e:?}"));
        assert_eq!(
            (header.cod.use_sop, header.cod.use_eph),
            (sop, eph),
            "Scod {scod:#04X}"
        );
    }
}

/// `Scod` bits 3-7 are reserved; setting one is an illegal field, not a feature
/// we have yet to decode.
#[test]
fn reserved_scod_bits_are_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0x08, 0, 1, 0, 5, 4, 4, 0, 1)),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn reversible_color_transform_parses() {
    // Three matching components, 5/3 wavelet, MCT signaled: this is RCT.
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_body(3, &[(7, 1, 1); 3])),
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 1)), // mct = 1, 5/3
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let (header, _, _) = parse_main_header(&bytes).expect("RCT header parses");
    assert!(header.cod.multiple_component_transform);
    assert_eq!(header.cod.coding.transform, Transform::Reversible53);
}

/// The wavelet chooses the transform, so MCT on the 9/7 path is ICT (issue #76).
/// A well-formed three-component 9/7 codestream with the transform signaled
/// parses; the geometry check accepts three matching components on either arm.
#[test]
fn irreversible_color_transform_parses() {
    let header = parsed(&[
        seg(marker::SIZ, &siz_body(3, &[(7, 1, 1); 3])),
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 0)), // mct = 1, 9/7
        seg(marker::QCD, &qcd_expounded(2, &[(8, 0); 16])),
    ]);
    assert!(header.cod.multiple_component_transform);
    assert_eq!(header.cod.coding.transform, Transform::Irreversible97);
}

/// The three color components must share a wavelet: a COC that moves one of the
/// first three to the other arm makes the transform undefined (integers on one,
/// floats on another), and is rejected.
#[test]
fn a_color_transform_over_mixed_wavelets_is_unsupported() {
    // All-9/7 COD with MCT; a COC drops component 1 to 5/3.
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_body(3, &[(7, 1, 1); 3])),
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 0)), // mct = 1, 9/7
        seg(marker::COC, &coc_body(&[1], 0, 5, 4, 4, 0, 1)),    // component 1 → 5/3
        seg(marker::QCD, &qcd_expounded(2, &[(8, 0); 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Unsupported(_)));
}

/// `Smct = 2` selects Part 2's array MCT, a different feature.
#[test]
fn array_multiple_component_transform_is_unsupported() {
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_body(3, &[(7, 1, 1); 3])),
        seg(marker::COD, &cod_body(0, 0, 1, 2, 5, 4, 4, 0, 1)), // mct = 2
    ]);
    assert!(matches!(err(&bytes), Error::Unsupported(_)));
}

/// The color transform is defined over the first three components, so on an
/// image of one or two it has nothing to apply to. OpenJPEG skips it there
/// (`opj_tcd_mct_decode`), and so does this decoder: the header parses, with
/// the flag kept as read, and either wavelet passes.
#[test]
fn a_color_transform_on_fewer_than_three_components_is_skipped() {
    for count in [1u16, 2] {
        for wavelet in [0, 1] {
            let header = parsed(&[
                seg(
                    marker::SIZ,
                    &siz_body(count, &vec![(7, 1, 1); count.into()]),
                ),
                seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, wavelet)),
                seg(marker::QCD, &qcd_expounded(2, &[(8, 0); 16])),
            ]);
            assert!(header.cod.multiple_component_transform);
            assert!(!crate::mct::applies(true, header.components.len()));
        }
    }
}

/// The same on a tile: a tile-part COD that signals the transform on a
/// one-component image passes the tile check, which looks at no component
/// past the first.
#[test]
fn a_tile_color_transform_on_one_component_is_skipped() {
    let tile_cod = seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 1));
    let data = [0u8];
    let psot = psot_for(&data) + tile_cod.len() as u32;
    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot, 0, 1));
    bytes.extend_from_slice(&tile_cod);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&data);
    bytes.extend_from_slice(&be16(marker::EOC));
    parse(&bytes).expect("a tile COD with the transform on one component");
}

/// The three transformed components must share a depth, sign, and sub-sampling.
#[test]
fn color_transform_needs_matching_components() {
    let bytes = codestream(&[
        seg(
            marker::SIZ,
            &siz_body(3, &[(7, 1, 1), (11, 1, 1), (7, 1, 1)]),
        ),
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn reserved_transform_is_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 5)),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn out_of_subset_marker_is_unsupported() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::MCT, &[0, 0]), // a Part 2 multiple-component transform
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Unsupported(_)));
}

/// A POC marker is decoded now: it parses into progression volumes rather than
/// being rejected. A single volume covering the whole codestream in LRCP is a
/// no-op relative to the COD order, but it must round-trip through the parser.
#[test]
fn a_poc_marker_parses_into_volumes() {
    // One volume: resolutions [0, 6), components [0, 1), layers [0, 1), LRCP.
    let poc = [0u8, 0, 0, 1, 6, 1, 0];
    let header = vec![
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::POC, &poc),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let data = [0xDE, 0xAD];
    let bytes = assemble(&header, &synth::sot(0, psot_for(&data), 0, 1), &data, true);
    let cs = parse(&bytes).expect("POC parses");
    assert_eq!(cs.header.poc.len(), 1);
    let v = cs.header.poc[0];
    assert_eq!((v.res_start, v.res_end), (0, 6));
    assert_eq!((v.comp_start, v.comp_end), (0, 1));
    assert_eq!(v.layer_end, 1);
    assert_eq!(v.progression, markers::Progression::Lrcp);
}

/// A POC body of `n` copies of the whole-codestream LRCP volume.
fn poc_volumes(n: usize) -> Vec<u8> {
    [0u8, 0, 0, 1, 6, 1, 0]
        .iter()
        .copied()
        .cycle()
        .take(7 * n)
        .collect()
}

/// `LYEpoc` ranges over 1–65535 (Table A-33): a zero-layer volume would enclose
/// no packets, so it is a malformed field like an empty resolution or component
/// range, not a no-op.
#[test]
fn a_poc_volume_with_zero_layers_is_a_marker_error() {
    let poc = [0u8, 0, 0, 0, 6, 1, 0]; // LYEpoc == 0
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::POC, &poc),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// The volume list is capped at OpenJPEG's 32 (`opj_tcp_t::pocs`): every volume
/// re-enumerates the packet space and a duplicate emission consumes no bitstream
/// bytes, so an uncapped list buys quadratic work with linear input. 32 volumes
/// parse; 33 reject as the guard, whether they arrive in one marker or split
/// across two.
#[test]
fn a_poc_past_the_volume_guard_is_a_limit() {
    let header = |poc_segs: &[Vec<u8>]| {
        let mut h = vec![
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_default(1)),
        ];
        h.extend(poc_segs.iter().cloned());
        h.push(seg(marker::QCD, &qcd_none(2, &[8; 16])));
        h
    };
    let at_cap = codestream(&header(&[seg(marker::POC, &poc_volumes(32))]));
    assert!(
        parse_main_header(&at_cap).is_ok(),
        "32 volumes are within the guard"
    );

    let one_marker = codestream(&header(&[seg(marker::POC, &poc_volumes(33))]));
    assert!(crate::error::is_fixed_limit(
        &err(&one_marker),
        crate::LimitKind::PocVolumes
    ));

    let split = codestream(&header(&[
        seg(marker::POC, &poc_volumes(20)),
        seg(marker::POC, &poc_volumes(13)),
    ]));
    assert!(crate::error::is_fixed_limit(
        &err(&split),
        crate::LimitKind::PocVolumes
    ));
}

/// The guard bounds the list a tile walks. A tile POC replaces the main
/// header's, so a main header at the cap leaves a tile-part POC room, and the
/// main volumes do not count against it. The tile's own volumes still share
/// the guard across its markers: 20 and 13 reject.
#[test]
fn the_poc_guard_binds_the_volumes_a_tile_walks() {
    let header = vec![
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::POC, &poc_volumes(32)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let tile_poc = seg(marker::POC, &poc_volumes(1));
    let bytes = assemble_with_tile_markers(&header, &[tile_poc], &[1, 2]);
    let cs = parse(&bytes).expect("a tile POC replaces the 32 main volumes");
    assert_eq!(cs.tile_header(0).expect("resolve tile 0").poc.len(), 1);

    let split = [
        seg(marker::POC, &poc_volumes(20)),
        seg(marker::POC, &poc_volumes(13)),
    ];
    let bytes = assemble_with_tile_markers(&header, &split, &[1, 2]);
    let error = parse(&bytes).expect_err("33 tile volumes should reject");
    assert!(crate::error::is_fixed_limit(
        &error,
        crate::LimitKind::PocVolumes
    ));
}

/// `Xcrg`/`Ycrg` big-endian per component — the `CRG` body (A.9.1).
fn crg_body(offsets: &[(u16, u16)]) -> Vec<u8> {
    let mut b = Vec::with_capacity(offsets.len() * 4);
    for &(x, y) in offsets {
        b.extend_from_slice(&be16(x));
        b.extend_from_slice(&be16(y));
    }
    b
}

/// A CRG records one `(Xcrg, Ycrg)` sub-pixel offset per component; the decode is
/// unaffected (the offsets are for display registration, A.9.1). The values match
/// the ones `p0_03` carries.
#[test]
fn a_crg_marker_records_the_registration_offsets() {
    let header = vec![
        seg(marker::SIZ, &siz_body(3, &[(15, 1, 1); 3])),
        seg(marker::COD, &cod_default(1)),
        seg(
            marker::CRG,
            &crg_body(&[(65424, 32558), (0, 0), (1, 0xFFFF)]),
        ),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let data = [0xDE, 0xAD];
    let bytes = assemble(&header, &synth::sot(0, psot_for(&data), 0, 1), &data, true);
    let cs = parse(&bytes).expect("CRG parses");
    assert_eq!(cs.header.crg, vec![(65424, 32558), (0, 0), (1, 0xFFFF)]);
}

/// The CRG body is exactly `4 · Csiz` bytes; a body of any other length is a
/// malformed field, not a missing feature — like OpenJPEG's own length check.
#[test]
fn a_crg_of_the_wrong_length_is_a_marker_error() {
    // Two components need 8 bytes; give 4.
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_body(2, &[(15, 1, 1); 2])),
        seg(marker::COD, &cod_default(1)),
        seg(marker::CRG, &crg_body(&[(1, 2)])),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// One CRG per codestream (A.9.1); a second is a malformed header.
#[test]
fn a_duplicate_crg_is_a_codestream_error() {
    let crg = seg(marker::CRG, &crg_body(&[(1, 2)]));
    let mut segs = vec![
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
    ];
    segs.push(crg.clone());
    segs.push(crg);
    segs.push(seg(marker::QCD, &qcd_none(2, &[8; 16])));
    assert!(matches!(err(&codestream(&segs)), Error::Codestream(_)));
}

#[test]
fn missing_cod_is_codestream() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn missing_qcd_is_codestream() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn duplicate_cod_is_codestream() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn reserved_decomposition_levels_is_marker() {
    // Table A-15 allows 0–32 levels; 33 is a reserved encoding, rejected at
    // parse rather than deep in tier-2.
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 33, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 97])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn too_few_qcd_steps_for_the_decomposition_is_marker() {
    // NL = 5 needs 3·5 + 1 = 16 entries; 10 leaves subbands without a step.
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 10])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn too_few_expounded_qcd_steps_is_marker() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &qcd_expounded(1, &[(10, 1234); 3])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn irreversible_wavelet_with_no_quantization_is_marker() {
    // 9/7 coefficients need a scalar step to mean anything; the pairing is
    // rejected at parse rather than misreported during dequantization.
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn reserved_quant_style_is_marker() {
    let mut body = vec![(2u8 << 5) | 3]; // style 3 is reserved
    body.extend_from_slice(&be16(0));
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &body),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn oversized_qcd_step_table_is_capped() {
    // 120 one-byte entries, more than the 3·32 + 1 subbands a 32-level
    // decomposition can carry. The excess is dropped — OpenJPEG caps at
    // J2K_MAXBANDS and decodes — so a 65535-byte Lqcd cannot be cloned into
    // every component's parameters (the memory amplifier).
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 120])),
    ]);
    let (header, _, _) = parse_main_header(&bytes).expect("padding parses");
    assert_eq!(header.qcd.steps.len(), 97);
    assert_eq!(header.qcd.steps[0], (8, 0));
}

#[test]
fn oversized_expounded_qcd_step_table_is_capped() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(0)),
        seg(marker::QCD, &qcd_expounded(1, &[(10, 1234); 120])),
    ]);
    let (header, _, _) = parse_main_header(&bytes).expect("padding parses");
    assert_eq!(header.qcd.steps.len(), 97);
    assert_eq!(header.qcd.steps[0], (10, 1234));
}

#[test]
fn full_depth_qcd_step_table_parses() {
    // Exactly 97 entries is legal even though this COD only needs 16.
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 97])),
    ]);
    assert!(parse_main_header(&bytes).is_ok());
}

#[test]
fn eoc_before_tile_part_is_codestream() {
    let mut bytes = be16(marker::SOC).to_vec();
    bytes.extend_from_slice(&seg(marker::SIZ, &one_component()));
    bytes.extend_from_slice(&seg(marker::COD, &cod_default(1)));
    bytes.extend_from_slice(&seg(marker::QCD, &qcd_none(2, &[8; 16])));
    bytes.extend_from_slice(&be16(marker::EOC));
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn non_marker_ff00_and_ffff_are_lost_sync() {
    // 0xFF00 and 0xFFFF are assigned to no marker; walking them as segments
    // would read the following bytes as a length. They are lost sync, a
    // malformed codestream rather than an unsupported feature.
    for code in [0xFF00u16, 0xFFFF] {
        let mut bytes = be16(marker::SOC).to_vec();
        bytes.extend_from_slice(&seg(marker::SIZ, &one_component()));
        bytes.extend_from_slice(&be16(code));
        bytes.extend_from_slice(&[0x00, 0x04, 0xAA, 0xBB]); // a plausible fake segment
        assert!(matches!(err(&bytes), Error::Codestream(_)), "{code:#06X}");
    }
}

#[test]
fn unknown_marker_without_a_length_is_incomplete() {
    // Stepping over an unknown marker needs its length to be there. At the very
    // end of the input there is nothing to read: the input ends inside the main
    // header, which more bytes may complete.
    let mut bytes = be16(marker::SOC).to_vec();
    bytes.extend_from_slice(&seg(marker::SIZ, &one_component()));
    bytes.extend_from_slice(&be16(0xFF01)); // not a marker we know
    assert!(matches!(err(&bytes), Error::Incomplete(_)));
}

// --- tile-part walk (issue #6) -------------------------------------------
//
// As with the main header, each stream is assembled from the Annex A field
// layout so the expectation is checked against the spec, not the parser. The
// `opj_dump` cross-check on real seed codestreams lands with the fixture
// corpus (#4); these synthetic cases pin the offset/length and reject logic.

/// A complete, in-subset main header: SIZ + reversible COD + no-quant QCD.
fn default_header() -> Vec<Vec<u8>> {
    vec![
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]
}

/// SOC + `header` + `sot` + SOD + `data`, optionally closed by EOC.
fn assemble(header: &[Vec<u8>], sot: &[u8], data: &[u8], eoc: bool) -> Vec<u8> {
    let mut s = be16(marker::SOC).to_vec();
    for part in header {
        s.extend_from_slice(part);
    }
    s.extend_from_slice(sot);
    s.extend_from_slice(&be16(marker::SOD));
    s.extend_from_slice(data);
    if eoc {
        s.extend_from_slice(&be16(marker::EOC));
    }
    s
}

/// `Psot` spanning one tile-part: the 12-byte SOT segment, the 2-byte SOD
/// marker, plus the packet data.
fn psot_for(data: &[u8]) -> u32 {
    (12 + 2 + data.len()) as u32
}

fn perr(bytes: &[u8]) -> Error {
    parse(bytes).expect_err("should reject")
}

#[test]
fn valid_single_tile_part_parses() {
    let data = [0xDE, 0xAD, 0xBE, 0xEF];
    let sot = synth::sot(0, psot_for(&data), 0, 1);
    let bytes = assemble(&default_header(), &sot, &data, true);

    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tiles.len(), 1);
    assert_eq!(cs.tiles[0].index, 0);
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..]);
    assert_eq!(cs.header.cod.coding.transform, Transform::Reversible53);
}

#[test]
fn psot_zero_runs_to_eoc() {
    let data = [1, 2, 3, 4, 5];
    let sot = synth::sot(0, 0, 0, 1); // last tile-part: extends to EOC
    let bytes = assemble(&default_header(), &sot, &data, true);

    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..]);
}

/// Bytes after the closing EOC are ignored when `Psot` declares the length,
/// as OpenJPEG ignores them. A `Psot = 0` tile-part has no declared length —
/// everything to the buffer-end EOC is the tile (also OpenJPEG's reading, and
/// the only sound one: SOP's raw `Nsop` bytes can spell `FF D9`, so scanning
/// for an earlier EOC could truncate a valid tile).
#[test]
fn trailing_bytes_after_eoc_are_ignored_when_psot_declares_the_length() {
    let data = [1, 2, 3, 4, 5];
    let sot = synth::sot(0, psot_for(&data), 0, 1);
    let mut bytes = assemble(&default_header(), &sot, &data, true);
    bytes.extend_from_slice(&[0xAB, 0xCD, 0xFF, 0xD9]); // garbage ending in FF D9
    let cs = parse(&bytes).expect("trailing bytes after the declared extent");
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..]);

    // With Psot = 0 the same tail is absorbed into the tile up to the final
    // EOC; the packet self-check downstream is what rejects it. Anchoring is
    // pinned here: the embedded FF D9 must NOT terminate the data early.
    let sot = synth::sot(0, 0, 0, 1);
    let mut bytes = assemble(&default_header(), &sot, &data, true);
    bytes.extend_from_slice(&[0xAB, 0xCD, 0xFF, 0xD9]);
    let cs = parse(&bytes).expect("EOC anchored at the buffer end");
    assert_eq!(cs.tiles[0].data.len(), data.len() + 4);
}

#[test]
fn empty_tile_part_data_parses() {
    let sot = synth::sot(0, psot_for(&[]), 0, 1);
    let bytes = assemble(&default_header(), &sot, &[], true);

    let cs = parse(&bytes).expect("parse");
    assert!(cs.tiles[0].data.is_empty());
}

#[test]
fn tile_part_header_comment_is_skipped() {
    let data = [9, 9];
    let com = seg(marker::COM, &[0, 1, b'x']);
    let psot = (12 + com.len() + 2 + data.len()) as u32;

    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot, 0, 1));
    bytes.extend_from_slice(&com);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&data);
    bytes.extend_from_slice(&be16(marker::EOC));

    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..]);
}

/// `Isot` must name a tile the grid holds. The default header is a single tile,
/// so tile 1 does not exist and the codestream is malformed.
#[test]
fn a_tile_index_past_the_grid_is_codestream() {
    let sot = synth::sot(1, 0, 0, 1); // Isot = 1, but the grid holds one tile
    let bytes = assemble(&default_header(), &sot, &[1, 2], true);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// `TNsot` states how many tile-parts the tile has. A tile that declares two and
/// carries one is truncated, whatever the rest of the codestream says.
#[test]
fn a_tnsot_the_tile_parts_do_not_add_up_to_is_codestream() {
    let data = [1, 2];
    let sot = synth::sot(0, psot_for(&data), 0, 2); // TNsot = 2, but only one part follows
    let bytes = assemble(&default_header(), &sot, &data, true);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// A tile's parts are numbered from zero and arrive in order (A.4.2), so the
/// first one to appear must be `TPsot = 0`. Starting at 1 means part 0 is missing.
#[test]
fn a_tile_part_index_out_of_order_is_codestream() {
    let sot = synth::sot(0, 0, 1, 1); // TPsot = 1 with no part 0 before it
    let bytes = assemble(&default_header(), &sot, &[1, 2], true);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// A tile split across several tile-parts is one tile: its parts' packet bytes
/// are joined, in `TPsot` order, into the single stream the packet walk reads.
/// A tile-part holds a whole number of packets (B.9), so the join is exact.
#[test]
fn several_tile_parts_of_one_tile_are_joined_in_order() {
    let first_data = [7, 7, 7];
    // TNsot = 0 in the first part: "not stated yet", which A.4.2 allows.
    let first = synth::sot(0, psot_for(&first_data), 0, 0);

    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&first);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&first_data);
    // The last part carries Psot = 0, so it runs to the closing EOC.
    bytes.extend_from_slice(&synth::sot(0, 0, 1, 2));
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&[8, 8]);
    bytes.extend_from_slice(&be16(marker::EOC));

    let cs = parse(&bytes).expect("two tile-parts of one tile");
    assert_eq!(cs.tiles.len(), 1);
    assert_eq!(cs.tiles[0].data.as_ref(), &[7, 7, 7, 8, 8]);
}

/// Every tile of the grid must be carried. A codestream that names a 2x1 grid and
/// ships one tile describes an image it does not contain — a truncation, not a
/// feature to decode around.
#[test]
fn a_tile_with_no_tile_part_is_codestream() {
    let header = vec![
        // 512x256 in 256-wide tiles: a 2x1 grid.
        seg(marker::SIZ, &siz_geom(512, 256, 0, 0, 256, 256, 0, 0)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    // Only tile 0 is carried; tile 1 never appears.
    let bytes = assemble(&header, &synth::sot(0, 0, 0, 1), &[1, 2], true);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

// --- encoder quirks OpenJPEG corrects (issue #282) ----------------------

/// One tile-part for [`tile_parts`]: `(Isot, TPsot, TNsot, header markers)`.
type Part = (u16, u8, u8, Vec<Vec<u8>>);

/// SOC, `header`, then each part with one data byte of its own, then EOC.
fn tile_parts(header: &[Vec<u8>], parts: &[Part]) -> Vec<u8> {
    let mut bytes = be16(marker::SOC).to_vec();
    for s in header {
        bytes.extend_from_slice(s);
    }
    for (at, (isot, tpsot, tnsot, markers)) in parts.iter().enumerate() {
        let markers = markers.concat();
        let data = [at as u8];
        let psot = psot_for(&data) + markers.len() as u32;
        bytes.extend_from_slice(&synth::sot(*isot, psot, *tpsot, *tnsot));
        bytes.extend_from_slice(&markers);
        bytes.extend_from_slice(&be16(marker::SOD));
        bytes.extend_from_slice(&data);
    }
    bytes.extend_from_slice(&be16(marker::EOC));
    bytes
}

/// A 2x1 grid of one component.
fn two_tiles() -> Vec<Vec<u8>> {
    vec![
        seg(marker::SIZ, &siz_geom(512, 256, 0, 0, 256, 256, 0, 0)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]
}

/// Parts numbered 0 to N with N declared, interleaved across two tiles, as
/// Adobe Photoshop's plug-in writes them. OpenJPEG raises every count by one
/// (`opj_j2k_need_nb_tile_parts_correction`), and so does this decoder: each
/// tile gets all its parts, in order.
#[test]
fn a_last_tpsot_equal_to_tnsot_raises_every_count() {
    let bytes = tile_parts(
        &two_tiles(),
        &[
            (0, 0, 2, vec![]),
            (1, 0, 2, vec![]),
            (0, 1, 2, vec![]),
            (1, 1, 2, vec![]),
            (0, 2, 2, vec![]),
            (1, 2, 2, vec![]),
        ],
    );
    let cs = parse(&bytes).expect("TPsot == TNsot on the last parts");
    assert_eq!(cs.tiles[0].data.as_ref(), &[0, 2, 4]);
    assert_eq!(cs.tiles[1].data.as_ref(), &[1, 3, 5]);
}

/// OpenJPEG looks for the extra part once, when the first tile has all the
/// parts it declares. A tile that completes later with an extra part is not
/// looked at, and its extra part is refused, as OpenJPEG refuses it.
#[test]
fn the_extra_part_is_looked_for_only_when_the_first_tile_completes() {
    let bytes = tile_parts(
        &two_tiles(),
        &[(0, 0, 1, vec![]), (1, 0, 1, vec![]), (1, 1, 1, vec![])],
    );
    let e = perr(&bytes);
    assert!(
        matches!(&e, Error::Codestream(m) if m.message().contains("tile-part 1 of a declared 1")),
        "got {e:?}"
    );
}

/// The correction needs the next part of the tile to have `TPsot == TNsot`.
/// One that declares a different count is refused, as before.
#[test]
fn an_extra_part_with_another_count_is_refused() {
    let bytes = tile_parts(&default_header(), &[(0, 0, 1, vec![]), (0, 1, 2, vec![])]);
    let e = perr(&bytes);
    assert!(
        matches!(&e, Error::Codestream(m) if m.message().contains("declares 2 tile-parts in one `SOT` and 1")),
        "got {e:?}"
    );
}

/// Once raised, every count is held to the parts that arrive: a tile that
/// carries only the parts it declared is now one short, and refused.
#[test]
fn a_raised_count_is_still_held_to_the_parts() {
    let bytes = tile_parts(
        &two_tiles(),
        &[(0, 0, 1, vec![]), (0, 1, 1, vec![]), (1, 0, 1, vec![])],
    );
    let e = perr(&bytes);
    assert!(
        matches!(&e, Error::Codestream(m) if m.message().contains("tile 1 declares 2 tile-parts but carries 1")),
        "got {e:?}"
    );
}

/// The main header's COD and QCD restated in a later tile-part change nothing,
/// so they are accepted and dropped, as OpenJPEG reads them (it accepts a COD
/// in any tile-part header). BAP Image Systems writes them so.
#[test]
fn a_later_tile_part_may_restate_the_cod_and_qcd_in_force() {
    let restated = vec![
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let bytes = tile_parts(
        &default_header(),
        &[
            (0, 0, 3, vec![]),
            (0, 1, 3, restated.clone()),
            (0, 2, 3, restated),
        ],
    );
    let cs = parse(&bytes).expect("COD and QCD restated");
    assert_eq!(cs.tiles[0].header, TileHeader::default());
    assert_eq!(cs.tiles[0].data.as_ref(), &[0, 1, 2]);
}

/// A tile's own COD from its first part may be restated too.
#[test]
fn a_later_tile_part_may_restate_the_tiles_own_cod() {
    let own = seg(marker::COD, &cod_body(0, 0, 2, 0, 5, 4, 4, 0, 1)); // two layers
    let bytes = tile_parts(
        &default_header(),
        &[(0, 0, 2, vec![own.clone()]), (0, 1, 2, vec![own])],
    );
    let cs = parse(&bytes).expect("the tile's COD restated");
    assert_eq!(
        cs.tiles[0].header.overrides.cod.as_ref().map(|c| c.layers),
        Some(2)
    );
}

/// A refusal case: its name, the first part's markers, the later part's
/// markers, and what the error names.
type Refusal = (&'static str, Vec<Vec<u8>>, Vec<Vec<u8>>, &'static str);

/// The later part's markers, each refused because it differs from the value
/// in force, with what the error names.
fn later_part_refusals() -> Vec<Refusal> {
    let qcc = |index: u8, exponent: u8| {
        let mut body = vec![index];
        body.extend_from_slice(&qcd_none(2, &[exponent; 16]));
        seg(marker::QCC, &body)
    };
    vec![
        (
            "a COD with another layer count",
            vec![],
            vec![seg(marker::COD, &cod_body(0, 0, 2, 0, 5, 4, 4, 0, 1))],
            "a `COD` that differs",
        ),
        (
            "a QCD with other exponents",
            vec![],
            vec![seg(marker::QCD, &qcd_none(2, &[9; 16]))],
            "a `QCD` that differs",
        ),
        (
            "a COC with other code-blocks",
            vec![],
            vec![seg(marker::COC, &coc_body(&[0], 0, 5, 3, 3, 0, 1))],
            "a `COC` for component 0 that differs",
        ),
        (
            "a QCC with other exponents",
            vec![],
            vec![qcc(0, 9)],
            "a `QCC` for component 0 that differs",
        ),
        (
            // OpenJPEG would write the COD over the tile's COC; here the COC
            // wins. The two readings differ, so neither is guessed.
            "the main COD over a tile COC that differs from it",
            vec![seg(marker::COC, &coc_body(&[0], 0, 5, 3, 3, 0, 1))],
            vec![seg(marker::COD, &cod_default(1))],
            "a `COD` that differs",
        ),
        (
            "the main QCD over a tile QCC that differs from it",
            vec![qcc(0, 9)],
            vec![seg(marker::QCD, &qcd_none(2, &[8; 16]))],
            "a `QCD` that differs",
        ),
        (
            "the main COD where the tile's own COD differs",
            vec![seg(marker::COD, &cod_body(0, 0, 2, 0, 5, 4, 4, 0, 1))],
            vec![seg(marker::COD, &cod_default(1))],
            "a `COD` that differs",
        ),
        (
            "the main QCD where the tile's own QCD differs",
            vec![seg(marker::QCD, &qcd_none(2, &[9; 16]))],
            vec![seg(marker::QCD, &qcd_none(2, &[8; 16]))],
            "a `QCD` that differs",
        ),
        (
            "a COC that differs from the tile's own COD",
            vec![seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 3, 3, 0, 1))],
            vec![seg(marker::COC, &coc_body(&[0], 0, 5, 4, 4, 0, 1))],
            "a `COC` for component 0 that differs",
        ),
        (
            "a COC that differs from the tile's own COC",
            vec![seg(marker::COC, &coc_body(&[0], 0, 5, 3, 3, 0, 1))],
            vec![seg(marker::COC, &coc_body(&[0], 0, 5, 4, 4, 0, 1))],
            "a `COC` for component 0 that differs",
        ),
        (
            "a QCC that differs from the tile's own QCD",
            vec![seg(marker::QCD, &qcd_none(2, &[9; 16]))],
            vec![qcc(0, 8)],
            "a `QCC` for component 0 that differs",
        ),
        (
            "a QCC that differs from the tile's own QCC",
            vec![qcc(0, 9)],
            vec![qcc(0, 8)],
            "a `QCC` for component 0 that differs",
        ),
    ]
}

/// A later part's COD, COC, QCD or QCC that differs from the value in force
/// is refused: the earlier parts are read under one value and the later ones
/// would name another, and which the encoder meant is not in the file.
#[test]
fn a_later_tile_part_that_changes_a_value_in_force_is_refused() {
    for (case, first, later, names) in later_part_refusals() {
        let bytes = tile_parts(&default_header(), &[(0, 0, 2, first), (0, 1, 2, later)]);
        let e = perr(&bytes);
        assert!(
            matches!(&e, Error::Codestream(m) if m.message().contains(names) && m.message().contains("tile 0")),
            "{case}: got {e:?}"
        );
    }
}

/// A COC or QCC restating its component's value is accepted, whether that
/// value comes from the main header, the tile's COD/QCD, or its own COC/QCC.
#[test]
fn a_later_tile_part_may_restate_a_coc_or_qcc_in_force() {
    let qcc = |exponent: u8| {
        let mut body = vec![0];
        body.extend_from_slice(&qcd_none(2, &[exponent; 16]));
        seg(marker::QCC, &body)
    };
    let coc = |xcb: u8| seg(marker::COC, &coc_body(&[0], 0, 5, xcb, xcb, 0, 1));
    for (first, later) in [
        // From the main header.
        (vec![], vec![coc(4), qcc(8)]),
        // From the tile's own COD and QCD.
        (
            vec![
                seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 3, 3, 0, 1)),
                seg(marker::QCD, &qcd_none(2, &[9; 16])),
            ],
            vec![coc(3), qcc(9)],
        ),
        // From the tile's own COC and QCC.
        (vec![coc(3), qcc(9)], vec![coc(3), qcc(9)]),
    ] {
        let bytes = tile_parts(&default_header(), &[(0, 0, 2, first), (0, 1, 2, later)]);
        parse(&bytes).expect("a COC and QCC restated");
    }
}

/// A main-header COC makes a component code other than the main COD says, so
/// a later COD restating the main COD would change it in OpenJPEG's reading
/// and is refused. A main QCC does the same to a later QCD. Without the main
/// COC or QCC, the same restatement is accepted.
#[test]
fn a_restated_main_cod_or_qcd_over_a_main_coc_or_qcc_is_refused() {
    let mut qcc = vec![1];
    qcc.extend_from_slice(&qcd_none(2, &[9; 16]));
    for (extra, later, names) in [
        (
            seg(marker::COC, &coc_body(&[1], 0, 5, 3, 3, 0, 1)),
            seg(marker::COD, &cod_default(1)),
            "a `COD` that differs",
        ),
        (
            seg(marker::QCC, &qcc),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
            "a `QCD` that differs",
        ),
    ] {
        let mut header = vec![
            seg(marker::SIZ, &siz_body(2, &[(7, 1, 1); 2])),
            seg(marker::COD, &cod_default(1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ];
        let parts = [(0, 0, 2, vec![]), (0, 1, 2, vec![later])];
        parse(&tile_parts(&header, &parts)).expect("no main COC or QCC");
        header.push(extra);
        let e = perr(&tile_parts(&header, &parts));
        assert!(
            matches!(&e, Error::Codestream(m) if m.message().contains(names)),
            "got {e:?}"
        );
    }
}

/// RGN is not among the markers a later part may restate: it stays refused.
#[test]
fn a_later_tile_part_rgn_is_still_refused() {
    let later = vec![seg(marker::RGN, &rgn_body(&[0], 0, 0))];
    let bytes = tile_parts(&default_header(), &[(0, 0, 2, vec![]), (0, 1, 2, later)]);
    assert!(
        matches!(perr(&bytes), Error::Codestream(m) if m.message().contains("other than the first"))
    );
}

/// PPM's payload frames one packet-header chunk per tile-part with a 4-byte
/// `Nppm` length (A.7.4). `decode_ppm_chunks` strips the lengths and returns the
/// per-tile-part chunks, in `Zppm` order, joining markers so an `Nppm` can
/// straddle a marker boundary — the same bytes an inline codestream would carry
/// as each tile-part's packet headers, which is why a PPM stream decodes to the
/// same packets as its inline equivalent (proven end-to-end by `p1_03`/`p1_05`).
#[test]
fn ppm_chunks_split_by_nppm_across_markers() {
    // Two tile-parts in one marker: Nppm 1 then Nppm 2.
    let one = decode_ppm_chunks(vec![(0, vec![0, 0, 0, 1, 0xAA, 0, 0, 0, 2, 0xBB, 0xCC])]).unwrap();
    assert_eq!(one, vec![vec![0xAA], vec![0xBB, 0xCC]]);

    // Nppm=3 straddles two markers; joined in Zppm order (given out of order).
    let split =
        decode_ppm_chunks(vec![(1, vec![0xBB, 0xCC]), (0, vec![0, 0, 0, 3, 0xAA])]).unwrap();
    assert_eq!(split, vec![vec![0xAA, 0xBB, 0xCC]]);

    // A zero-length chunk is a tile-part that carries no packet headers.
    assert_eq!(
        decode_ppm_chunks(vec![(0, vec![0, 0, 0, 0])]).unwrap(),
        vec![Vec::<u8>::new()]
    );

    // No PPM markers: no chunks.
    assert_eq!(decode_ppm_chunks(vec![]).unwrap(), Vec::<Vec<u8>>::new());
}

/// A malformed PPM payload — a duplicate `Zppm`, an `Nppm` the payload cannot
/// satisfy, or a trailing fragment too short to be a length — is a codestream
/// error, not a wrong decode.
#[test]
fn ppm_chunks_reject_malformed_framing() {
    // Nppm=5 but only one byte follows.
    assert!(matches!(
        decode_ppm_chunks(vec![(0, vec![0, 0, 0, 5, 0xAA])]),
        Err(Error::Codestream(_))
    ));
    // Three trailing bytes: too short for a 4-byte Nppm.
    assert!(matches!(
        decode_ppm_chunks(vec![(0, vec![0, 0, 0])]),
        Err(Error::Codestream(_))
    ));
    // Two markers share Zppm 0.
    assert!(matches!(
        decode_ppm_chunks(vec![(0, vec![0, 0, 0, 0]), (0, vec![0, 0, 0, 0])]),
        Err(Error::Codestream(_))
    ));
}

/// PPT moves the tile's packet headers into the tile-part header (A.7.5): it
/// parses into the tile's packed-header buffer, ordered by `Zppt`, and the
/// tile-part data is only the packet bodies. Two PPT markers, out of Zppt order,
/// stitch back in order.
#[test]
fn tile_part_ppt_collects_the_packed_headers() {
    let data = [0xBB, 0xBB];
    // Zppt 1 carries `[0xCD]`, Zppt 0 carries `[0xAB]`; the buffer is `AB CD`.
    let ppt1 = seg(marker::PPT, &[1, 0xCD]);
    let ppt0 = seg(marker::PPT, &[0, 0xAB]);
    let psot = (12 + ppt1.len() + ppt0.len() + 2 + data.len()) as u32;

    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot, 0, 1));
    bytes.extend_from_slice(&ppt1);
    bytes.extend_from_slice(&ppt0);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&data);
    bytes.extend_from_slice(&be16(marker::EOC));

    let cs = parse(&bytes).expect("PPT parses");
    assert_eq!(cs.tiles[0].packed_headers, vec![0xAB, 0xCD]);
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..]);
}

/// A `Zppt` repeated across a tile-part's PPT markers is a malformed header.
#[test]
fn tile_part_duplicate_zppt_is_a_codestream_error() {
    let data = [0xBB];
    let a = seg(marker::PPT, &[0, 0x11]);
    let b = seg(marker::PPT, &[0, 0x22]); // Zppt 0 again
    let psot = (12 + a.len() + b.len() + 2 + data.len()) as u32;

    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot, 0, 1));
    bytes.extend_from_slice(&a);
    bytes.extend_from_slice(&b);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&data);
    bytes.extend_from_slice(&be16(marker::EOC));

    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// TLM is main-header-only (A.7.1) and SOP/EPH belong after SOD, so meeting
/// one in a tile-part header is a malformed codestream — unlike the QCC above,
/// which is legal there and merely outside the subset.
#[test]
fn structurally_illegal_tile_header_marker_is_codestream() {
    let data = [1, 2];
    for illegal in [seg(marker::TLM, &[0, 0x60]), seg(marker::SOP, &[0, 0])] {
        let psot = (12 + illegal.len() + 2 + data.len()) as u32;
        let mut bytes = be16(marker::SOC).to_vec();
        for part in default_header() {
            bytes.extend_from_slice(&part);
        }
        bytes.extend_from_slice(&synth::sot(0, psot, 0, 1));
        bytes.extend_from_slice(&illegal);
        bytes.extend_from_slice(&be16(marker::SOD));
        bytes.extend_from_slice(&data);
        bytes.extend_from_slice(&be16(marker::EOC));

        assert!(matches!(perr(&bytes), Error::Codestream(_)));
    }
}

#[test]
fn unexpected_tile_header_marker_is_codestream() {
    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, 0, 0, 1));
    bytes.extend_from_slice(&be16(0xFF30)); // reserved, not valid in a header
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

#[test]
fn psot_overrun_is_codestream() {
    let data = [1, 2];
    let sot = synth::sot(0, 9999, 0, 1); // Psot far past the buffer
    let bytes = assemble(&default_header(), &sot, &data, true);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

#[test]
fn missing_eoc_is_codestream() {
    let data = [1, 2];
    let sot = synth::sot(0, psot_for(&data), 0, 1);
    let bytes = assemble(&default_header(), &sot, &data, false); // no EOC
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

#[test]
fn psot_zero_without_eoc_loses_two_bytes_but_parses() {
    let data = [1, 2, 3];
    let sot = synth::sot(0, 0, 0, 1);
    let bytes = assemble(&default_header(), &sot, &data, false);
    // The last two bytes are taken for the EOC, as in OpenJPEG.
    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tiles[0].data.as_ref(), &data[..1]);
}

#[test]
fn psot_zero_with_one_byte_after_sod_is_codestream() {
    let sot = synth::sot(0, 0, 0, 1);
    let bytes = assemble(&default_header(), &sot, &[7], false);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

#[test]
fn truncated_sot_is_codestream() {
    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&be16(marker::SOT));
    bytes.extend_from_slice(&be16(10)); // Lsot promises 8 body bytes
    bytes.extend_from_slice(&[0, 0]); // only 2 are present
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

// --- per-component SIZ geometry (issue #56) -------------------------------

/// A valid header carrying `comps` components, for exercising `decode_siz`
/// directly: `parse_main_header` rejects anything but one component.
fn siz_of(csiz: u16, comps: &[(u8, u8, u8)]) -> Siz {
    let body = siz_body(csiz, comps);
    decode_siz(Cursor::new(&body)).expect("SIZ parses")
}

#[test]
fn multi_component_siz_parses_every_component() {
    // 3 components: 8-bit unsigned, 12-bit signed, 1-bit unsigned.
    let siz = siz_of(3, &[(7, 1, 1), (0x80 | 11, 1, 1), (0, 1, 1)]);
    assert_eq!(
        siz.components,
        vec![
            SizComponent {
                bit_depth: 8,
                signed: false,
                x_sampling: 1,
                y_sampling: 1
            },
            SizComponent {
                bit_depth: 12,
                signed: true,
                x_sampling: 1,
                y_sampling: 1
            },
            SizComponent {
                bit_depth: 1,
                signed: false,
                x_sampling: 1,
                y_sampling: 1
            },
        ]
    );
    // Unit sub-sampling: every component covers the whole image area.
    assert_eq!(siz.image_extent_at(0), (512, 256));
    for i in 0..3 {
        assert_eq!(siz.component_extent(i), Some((512, 256)));
    }
    assert_eq!(siz.component_extent(3), None);
}

#[test]
fn subsampled_siz_derives_each_component_extent() {
    // Image is 512x256 at the origin; the four classic sub-sampling factors.
    let siz = siz_of(4, &[(7, 1, 1), (7, 2, 1), (7, 1, 2), (7, 2, 2)]);
    assert_eq!(siz.image_extent_at(0), (512, 256));
    assert_eq!(siz.component_extent(0), Some((512, 256)));
    assert_eq!(siz.component_extent(1), Some((256, 256)));
    assert_eq!(siz.component_extent(2), Some((512, 128)));
    assert_eq!(siz.component_extent(3), Some((256, 128)));
}

#[test]
fn component_extent_ceils_each_edge_separately() {
    // The spec subtracts two ceilings; it does not ceil the difference. With
    // Xsiz=9, XOsiz=1 and XRsiz=2 the two forms disagree:
    //   ceil(9/2) - ceil(1/2) = 5 - 1 = 4   (the standard)
    //   ceil((9 - 1)/2)       = 4           (agrees here)
    // but at XOsiz=3 they diverge:
    //   ceil(9/2) - ceil(3/2) = 5 - 2 = 3   (the standard)
    //   ceil((9 - 3)/2)       = 3           (agrees)
    // and at Xsiz=8, XOsiz=1:
    //   ceil(8/2) - ceil(1/2) = 4 - 1 = 3   (the standard)
    //   ceil((8 - 1)/2)       = 4           (wrong)
    let mut siz = siz_of(1, &[(7, 2, 2)]);
    siz.x_size = 8;
    siz.y_size = 8;
    siz.x_offset = 1;
    siz.y_offset = 1;
    assert_eq!(siz.component_extent(0), Some((3, 3)));
    assert_eq!(siz.image_extent_at(0), (7, 7));
}

#[test]
fn too_many_components_is_marker() {
    // Csiz above the Table A-9 limit of 16384, without the body to match: the
    // count is rejected before any allocation is sized from it.
    let body = siz_body(markers::MAX_COMPONENTS + 1, &[]);
    assert!(matches!(
        decode_siz(Cursor::new(&body)),
        Err(Error::Marker(_))
    ));
}

#[test]
fn component_record_count_must_match_csiz() {
    // Csiz claims 2 components but only one 3-byte record follows.
    let body = siz_body(2, &[(7, 1, 1)]);
    assert!(matches!(
        decode_siz(Cursor::new(&body)),
        Err(Error::Codestream(_))
    ));
}

#[test]
fn zero_sub_sampling_factor_is_marker() {
    for comp in [(7, 0, 1), (7, 1, 0)] {
        let body = siz_body(1, &[comp]);
        assert!(
            matches!(decode_siz(Cursor::new(&body)), Err(Error::Marker(_))),
            "{comp:?} should reject"
        );
    }
}

#[test]
fn bit_depth_above_38_is_marker() {
    // Ssiz low 7 bits are depth-1: 37 -> depth 38 (the Table A-11 limit), 38 -> 39.
    assert_eq!(siz_of(1, &[(37, 1, 1)]).components[0].bit_depth, 38);
    let body = siz_body(1, &[(38, 1, 1)]);
    assert!(matches!(
        decode_siz(Cursor::new(&body)),
        Err(Error::Marker(_))
    ));
    // The sign bit must not be mistaken for depth.
    assert_eq!(siz_of(1, &[(0x80 | 37, 1, 1)]).components[0].bit_depth, 38);
    assert!(siz_of(1, &[(0x80 | 37, 1, 1)]).components[0].signed);
}

/// A 4096x4096 SIZ carrying `count` unit-sampled 8-bit components. One such
/// component sits inside the decode guard; enough of them do not.
fn many_component_siz(count: u16) -> Vec<u8> {
    let mut body = siz_geom(4096, 4096, 0, 0, 4096, 4096, 0, 0);
    body.truncate(body.len() - 5); // drop the Csiz and its one component record
    body.extend_from_slice(&be16(count));
    for _ in 0..count {
        body.extend_from_slice(&[7, 1, 1]);
    }
    body
}

#[test]
fn many_components_exceed_the_sample_budget() {
    // Each component is reconstructed into its own buffer, so the guard bounds
    // the *sum* of the component areas. A 4096x4096 image is well inside the
    // single-component guard; a hundred of its components are not.
    let bytes = codestream(&[
        seg(marker::SIZ, &many_component_siz(100)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let header = parse_main_header(&bytes).unwrap().0;
    let cap = crate::samples::MAX_IMAGE_SAMPLES;
    let e = crate::samples::check_codestream(&header.siz, 0, cap).unwrap_err();
    assert!(
        matches!(&e, Error::Limit(m) if m.message().starts_with("a decode of 100 components needs 1677721600 samples")),
        "got {e:?}"
    );

    // One component of the same image stays inside the guard.
    let bytes = codestream(&[
        seg(marker::SIZ, &siz_geom(4096, 4096, 0, 0, 4096, 4096, 0, 0)),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(parse_main_header(&bytes).is_ok());
}

// --- main-header marker walk (issue #56) ----------------------------------

/// A valid single-component header with `extra` spliced in before the SOT.
fn header_with(extra: &[u8]) -> Vec<u8> {
    let mut bytes = be16(marker::SOC).to_vec();
    bytes.extend_from_slice(&seg(marker::SIZ, &one_component()));
    bytes.extend_from_slice(&seg(marker::COD, &cod_default(1)));
    bytes.extend_from_slice(&seg(marker::QCD, &qcd_none(2, &[8; 16])));
    bytes.extend_from_slice(extra);
    bytes.extend_from_slice(&be16(marker::SOT));
    bytes
}

#[test]
fn reserved_markers_carry_no_segment() {
    // 0xFF30..=0xFF3F stand alone. A walker that reads a length after one of
    // them swallows the SOT that follows. p0_02 has 0xFF30 in its main header.
    for code in [0xFF30u16, 0xFF37, 0xFF3F] {
        let bytes = header_with(&be16(code));
        parse_main_header(&bytes).unwrap_or_else(|e| panic!("{code:#06X} should walk: {e:?}"));
    }
    // Several in a row, and adjacent to other segments.
    let mut extra = be16(0xFF30).to_vec();
    extra.extend_from_slice(&be16(0xFF3F));
    extra.extend_from_slice(&seg(marker::COM, b"note"));
    extra.extend_from_slice(&be16(0xFF31));
    assert!(parse_main_header(&header_with(&extra)).is_ok());
}

/// An unknown marker is *walked* by its length — that is what lets the header be
/// traversed — but the decoder will not decode past it. Every marker code is
/// allocated by some part of the standard, and an unknown one may change what
/// the packet data means, so silently ignoring it would risk a wrong image.
#[test]
fn unknown_marker_segments_are_walked_then_reported_unsupported() {
    // Codes this decoder names — the Part 2 block (0xFF74..=0xFF78) among them —
    // reject under their own message, checked in the reject matrix. These are the
    // ones it genuinely does not recognize, which the walk must still step over.
    for code in [
        0xFF01u16, // no part of the standard we implement
        0xFF2F,    // just below the reserved segment-less range
        0xFF40,    // just above it
        0xFF73,    // just below the Part 2 block
        0xFF79,    // just above the Part 2 block
    ] {
        let bytes = header_with(&seg(code, &[1, 2, 3, 4]));

        // The walk locates it and keeps going: the SOT after it is still found.
        let (segments, _) =
            walk_main_header(&bytes).unwrap_or_else(|e| panic!("{code:#06X}: {e:?}"));
        assert!(
            segments.iter().any(|s| s.code == code),
            "{code:#06X} located"
        );

        // Interpreting the header then refuses to guess what it meant.
        let e = err(&bytes);
        assert!(
            matches!(&e, Error::Unsupported(m) if m.message().contains("unrecognized")),
            "{code:#06X}: got {e:?}",
        );
    }
}

#[test]
fn a_non_marker_where_a_marker_belongs_is_codestream() {
    // Every marker's high byte is 0xFF; anything else means we have lost sync.
    let bytes = header_with(&[0x12, 0x34]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn header_altering_markers_are_rejected_not_skipped() {
    // These are known markers outside the subset. Each changes how the
    // codestream is interpreted, so each is named and rejected rather than
    // passed over. PPM has left this list — it is decoded now (issue #71); the
    // length markers TLM/PLM/PLT are absent too, being informational (#72).
    // CAP has left it too: it is read (#340).
    for code in [marker::PPT, marker::SOP] {
        let bytes = header_with(&seg(code, &[0, 0]));
        assert!(
            matches!(err(&bytes), Error::Unsupported(_)),
            "{code:#06X} should be Unsupported"
        );
    }
    // EPH carries no segment, so it is spliced in bare.
    let bytes = header_with(&be16(marker::EPH));
    assert!(matches!(err(&bytes), Error::Unsupported(_)));
}

#[test]
fn duplicate_siz_is_codestream() {
    let bytes = header_with(&seg(marker::SIZ, &one_component()));
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

#[test]
fn a_second_soc_in_the_main_header_is_codestream() {
    let bytes = header_with(&be16(marker::SOC));
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// A segment-less marker costs two input bytes but one located-segment record,
/// so a run of them must not grow the list without bound.
#[test]
fn too_many_marker_segments_is_codestream() {
    let mut extra = Vec::new();
    for _ in 0..=MAX_MAIN_HEADER_SEGMENTS {
        extra.extend_from_slice(&be16(0xFF30));
    }
    let bytes = header_with(&extra);
    assert!(matches!(err(&bytes), Error::Codestream(_)));

    // One under the cap still walks (the three real segments plus the run).
    let mut extra = Vec::new();
    for _ in 0..MAX_MAIN_HEADER_SEGMENTS - 4 {
        extra.extend_from_slice(&be16(0xFF30));
    }
    assert!(parse_main_header(&header_with(&extra)).is_ok());
}

// --- corpus cross-check against the opj_dump oracle (issue #56) ------------

fn corpus_dir() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/conformance")
}

/// Read a `.pgx` reference image's declared dimensions from its header line.
///
/// The full reader lives in `tests/conformance_part4.rs`; here we only need the
/// trailing `<width> <height>`, which is the last two whitespace-separated
/// tokens of the first line whatever the sign is spelled like.
fn pgx_extent(path: &std::path::Path) -> (u32, u32) {
    let bytes = std::fs::read(path).expect("read reference");
    let end = bytes.iter().position(|&b| b == b'\n').expect("header line");
    let header = std::str::from_utf8(&bytes[..end]).expect("ASCII header");
    let tokens: Vec<&str> = header.split_ascii_whitespace().collect();
    let n = tokens.len();
    (
        tokens[n - 2].parse().expect("width"),
        tokens[n - 1].parse().expect("height"),
    )
}

/// Every conformance main header walks, and the per-component geometry SIZ
/// yields agrees with `opj_dump` — which is what `manifest.json`'s `features`
/// block records (see its `provenance.features`).
///
/// This is the oracle for issue #56: depth, sign, and sub-sampling for all
/// `Csiz` components of 23 real codestreams, including `p0_13`'s 257 components
/// and the four sub-sampling shapes in `p0_06`. The walk covers markers the
/// decoder rejects (COC, PPM, POC, …) and `p0_02`'s reserved `0xFF30`, because
/// walking is subset-agnostic.
///
/// Returns early if the corpus is absent: it is `exclude`d from the packaged
/// crate, so a `cargo test` unpacked from crates.io has no fixtures.
#[test]
fn siz_matches_opj_dump_across_the_conformance_corpus() {
    let dir = corpus_dir();
    let Ok(text) = std::fs::read_to_string(dir.join("manifest.json")) else {
        return;
    };
    let manifest: serde_json::Value = serde_json::from_str(&text).expect("manifest parses");

    for entry in manifest["entries"].as_array().expect("entries") {
        let name = entry["codestream"].as_str().expect("codestream path");
        let bytes = std::fs::read(dir.join(name)).expect("read codestream");

        let (segments, _) = walk_main_header(&bytes).unwrap_or_else(|e| panic!("{name}: {e:?}"));
        assert_eq!(segments[0].code, marker::SIZ, "{name}: SIZ must be first");
        let siz = decode_siz(Cursor::new(segments[0].body))
            .unwrap_or_else(|e| panic!("{name}: decode_siz: {e:?}"));

        let features = &entry["features"];
        // `features.width`/`height` are `Xsiz`/`Ysiz`, the reference grid, not
        // the image area — p1_01 declares 127x227 with a (5, 128) origin.
        assert_eq!(
            siz.x_size as u64,
            features["width"].as_u64().unwrap(),
            "{name}: Xsiz"
        );
        assert_eq!(
            siz.y_size as u64,
            features["height"].as_u64().unwrap(),
            "{name}: Ysiz"
        );
        assert_eq!(
            siz.components.len() as u64,
            features["components"].as_u64().unwrap(),
            "{name}: Csiz",
        );

        for (i, comp) in siz.components.iter().enumerate() {
            assert_eq!(
                comp.bit_depth as u64,
                features["precision"][i].as_u64().unwrap(),
                "{name}: component {i} depth",
            );
            assert_eq!(
                comp.signed,
                features["signed"][i].as_bool().unwrap(),
                "{name}: component {i} sign",
            );
            assert_eq!(
                [comp.x_sampling as u64, comp.y_sampling as u64],
                [
                    features["subsampling"][i][0].as_u64().unwrap(),
                    features["subsampling"][i][1].as_u64().unwrap(),
                ],
                "{name}: component {i} sub-sampling",
            );
        }

        // The class-1 references are one `.pgx` per graded component, decoded
        // at the entry's recorded `reduction` (OpenJPEG's `C1P0_ResFactor_list`;
        // 0 everywhere but p0_08) — so their dimensions are the oracle for
        // `component_extent_at` at that reduction, for all 23 entries. A corpus
        // refresh that changes a factor without re-recording it fails here.
        let reduction = entry["reduction"]
            .as_u64()
            .unwrap_or_else(|| panic!("{name}: manifest entry records no reduction"))
            as u8;
        for (i, reference) in entry["references"]["class1"]
            .as_array()
            .expect("class1 refs")
            .iter()
            .enumerate()
        {
            let (rw, rh) = pgx_extent(&dir.join(reference.as_str().unwrap()));
            let (cw, ch) = siz
                .component_extent_at(i, reduction)
                .expect("graded component exists");
            assert_eq!(
                (cw, ch),
                (rw, rh),
                "{name}: component {i} extent at reduction {reduction} disagrees with its \
                 reference",
            );
        }
    }
}

/// `p0_02` carries the reserved segment-less marker `0xFF30` in its main header,
/// after `COM` and before `SOT`. The walk runs to completion before any segment
/// is interpreted, so the whole header — `0xFF30` included — is traversed on the
/// way to the `Unsupported` verdict its `COD` earns.
///
/// A walker that read a length after `0xFF30` would consume the `SOT` and report
/// `Incomplete` (the input ending inside the header) instead. That is the bug this
/// codestream exists to catch, so assert the *kind* of failure: a feature
/// rejection means the walk got there, a structural one means it did not.
#[test]
fn p0_02_reserved_marker_walks_cleanly() {
    let path = corpus_dir().join("codestreams/p0_02.j2k");
    let Ok(bytes) = std::fs::read(&path) else {
        return;
    };

    let (segments, sot) = walk_main_header(&bytes).expect("main header walks");
    assert!(sot.is_ok(), "the walk reaches the SOT: {sot:?}");
    assert!(
        segments.iter().any(|s| s.code == 0xFF30),
        "p0_02 should carry the reserved 0xFF30 marker",
    );
    assert!(
        segments
            .iter()
            .find(|s| s.code == 0xFF30)
            .unwrap()
            .body
            .is_empty(),
        "0xFF30 carries no segment",
    );

    // The walk steps over `0xFF30` and the whole header parses: p0_02's COD, its
    // COC, and its `restart | pterm | segsym` style are all decoded. A naive
    // walker reports `Incomplete` here instead,
    // which is the regression this pins.
    let cs = parse(&bytes).expect("p0_02's main header is inside the decoded subset");

    // The COC overrides component 0, so the resolved parameters are its, not
    // COD's. p0_02 has one component and `opj_dump` reports `cblksty=0x34`.
    assert_eq!(cs.header.components.len(), 1);
    assert_eq!(cs.header.components[0].coding.code_block_style, 0x34);
}

// --- the reject matrix (issue #78) ----------------------------------------

/// Which typed error a caller sees, per the mapping the crate commits to:
/// `Codestream` for structural damage (truncation, lost sync, a missing
/// required marker), `Incomplete` for input that ends inside the main header,
/// `Marker` for a field encoded illegally, `Unsupported`
/// for valid JPEG 2000 that falls outside the decoded subset, and `Limit` for
/// an input past one of the decoder's resource guards.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Variant {
    Codestream,
    Incomplete,
    Marker,
    Unsupported,
    Limit,
}

fn variant_of(e: &Error) -> Variant {
    match e {
        Error::Codestream(_) => Variant::Codestream,
        Error::Incomplete(_) => Variant::Incomplete,
        Error::Marker(_) => Variant::Marker,
        Error::Unsupported(_) => Variant::Unsupported,
        Error::Limit(_) => Variant::Limit,
        other => panic!("main-header parsing should not raise {other:?}"),
    }
}

/// A valid single-component header with a COD whose fields are overridden.
fn header_with_cod(cod: Vec<u8>) -> Vec<u8> {
    codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ])
}

/// Every input outside the decoded subset, mapped to the typed error a caller
/// sees. This is the contract: valid-but-not-yet-decoded is `Unsupported`, an
/// input past a resource guard is `Limit`, an illegal field is `Marker`, and
/// structural damage is `Codestream`. Nothing
/// here may be silently accepted — the alternative to a clean rejection is not
/// a slightly wrong image, it is an arbitrary one.
///
/// As each Phase 2 milestone lands, its row moves out of this table and into
/// the decoded set. A row that stops rejecting fails here first. The JP2 box
/// layer has its own matrix in `src/jp2/tests.rs`.
#[test]
fn reject_matrix_maps_every_out_of_subset_input_to_its_typed_error() {
    // (what the input carries, the error it produced, the variant it must be)
    let mut rows: Vec<(&str, Error, Variant)> = vec![
        // CAP and CPF are read now (#340), so CAP left this table; what
        // remains is the capabilities not decoded and the malformed fields.
        (
            "CAP whose length disagrees with Pcap",
            err(&header_with(&seg(marker::CAP, &[0, 2, 0, 0]))),
            Variant::Marker,
        ),
        (
            "CAP signaling a Part 2 capability",
            err(&header_with(&seg(marker::CAP, &cap_body(PART2_PCAP, &[0])))),
            Variant::Unsupported,
        ),
        (
            "CAP signaling MULTIHT",
            err(&header_with(&seg(marker::CAP, &cap15(0x2000)))),
            Variant::Unsupported,
        ),
        (
            "a second CAP",
            err(&header_with(
                &[seg(marker::CAP, &cap15(3)), seg(marker::CAP, &cap15(3))].concat(),
            )),
            Variant::Codestream,
        ),
        (
            "CPF of an odd byte count",
            err(&header_with(&seg(marker::CPF, &[0, 2, 0]))),
            Variant::Marker,
        ),
        (
            "a second CPF",
            err(&header_with(
                &[seg(marker::CPF, &[0, 2]), seg(marker::CPF, &[0, 2])].concat(),
            )),
            Variant::Codestream,
        ),
        (
            "CAP in a tile-part header",
            perr(&assemble_with_tile_markers(
                &default_header(),
                &[seg(marker::CAP, &cap15(3))],
                &[0],
            )),
            Variant::Codestream,
        ),
        (
            "CPF in a tile-part header",
            perr(&assemble_with_tile_markers(
                &default_header(),
                &[seg(marker::CPF, &[0, 2])],
                &[0],
            )),
            Variant::Codestream,
        ),
        (
            "RGN in a codestream whose CAP says it has none",
            err(&header_with(
                &[
                    seg(marker::CAP, &cap15(3)),
                    seg(marker::RGN, &rgn_body(&[0], 0, 4)),
                ]
                .concat(),
            )),
            Variant::Codestream,
        ),
        (
            "tile-part RGN in a codestream whose CAP says it has none",
            perr(&assemble_with_tile_markers(
                &[default_header(), vec![seg(marker::CAP, &cap15(3))]].concat(),
                &[seg(marker::RGN, &rgn_body(&[0], 0, 4))],
                &[0],
            )),
            Variant::Codestream,
        ),
        // Multiple components are decoded, so they left this table. The
        // sample limit that bounds them depends on the caller's options, so
        // it is checked after this parse (`many_components_exceed_the_sample_budget`).
        // A non-zero image origin is decoded now; one at or past the far edge
        // (XOsiz >= Xsiz, Table A-9) encloses no image and is an illegal field.
        (
            "image origin at the far edge",
            err(&codestream(&[seg(
                marker::SIZ,
                &siz_geom(512, 256, 512, 0, 512, 256, 0, 0),
            )])),
            Variant::Marker,
        ),
        // A tile grid is decoded now; one finer than `Isot` can name is not a
        // missing feature but an illegal field, since no tile-part could ever
        // name its tiles.
        (
            "tile grid past the Isot range",
            err(&codestream(&[seg(
                marker::SIZ,
                &siz_geom(65536, 1, 0, 0, 1, 1, 0, 0),
            )])),
            Variant::Marker,
        ),
        // The precinct partition is decoded, so it left this table; a zero
        // exponent above resolution 0 is still an illegal field.
        (
            "zero precinct exponent above resolution 0",
            err(&header_with_cod({
                let mut body = cod_body(0x01, 0, 1, 0, 1, 4, 4, 0, 1);
                body.extend_from_slice(&[0x55, 0x50]);
                body
            })),
            Variant::Marker,
        ),
        // The SOP/EPH delimiters are decoded, so they left this table; a
        // reserved Scod bit is still an illegal field.
        (
            "reserved Scod bit",
            err(&header_with_cod(cod_body(0x08, 0, 1, 0, 5, 4, 4, 0, 1))),
            Variant::Marker,
        ),
        // Every progression order is decoded, so they left this table; a
        // reserved code is still an illegal field.
        // Multiple quality layers are decoded, so they left this table; a
        // declared zero is still an illegal field.
        (
            "zero quality layers",
            err(&header_with_cod(cod_body(0, 0, 0, 0, 5, 4, 4, 0, 1))),
            Variant::Marker,
        ),
        // Both color transforms are decoded now (RCT and ICT), so they left
        // this table, and on fewer than three components the transform is
        // skipped. What remains out of subset: Part 2's array MCT, and a
        // codestream that mixes wavelets across the three components.
        (
            "color transform over mixed wavelets",
            err(&codestream(&[
                seg(marker::SIZ, &siz_body(3, &[(7, 1, 1); 3])),
                seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 0)),
                seg(marker::COC, &coc_body(&[1], 0, 5, 4, 4, 0, 1)),
                seg(marker::QCD, &qcd_expounded(2, &[(8, 0); 16])),
            ])),
            Variant::Unsupported,
        ),
        (
            "Part 2 array multiple-component transform",
            err(&header_with_cod(cod_body(0, 0, 1, 2, 5, 4, 4, 0, 1))),
            Variant::Unsupported,
        ),
        (
            "reserved progression order",
            err(&header_with_cod(cod_body(0, 5, 1, 0, 5, 4, 4, 0, 1))),
            Variant::Marker,
        ),
        (
            "reserved wavelet transform",
            err(&header_with_cod(cod_body(0, 0, 1, 0, 5, 4, 4, 0, 2))),
            Variant::Marker,
        ),
        (
            "zero components",
            err(&codestream(&[seg(marker::SIZ, &siz_body(0, &[]))])),
            Variant::Marker,
        ),
        (
            "component count above the 16384 limit",
            err(&codestream(&[seg(
                marker::SIZ,
                &siz_body(markers::MAX_COMPONENTS + 1, &[]),
            )])),
            Variant::Marker,
        ),
        (
            "zero sub-sampling factor",
            err(&codestream(&[seg(marker::SIZ, &siz_body(1, &[(7, 0, 1)]))])),
            Variant::Marker,
        ),
        (
            "bit depth above 38",
            err(&codestream(&[seg(
                marker::SIZ,
                &siz_body(1, &[(38, 1, 1)]),
            )])),
            Variant::Marker,
        ),
        (
            "zero-size image",
            err(&codestream(&[seg(
                marker::SIZ,
                &siz_geom(0, 256, 0, 0, 512, 256, 0, 0),
            )])),
            Variant::Marker,
        ),
        (
            "missing SOC",
            err(&seg(marker::SIZ, &one_component())),
            Variant::Codestream,
        ),
        (
            "SIZ not the first marker",
            err(&codestream(&[seg(marker::COD, &cod_default(1))])),
            Variant::Codestream,
        ),
        (
            "unknown marker without a length, at the end of the input",
            err(&{
                let mut b = be16(marker::SOC).to_vec();
                b.extend_from_slice(&seg(marker::SIZ, &one_component()));
                b.extend_from_slice(&be16(0xFF01));
                b
            }),
            Variant::Incomplete,
        ),
        (
            "duplicate COD",
            err(&codestream(&[
                seg(marker::SIZ, &one_component()),
                seg(marker::COD, &cod_default(1)),
                seg(marker::COD, &cod_default(1)),
                seg(marker::QCD, &qcd_none(2, &[8; 16])),
            ])),
            Variant::Codestream,
        ),
    ];

    // Every main-header marker the subset does not decode. TLM and PLM have
    // left this table (informational, decoded — issue #72); PPM too (its packed
    // packet headers are decoded — issue #71); PLT is decoded in the tile-part
    // header and structurally illegal in the main one.
    for (name, code) in [("PPT", marker::PPT), ("SOP", marker::SOP)] {
        rows.push((
            name,
            err(&header_with(&seg(code, &[0, 0]))),
            Variant::Unsupported,
        ));
    }

    // Every JPEG 2000 Part 2 codestream marker (0xFF74..=0xFF78): out of the
    // Part 1 subset, so each is an `Unsupported` feature the moment it appears,
    // never half-parsed as Part 1 (issue #78).
    for (name, code) in [
        ("MCT", marker::MCT),
        ("MCC", marker::MCC),
        ("NLT", marker::NLT),
        ("MCO", marker::MCO),
        ("CBD", marker::CBD),
    ] {
        rows.push((
            name,
            err(&header_with(&seg(code, &[0, 0]))),
            Variant::Unsupported,
        ));
    }
    rows.push((
        "PLT in the main header",
        err(&header_with(&seg(marker::PLT, &[0, 0]))),
        Variant::Codestream,
    ));
    rows.push((
        "EPH",
        err(&header_with(&be16(marker::EPH))),
        Variant::Unsupported,
    ));

    // Every code-block style flag that is not yet decoded, individually. Each
    // changes how Tier-1 reads a code-block, so none may be ignored. `bypass`,
    // `restart`, `predictable termination`, `segmentation symbols`, `vertically
    // causal context`, `reset context probabilities` and the HT bit have left
    // this table, leaving only the HTJ2K mixed-mode bit without the HT bit,
    // which `check_block_coder` refuses.
    use markers::code_block_style::{HT, LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL};
    for (bit, name) in markers::code_block_style::FLAGS {
        if bit & (LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET | HT) != 0 {
            continue;
        }
        rows.push((
            name,
            err(&header_with_cod(cod_body(0, 0, 1, 0, 5, 4, 4, bit, 1))),
            Variant::Unsupported,
        ));
    }
    // MIXED is decoded, but ISO/IEC 15444-15 A.4 allows its Part 1 blocks
    // neither bypass nor termination on each pass, and a `CAP` that says each
    // tile-component holds one kind of block (HTDECLARED) rules it out.
    for (name, bit) in [("MIXED with bypass", LAZY), ("MIXED with termall", TERMALL)] {
        rows.push((
            name,
            err(&header_with_cod(cod_body(
                0,
                0,
                1,
                0,
                5,
                4,
                4,
                0xC0 | bit,
                1,
            ))),
            Variant::Marker,
        ));
    }
    rows.push((
        "MIXED under an HTDECLARED CAP",
        err(&codestream(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::CAP, &cap15(0x8000)),
            seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0xC0, 1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ])),
        Variant::Codestream,
    ));

    let wrong: Vec<String> = rows
        .iter()
        .filter(|(_, error, want)| variant_of(error) != *want)
        .map(|(feature, error, want)| format!("  {feature}: expected {want:?}, got {error:?}"))
        .collect();
    assert!(
        wrong.is_empty(),
        "{} inputs mapped to the wrong error variant:\n{}",
        wrong.len(),
        wrong.join("\n"),
    );
}

/// The decoded style bits — bypass, restart, predictable termination,
/// segmentation symbols, vertically causal context, and reset context
/// probabilities — parse, and so do the HT bit and MIXED; only the
/// mixed-mode bit without the HT bit does not, and a style byte mixing it
/// with decoded flags still rejects, naming only the part that blocks it.
#[test]
fn the_decoded_styles_parse_and_the_rest_still_reject() {
    use markers::code_block_style::{HT, LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL};

    // Every combination of the decoded flags parses.
    for style in [
        0,
        LAZY,
        TERMALL,
        PTERM,
        SEGSYM,
        VCAUSAL,
        RESET,
        LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET,
        HT,
        HT | VCAUSAL,
        0xC0,
        0xC0 | PTERM | SEGSYM | VCAUSAL | RESET,
    ] {
        let bytes = codestream(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, style, 1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]);
        let (header, _, _) = parse_main_header(&bytes).expect("a decoded style parses");
        assert_eq!(header.cod.coding.code_block_style, style);
    }

    // A decoded flag beside an undecoded one: the message names only the
    // undecoded half, so it says what is actually missing.
    let e = err(&header_with_cod(cod_body(
        0,
        0,
        1,
        0,
        5,
        4,
        4,
        VCAUSAL | RESET | 0x80, // + HTJ2K mixed-mode block coding
        1,
    )));
    let Error::Unsupported(message) = &e else {
        panic!("got {e:?}")
    };
    assert!(message.message().contains("mixed-mode"), "{message}");
    for decoded in [
        "high-throughput",
        "selective arithmetic coding bypass",
        "vertically causal context",
        "reset context probabilities",
        "termination on each coding pass",
        "segmentation symbols",
        "predictable termination",
    ] {
        assert!(
            !message.message().contains(decoded),
            "{decoded} is decoded and must not be named as a blocker: {message}"
        );
    }
}

/// A code-block style names the flags it carries, so a rejection tells the
/// caller which feature to look up rather than printing a bare bit pattern.
#[test]
fn code_block_style_rejection_names_the_flags() {
    // The undecoded flag is the HTJ2K mixed-mode bit without the HT bit. The
    // high bits select the HTJ2K block coder rather than being reserved, so
    // it is named: with or without a CAP, the style byte decides the coder
    // and must not read as the default style.
    for style in [0x80u8, 0x88] {
        let e = err(&header_with_cod(cod_body(0, 0, 1, 0, 5, 4, 4, style, 1)));
        let Error::Unsupported(message) = &e else {
            panic!("{style:#04X}: got {e:?}")
        };
        assert!(
            message.message().contains("mixed-mode"),
            "{style:#04X}: {message}"
        );
        assert!(
            !message.message().contains("high-throughput"),
            "{style:#04X}: {message}"
        );
    }

    // Every bit of the style byte is allocated, so nothing goes unnamed.
    let all: u8 = markers::code_block_style::FLAGS
        .iter()
        .fold(0, |acc, (bit, _)| acc | bit);
    assert_eq!(all, u8::MAX, "every style bit must be named");
}

// --- COC / QCC per-component overrides (issue #58) -------------------------

/// `SPcoc` body: the tail COD and COC share, minus the component index and
/// `Scoc`.
fn coc_body(
    index_bytes: &[u8],
    scoc: u8,
    nl: u8,
    xcb: u8,
    ycb: u8,
    style: u8,
    transform: u8,
) -> Vec<u8> {
    let mut b = index_bytes.to_vec();
    b.push(scoc);
    b.extend_from_slice(&[nl, xcb, ycb, style, transform]);
    b
}

fn parsed(segments: &[Vec<u8>]) -> crate::codestream::MainHeader {
    let (header, _, _) = parse_main_header(&codestream(segments)).expect("parses");
    header
}

/// The whole of A.6.2 and A.6.5: a component with no COC takes COD's coding
/// parameters, one with a COC takes the COC's, and the same for QCC over QCD.
#[test]
fn overrides_resolve_else_default_per_component() {
    let siz = siz_body(3, &[(15, 1, 1); 3]);
    let header = parsed(&[
        seg(marker::SIZ, &siz),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        // Component 1 alone overrides the coding style: 3 levels, restart.
        seg(marker::COC, &coc_body(&[1], 0, 3, 2, 2, 0x04, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
        // Component 2 alone overrides the quantization: 4 guard bits. Its
        // levels stay COD's 5, so the table needs the full 16 entries.
        seg(marker::QCC, &{
            let mut b = vec![2u8];
            b.extend_from_slice(&qcd_none(4, &[9; 16]));
            b
        }),
    ]);

    // Component 0: both defaults.
    assert_eq!(header.components[0].coding, header.cod.coding);
    assert_eq!(header.components[0].quant, header.qcd);

    // Component 1: COC's coding, QCD's quantization.
    assert_eq!(header.components[1].coding.decomposition_levels, 3);
    assert_eq!(header.components[1].coding.code_block_style, 0x04);
    assert_eq!(header.components[1].coding.code_block_width, 2);
    assert_eq!(header.components[1].quant, header.qcd);

    // Component 2: COD's coding, QCC's quantization.
    assert_eq!(header.components[2].coding, header.cod.coding);
    assert_eq!(header.components[2].quant.guard_bits, 4);
    assert_ne!(header.components[2].quant, header.qcd);
}

/// `Ccoc`/`Cqcc` is one byte while `Csiz < 257` and two bytes at 257 and above
/// (A.6.2). Read at the wrong width, every field after it shifts by a byte and
/// the segment either overruns or decodes garbage. `p0_13` has 257 components,
/// so this boundary is live in the corpus.
#[test]
fn component_index_is_two_bytes_from_257_components() {
    // 256 components: one-byte index.
    let narrow = vec![(15u8, 1u8, 1u8); 256];
    let header = parsed(&[
        seg(marker::SIZ, &siz_body(256, &narrow)),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        seg(marker::COC, &coc_body(&[255], 0, 3, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.components[255].coding.decomposition_levels, 3);
    assert_eq!(header.components[0].coding.decomposition_levels, 5);

    // 257 components: two-byte index. The same one-byte body must now fail.
    let wide = vec![(15u8, 1u8, 1u8); 257];
    let header = parsed(&[
        seg(marker::SIZ, &siz_body(257, &wide)),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        seg(marker::COC, &coc_body(&[0x01, 0x00], 0, 3, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.components[256].coding.decomposition_levels, 3);
    assert_eq!(header.components[0].coding.decomposition_levels, 5);
}

#[test]
fn an_override_past_the_component_count_is_a_marker_error() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::COC, &coc_body(&[3], 0, 3, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// A.6.2 and A.6.5 allow one COC and one QCC per component per header. A second
/// is malformed, not a later-wins override — guessing would decode an image the
/// encoder never described.
#[test]
fn a_second_override_for_one_component_is_a_codestream_error() {
    let coc = seg(marker::COC, &coc_body(&[0], 0, 3, 4, 4, 0, 1));
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        coc.clone(),
        coc,
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));

    let qcc = seg(marker::QCC, &{
        let mut b = vec![0u8];
        b.extend_from_slice(&qcd_none(2, &[8; 16]));
        b
    });
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
        qcc.clone(),
        qcc,
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// `Scoc` bit 0 signals an explicit precinct partition for one component, which
/// overrides COD's for that component alone; its other seven bits are reserved
/// and must be zero.
#[test]
fn a_coc_carries_its_own_precinct_partition() {
    let with = |scoc, tail: &[u8]| {
        let mut coc = coc_body(&[0], scoc, 3, 4, 4, 0, 1);
        coc.extend_from_slice(tail);
        let header = vec![
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_default(1)),
            seg(marker::COC, &coc),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ];
        let data = [0xDE, 0xAD];
        assemble(&header, &synth::sot(0, psot_for(&data), 0, 1), &data, true)
    };
    // Four resolutions (NL = 3), so four precinct bytes.
    let bytes = with(0x01, &[0x22, 0x33, 0x44, 0x55]);
    let cs = parse(&bytes).expect("COC precincts parse");
    assert_eq!(
        cs.header.components[0].coding.precinct_sizes,
        vec![(2, 2), (3, 3), (4, 4), (5, 5)],
    );
    // COD's own partition stays maximal — the COC replaced it for the component,
    // not for the codestream.
    assert!(cs.header.cod.coding.precinct_sizes.is_empty());

    assert!(matches!(perr(&with(0x02, &[])), Error::Marker(_)));
    assert!(matches!(perr(&with(0x80, &[])), Error::Marker(_)));
}

/// A COC's style byte goes through the same gate COD's does: an undecoded flag
/// on any component is still undecoded.
#[test]
fn a_coc_cannot_smuggle_in_an_undecoded_code_block_style() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::COC, &coc_body(&[0], 0, 3, 4, 4, 0x80, 1)), // mixed-mode bit alone (undecoded)
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    let e = err(&bytes);
    let Error::Unsupported(message) = &e else {
        panic!("got {e:?}")
    };
    assert!(message.message().contains("mixed-mode"), "{message}");
    assert!(
        message.message().contains("COC"),
        "the message must name the marker: {message}"
    );
}

/// Which color transform applies follows from the wavelet, and COC makes the
/// wavelet per component. RCT is defined over three integer components, so a COC
/// that moves one of the first three to 9/7 describes a transform that does not
/// exist.
#[test]
fn a_coc_moving_a_color_component_to_the_97_wavelet_is_unsupported() {
    // Each 9/7 component gets a scalar QCC so the wavelet/quant pairing is
    // sound and the failure under test is the color transform alone.
    let scalar_qcc = |component: u8| {
        seg(marker::QCC, &{
            let mut b = vec![component];
            b.extend_from_slice(&qcd_expounded(2, &[(8, 0); 16]));
            b
        })
    };

    let siz = siz_body(3, &[(15, 1, 1); 3]);
    let bytes = codestream(&[
        seg(marker::SIZ, &siz),
        // mct = 1, reversible 5/3: a valid RCT codestream.
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 1)),
        // ... except component 1 is 9/7.
        seg(marker::COC, &coc_body(&[1], 0, 5, 4, 4, 0, 0)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
        scalar_qcc(1),
    ]);
    let e = err(&bytes);
    let Error::Unsupported(message) = &e else {
        panic!("got {e:?}")
    };
    assert!(message.message().contains("component 1"), "{message}");

    // A fourth component on 9/7 is outside the transform, so it is allowed.
    let siz = siz_body(4, &[(15, 1, 1); 4]);
    let bytes = codestream(&[
        seg(marker::SIZ, &siz),
        seg(marker::COD, &cod_body(0, 0, 1, 1, 5, 4, 4, 0, 1)),
        seg(marker::COC, &coc_body(&[3], 0, 5, 4, 4, 0, 0)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
        scalar_qcc(3),
    ]);
    assert!(parse_main_header(&bytes).is_ok());
}

/// A malformed QCC must report as a QCC fault, not as a fault in QCD. The two
/// share a body parser, and a per-component override that blames the
/// codestream-wide default sends a reader to the wrong marker.
#[test]
fn a_malformed_qcc_names_qcc_and_not_qcd() {
    // Scalar expounded (style 2) with an odd-length step table: truncated.
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
        seg(marker::QCC, &[0, (2 << 5) | 2, 0x00]),
    ]);
    let e = err(&bytes);
    let Error::Codestream(message) = &e else {
        panic!("got {e:?}")
    };
    assert!(message.message().contains("QCC"), "{message}");
    assert!(!message.message().contains("QCD"), "{message}");
}

// --- RGN: region of interest, maxshift (issue #77) --------------------------

fn rgn_body(index_bytes: &[u8], srgn: u8, shift: u8) -> Vec<u8> {
    let mut b = index_bytes.to_vec();
    b.extend_from_slice(&[srgn, shift]);
    b
}

/// An RGN names one component and lifts its region above the background by
/// `SPrgn` bit-planes. Components it does not name keep a shift of zero.
#[test]
fn rgn_sets_the_maxshift_of_one_component() {
    let header = parsed(&[
        seg(marker::SIZ, &siz_body(3, &[(15, 1, 1); 3])),
        seg(marker::COD, &cod_default(1)),
        seg(marker::RGN, &rgn_body(&[1], 0, 9)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.components[0].roi_shift, 0);
    assert_eq!(header.components[1].roi_shift, 9);
    assert_eq!(header.components[2].roi_shift, 0);
}

/// `Crgn` has the same width rule as `Ccoc` and `Cqcc`: one byte below 257
/// components, two from 257 up.
#[test]
fn rgn_component_index_is_two_bytes_from_257_components() {
    let header = parsed(&[
        seg(marker::SIZ, &siz_body(257, &vec![(15u8, 1u8, 1u8); 257])),
        seg(marker::COD, &cod_default(1)),
        seg(marker::RGN, &rgn_body(&[0x01, 0x00], 0, 4)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.components[256].roi_shift, 4);
    assert_eq!(header.components[0].roi_shift, 0);
}

/// `Srgn = 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 Part 2 style
/// decodes there as though it were maxshift; reject it instead.
#[test]
fn a_non_maxshift_roi_style_is_unsupported() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::RGN, &rgn_body(&[0], 1, 9)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Unsupported(_)));
}

#[test]
fn an_rgn_past_the_component_count_is_a_marker_error() {
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::RGN, &rgn_body(&[3], 0, 9)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

#[test]
fn a_second_rgn_for_one_component_is_a_codestream_error() {
    let rgn = seg(marker::RGN, &rgn_body(&[0], 0, 9));
    let bytes = codestream(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        rgn.clone(),
        rgn,
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// A short or long RGN segment is malformed: `Lrgn` is exactly `2 + Crgn`.
#[test]
fn a_wrong_length_rgn_is_rejected() {
    for body in [vec![0u8, 0], vec![0u8, 0, 9, 9]] {
        let bytes = codestream(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_default(1)),
            seg(marker::RGN, &body),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]);
        assert!(
            matches!(err(&bytes), Error::Codestream(_)),
            "{body:?} should reject"
        );
    }
}

/// SOC + `header` + a tile-part whose header carries `markers` before SOD.
///
/// The markers ride in the `sot` slot of [`assemble`], which splices its
/// argument verbatim between the main header and SOD — one byte layout for
/// every tile-part test. `Psot` counts them as part of the tile-part header.
fn assemble_with_tile_markers(header: &[Vec<u8>], markers: &[Vec<u8>], data: &[u8]) -> Vec<u8> {
    let markers_len: usize = markers.iter().map(Vec::len).sum();
    let mut sot = synth::sot(0, psot_for(data) + markers_len as u32, 0, 1);
    for m in markers {
        sot.extend_from_slice(m);
    }
    assemble(header, &sot, data, true)
}

/// A tile-part RGN *replaces* the main header's for that tile (A.6.3), so
/// honoring only the main-header one would decode a different image rather
/// than a slightly worse one. `p0_06` is exactly this codestream: maxshift 11
/// in the main header, 9 in the tile-part header — 9 is what the tile was
/// coded with.
///
/// The override belongs to the *tile*, so it lands on the tile's header and the
/// main header keeps its own value. Another tile of the same image, carrying no
/// RGN, would still take 11.
#[test]
fn a_tile_part_rgn_overrides_the_main_header_shift() {
    let mut header = default_header();
    header.push(seg(marker::RGN, &rgn_body(&[0], 0, 11)));
    let rgn = seg(marker::RGN, &rgn_body(&[0], 0, 9));
    let bytes = assemble_with_tile_markers(&header, &[rgn], &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tile_header(0).unwrap().components[0].roi_shift, 9);
    assert_eq!(
        cs.header.components[0].roi_shift, 11,
        "the tile's override must not be written back over the main header"
    );
}

/// A tile-part RGN with no main-header counterpart sets the shift from zero,
/// and it applies only to the component it names.
#[test]
fn a_tile_part_rgn_names_one_component() {
    let header = [
        seg(marker::SIZ, &siz_body(3, &[(15, 1, 1); 3])),
        seg(marker::COD, &cod_default(1)),
        seg(marker::RGN, &rgn_body(&[2], 0, 11)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let rgn = seg(marker::RGN, &rgn_body(&[1], 0, 9));
    let bytes = assemble_with_tile_markers(&header, &[rgn], &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.components[0].roi_shift, 0);
    assert_eq!(tile.components[1].roi_shift, 9, "the tile-part's RGN");
    assert_eq!(
        tile.components[2].roi_shift, 11,
        "the main header's, unopposed"
    );
}

/// A tile-part POC **overrides** the main header's (A.6.6: "Tile-part POC >
/// Main POC"): the tile walks its own volumes only. OpenJPEG appends the
/// tile's volumes after the main header's instead (docs/openjpeg-departures.md). The
/// main header keeps its own volume for any tile without a POC.
#[test]
fn a_tile_part_poc_overrides_the_main_header_poc() {
    // Main POC: resolutions [0, 2), LRCP. Tile POC: resolutions [0, 3), RLCP.
    let main_poc = [0u8, 0, 0, 1, 2, 1, 0];
    let header = [
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::POC, &main_poc),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let tile_poc = seg(marker::POC, &[0u8, 0, 0, 1, 3, 1, 1]);
    let bytes = assemble_with_tile_markers(&header, &[tile_poc], &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.poc.len(), 1, "the tile's volume alone");
    assert_eq!(
        (tile.poc[0].res_end, tile.poc[0].progression),
        (3, markers::Progression::Rlcp),
        "the tile-part's volume, not the main header's",
    );
    assert_eq!(cs.header.poc.len(), 1);
    assert_eq!(cs.header.poc[0].progression, markers::Progression::Lrcp);
}

/// Two tile-parts of tile 0: the first with no markers, the second with
/// `second_markers` in its header.
fn with_later_tile_part_markers(header: &[Vec<u8>], second_markers: &[Vec<u8>]) -> Vec<u8> {
    let mut bytes = be16(marker::SOC).to_vec();
    for part in header {
        bytes.extend_from_slice(part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot_for(&[1]), 0, 2));
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.push(1);
    let markers: usize = second_markers.iter().map(Vec::len).sum();
    bytes.extend_from_slice(&synth::sot(0, psot_for(&[2]) + markers as u32, 1, 2));
    for m in second_markers {
        bytes.extend_from_slice(m);
    }
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.push(2);
    bytes.extend_from_slice(&be16(marker::EOC));
    bytes
}

/// A.6.6 puts a tile's POC in its first tile-part. When the first POC is in a
/// later one, the first packets can only have followed the main header's
/// order, so the tile walks the main volumes and then its own, as OpenJPEG
/// does, and the 32-volume budget counts both.
#[test]
fn a_poc_first_seen_in_a_later_tile_part_appends_to_the_main_header_poc() {
    let header = |main_volumes: usize| {
        vec![
            seg(marker::SIZ, &one_component()),
            seg(marker::COD, &cod_default(1)),
            seg(marker::POC, &poc_volumes(main_volumes)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]
    };
    let tile_poc = seg(marker::POC, &[0u8, 0, 0, 1, 3, 1, 1]);
    let bytes = with_later_tile_part_markers(&header(1), std::slice::from_ref(&tile_poc));
    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.poc.len(), 2, "main volume then tile volume");
    assert_eq!(tile.poc[0], cs.header.poc[0]);
    assert_eq!(
        (tile.poc[1].res_end, tile.poc[1].progression),
        (3, markers::Progression::Rlcp),
    );

    let bytes = with_later_tile_part_markers(&header(32), &[tile_poc]);
    let error = parse(&bytes).expect_err("33 walked volumes should reject");
    assert!(crate::error::is_fixed_limit(
        &error,
        crate::LimitKind::PocVolumes
    ));
}

/// A tile with no POC of its own keeps the main header's volumes.
#[test]
fn a_tile_without_a_poc_keeps_the_main_header_poc() {
    let main_poc = [0u8, 0, 0, 1, 2, 1, 0];
    let header = [
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_default(1)),
        seg(marker::POC, &main_poc),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    // A tile COD makes the tile resolve to its own header rather than borrow
    // the main header's.
    let tile_cod = seg(marker::COD, &cod_default(1));
    let bytes = assemble_with_tile_markers(&header, &[tile_cod], &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.poc, cs.header.poc);
    assert_eq!(tile.poc.len(), 1);
}

/// **A tile COD outranks a main-header COC.** This is the whole reason the main
/// header keeps its raw overrides rather than only its resolved components.
///
/// A.6.1's precedence for a component is `tile COC > tile COD > main COC > main
/// COD`. Component 0 here has a main-header COC (3 levels) and the tile carries a
/// COD (2 levels). Resolving the tile by laying its markers over the main
/// header's *resolved* components would leave the main COC's 3 levels on top —
/// the value that lost — and every subband bound, packet count and code-block in
/// the tile would be computed for a pyramid the encoder never used.
///
/// Component 1, with no COC anywhere, takes the tile COD too; a component whose
/// COC is in the *tile* header would outrank it, which the next test covers.
#[test]
fn a_tile_cod_outranks_a_main_header_coc() {
    let header = [
        seg(marker::SIZ, &siz_body(2, &[(15, 1, 1); 2])),
        // Main COD: 5 levels for everything.
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        // Main COC: component 0 alone drops to 3 levels.
        seg(marker::COC, &coc_body(&[0], 0, 3, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    // Tile COD: 2 levels, for every component of this tile.
    let tile_cod = seg(marker::COD, &cod_body(0, 0, 1, 0, 2, 4, 4, 0, 1));
    let bytes = assemble_with_tile_markers(&header, &[tile_cod], &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(
        tile.components[0].coding.decomposition_levels, 2,
        "the tile COD must beat the main-header COC, not lose to it"
    );
    assert_eq!(tile.components[1].coding.decomposition_levels, 2);

    // The main header keeps its own resolution: another tile carrying no COD
    // would still see the COC's 3 levels.
    assert_eq!(cs.header.components[0].coding.decomposition_levels, 3);
    assert_eq!(cs.header.components[1].coding.decomposition_levels, 5);
}

/// The rest of A.6.1's ladder: a tile COC beats the tile COD, and a component
/// named by neither tile marker falls back through the main COC to the main COD.
/// The same order governs QCC over QCD.
#[test]
fn tile_overrides_resolve_in_the_standard_s_precedence_order() {
    let header = [
        seg(marker::SIZ, &siz_body(3, &[(15, 1, 1); 3])),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        // Component 2's only override lives in the main header.
        seg(marker::COC, &coc_body(&[2], 0, 4, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let tile_markers = [
        // Tile COD: 2 levels, the tile's new default.
        seg(marker::COD, &cod_body(0, 0, 1, 0, 2, 4, 4, 0, 1)),
        // Tile COC: component 0 alone goes to 1 level, outranking the tile COD.
        seg(marker::COC, &coc_body(&[0], 0, 1, 4, 4, 0, 1)),
        // Tile QCD: 5 guard bits for the tile.
        seg(marker::QCD, &qcd_none(5, &[8; 16])),
        // Tile QCC: component 1 alone goes to 6, outranking the tile QCD.
        seg(marker::QCC, &{
            let mut b = vec![1u8];
            b.extend_from_slice(&qcd_none(6, &[8; 16]));
            b
        }),
    ];
    let bytes = assemble_with_tile_markers(&header, &tile_markers, &[1, 2]);

    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    let levels = |c: usize| tile.components[c].coding.decomposition_levels;
    assert_eq!(levels(0), 1, "tile COC beats tile COD");
    assert_eq!(levels(1), 2, "tile COD, with no COC anywhere");
    assert_eq!(levels(2), 2, "tile COD beats the main COC's 4");

    let guard = |c: usize| tile.components[c].quant.guard_bits;
    assert_eq!(guard(0), 5, "tile QCD");
    assert_eq!(guard(1), 6, "tile QCC beats tile QCD");
    assert_eq!(guard(2), 5, "tile QCD");
}

/// A component named by no tile marker at all still resolves through the main
/// header's own ladder, unchanged.
#[test]
fn a_tile_with_no_overrides_takes_the_main_header_s_resolution() {
    let header = [
        seg(marker::SIZ, &siz_body(2, &[(15, 1, 1); 2])),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1)),
        seg(marker::COC, &coc_body(&[0], 0, 3, 4, 4, 0, 1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ];
    let bytes = assemble(&header, &synth::sot(0, 0, 0, 1), &[1, 2], true);

    let cs = parse(&bytes).expect("parse");
    assert_eq!(cs.tile_header(0).unwrap().components, cs.header.components);
}

/// The coding-parameter overrides belong to the *first* tile-part of a tile
/// (A.4.2): they say how the tile's packets are read, and a later part cannot
/// restate what the earlier parts were already decoded under. A conformant
/// encoder never emits one, so a codestream that does is malformed.
#[test]
fn a_coding_override_in_a_later_tile_part_is_codestream() {
    let first_data = [7, 7, 7];
    let tile_cod = seg(marker::COD, &cod_body(0, 0, 1, 0, 2, 4, 4, 0, 1));

    let mut bytes = be16(marker::SOC).to_vec();
    for part in default_header() {
        bytes.extend_from_slice(&part);
    }
    bytes.extend_from_slice(&synth::sot(0, psot_for(&first_data), 0, 2));
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&first_data);
    // The second tile-part carries a COD, which only the first one may.
    bytes.extend_from_slice(&synth::sot(0, 0, 1, 2));
    bytes.extend_from_slice(&tile_cod);
    bytes.extend_from_slice(&be16(marker::SOD));
    bytes.extend_from_slice(&[8, 8]);
    bytes.extend_from_slice(&be16(marker::EOC));

    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// A tile COD/QCD pair must hold every invariant the main header's does: the
/// quantization table has to cover the levels the coding style declares. A tile
/// COD that deepens the pyramid past what the main QCD's table describes is a
/// malformed marker, caught when the tile resolves rather than at decode time.
#[test]
fn a_tile_cod_outrunning_the_quantization_table_is_marker() {
    let header = [
        seg(marker::SIZ, &one_component()),
        seg(marker::COD, &cod_body(0, 0, 1, 0, 2, 4, 4, 0, 1)),
        // Seven entries: enough for 2 levels (3*2 + 1), not for 5.
        seg(marker::QCD, &qcd_none(2, &[8; 7])),
    ];
    let tile_cod = seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0, 1));
    let bytes = assemble_with_tile_markers(&header, &[tile_cod], &[1, 2]);
    assert!(matches!(perr(&bytes), Error::Marker(_)));
}

/// A.6.3 allows one RGN per component per header. Two in the same tile-part
/// header for one component is a malformed codestream, exactly as it is in the
/// main header; guessing which wins would decode an image the encoder never
/// described.
#[test]
fn a_second_tile_part_rgn_for_one_component_is_a_codestream_error() {
    let rgn = seg(marker::RGN, &rgn_body(&[0], 0, 9));
    let bytes = assemble_with_tile_markers(&default_header(), &[rgn.clone(), rgn], &[1, 2]);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// The tile-part form goes through the same `decode_rgn` as the main header's,
/// so a non-maxshift style rejects as unsupported there too.
#[test]
fn a_tile_part_rgn_with_a_part_2_style_is_unsupported() {
    let rgn = seg(marker::RGN, &rgn_body(&[0], 1, 9));
    let bytes = assemble_with_tile_markers(&default_header(), &[rgn], &[1, 2]);
    assert!(matches!(perr(&bytes), Error::Unsupported(_)));
}

// --- TLM / PLM / PLT: length markers (issue #72) -----------------------------

use super::markers::TlmEntry;

/// The TLM entries of a codestream's main header, in marker order. The parse
/// checks each one and drops it, so this reads them again from the header.
fn tlm_entries(bytes: &[u8]) -> Vec<TlmEntry> {
    let (segments, _) = walk_main_header(bytes).expect("walks");
    let siz = decode_siz(Cursor::new(segments[0].body)).expect("SIZ");
    let mut seen = 0;
    let mut entries = Vec::new();
    for tlm in segments.iter().filter(|s| s.code == marker::TLM) {
        decode_tlm(Cursor::new(tlm.body), &siz, &mut seen, |e| entries.push(e)).expect("TLM");
    }
    entries
}

/// TLM body: `Ztlm`, `Stlm`, then the entry bytes verbatim.
fn tlm_body(stlm: u8, entries: &[u8]) -> Vec<u8> {
    let mut b = vec![0, stlm];
    b.extend_from_slice(entries);
    b
}

/// Length markers are informational, so the parse checks TLM's entries and
/// nothing more. `Stlm = 0x60` is `ST = 2` (two-byte tile indices) and
/// `SP = 1` (four-byte lengths) — the shape `p0_05` carries.
#[test]
fn tlm_records_the_tile_part_lengths() {
    let mut segments = default_header();
    segments.push(seg(
        marker::TLM,
        &tlm_body(0x60, &[0, 0, 0x00, 0x13, 0xFF, 0x4C]),
    ));
    parsed(&segments);
    assert_eq!(
        tlm_entries(&codestream(&segments)),
        vec![TlmEntry {
            tile_index: 0,
            length: 0x0013_FF4C,
        }]
    );
}

/// `ST = 0` omits the tile index — entry order implies it — and `SP = 0`
/// carries two-byte lengths. Entries accumulate across TLM markers in order.
#[test]
fn tlm_indices_can_be_implied_and_lengths_two_bytes() {
    let mut segments = default_header();
    segments.push(seg(marker::TLM, &tlm_body(0x00, &[0x12, 0x34])));
    parsed(&segments);
    assert_eq!(
        tlm_entries(&codestream(&segments)),
        vec![TlmEntry {
            tile_index: 0,
            length: 0x1234,
        }]
    );
}

/// Two TLM markers concatenate: one list of tile-parts, in codestream order.
#[test]
fn tlm_entries_accumulate_across_markers() {
    let mut segments = default_header();
    // ST = 1 (one-byte explicit index), SP = 0: entries `index, len16`.
    segments.push(seg(marker::TLM, &tlm_body(0x10, &[0, 0x00, 0x14])));
    segments.push(seg(marker::TLM, &tlm_body(0x10, &[0, 0x00, 0x2C])));
    parsed(&segments);
    let tlm = tlm_entries(&codestream(&segments));
    assert_eq!(tlm.len(), 2);
    assert_eq!(tlm[0].length, 0x14);
    assert_eq!(tlm[1].length, 0x2C);
}

/// `ST = 3` is undefined (Table A-33). OpenJPEG warns and ignores the TLM
/// chain; as with `Scoc`, rejecting the illegal encoding is stricter.
#[test]
fn tlm_st_3_is_a_marker_error() {
    let mut segments = default_header();
    segments.push(seg(marker::TLM, &tlm_body(0x30, &[0, 0, 0, 0])));
    let bytes = codestream(&segments);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// `Stlm` defines only bits 4–6; a reserved bit set is an illegal encoding.
#[test]
fn tlm_reserved_stlm_bits_are_a_marker_error() {
    for stlm in [0x01u8, 0x08, 0x80] {
        let mut segments = default_header();
        segments.push(seg(marker::TLM, &tlm_body(stlm, &[0, 0x10])));
        let bytes = codestream(&segments);
        assert!(matches!(err(&bytes), Error::Marker(_)), "Stlm {stlm:#04X}");
    }
}

/// A body that does not divide into whole entries is malformed.
#[test]
fn tlm_misaligned_body_is_a_codestream_error() {
    let mut segments = default_header();
    segments.push(seg(marker::TLM, &tlm_body(0x60, &[0, 0, 0, 0x13])));
    let bytes = codestream(&segments);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// The subset's grid is a single tile — enforced at SIZ — so an entry naming
/// any other tile points at nothing. OpenJPEG makes the same range check
/// against its tile grid.
#[test]
fn tlm_naming_a_missing_tile_is_a_marker_error() {
    let mut segments = default_header();
    segments.push(seg(marker::TLM, &tlm_body(0x10, &[1, 0x00, 0x14])));
    let bytes = codestream(&segments);
    assert!(matches!(err(&bytes), Error::Marker(_)));
}

/// PLM is validated for its `Zplm` byte and otherwise skipped, exactly as
/// OpenJPEG skips it: its packet-length chains may split across PLM markers
/// mid-entry, so nothing else can be checked per marker. Synthetic fixture —
/// no conformance entry carries PLM (`tests/conformance_corpus.rs` pins that
/// gap): `Zplm = 0`, then one `Nplm = 2` chain of a two-byte packet length.
#[test]
fn plm_parses_and_is_skipped() {
    let mut segments = default_header();
    segments.push(seg(marker::PLM, &[0, 2, 0x85, 0x02]));
    parsed(&segments);
    assert_eq!(tlm_entries(&codestream(&segments)), vec![]);
}

/// A PLM with no `Zplm` byte at all is malformed.
#[test]
fn plm_without_zplm_is_a_codestream_error() {
    let mut segments = default_header();
    segments.push(seg(marker::PLM, &[]));
    let bytes = codestream(&segments);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// PLT parses in the tile-part header: `Zplt`, then packet lengths as
/// base-128 byte chains (high bit = another byte follows). The lengths are
/// discarded; the parse only requires whole chains.
#[test]
fn plt_parses_in_the_tile_part_header() {
    // Two packet lengths: 0x282 (two bytes, 0x85 then 0x02) and 0x10 (one).
    let plt = seg(marker::PLT, &[0, 0x85, 0x02, 0x10]);
    let bytes = assemble_with_tile_markers(&default_header(), &[plt], &[1, 2]);
    parse(&bytes).expect("PLT is informational and parses");
}

/// A PLT whose last byte still has the continuation bit set ends mid-entry —
/// malformed, and OpenJPEG's `opj_j2k_read_plt` rejects it the same way.
#[test]
fn plt_ending_mid_entry_is_a_codestream_error() {
    let plt = seg(marker::PLT, &[0, 0x85]);
    let bytes = assemble_with_tile_markers(&default_header(), &[plt], &[1, 2]);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// PLT belongs to the tile-part header alone (A.7.3); in the main header it is
/// a malformed codestream, not a missing feature.
#[test]
fn plt_in_the_main_header_is_a_codestream_error() {
    let mut segments = default_header();
    segments.push(seg(marker::PLT, &[0, 0x10]));
    let bytes = codestream(&segments);
    assert!(matches!(err(&bytes), Error::Codestream(_)));
}

/// PLM belongs to the main header alone (A.7.2); in a tile-part header it is
/// a malformed codestream.
#[test]
fn plm_in_the_tile_part_header_is_a_codestream_error() {
    let plm = seg(marker::PLM, &[0]);
    let bytes = assemble_with_tile_markers(&default_header(), &[plm], &[1, 2]);
    assert!(matches!(perr(&bytes), Error::Codestream(_)));
}

/// `p0_05`'s TLM against the codestream itself: the single entry must name
/// tile 0 with the exact `Psot` its SOT declares (`opj_dump` does not print
/// TLM, so the codestream is the reference here — Ptlm and Psot describe the
/// same span, A.4.2 and A.7.1). Returns early if the corpus is absent: it is
/// `exclude`d from the packaged crate.
#[test]
fn tlm_of_p0_05_matches_its_tile_part_length() {
    let path = corpus_dir().join("codestreams/p0_05.j2k");
    let Ok(bytes) = std::fs::read(&path) else {
        return;
    };

    parse(&bytes).expect("p0_05 parses");
    let tlm = tlm_entries(&bytes);
    assert_eq!(tlm.len(), 1, "one tile-part, one entry");
    assert_eq!(tlm[0].tile_index, 0);

    // Psot: bytes 6..10 of the SOT segment (marker, Lsot, Isot precede it).
    let sot = bytes
        .windows(2)
        .position(|w| w == be16(marker::SOT))
        .expect("SOT");
    let psot = u32::from_be_bytes(bytes[sot + 6..sot + 10].try_into().unwrap());
    assert_eq!(tlm[0].length, psot);
}

// --- The quick tile-header check (issue #256) --------------------------------

/// A small deterministic generator (xorshift64*), so the cases below are the
/// same on every run.
struct Rng(u64);

impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 >> 12;
        self.0 ^= self.0 << 25;
        self.0 ^= self.0 >> 27;
        self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
    }

    /// A value in `0..n`.
    fn below(&mut self, n: u64) -> u64 {
        self.next() % n
    }

    fn chance(&mut self, one_in: u64) -> bool {
        self.below(one_in) == 0
    }

    fn transform(&mut self) -> Transform {
        if self.chance(2) {
            Transform::Reversible53
        } else {
            Transform::Irreversible97
        }
    }

    /// Decomposition levels: half the time 0 to 3, half the time anything up
    /// to the 32 the standard allows (Table A-15).
    fn levels(&mut self) -> u8 {
        if self.chance(2) {
            self.below(4) as u8
        } else {
            self.below(33) as u8
        }
    }

    /// A quantization for a component of `levels` decomposition levels: most
    /// often one entry short of, at, or one past the `3·NL + 1` it needs, and
    /// otherwise any count up to the 97 of a 32-level decomposition.
    fn quant(&mut self, levels: u8) -> Qcd {
        let style = match self.below(3) {
            0 => QuantStyle::None,
            1 => QuantStyle::ScalarDerived,
            _ => QuantStyle::ScalarExpounded,
        };
        let needed = 3 * u64::from(levels) + 1;
        let steps = if style == QuantStyle::ScalarDerived {
            1
        } else if self.chance(4) {
            1 + self.below(97)
        } else {
            (needed + self.below(3)).saturating_sub(1).clamp(1, 97)
        };
        Qcd {
            style,
            guard_bits: 2,
            steps: vec![(8, 0); steps as usize],
        }
    }

    fn cod(&mut self, components: usize) -> Cod {
        // Drawn in this order so the generated cases stay the same.
        let decomposition_levels = self.levels();
        let multiple_component_transform = components >= 3 && self.chance(3);
        let transform = self.transform();
        Cod {
            progression: Progression::Lrcp,
            layers: 1,
            use_sop: false,
            use_eph: false,
            multiple_component_transform,
            coding: Coding {
                decomposition_levels,
                code_block_width: 4,
                code_block_height: 4,
                code_block_style: 0,
                transform,
                precinct_sizes: vec![],
            },
        }
    }

    fn coding(&mut self) -> Coding {
        Coding {
            decomposition_levels: self.levels(),
            code_block_width: 4,
            code_block_height: 4,
            code_block_style: 0,
            transform: self.transform(),
            precinct_sizes: vec![],
        }
    }

    fn poc(&mut self) -> Vec<PocVolume> {
        let volume = PocVolume {
            res_start: 0,
            res_end: 1,
            comp_start: 0,
            comp_end: 1,
            layer_end: 1,
            progression: Progression::Lrcp,
        };
        // Mostly none, sometimes past the 32-volume budget on its own. A main
        // header past it is discarded by `main_header`; a tile list past it
        // must be refused by both checks.
        let count = if self.chance(3) { self.below(40) } else { 0 };
        vec![volume; count as usize]
    }

    /// A main header the main-header checks accept, or `None`. One in five
    /// has 255 to 300 components, either side of the 257 at which the
    /// component indices of COC, QCC, RGN and POC take two bytes.
    fn main_header(&mut self) -> Option<MainHeader> {
        let components = if self.chance(5) {
            255 + self.below(46) as usize
        } else {
            1 + self.below(6) as usize
        };
        let comp = SizComponent {
            bit_depth: 8,
            signed: false,
            x_sampling: 1,
            y_sampling: 1,
        };
        let mut siz_components = vec![comp; components];
        if components >= 3 && self.chance(6) {
            siz_components[2].bit_depth = 9;
        }
        let siz = Siz {
            x_size: 8,
            y_size: 8,
            x_offset: 0,
            y_offset: 0,
            tile_width: 8,
            tile_height: 8,
            tile_x_offset: 0,
            tile_y_offset: 0,
            components: siz_components,
        };
        let cod = self.cod(components);
        let qcd = self.quant(cod.coding.decomposition_levels);
        let mut header = MainHeader::new(siz, cod, qcd);
        header.poc = self.poc();
        for index in self.named(components) {
            let coding = (!self.chance(3)).then(|| self.coding());
            let params = &mut header.components[index];
            if let Some(coding) = coding {
                params.coding = coding;
            }
            let levels = params.coding.decomposition_levels;
            if !self.chance(3) {
                header.components[index].quant = self.quant(levels);
            }
        }
        (validate_resolved(&header).is_ok() && header.poc.len() <= MAX_POC_VOLUMES)
            .then_some(header)
    }

    /// Indices among `components`, each at most once, in a random order:
    /// each one in three of a few components, or up to four of many.
    fn named(&mut self, components: usize) -> Vec<usize> {
        let mut out: Vec<usize> = if components <= 8 {
            (0..components).filter(|_| self.chance(3)).collect()
        } else {
            let count = self.below(5);
            let mut picked: Vec<usize> = (0..count)
                .map(|_| self.below(components as u64) as usize)
                .collect();
            picked.sort_unstable();
            picked.dedup();
            picked
        };
        for i in (1..out.len()).rev() {
            out.swap(i, self.below(i as u64 + 1) as usize);
        }
        out
    }

    /// A tile header over `main`. Each quantization is drawn near what the
    /// component it lands on needs, so both verdicts stay common.
    fn tile_header(&mut self, main: &MainHeader) -> TileHeader {
        let components = main.components.len();
        let poc = self.poc();
        let cod = self.chance(2).then(|| self.cod(components));
        let coc: Vec<(usize, Coding)> = (self.named(components).into_iter())
            .map(|i| (i, self.coding()))
            .collect();
        // The levels component `index` takes in the tile.
        let levels = |index: usize| {
            coc.iter()
                .find(|(i, _)| *i == index)
                .map(|(_, c)| c.decomposition_levels)
                .or(cod.as_ref().map(|c| c.coding.decomposition_levels))
                .unwrap_or(main.components[index].coding.decomposition_levels)
        };
        let qcd_levels = cod
            .as_ref()
            .map_or(main.cod.coding.decomposition_levels, |c| {
                c.coding.decomposition_levels
            });
        let qcd = self.chance(2).then(|| self.quant(qcd_levels));
        let qcc = (self.named(components).into_iter())
            .map(|i| (i, self.quant(levels(i))))
            .collect();
        let rgn = (self.named(components).into_iter())
            .map(|i| (i, self.below(8) as u8))
            .collect();
        TileHeader {
            overrides: Overrides {
                cod,
                qcd,
                coc,
                qcc,
                rgn,
            },
            // As the parser sets it: only a nonempty list can start in the
            // first tile-part.
            poc_in_first_part: !poc.is_empty() && self.chance(2),
            poc,
        }
    }
}

/// How often each verdict came up, overall and on the wide cases.
#[derive(Default, Debug)]
struct Verdicts {
    valid: u32,
    invalid: u32,
    many_valid: u32,
    many_invalid: u32,
    deep_valid: u32,
    deep_invalid: u32,
}

impl Verdicts {
    fn add(&mut self, main: &MainHeader, tile: &TileHeader, valid: bool) {
        let many = main.components.len() >= 257;
        let deep = main
            .components
            .iter()
            .map(|c| c.coding.decomposition_levels)
            .chain(
                tile.overrides
                    .cod
                    .iter()
                    .map(|c| c.coding.decomposition_levels),
            )
            .chain(
                tile.overrides
                    .coc
                    .iter()
                    .map(|(_, c)| c.decomposition_levels),
            )
            .any(|levels| levels > 3);
        let count = |yes: &mut u32, no: &mut u32| *if valid { yes } else { no } += 1;
        count(&mut self.valid, &mut self.invalid);
        if many {
            count(&mut self.many_valid, &mut self.many_invalid);
        }
        if deep {
            count(&mut self.deep_valid, &mut self.deep_invalid);
        }
    }

    /// Both verdicts are common overall, with 257 or more components, and
    /// with more than 3 levels, so no side of the check goes untested.
    fn assert_both(&self, overall: u32, wide: u32) {
        let s = self;
        assert!(
            s.valid > overall
                && s.invalid > overall
                && s.many_valid > wide
                && s.many_invalid > wide
                && s.deep_valid > wide
                && s.deep_invalid > wide,
            "{s:?}"
        );
    }
}

/// The quick check `parse_tiles` runs on every tile agrees with resolving the
/// tile's header in full, the old per-tile check, on 20000 random main and
/// tile headers: every mix of tile COD, QCD, COC, QCC, RGN and POC over main
/// headers with and without their own COCs and QCCs, both wavelets, all
/// three quantization styles, the color transform, 0 to 32 decomposition
/// levels, 1 to 97 step entries, up to 300 components, and tile POCs that
/// start in the first tile-part or only in a later one. The quick check is
/// what lets a tile cost its own markers rather than the component count;
/// any rule it gets wrong shows here as a disagreement.
#[test]
fn the_quick_tile_check_agrees_with_the_full_resolution() {
    let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
    let mut verdicts = Verdicts::default();
    let mut cases = 0;
    while cases < 20_000 {
        let Some(main) = rng.main_header() else {
            continue;
        };
        cases += 1;
        let tile = rng.tile_header(&main);
        let full = check_tile_in_full(&main, &tile, 0).is_ok();
        let quick = tile_header_is_valid(&main, &OnceCell::new(), &tile);
        assert_eq!(quick, full, "case {cases}: main {main:?}, tile {tile:?}");
        verdicts.add(&main, &tile, full);
    }
    verdicts.assert_both(2000, 200);
}

// The generated headers written out as marker segments (Annex A), for the
// byte-level check below.

/// A component index: one byte below 257 components, two from 257 on.
fn component_index(index: usize, components: usize) -> Vec<u8> {
    if components < 257 {
        vec![index as u8]
    } else {
        be16(index as u16).to_vec()
    }
}

fn transform_byte(transform: Transform) -> u8 {
    match transform {
        Transform::Irreversible97 => 0,
        Transform::Reversible53 => 1,
    }
}

/// `SPcod`/`SPcoc` after the progression fields: levels, code-block size and
/// style, wavelet. Every generated coding has a maximal precinct partition.
fn coding_bytes(coding: &Coding) -> [u8; 5] {
    [
        coding.decomposition_levels,
        coding.code_block_width,
        coding.code_block_height,
        coding.code_block_style,
        transform_byte(coding.transform),
    ]
}

fn cod_segment(cod: &Cod) -> Vec<u8> {
    let mut b = vec![0, cod.progression as u8];
    b.extend_from_slice(&be16(cod.layers));
    b.push(u8::from(cod.multiple_component_transform));
    b.extend_from_slice(&coding_bytes(&cod.coding));
    seg(marker::COD, &b)
}

fn coc_segment(index: usize, coding: &Coding, components: usize) -> Vec<u8> {
    let mut b = component_index(index, components);
    b.push(0);
    b.extend_from_slice(&coding_bytes(coding));
    seg(marker::COC, &b)
}

/// `Sqcd` and the step table, as `decode_quant` reads them.
fn quant_bytes(qcd: &Qcd) -> Vec<u8> {
    let style = match qcd.style {
        QuantStyle::None => 0,
        QuantStyle::ScalarDerived => 1,
        QuantStyle::ScalarExpounded => 2,
    };
    let mut b = vec![(qcd.guard_bits << 5) | style];
    for &(exponent, mantissa) in &qcd.steps {
        if qcd.style == QuantStyle::None {
            b.push(exponent << 3);
        } else {
            b.extend_from_slice(&be16((u16::from(exponent) << 11) | mantissa));
        }
    }
    b
}

fn qcc_segment(index: usize, qcd: &Qcd, components: usize) -> Vec<u8> {
    let mut b = component_index(index, components);
    b.extend_from_slice(&quant_bytes(qcd));
    seg(marker::QCC, &b)
}

fn rgn_segment(index: usize, shift: u8, components: usize) -> Vec<u8> {
    let mut b = component_index(index, components);
    b.extend_from_slice(&[0, shift]);
    seg(marker::RGN, &b)
}

fn poc_segment(volumes: &[PocVolume], components: usize) -> Vec<u8> {
    let mut b = Vec::new();
    for v in volumes {
        b.push(v.res_start);
        b.extend_from_slice(&component_index(usize::from(v.comp_start), components));
        b.extend_from_slice(&be16(v.layer_end));
        b.push(v.res_end);
        b.extend_from_slice(&component_index(usize::from(v.comp_end), components));
        b.push(v.progression as u8);
    }
    seg(marker::POC, &b)
}

/// The main header's segments: SIZ, COD, QCD, a COC or QCC for each
/// component that differs from the defaults, and any POC.
fn main_segments(main: &MainHeader) -> Vec<Vec<u8>> {
    let siz = &main.siz;
    let components = siz.components.len();
    let mut b = be16(0).to_vec();
    for v in [siz.x_size, siz.y_size, siz.x_offset, siz.y_offset] {
        b.extend_from_slice(&v.to_be_bytes());
    }
    let tiles = [
        siz.tile_width,
        siz.tile_height,
        siz.tile_x_offset,
        siz.tile_y_offset,
    ];
    for v in tiles {
        b.extend_from_slice(&v.to_be_bytes());
    }
    b.extend_from_slice(&be16(components as u16));
    for c in &siz.components {
        let ssiz = (c.bit_depth - 1) | (u8::from(c.signed) << 7);
        b.extend_from_slice(&[ssiz, c.x_sampling, c.y_sampling]);
    }
    let mut segments = vec![
        seg(marker::SIZ, &b),
        cod_segment(&main.cod),
        seg(marker::QCD, &quant_bytes(&main.qcd)),
    ];
    let default = &main.cod.coding;
    for (index, params) in main.components.iter().enumerate() {
        if params.coding != *default {
            segments.push(coc_segment(index, &params.coding, components));
        }
        if params.quant != main.qcd {
            segments.push(qcc_segment(index, &params.quant, components));
        }
    }
    if !main.poc.is_empty() {
        segments.push(poc_segment(&main.poc, components));
    }
    segments
}

/// The codestream for `main` with one tile carrying `tile`'s markers. The
/// coding markers and RGN go in the first tile-part. A POC that starts in
/// the first part puts its first half there and the rest, if any, in a
/// second tile-part; any other POC goes in the second tile-part alone.
fn tile_codestream(main: &MainHeader, tile: &TileHeader) -> Vec<u8> {
    let components = main.components.len();
    let mut first = Vec::new();
    if let Some(cod) = &tile.overrides.cod {
        first.push(cod_segment(cod));
    }
    if let Some(qcd) = &tile.overrides.qcd {
        first.push(seg(marker::QCD, &quant_bytes(qcd)));
    }
    for (index, coding) in &tile.overrides.coc {
        first.push(coc_segment(*index, coding, components));
    }
    for (index, qcd) in &tile.overrides.qcc {
        first.push(qcc_segment(*index, qcd, components));
    }
    for &(index, shift) in &tile.overrides.rgn {
        first.push(rgn_segment(index, shift, components));
    }
    let mut later = Vec::new();
    if tile.poc_in_first_part {
        let split = tile.poc.len().div_ceil(2);
        first.push(poc_segment(&tile.poc[..split], components));
        if split < tile.poc.len() {
            later.push(poc_segment(&tile.poc[split..], components));
        }
    } else if !tile.poc.is_empty() {
        later.push(poc_segment(&tile.poc, components));
    }
    let mut parts = vec![first];
    if !later.is_empty() {
        parts.push(later);
    }

    let mut bytes = be16(marker::SOC).to_vec();
    for s in main_segments(main) {
        bytes.extend_from_slice(&s);
    }
    let data = [0u8];
    for (at, markers) in parts.iter().enumerate() {
        let markers = markers.concat();
        let psot = psot_for(&data) + markers.len() as u32;
        bytes.extend_from_slice(&synth::sot(0, psot, at as u8, parts.len() as u8));
        bytes.extend_from_slice(&markers);
        bytes.extend_from_slice(&be16(marker::SOD));
        bytes.extend_from_slice(&data);
    }
    bytes.extend_from_slice(&be16(marker::EOC));
    bytes
}

/// The same agreement from the bytes: 5000 generated header pairs are written
/// out as codestreams, and `parse` accepts one exactly when the full
/// resolution accepts its pair, reading the main and tile headers back as
/// generated. This reaches what the struct-level check cannot: the two-byte
/// component indices from 257 components on, and a tile POC split across
/// tile-parts or carried only by a later one.
#[test]
fn the_quick_tile_check_agrees_with_the_full_resolution_from_the_bytes() {
    let mut rng = Rng(0xD1B5_4A32_D192_ED03);
    let mut verdicts = Verdicts::default();
    let mut cases = 0;
    while cases < 5_000 {
        let Some(main) = rng.main_header() else {
            continue;
        };
        cases += 1;
        let tile = rng.tile_header(&main);
        let full = check_tile_in_full(&main, &tile, 0);
        let bytes = tile_codestream(&main, &tile);
        match parse(&bytes) {
            Ok(cs) => {
                assert!(full.is_ok(), "case {cases}: parsed, but {full:?}");
                assert_eq!(cs.header, main, "case {cases}: main header");
                assert_eq!(cs.tiles[0].header, tile, "case {cases}: tile header");
            }
            Err(e) => assert!(full.is_err(), "case {cases}: refused with {e}"),
        }
        verdicts.add(&main, &tile, full.is_ok());
    }
    verdicts.assert_both(500, 50);
}

/// A tile-part COC alone, with no tile COD or QCD, still overrides the coding
/// of the component it names: the tile decodes with 2 levels where the main
/// header has 5. A tile with markers of its own is never the main header
/// borrowed.
#[test]
fn a_tile_part_coc_alone_overrides_its_component() {
    let coc = seg(marker::COC, &coc_body(&[0], 0, 2, 4, 4, 0, 1));
    let bytes = assemble_with_tile_markers(&default_header(), &[coc], &[1, 2]);
    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.components[0].coding.decomposition_levels, 2);
    assert_eq!(cs.header.components[0].coding.decomposition_levels, 5);
}

/// A tile-part QCC alone overrides the quantization of the component it
/// names, as the COC does its coding.
#[test]
fn a_tile_part_qcc_alone_overrides_its_component() {
    let qcc = seg(marker::QCC, &{
        let mut b = vec![0u8];
        b.extend_from_slice(&qcd_none(2, &[9; 16]));
        b
    });
    let bytes = assemble_with_tile_markers(&default_header(), &[qcc], &[1, 2]);
    let cs = parse(&bytes).expect("parse");
    let tile = cs.tile_header(0).expect("resolve tile 0");
    assert_eq!(tile.components[0].quant.steps[0], (9, 0));
    assert_eq!(cs.header.components[0].quant.steps[0], (8, 0));
}

/// A.6 allows one COC and one QCC per component in a tile-part header, as in
/// the main header; a second one for the same component is malformed.
#[test]
fn a_second_tile_part_coc_or_qcc_for_one_component_is_a_codestream_error() {
    let coc = seg(marker::COC, &coc_body(&[0], 0, 2, 4, 4, 0, 1));
    let qcc = seg(marker::QCC, &{
        let mut b = vec![0u8];
        b.extend_from_slice(&qcd_none(2, &[8; 16]));
        b
    });
    for (name, marker) in [("COC", coc), ("QCC", qcc)] {
        let bytes =
            assemble_with_tile_markers(&default_header(), &[marker.clone(), marker], &[1, 2]);
        match perr(&bytes) {
            Error::Codestream(m) => assert!(m.message().contains("duplicate"), "{name}: {m}"),
            other => panic!("{name}: {other}"),
        }
    }
}

/// `ST = 0` implies each entry's tile by its place among every TLM entry,
/// across markers, so in a one-tile grid a second entry, even in a second
/// marker, names tile 1, which the grid does not hold.
#[test]
fn tlm_implied_indices_count_across_markers() {
    let mut segments = default_header();
    segments.push(seg(marker::TLM, &tlm_body(0x00, &[0x12, 0x34])));
    segments.push(seg(marker::TLM, &tlm_body(0x00, &[0x12, 0x34])));
    match err(&codestream(&segments)) {
        Error::Marker(m) => assert!(m.message().contains("names tile 1"), "{m}"),
        other => panic!("{other}"),
    }
}

/// Every duplicate-marker message, in both headers, word for word, through
/// `crate::decode`. The main header and the tile-part header share one
/// override reader; the tile-part header's messages carry the
/// "in the tile-part header" suffix and the main header's do not.
///
/// The last two cases pin which fault a second, malformed COD reports: the
/// main header refuses the duplicate before it reads the body, and a tile-part
/// header reads the body first.
#[test]
fn duplicate_override_messages_are_pinned_for_both_headers() {
    let coc = seg(marker::COC, &coc_body(&[0], 0, 2, 4, 4, 0, 1));
    let qcc = seg(marker::QCC, &{
        let mut b = vec![0u8];
        b.extend_from_slice(&qcd_none(2, &[8; 16]));
        b
    });
    let rgn = seg(marker::RGN, &rgn_body(&[0], 0, 3));
    let cod = seg(marker::COD, &cod_default(1));
    let qcd = seg(marker::QCD, &qcd_none(2, &[8; 16]));
    // A COD with the reserved progression order 9.
    let bad_cod = seg(marker::COD, &cod_body(0, 9, 1, 0, 5, 4, 4, 0, 1));

    let main_with = |extra: &[Vec<u8>]| {
        let mut header = default_header();
        header.extend_from_slice(extra);
        assemble_with_tile_markers(&header, &[], &[1, 2])
    };
    let tile_with =
        |markers: &[Vec<u8>]| assemble_with_tile_markers(&default_header(), markers, &[1, 2]);
    let twice = |m: &Vec<u8>| [m.clone(), m.clone()];

    let rows: Vec<(&str, Vec<u8>, &str)> = vec![
        (
            "main COD",
            main_with(std::slice::from_ref(&cod)),
            "duplicate `COD` marker",
        ),
        (
            "main QCD",
            main_with(std::slice::from_ref(&qcd)),
            "duplicate `QCD` marker",
        ),
        (
            "main COC",
            main_with(&twice(&coc)),
            "duplicate `COC` marker for component 0",
        ),
        (
            "main QCC",
            main_with(&twice(&qcc)),
            "duplicate `QCC` marker for component 0",
        ),
        (
            "main RGN",
            main_with(&twice(&rgn)),
            "duplicate `RGN` marker for component 0",
        ),
        (
            "tile COD",
            tile_with(&twice(&cod)),
            "duplicate `COD` marker in the tile-part header",
        ),
        (
            "tile QCD",
            tile_with(&twice(&qcd)),
            "duplicate `QCD` marker in the tile-part header",
        ),
        (
            "tile COC",
            tile_with(&twice(&coc)),
            "duplicate `COC` marker for component 0 in the tile-part header",
        ),
        (
            "tile QCC",
            tile_with(&twice(&qcc)),
            "duplicate `QCC` marker for component 0 in the tile-part header",
        ),
        (
            "tile RGN",
            tile_with(&twice(&rgn)),
            "duplicate `RGN` marker for component 0 in the tile-part header",
        ),
        (
            "later tile-part RGN",
            tile_parts(
                &default_header(),
                &[(0, 0, 2, vec![]), (0, 1, 2, vec![rgn.clone()])],
            ),
            "marker 0xFF5E appears in a tile-part header other than the first; \
             the coding-parameter overrides belong to the first tile-part of a tile",
        ),
        (
            "main malformed second COD",
            main_with(std::slice::from_ref(&bad_cod)),
            "duplicate `COD` marker",
        ),
    ];
    for (name, bytes, expected) in rows {
        match crate::decode(&bytes) {
            Err(Error::Codestream(m)) => assert_eq!(m.message(), expected, "{name}"),
            other => panic!("{name}: {other:?}"),
        }
    }
    match crate::decode(&tile_with(&[cod, bad_cod])) {
        Err(Error::Marker(m)) => assert_eq!(m.message(), "reserved progression order 9"),
        other => panic!("tile malformed second COD: {other:?}"),
    }
}

// --- CAP, CPF and the block-coder guard (issue #340) -----------------------

/// `Pcap` with only bit 2 (from the MSB) set: a Part 2 capability.
const PART2_PCAP: u32 = 1 << 30;

/// A CAP body: `Pcap`, then one `Ccap` word per set bit.
fn cap_body(pcap: u32, ccap: &[u16]) -> Vec<u8> {
    let mut b = pcap.to_be_bytes().to_vec();
    for &word in ccap {
        b.extend_from_slice(&be16(word));
    }
    b
}

/// A CAP body that signals Part 15 only, with `Ccap15`.
fn cap15(ccap15: u16) -> Vec<u8> {
    cap_body(PCAP_PART15, &[ccap15])
}

/// `Ccap15` bit 12 at 0 says the codestream holds no `RGN` (T.814 A.3.4),
/// so a main-header `RGN` is refused, before or after the `CAP`. With the
/// bit set, or with no Part 15 `CAP` at all, the same `RGN` is read.
#[test]
fn a_main_header_rgn_against_a_rgn_free_cap_is_codestream() {
    let rgn = || seg(marker::RGN, &rgn_body(&[0], 0, 4));
    let cap = |ccap15| seg(marker::CAP, &cap15(ccap15));
    let [siz, cod, qcd] = <[Vec<u8>; 3]>::try_from(default_header()).unwrap();
    for segments in [
        [siz.clone(), cap(0x0003), rgn(), cod.clone(), qcd.clone()],
        [siz.clone(), rgn(), cap(0x0003), cod.clone(), qcd.clone()],
        [siz.clone(), rgn(), cod.clone(), qcd.clone(), cap(0x0003)],
    ] {
        let e = err(&codestream(&segments));
        assert!(
            matches!(&e, Error::Codestream(m) if m.message().contains("`Ccap15` bit 12 is 0")),
            "got {e:?}"
        );
    }
    for segments in [
        [siz.clone(), cap(0x1003), rgn(), cod.clone(), qcd.clone()],
        [siz.clone(), rgn(), cod.clone(), qcd.clone(), cap(0x1003)],
    ] {
        assert_eq!(parsed(&segments).components[0].roi_shift, 4);
    }
    let header = parsed(&[
        siz.clone(),
        seg(marker::CAP, &cap_body(0, &[])),
        rgn(),
        cod,
        qcd,
    ]);
    assert_eq!(header.components[0].roi_shift, 4);
}

/// A tile-part `RGN` is held to the main header's `CAP` the same way.
#[test]
fn a_tile_part_rgn_against_a_rgn_free_cap_is_codestream() {
    let rgn = seg(marker::RGN, &rgn_body(&[0], 0, 4));
    let mut header = default_header();
    header.insert(1, seg(marker::CAP, &cap15(0x0003)));
    let bytes = assemble_with_tile_markers(&header, std::slice::from_ref(&rgn), &[1, 2]);
    let e = parse(&bytes).expect_err("RGN-free CAP");
    assert!(
        matches!(&e, Error::Codestream(m) if m.message().contains("`Ccap15` bit 12 is 0")),
        "got {e:?}"
    );

    header[1] = seg(marker::CAP, &cap15(0x1003));
    let bytes = assemble_with_tile_markers(&header, &[rgn], &[1, 2]);
    let cs = parse(&bytes).expect("CAP allows RGN");
    assert_eq!(cs.tile_header(0).unwrap().components[0].roi_shift, 4);
}

/// A CAP and a CPF beside Part 1 code-blocks parse and are kept: the style
/// bits, not CAP, decide the block coder.
#[test]
fn cap_and_cpf_are_read_and_kept() {
    let header = parsed(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::CAP, &cap15(0x0003)),
        seg(marker::CPF, &[0, 2]),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.ccap15, Some(markers::Ccap15(0x0003)));
    assert_eq!(header.cpf, Some(markers::Cpf { words: vec![2] }));

    // A CAP that signals no capability at all carries no `Ccap` word.
    let header = parsed(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::CAP, &cap_body(0, &[])),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!((header.ccap15, header.cpf), (None, None));

    // No CAP, no CPF.
    let header = parsed(&default_header());
    assert_eq!((header.ccap15, header.cpf), (None, None));
}

#[test]
fn a_cap_whose_length_disagrees_with_pcap_is_marker() {
    for body in [
        vec![],
        vec![0, 2],
        vec![0, 2, 0, 0],               // Part 15 set, no `Ccap15`
        cap_body(0, &[3]),              // no part set, one word
        cap_body(PCAP_PART15, &[3, 3]), // one part set, two words
    ] {
        let e = err(&header_with(&seg(marker::CAP, &body)));
        let Error::Marker(message) = &e else {
            panic!("{body:?}: got {e:?}")
        };
        assert!(message.message().contains("`CAP`"), "{message}");
    }
}

#[test]
fn a_cap_signaling_another_part_is_unsupported_naming_it() {
    for (pcap, part) in [(PART2_PCAP, 2), (PCAP_PART15 | 1 << 15, 17)] {
        let words = vec![0; pcap.count_ones() as usize];
        let e = err(&header_with(&seg(marker::CAP, &cap_body(pcap, &words))));
        let Error::Unsupported(message) = &e else {
            panic!("{pcap:#010X}: got {e:?}")
        };
        assert!(
            message
                .message()
                .contains(&format!("ISO/IEC 15444-{part},")),
            "{message}"
        );
    }
    // Part 1 has no extended capabilities and no part past 17 exists, so
    // those bits are named as bits, not as parts.
    for (pcap, bit) in [(1u32 << 31, 1), (1 << 14, 18), (1, 32)] {
        let words = vec![0; pcap.count_ones() as usize];
        let e = err(&header_with(&seg(marker::CAP, &cap_body(pcap, &words))));
        let Error::Unsupported(message) = &e else {
            panic!("{pcap:#010X}: got {e:?}")
        };
        assert!(
            message.message().contains(&format!(
                "`Pcap` bit {bit}, counted from the MSB, which names no part"
            )),
            "{message}"
        );
    }
}

/// MULTIHT is refused; the HTONLY, HTDECLARED and MIXED coder sets are read,
/// with every other `Ccap15` bit kept as it is, reserved ones included.
#[test]
fn multiht_is_unsupported_and_every_other_ccap15_is_kept() {
    let e = err(&header_with(&seg(marker::CAP, &cap15(0x2000 | 0x0003))));
    let Error::Unsupported(message) = &e else {
        panic!("got {e:?}")
    };
    assert!(message.message().contains("MULTIHT"), "{message}");

    for ccap15 in [0x0000, 0x8000, 0xC000, 0x4000, 0x07C0, 0xDFFF] {
        let header = parsed(&[
            seg(marker::SIZ, &one_component()),
            seg(marker::CAP, &cap15(ccap15)),
            seg(marker::COD, &cod_default(1)),
            seg(marker::QCD, &qcd_none(2, &[8; 16])),
        ]);
        assert_eq!(header.ccap15, Some(markers::Ccap15(ccap15)));
    }
}

#[test]
fn a_second_cap_or_cpf_is_codestream() {
    for (code, body) in [(marker::CAP, cap15(3)), (marker::CPF, vec![0, 2])] {
        let twice = [seg(code, &body), seg(code, &body)].concat();
        let e = err(&header_with(&twice));
        let Error::Codestream(message) = &e else {
            panic!("{code:#06X}: got {e:?}")
        };
        assert!(message.message().contains("duplicate"), "{message}");
    }
}

#[test]
fn a_cpf_that_is_not_whole_words_is_marker() {
    for body in [&[][..], &[0][..], &[0, 2, 0][..]] {
        let e = err(&header_with(&seg(marker::CPF, body)));
        let Error::Marker(message) = &e else {
            panic!("{body:?}: got {e:?}")
        };
        assert!(message.message().contains("`CPF`"), "{message}");
    }
    // Several words, the last zero, are read as they are: T.814 A.6 asks the
    // encoder for the shortest form, and the profile changes no sample.
    let header = parsed(&[
        seg(marker::SIZ, &one_component()),
        seg(marker::CPF, &[0, 2, 0, 0]),
        seg(marker::COD, &cod_default(1)),
        seg(marker::QCD, &qcd_none(2, &[8; 16])),
    ]);
    assert_eq!(header.cpf.map(|c| c.words), Some(vec![2, 0]));
}

#[test]
fn cap_or_cpf_in_a_tile_part_header_is_codestream() {
    for (code, body) in [(marker::CAP, cap15(3)), (marker::CPF, vec![0, 2])] {
        let bytes = assemble_with_tile_markers(&default_header(), &[seg(code, &body)], &[0]);
        let e = perr(&bytes);
        let Error::Codestream(message) = &e else {
            panic!("{code:#06X}: got {e:?}")
        };
        assert!(message.message().contains("tile-part header"), "{message}");
    }
}

/// The block-coder guard reads the style bits alone, whether or not the
/// codestream signals Part 15: with a CAP, and with none and `Rsiz` 0. An HT
/// or MIXED style parses either way and the mixed-mode bit without the HT
/// bit is refused either way. OpenJPEG 2.5.0 decodes the HT shapes, reading
/// the style bits alone.
#[test]
fn an_ht_or_mixed_style_parses_and_bit_7_alone_is_unsupported_with_or_without_cap() {
    for style in [0x40, 0x48, 0xC0, 0xC8, 0x80] {
        for cap in [None, Some(seg(marker::CAP, &cap15(0x0003)))] {
            let mut segments = vec![seg(marker::SIZ, &one_component())];
            segments.extend(cap.clone());
            segments.push(seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, style, 1)));
            segments.push(seg(marker::QCD, &qcd_none(2, &[8; 16])));
            let bytes = codestream(&segments);
            if style & 0x40 != 0 {
                let (header, _, _) = parse_main_header(&bytes)
                    .unwrap_or_else(|e| panic!("{style:#04X}, CAP {}: {e:?}", cap.is_some()));
                assert_eq!(header.cod.coding.code_block_style, style);
                continue;
            }
            let e = err(&bytes);
            let Error::Unsupported(message) = &e else {
                panic!("{style:#04X}, CAP {}: got {e:?}", cap.is_some())
            };
            assert!(
                message
                    .message()
                    .contains("`COD` code-block style (HTJ2K mixed-mode"),
                "{message}"
            );
        }
    }
}

/// A tile-part COD or COC goes through the same guard as the main header's:
/// the mixed-mode bit alone is `Unsupported`, and MIXED with bypass or
/// termall is `Marker`.
#[test]
fn a_tile_part_style_goes_through_the_block_coder_guard() {
    for (style, unsupported) in [(0x80, true), (0xC1, false), (0xC4, false)] {
        let cod = seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, style, 1));
        let coc = seg(marker::COC, &coc_body(&[0], 0, 5, 4, 4, style, 1));
        for (name, tile_marker) in [("`COD`", cod), ("`COC`", coc)] {
            let bytes = assemble_with_tile_markers(&default_header(), &[tile_marker], &[0]);
            let e = perr(&bytes);
            let message = match (&e, unsupported) {
                (Error::Unsupported(m), true) => {
                    assert!(m.message().contains("mixed-mode"), "{m}");
                    m
                }
                (Error::Marker(m), false) => {
                    assert!(m.message().contains("MIXED"), "{m}");
                    m
                }
                _ => panic!("{style:#04X} {name}: got {e:?}"),
            };
            assert!(message.message().contains(name), "{message}");
        }
    }
}

/// The guard runs as each segment is read, so a main header cut after a COD
/// it refuses is refused for the style, not reported as incomplete: more
/// bytes could not make it decode.
#[test]
fn a_cut_header_holding_a_refused_style_is_refused_not_incomplete() {
    for style in [0x80, 0xC1] {
        let mut bytes = be16(marker::SOC).to_vec();
        bytes.extend_from_slice(&seg(marker::SIZ, &one_component()));
        bytes.extend_from_slice(&seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, style, 1)));
        // A QCD cut inside its body.
        bytes.extend_from_slice(&seg(marker::QCD, &qcd_none(2, &[8; 16]))[..6]);
        let e = err(&bytes);
        assert!(
            matches!(e, Error::Unsupported(_) | Error::Marker(_)),
            "{style:#04X}: got {e:?}"
        );
    }
}

/// `Ccap15` bits 15-14 at `10` (HTDECLARED, ISO/IEC 15444-15 A.3.2) say no
/// code-block style sets bit 7, so a MIXED style under them is `Codestream`,
/// whether `CAP` comes before or after the COD, or a COC or a tile-part
/// marker sets it. `00` (HTONLY) allows a MIXED style (A.3.2 NOTE), and `11`
/// and no `CAP` allow MIXED.
#[test]
fn a_mixed_style_under_an_htdeclared_cap_is_codestream() {
    let cap = |ccap15| seg(marker::CAP, &cap15(ccap15));
    let mixed_cod = seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, 0xC0, 1));
    let qcd = seg(marker::QCD, &qcd_none(2, &[8; 16]));
    let siz = seg(marker::SIZ, &one_component());
    let refused = |bytes: &[u8], e: Error| {
        let Error::Codestream(message) = &e else {
            panic!("got {e:?} for {bytes:02X?}")
        };
        assert!(
            message.message().contains("HTDECLARED") || message.message().contains("15-14"),
            "{message}"
        );
    };
    for header in [
        vec![siz.clone(), cap(0x8000), mixed_cod.clone(), qcd.clone()],
        vec![siz.clone(), mixed_cod.clone(), cap(0x8000), qcd.clone()],
        vec![
            siz.clone(),
            cap(0x8000),
            seg(marker::COD, &cod_default(1)),
            seg(marker::COC, &coc_body(&[0], 0, 5, 4, 4, 0xC0, 1)),
            qcd.clone(),
        ],
    ] {
        let bytes = codestream(&header);
        refused(&bytes, err(&bytes));
    }
    // In a tile-part header: the tile's resolved style is checked.
    let main = vec![
        siz.clone(),
        cap(0x8000),
        seg(marker::COD, &cod_default(1)),
        qcd.clone(),
    ];
    let tile = seg(marker::COC, &coc_body(&[0], 0, 5, 4, 4, 0xC0, 1));
    let bytes = assemble_with_tile_markers(&main, &[tile], &[0]);
    let cs = parse(&bytes).expect("parse");
    refused(&bytes, cs.tile_header(0).expect_err("resolve tile 0"));
    // HTDECLARED with an HT or Part 1 style is fine, and so are the other
    // coder sets with MIXED.
    for (ccap15, style) in [
        (0x8000, 0x40),
        (0x8000, 0x00),
        (0x0000, 0xC0),
        (0xC000, 0xC0),
    ] {
        parsed(&[
            siz.clone(),
            cap(ccap15),
            seg(marker::COD, &cod_body(0, 0, 1, 0, 5, 4, 4, style, 1)),
            qcd.clone(),
        ]);
    }
}

/// `Ccap15` and `CPFnum` of the HT conformance codestreams, as the
/// `jp2codestream.py` logs of the WG1 htj2k-codestreams repository record them
/// (commit f6b9ede, `descriptions_htj2k_profile0/` and `_profile1/`,
/// `<name>syntax.txt`: "Extended capabilities for part 15" and
/// "Corresponding Profile"). `ds0_ht_06_b15` has no log. `None` is a file
/// with no CPF.
#[rustfmt::skip]
const HT_LOGS: &[(&str, u16, Option<u64>)] = &[
    ("ds0_hm_06_b11", 0xd823, Some(2)), ("ds0_hm_06_b18", 0xd82a, Some(2)),
    ("ds0_hm_15_b8", 0xd800, Some(1)), ("ds0_ht_01_b11", 0x0003, Some(1)),
    ("ds0_ht_02_b11", 0x0023, Some(1)), ("ds0_ht_02_b12", 0x0024, Some(1)),
    ("ds0_ht_03_b11", 0x1803, Some(1)), ("ds0_ht_03_b14", 0x1806, Some(1)),
    ("ds0_ht_04_b11", 0x0023, Some(1)), ("ds0_ht_04_b12", 0x0024, Some(1)),
    ("ds0_ht_05_b11", 0x0023, Some(1)), ("ds0_ht_05_b12", 0x0024, Some(1)),
    ("ds0_ht_06_b11", 0x1823, Some(2)), ("ds0_ht_06_b18", 0x182a, Some(2)),
    ("ds0_ht_07_b11", 0x0803, Some(1)), ("ds0_ht_07_b15", 0x0807, Some(1)),
    ("ds0_ht_07_b16", 0x0808, Some(1)), ("ds0_ht_08_b11", 0x0003, Some(1)),
    ("ds0_ht_08_b15", 0x0007, Some(1)), ("ds0_ht_08_b16", 0x0008, Some(1)),
    ("ds0_ht_09_b11", 0x0023, None), ("ds0_ht_10_b11", 0x0003, Some(1)),
    ("ds0_ht_11_b10", 0x0002, Some(1)), ("ds0_ht_12_b11", 0x0003, Some(1)),
    ("ds0_ht_13_b11", 0x1003, Some(1)), ("ds0_ht_14_b11", 0x0003, None),
    ("ds0_ht_15_b11", 0x1803, Some(1)), ("ds0_ht_15_b14", 0x1806, Some(1)),
    ("ds0_ht_16_b11", 0x0003, None), ("ds1_ht_01_b11", 0x0023, Some(2)),
    ("ds1_ht_01_b12", 0x0024, Some(2)), ("ds1_ht_02_b11", 0x0823, Some(2)),
    ("ds1_ht_02_b12", 0x0824, Some(2)), ("ds1_ht_03_b11", 0x0023, Some(2)),
    ("ds1_ht_03_b12", 0x0024, Some(2)), ("ds1_ht_04_b9", 0x0821, Some(2)),
    ("ds1_ht_05_b11", 0x0823, Some(2)), ("ds1_ht_06_b11", 0x0023, Some(2)),
    ("ds1_ht_07_b11", 0x0003, Some(2)), ("hifi_ht1_02", 0x0026, None),
];

/// The magnitude bound `B` that `Ccap15` bits 0-4 signal (T.814 A.3.7).
fn magnitude_bound(ccap15: u16) -> u32 {
    markers::Ccap15(ccap15).magnitude_bound()
}

/// `B` at each edge of A.3.7's cases, and in Table 4 (8.7.3): MAGB0 is 8,
/// MAGB19 is 27, MAGB20 is 31, MAGB30 is 71 and MAGB31 is 74. The other
/// bits do not change it.
#[test]
fn ccap15_magnitude_bound_follows_a_3_7() {
    for (p, b) in [
        (0, 8),
        (1, 9),
        (3, 11),
        (19, 27),
        (20, 31),
        (21, 35),
        (30, 71),
        (31, 74),
    ] {
        assert_eq!(magnitude_bound(p), b, "P = {p}");
        assert_eq!(
            magnitude_bound(0xFFE0 | p),
            b,
            "P = {p} with every other bit set"
        );
    }
}

/// `Ccap15` bit 12 alone says whether `RGN` markers may be present.
#[test]
fn ccap15_bit_12_is_the_rgn_bit() {
    assert!(markers::Ccap15(0x1000).rgn());
    assert!(!markers::Ccap15(0xEFFF).rgn());
}

/// `CPFnum = -1 + Σ Pcpf_i · 2^(16(i-1))` (T.814 A.6), for the short `CPF`s
/// of the corpus.
fn cpf_number(cpf: &markers::Cpf) -> u64 {
    assert!(cpf.words.len() <= 4, "{cpf:?}");
    let sum = (cpf.words.iter().rev()).fold(0u64, |acc, &w| (acc << 16) | u64::from(w));
    sum - 1
}

/// Every HT conformance codestream: its CAP and CPF decode to the values its
/// log records, and the whole header parses, the MIXED files' included.
#[test]
fn the_ht_corpus_decodes_its_cap_and_cpf_and_parses() {
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/conformance/ht/codestreams");
    let mut names: Vec<String> = std::fs::read_dir(&dir)
        .unwrap_or_else(|e| panic!("{}: {e}", dir.display()))
        .map(|entry| {
            let name = entry.unwrap().file_name().into_string().unwrap();
            name.strip_suffix(".j2k")
                .expect("only .j2k files")
                .to_owned()
        })
        .collect();
    names.sort();
    assert_eq!(names.len(), 41);

    let mut decoded = std::collections::BTreeMap::new();
    for name in &names {
        let bytes = std::fs::read(dir.join(format!("{name}.j2k"))).unwrap();
        let (segments, end) = walk_main_header(&bytes).expect(name);
        end.expect(name);
        let caps: Vec<_> = segments.iter().filter(|s| s.code == marker::CAP).collect();
        assert_eq!(caps.len(), 1, "{name}");
        let ccap15 = decode_cap(Cursor::new(caps[0].body))
            .unwrap_or_else(|e| panic!("{name}: {e}"))
            .unwrap_or_else(|| panic!("{name}: CAP signals no Part 15 capability"))
            .0;
        let cpf = (segments.iter())
            .find(|s| s.code == marker::CPF)
            .map(|s| cpf_number(&decode_cpf(Cursor::new(s.body)).expect(name)));
        decoded.insert(name.as_str(), (ccap15, cpf));

        if let Err(e) = parse_main_header(&bytes) {
            panic!("{name}: {e:?}");
        }
    }

    for &(name, ccap15, cpf) in HT_LOGS {
        assert_eq!(decoded.remove(name), Some((ccap15, cpf)), "{name}");
    }
    // The one file with no log: its bound is the 15 of its name, and its
    // `_b11` and `_b18` siblings differ from it only in that bound.
    let (b15, cpf) = decoded.remove("ds0_ht_06_b15").expect("ds0_ht_06_b15");
    assert_eq!(magnitude_bound(b15), 15);
    for (sibling, bound) in [("ds0_ht_06_b11", 11), ("ds0_ht_06_b18", 18)] {
        let &(_, ccap15, sibling_cpf) = HT_LOGS.iter().find(|e| e.0 == sibling).unwrap();
        assert_eq!(magnitude_bound(ccap15), bound, "{sibling}");
        assert_eq!(ccap15 & !0x1F, b15 & !0x1F, "{sibling}");
        assert_eq!(sibling_cpf, cpf, "{sibling}");
    }
    assert!(decoded.is_empty(), "files with no log: {decoded:?}");
}