rust-j2k 0.3.0

Pure-Rust JPEG 2000 (ISO/IEC 15444) codec, built GRIB2-decode-first toward OpenJPEG-level coverage.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
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
//! Stage 1 — codestream parsing (ISO/IEC 15444-1 Annex A).
//!
//! Walks the marker segments of a raw J2K codestream: the main header
//! (SIZ / COD / QCD, plus optional COC / QCC / RGN / TLM / PLM / COM), then
//! the tile-parts (SOT, optional RGN / PLT / COM, SOD, data). Produces a
//! [`MainHeader`] of decode parameters and the byte ranges of each tile's
//! packet data — everything the later stages need, with no interpretation of
//! the entropy-coded bytes yet.
//!
//! The main header is located before it is judged: [`walk_main_header`] finds
//! every marker segment without caring what the decoder supports, and
//! [`parse_main_header`] then interprets them. That split is what lets a
//! codestream be traversed past a feature we cannot decode, and is what makes
//! the reserved segment-less markers and unknown segments handleable at all.

pub mod markers;

use std::borrow::Cow;

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

/// Parsed main-header decode parameters. COD/QCD carry the codestream-wide
/// defaults; [`components`](Self::components) carries each component's effective
/// parameters after any COC/QCC override and any RGN maxshift — the main
/// header's, replaced by the tile-part header's where one appears (A.6.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MainHeader {
    pub siz: Siz,
    pub cod: Cod,
    pub qcd: Qcd,
    /// Effective coding and quantization parameters per component, in SIZ order:
    /// COD/QCD's defaults with any COC/QCC override already applied. Every stage
    /// past the header reads these rather than [`cod`](Self::cod) or
    /// [`qcd`](Self::qcd), which hold the codestream-wide defaults.
    pub components: Vec<ComponentParams>,
    /// Tile-part lengths from any TLM markers, in marker order; empty when the
    /// codestream carries none. Informational (A.7.1): decoding does not use
    /// them, so they are recorded for callers to check, not consulted.
    pub tlm: Vec<TlmEntry>,
    /// The progression volumes of any `POC` marker, in order; empty when the
    /// codestream carries none, in which case the packet order is [`cod`]'s
    /// single progression over every axis (A.6.6). A tile-part `POC` replaces
    /// this for its tile, the same way a tile COD replaces the coding style.
    ///
    /// [`cod`]: Self::cod
    pub poc: Vec<PocVolume>,
    /// `(Xcrg, Ycrg)` sub-pixel registration offsets per component, in SIZ
    /// order, from a `CRG` marker; empty when the codestream carries none
    /// (A.9.1). Informational: the offsets say how a display should register the
    /// components against one another, in units of `1/65536` of the reference-grid
    /// step, and do not change the decoded samples — so they are recorded for a
    /// caller to act on, not resampled here (OpenJPEG likewise reads past them).
    pub crg: Vec<(u16, u16)>,
}

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

/// One tile of the image: its index in the tile grid, the decode parameters in
/// force inside it, and its packet data.
///
/// A tile can be split across several tile-parts, interleaved with other tiles'
/// (A.4.2). They are gathered here: `data` is every one of this tile's
/// tile-parts' packet bytes, concatenated in `TPsot` order. Concatenation is
/// exact, not an approximation — a tile-part holds a whole number of packets
/// (B.9), so no packet straddles the seam — and it is what OpenJPEG does
/// (`opj_j2k_read_sod` appends each tile-part into the tile's buffer). It stays
/// borrowed for the overwhelmingly common single-part tile, and only copies when
/// there is more than one part to join.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tile<'a> {
    pub index: u32,
    /// This tile's own tile-part-header markers, as parsed. Resolve them against
    /// the main header with [`Codestream::tile_header`] to get the parameters the
    /// tile decodes under.
    ///
    /// They are *not* resolved into a whole header here, because a header is
    /// sized by the component count and there can be tens of thousands of tiles:
    /// materializing one per tile would cost `tiles × components`, which a header
    /// under 50 KB can drive into the gigabytes. Resolved one tile at a time, the
    /// cost is `tiles + components`.
    pub header: TileHeader,
    pub data: Cow<'a, [u8]>,
    /// The tile's packed packet headers (`PPT`), concatenated across its
    /// tile-parts; empty when the headers are inline with the bodies. When
    /// non-empty, Tier-2 reads every packet header from here and every packet
    /// body from [`data`](Self::data) (A.7.5).
    pub packed_headers: Vec<u8>,
}

/// A parsed codestream: the main header plus every tile, in tile-index order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Codestream<'a> {
    pub header: MainHeader,
    pub tiles: Vec<Tile<'a>>,
}

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

/// The JP2 signature box that opens every JP2 file (ISO/IEC 15444-1 Annex I.5.1):
/// a 12-byte box of type `jP  ` whose contents are the fixed `0D 0A 87 0A`.
const JP2_SIGNATURE: [u8; 12] = [
    0x00, 0x00, 0x00, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A,
];

/// Parse a raw codestream (must start with SOC, end with EOC).
///
/// Rejects the JP2 box wrapper (callers pass the bare codestream) and anything
/// outside the decoded feature set — HTJ2K, Part 2 extensions, unknown markers
/// — with [`Error::Unsupported`].
///
/// [`Error::Unsupported`]: crate::Error::Unsupported
pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
    // A JP2 file is valid JPEG 2000, just not the bare codestream this decoder
    // reads, so say which it is rather than complain about a missing SOC.
    if bytes.starts_with(&JP2_SIGNATURE) {
        return Err(Error::Unsupported(
            "JP2 file format wrapper; pass the contained codestream (the `jp2c` box contents)"
                .into(),
        ));
    }

    let (header, sot_offset, ppm) = parse_main_header(bytes)?;
    let tiles = walk_tiles(bytes, sot_offset, &header, &ppm)?;
    let codestream = Codestream { header, tiles };

    // Resolve every tile's header once, here, so a malformed tile-part header is
    // a parse error rather than a surprise partway through a decode. Each one is
    // dropped again immediately: they are sized by the component count, and a
    // codestream can declare tens of thousands of tiles.
    for index in 0..codestream.tiles.len() {
        let tile = codestream.tile_header(index)?;

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

    Ok(codestream)
}

/// A tile-part header's own markers (A.4.2): the tile-level COD/QCD defaults and
/// the per-component COC/QCC/RGN overrides that layer over them. Only the *first*
/// tile-part of a tile may carry any of these, so one per tile is enough however
/// many parts the tile is split into.
///
/// The per-component overrides are **sparse** — only the components a marker
/// actually names. Almost every tile carries none at all, and a dense vector per
/// tile would cost `tiles × components` for nothing.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct TileHeader {
    cod: Option<Cod>,
    qcd: Option<Qcd>,
    coc: Vec<(usize, Coding)>,
    qcc: Vec<(usize, Qcd)>,
    rgn: Vec<(usize, u8)>,
    /// A tile-part `POC`'s progression volumes; empty when the tile carries none,
    /// in which case the main header's `POC` (or its single COD order) governs.
    poc: Vec<PocVolume>,
}

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

/// Walk every tile-part from the first `SOT` to the closing `EOC` (A.4.2,
/// A.4.4) and gather them into one [`Tile`] per tile index.
///
/// Tile-parts of different tiles may interleave freely, so this accumulates by
/// `Isot` and joins each tile's parts at the end. Within one tile they must
/// arrive in `TPsot` order, and every tile of the grid must be present: a
/// codestream that skips one describes an image it does not carry, which is a
/// truncation, not a feature to decode around.
///
/// A `Psot` overrun, an out-of-range or out-of-order `TPsot`, a `TNsot` that
/// disagrees with the parts that arrive, a missing tile, or a missing `EOC` all
/// reject with [`Error::Codestream`].
fn walk_tiles<'a>(
    bytes: &'a [u8],
    sot_offset: usize,
    main: &MainHeader,
    ppm: &[Vec<u8>],
) -> Result<Vec<Tile<'a>>> {
    let tile_count = main.siz.num_tiles() as usize;
    // `PPM` (main header) supplies one packet-header chunk per tile-part in
    // codestream order; this counter walks them as the tile-parts are read.
    let mut ppm_seq = 0usize;
    let mut tiles: Vec<TileParts<'a>> = (0..tile_count)
        .map(|_| TileParts {
            parts: Vec::new(),
            declared_parts: None,
            header: TileHeader::default(),
            packed_headers: Vec::new(),
        })
        .collect();

    let mut part_offset = sot_offset;
    loop {
        let mut cur = Cursor::at(bytes, part_offset);
        // `parse_main_header` stopped on the first SOT and the loop below only
        // continues when it has just read one, so this is always present.
        if cur.u16()? != marker::SOT {
            return Err(Error::Codestream(
                "tile-part does not start with SOT".into(),
            ));
        }
        let sot = decode_sot(segment(&mut cur)?)?;

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

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

        let first_part = sot.tile_part_index == 0;
        let (tile_header, packed) = read_tile_part_header(&mut cur, &main.siz, first_part)?;
        if first_part {
            tile.header = tile_header;
        } else {
            // A later tile-part carries no coding-style overrides — those are
            // rejected inside `read_tile_part_header` — but its POC volumes are
            // legal and append to the tile's, so the progression can be split
            // across the tile's parts (A.6.6). Each part's list is capped, so
            // the accumulation across parts must be re-checked.
            check_poc_budget(tile.header.poc.len() + tile_header.poc.len())?;
            tile.header.poc.extend(tile_header.poc);
        }
        // Packed packet headers append across the tile's parts in TPsot order
        // (which is arrival order, enforced above), matching the body order.
        // They come from `PPT` (this tile-part's own markers) or `PPM` (the main
        // header, one chunk per tile-part in codestream order) — never both for
        // the same packets, so a codestream carrying each is out of subset.
        if ppm.is_empty() {
            tile.packed_headers.extend(packed);
        } else {
            if !packed.is_empty() {
                return Err(Error::Unsupported(
                    "a codestream carrying both PPM and PPT packed headers is not decoded".into(),
                ));
            }
            let chunk = ppm.get(ppm_seq).ok_or_else(|| {
                Error::Codestream(
                    "PPM carries fewer packet-header chunks than the codestream has tile-parts"
                        .into(),
                )
            })?;
            ppm_seq += 1;
            tile.packed_headers.extend_from_slice(chunk);
        }
        let data_start = cur.pos;

        // Psot counts from the SOT marker's first byte to the end of the
        // tile-part. Psot == 0 marks the *last* tile-part: it runs to the
        // closing EOC (A.4.2), anchored to the last two bytes of the buffer —
        // everything after SOD is the tile, which is also OpenJPEG's reading.
        // Scanning for the first FF D9 instead would be unsound: bit stuffing
        // keeps packet data and headers clear of it, but an SOP segment's Nsop
        // counter is two raw bytes and can spell FF D9 (packet 65497, or a 0xFF
        // low byte abutting 0xD9), which would silently truncate a valid tile.
        // The asymmetry with the Psot != 0 arm (which ignores bytes after its
        // EOC) is therefore deliberate: with no declared length there is nothing
        // else to anchor to.
        let data_end = if sot.psot == 0 {
            bytes
                .len()
                .checked_sub(2)
                .filter(|&end| end >= data_start && read_u16(bytes, end) == Some(marker::EOC))
                .ok_or_else(|| {
                    Error::Codestream("Psot=0 tile-part is not terminated by EOC".into())
                })?
        } else {
            let end = part_offset
                .checked_add(sot.psot as usize)
                .filter(|&end| end <= bytes.len())
                .ok_or_else(|| Error::Codestream("Psot overruns the codestream".into()))?;
            if end < data_start {
                return Err(Error::Codestream(
                    "Psot is shorter than the tile-part header".into(),
                ));
            }
            end
        };
        tiles[index].parts.push(&bytes[data_start..data_end]);

        // Another SOT continues the walk; EOC ends it. Anything else — or
        // nothing at all — means the tile-part chain does not close.
        match read_u16(bytes, data_end) {
            Some(marker::EOC) => break,
            Some(marker::SOT) => part_offset = data_end,
            Some(other) => {
                return Err(Error::Codestream(format!(
                    "expected SOT or EOC after a tile-part, found {other:#06X}"
                )));
            }
            None => return Err(Error::Codestream("missing EOC after the tile-part".into())),
        }
    }

    // Every PPM chunk maps to one tile-part; leftover chunks mean the main header
    // packed headers for tile-parts the codestream never carried.
    if ppm_seq != ppm.len() {
        return Err(Error::Codestream(format!(
            "PPM carries {} packet-header chunk(s) but the codestream has {ppm_seq} tile-part(s)",
            ppm.len(),
        )));
    }

    tiles
        .into_iter()
        .enumerate()
        .map(|(index, tile)| {
            if tile.parts.is_empty() {
                return Err(Error::Codestream(format!(
                    "the codestream carries no tile-part for tile {index}"
                )));
            }
            if let Some(declared) = tile.declared_parts {
                if usize::from(declared) != tile.parts.len() {
                    return Err(Error::Codestream(format!(
                        "tile {index} declares {declared} tile-parts but carries {}",
                        tile.parts.len()
                    )));
                }
            }
            // One part: borrow it. Several: join them, which is exact — a
            // tile-part holds a whole number of packets (B.9), so nothing
            // straddles the seam.
            let data = match <[&[u8]; 1]>::try_from(tile.parts.as_slice()) {
                Ok([only]) => Cow::Borrowed(only),
                Err(_) => Cow::Owned(tile.parts.concat()),
            };
            Ok(Tile {
                index: index as u32,
                header: tile.header,
                data,
                packed_headers: tile.packed_headers,
            })
        })
        .collect()
}

/// Read one tile-part header: the markers between its `SOT` segment and its
/// `SOD` (A.4.2). The cursor is left on the first byte of the packet data.
///
/// Only the *first* tile-part of a tile may carry the coding-parameter overrides
/// (COD/COC/QCD/QCC/RGN): they say how to read the tile's packets, and a
/// later part cannot restate what the earlier parts were already decoded under.
/// A conformant encoder never emits one; a codestream that does is malformed,
/// not merely unsupported.
fn read_tile_part_header(
    cur: &mut Cursor<'_>,
    siz: &Siz,
    first_part: bool,
) -> Result<(TileHeader, Vec<u8>)> {
    let mut tile = TileHeader::default();
    // `PPT` packet headers for this tile-part, collected as `(Zppt, bytes)` and
    // concatenated in `Zppt` order below.
    let mut ppt: Vec<(u8, Vec<u8>)> = Vec::new();
    // A.6 allows one of each per header. The tile-part tally is tracked apart
    // from the main header's: a tile-part marker over a main-header one for the
    // same component is the legal override, not a duplicate.
    let overrides_here = |code: u16| -> Result<()> {
        if first_part {
            Ok(())
        } else {
            Err(Error::Codestream(format!(
                "marker {code:#06X} appears in a tile-part header other than the first; \
                 the coding-parameter overrides belong to the first tile-part of a tile"
            )))
        }
    };

    loop {
        let m = cur.u16()?;
        match m {
            marker::SOD => break,
            marker::COM => {
                segment(cur)?;
            }
            marker::COD => {
                overrides_here(m)?;
                if tile.cod.replace(decode_cod(segment(cur)?)?).is_some() {
                    return Err(Error::Codestream(
                        "duplicate COD marker in the tile-part header".into(),
                    ));
                }
            }
            marker::QCD => {
                overrides_here(m)?;
                if tile
                    .qcd
                    .replace(decode_quant(segment(cur)?, "QCD")?)
                    .is_some()
                {
                    return Err(Error::Codestream(
                        "duplicate QCD marker in the tile-part header".into(),
                    ));
                }
            }
            marker::COC => {
                overrides_here(m)?;
                let (index, coding) = decode_coc(segment(cur)?, siz)?;
                if tile.coc.iter().any(|&(i, _)| i == index) {
                    return Err(Error::Codestream(format!(
                        "duplicate COC marker for component {index} in the tile-part header"
                    )));
                }
                tile.coc.push((index, coding));
            }
            marker::QCC => {
                overrides_here(m)?;
                let (index, quant) = decode_qcc(segment(cur)?, siz)?;
                if tile.qcc.iter().any(|&(i, _)| i == index) {
                    return Err(Error::Codestream(format!(
                        "duplicate QCC marker for component {index} in the tile-part header"
                    )));
                }
                tile.qcc.push((index, quant));
            }
            marker::RGN => {
                overrides_here(m)?;
                let (index, shift) = decode_rgn(segment(cur)?, siz)?;
                if tile.rgn.iter().any(|&(i, _)| i == index) {
                    return Err(Error::Codestream(format!(
                        "duplicate RGN marker for component {index} in the tile-part header"
                    )));
                }
                tile.rgn.push((index, shift));
            }
            // Packet lengths (A.7.3): informational, so the structure is
            // validated and the lengths discarded — the packets are read from
            // the data itself, and decoding must not depend on the hint.
            marker::PLT => {
                decode_plt(segment(cur)?)?;
            }
            // A tile-part POC sets the progression for this tile, replacing the
            // main header's. Unlike the coding-style overrides, it is legal in
            // *any* tile-part, not just the first (A.6.6, OpenJPEG's
            // `J2K_STATE_TPH`), and volumes accumulate across every one of the
            // tile's parts — so it is not gated by `overrides_here`.
            marker::POC => {
                decode_poc(segment(cur)?, siz, &mut tile.poc)?;
            }
            // Packed packet headers (A.7.5): this tile-part's packet headers,
            // moved out of the bitstream into the marker. `Zppt` orders the
            // markers of one tile-part; the bytes after it are `Ippt`. Legal in
            // any tile-part (the headers span all of them), so not gated by
            // `overrides_here`. Collected here and stitched into the tile's
            // packed buffer by the caller; a decoder that ignored them would read
            // packet headers off the packet bodies and decode garbage.
            marker::PPT => {
                let mut body = segment(cur)?;
                let zppt = body.u8()?;
                if ppt.iter().any(|&(z, _)| z == zppt) {
                    return Err(Error::Codestream(format!(
                        "duplicate PPT index Zppt {zppt} in one tile-part header"
                    )));
                }
                let ippt = body.take(body.remaining())?;
                ppt.push((zppt, ippt.to_vec()));
            }
            // These are legal markers, but not here: TLM and PLM are
            // main-header-only (A.7.1, A.7.2), and SOP/EPH delimit packets
            // after SOD. In a tile-part header they are a malformed
            // codestream, not a missing feature.
            marker::TLM | marker::PLM | marker::SOP | marker::EPH => {
                return Err(Error::Codestream(format!(
                    "marker {m:#06X} is not permitted in a tile-part header"
                )));
            }
            other => {
                return Err(Error::Codestream(format!(
                    "unexpected marker {other:#06X} in tile-part header"
                )));
            }
        }
    }
    // Stitch this tile-part's PPT markers into one buffer, ordered by Zppt.
    ppt.sort_by_key(|&(z, _)| z);
    let packed = ppt.into_iter().flat_map(|(_, bytes)| bytes).collect();
    Ok((tile, packed))
}

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

    // A tile COD/QCD is the tile's new default: it displaces the main header's
    // COD/QCD *and* any main-header COC/QCC, so it lands on every component.
    if let Some(cod) = &tile.cod {
        header.cod = cod.clone();
        let coding = header.cod.coding();
        for params in &mut header.components {
            params.coding = coding.clone();
        }
    }
    if let Some(qcd) = &tile.qcd {
        header.qcd = qcd.clone();
        for params in &mut header.components {
            params.quant = qcd.clone();
        }
    }

    // Then the tile's own per-component markers, which outrank its COD/QCD.
    // `decode_coc`/`decode_qcc`/`decode_rgn` already bounded each index by the
    // SIZ component count, so these cannot land outside the vector.
    for (index, coding) in &tile.coc {
        header.components[*index].coding = coding.clone();
    }
    for (index, quant) in &tile.qcc {
        header.components[*index].quant = quant.clone();
    }
    for (index, shift) in &tile.rgn {
        header.components[*index].roi_shift = *shift;
    }

    // A tile-part POC *appends* to the main header's, it does not replace it: a
    // tile inherits the main header's progression volumes and adds its own after
    // them (A.6.6). OpenJPEG seeds each tile's coding parameters from the main
    // header — POC volumes included — then `opj_j2k_read_poc` appends the
    // tile-part's, so the tile's order is `[main volumes…, tile volumes…]`. The
    // volume walk emits each packet by the first volume that reaches it, so the
    // two must stay in that order. `header.poc` is already the main header's
    // here, from `main.clone()` above. OpenJPEG's 32-entry array holds the
    // *combined* list, so the budget binds the sum, not each side.
    check_poc_budget(header.poc.len() + tile.poc.len())?;
    header.poc.extend(tile.poc.iter().copied());

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

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

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

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

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

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

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

    if cur.u16()? != marker::SOC {
        return Err(Error::Codestream(
            "does not start with the SOC marker".into(),
        ));
    }

    let mut segments = Vec::new();
    let sot_offset = loop {
        let code = cur.u16()?;
        match code {
            // The first SOT ends the main header; point the offset back at it.
            marker::SOT => break cur.pos - 2,

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

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

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

    Ok((segments, sot_offset))
}

/// Parse the main header up to (but not into) the first `SOT`.
///
/// Returns the decoded [`MainHeader`] and the byte offset of that `SOT` marker,
/// which is where tile-part walking (issue #6) begins. Stops before any
/// entropy-coded data, so it never touches packet bytes.
///
/// The header is walked in full by [`walk_main_header`] first, then each
/// located segment is interpreted in codestream order.
fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize, Vec<Vec<u8>>)> {
    let (segments, sot_offset) = walk_main_header(bytes)?;

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

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

    let mut cod = None;
    let mut qcd = None;
    let mut coc: Vec<Option<Coding>> = vec![None; siz.components.len()];
    let mut qcc: Vec<Option<Qcd>> = vec![None; siz.components.len()];
    let mut rgn: Vec<Option<u8>> = vec![None; siz.components.len()];
    let mut tlm: Vec<TlmEntry> = Vec::new();
    let mut poc: Vec<PocVolume> = Vec::new();
    let mut crg: Option<Vec<(u16, u16)>> = None;
    // Packed packet headers (A.7.4), collected as `(Zppm, Ippm)` and split into
    // per-tile-part chunks after the walk by `decode_ppm_chunks`.
    let mut ppm: Vec<(u8, Vec<u8>)> = Vec::new();

    for seg in &segments[1..] {
        let body = || Cursor::new(seg.body);
        match seg.code {
            marker::SIZ => {
                return Err(Error::Codestream("duplicate SIZ marker".into()));
            }
            marker::COD => {
                if cod.is_some() {
                    return Err(Error::Codestream("duplicate COD marker".into()));
                }
                cod = Some(decode_cod(body())?);
            }
            marker::QCD => {
                if qcd.is_some() {
                    return Err(Error::Codestream("duplicate QCD marker".into()));
                }
                qcd = Some(decode_quant(body(), "QCD")?);
            }
            // A.6.2 and A.6.5 allow at most one COC and one QCC per component in
            // a header. A second one is not a later-wins override; it is a
            // malformed header, and guessing which wins would decode an image
            // the encoder never described. OpenJPEG is silently last-wins here;
            // rejecting is stricter, and no conformant codestream carries two.
            marker::COC => {
                let (index, coding) = decode_coc(body(), &siz)?;
                if coc[index].replace(coding).is_some() {
                    return Err(Error::Codestream(format!(
                        "duplicate COC marker for component {index}"
                    )));
                }
            }
            marker::QCC => {
                let (index, quant) = decode_qcc(body(), &siz)?;
                if qcc[index].replace(quant).is_some() {
                    return Err(Error::Codestream(format!(
                        "duplicate QCC marker for component {index}"
                    )));
                }
            }
            // A.6.3 allows one RGN per component per header, like COC and QCC.
            marker::RGN => {
                let (index, shift) = decode_rgn(body(), &siz)?;
                if rgn[index].replace(shift).is_some() {
                    return Err(Error::Codestream(format!(
                        "duplicate RGN marker for component {index}"
                    )));
                }
            }
            // Comment: recognised, carries nothing the decoder needs.
            marker::COM => {}

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

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

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

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

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

            // Valid markers the decoded subset does not yet cover. Rejected
            // rather than skipped: each one changes how the codestream is
            // interpreted, so ignoring it would silently decode the wrong
            // image. CAP announces capabilities beyond Part 1 (an HTJ2K
            // codestream carries one), whose code-blocks this Tier-1 would
            // misread as Part 1. PPT/SOP/EPH belong after SOD or in a tile-part
            // header, not the main one.
            marker::CAP | marker::PPT | marker::SOP | marker::EPH => {
                return Err(Error::Unsupported(format!(
                    "marker {} is outside the decoded subset",
                    marker::describe(seg.code)
                )));
            }

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

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

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

    let cod = cod.ok_or_else(|| Error::Codestream("missing required COD marker".into()))?;
    let qcd = qcd.ok_or_else(|| Error::Codestream("missing required QCD marker".into()))?;

    // Start from COD/QCD's defaults, then lay each override over its component.
    // That is the whole of A.6.2's and A.6.5's resolution rule at the main
    // header's level; `resolve_tile_header` continues the ladder for a tile.
    let mut header = MainHeader::new(siz, cod, qcd);
    header.tlm = tlm;
    header.poc = poc;
    header.crg = crg.unwrap_or_default();
    for (params, ((coding, quant), shift)) in header
        .components
        .iter_mut()
        .zip(coc.into_iter().zip(qcc).zip(rgn))
    {
        if let Some(coding) = coding {
            params.coding = coding;
        }
        if let Some(quant) = quant {
            params.quant = quant;
        }
        if let Some(shift) = shift {
            params.roi_shift = shift;
        }
    }

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

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

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

    Ok(())
}

/// Upper bound on the declared image area (`Xsiz * Ysiz`), a robustness guard
/// against a malformed SIZ steering the per-subband and DWT buffers into an
/// overflowing or out-of-memory allocation. Sized for the GRIB2 grids decoded
/// today: 2^26 samples is 256 MiB as `i32`, well above operational grids (HRRR
/// ~1.9M, MRMS ~24.5M) and below anything that threatens the decode. Not a
/// format limit — raise it as larger imagery comes into scope.
const MAX_IMAGE_SAMPLES: u64 = 1 << 26;

/// Bound the samples a codestream can ask the decoder to allocate.
///
/// Every component is reconstructed into its own buffer, so the cost is the
/// *sum* of the component areas, not the image area. `Csiz` reaches 16384, so a
/// large image declared with many components would otherwise multiply the
/// allocation far past any single-component guard.
fn check_sample_budget(siz: &Siz) -> Result<()> {
    let mut total: u64 = 0;
    for index in 0..siz.components.len() {
        let (width, height) = siz
            .component_extent(index)
            .ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {index}")))?;
        total += u64::from(width) * u64::from(height);
        if total > MAX_IMAGE_SAMPLES {
            return Err(Error::Unsupported(format!(
                "components total over {MAX_IMAGE_SAMPLES} samples, above the decode guard"
            )));
        }
    }
    Ok(())
}

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

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

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

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

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

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

    let progression = match b.u8()? {
        0 => Progression::Lrcp,
        1 => Progression::Rlcp,
        2 => Progression::Rpcl,
        3 => Progression::Pcrl,
        4 => Progression::Cprl,
        other => {
            return Err(Error::Marker(format!("reserved progression order {other}")));
        }
    };

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

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

    let coding = decode_coding(&mut b, "COD", explicit_precincts)?;
    let Coding {
        decomposition_levels,
        code_block_width,
        code_block_height,
        code_block_style,
        transform,
        precinct_sizes,
    } = coding;
    b.expect_consumed("COD")?;

    Ok(Cod {
        progression,
        layers,
        decomposition_levels,
        code_block_width,
        code_block_height,
        code_block_style,
        use_sop,
        use_eph,
        multiple_component_transform,
        transform,
        // Maximal precincts (PPx=PPy=15) when Scod bit 0 is clear, signalled by
        // an empty list; explicit precincts were rejected above.
        precinct_sizes,
    })
}

/// The most progression volumes a tile's walk will honour, matching OpenJPEG's
/// 32-entry `opj_tcp_t::pocs` array ("Too many POCs" past it). The standard sets
/// no limit, but each volume re-enumerates the packet space and a duplicate
/// emission consumes no bitstream bytes, so an uncapped list is a quadratic
/// work bomb: `V` volumes over `P` one-byte packets cost `V·P` dedup probes
/// while the input pays for `P + 7V` bytes. The cap is enforced wherever
/// volumes accumulate — per marker, across a tile's parts, and on the resolved
/// main-plus-tile list.
const MAX_POC_VOLUMES: usize = 32;

/// Reject a progression-volume count past [`MAX_POC_VOLUMES`].
fn check_poc_budget(volumes: usize) -> Result<()> {
    if volumes > MAX_POC_VOLUMES {
        return Err(Error::Unsupported(format!(
            "{volumes} progression volumes exceeds the decode guard of {MAX_POC_VOLUMES}"
        )));
    }
    Ok(())
}

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

/// Decode the `SPcod`/`SPcoc` tail shared by COD and COC (Tables A-12, A-14):
/// decomposition levels, the two code-block exponents, the style byte, the
/// wavelet, and — when `explicit_precincts` — the per-resolution precinct sizes.
/// `origin` names the marker for error messages.
///
/// The precinct flag lives in `Scod`/`Scoc`, not here, so the caller reads it and
/// passes it down. When it is clear the partition is maximal and
/// `precinct_sizes` comes back empty.
fn decode_coding(b: &mut Cursor<'_>, origin: &str, explicit_precincts: bool) -> Result<Coding> {
    let decomposition_levels = b.u8()?;
    // Table A-15: 0–32 decomposition levels; 33–255 are reserved. A reserved
    // field encoding rejects at parse, like the wavelet and style bytes below.
    if decomposition_levels > 32 {
        return Err(Error::Marker(format!(
            "{origin} sets reserved decomposition level count {decomposition_levels} (max 32)"
        )));
    }
    let code_block_width = b.u8()?;
    let code_block_height = b.u8()?;
    let code_block_style = b.u8()?;
    // Each style flag changes how Tier-1 reads a code-block's coded segments.
    // Ignoring one does not decode a slightly different image, it decodes the
    // wrong one, so reject rather than half-decode until each lands. `bypass`,
    // `restart`, `predictable termination`, `segmentation symbols`, `vertically
    // causal context` and `reset context probabilities` are decoded; the two
    // HTJ2K bits are not.
    use markers::code_block_style::{LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL};
    let undecoded = code_block_style & !(LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET);
    if undecoded != 0 {
        return Err(Error::Unsupported(format!(
            "{origin} code-block style ({}) is outside the decoded subset",
            markers::code_block_style::describe(undecoded),
        )));
    }
    let transform = match b.u8()? {
        0 => Transform::Irreversible97,
        1 => Transform::Reversible53,
        other => {
            return Err(Error::Marker(format!(
                "{origin} sets reserved wavelet transform {other}"
            )));
        }
    };
    // One `SPcod` precinct byte per resolution — `NL + 1` of them, coarsest
    // first — each packing `PPx` in the low nibble and `PPy` in the high one
    // (Table A-21). They are exponents on that *resolution's* grid, so the same
    // byte means a different span at every level.
    let precinct_sizes = if explicit_precincts {
        let mut sizes = Vec::with_capacity(usize::from(decomposition_levels) + 1);
        for resolution in 0..=usize::from(decomposition_levels) {
            let byte = b.u8()?;
            let (ppx, ppy) = (byte & 0x0F, byte >> 4);
            // A 2^0 precinct is legal only at the coarsest resolution (Table
            // A-21). Above it the precinct is halved onto the subband grid, so a
            // zero exponent would ask for a 2^-1 code-block partition — the
            // geometry is not merely unusual, it does not exist.
            if resolution > 0 && (ppx == 0 || ppy == 0) {
                return Err(Error::Marker(format!(
                    "{origin} sets precinct 2^{ppx}×2^{ppy} at resolution {resolution}; \
                     a zero exponent is permitted only at resolution 0"
                )));
            }
            sizes.push((ppx, ppy));
        }
        sizes
    } else {
        Vec::new()
    };

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

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

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

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

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

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

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

    while b.remaining() > 0 {
        let tile_index = match st {
            0 => entries.len() as u32,
            1 => u32::from(b.u8()?),
            _ => u32::from(b.u16()?),
        };
        if tile_index >= siz.num_tiles() {
            return Err(Error::Marker(format!(
                "TLM names tile {tile_index}, but the grid holds {} tiles",
                siz.num_tiles()
            )));
        }
        let length = match sp {
            0 => u32::from(b.u16()?),
            _ => b.u32()?,
        };
        entries.push(TlmEntry { tile_index, length });
    }
    Ok(())
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#[cfg(test)]
mod tests;