rust_j2k/codestream/mod.rs
1//! Stage 1 — codestream parsing (ISO/IEC 15444-1 Annex A).
2//!
3//! Walks the marker segments of a raw J2K codestream: the main header
4//! (SIZ / COD / QCD, plus optional COC / QCC / RGN / TLM / PLM / COM), then
5//! the tile-parts (SOT, optional RGN / PLT / COM, SOD, data). Produces a
6//! [`MainHeader`] of decode parameters and the byte ranges of each tile's
7//! packet data — everything the later stages need, with no interpretation of
8//! the entropy-coded bytes yet.
9//!
10//! The main header is located before it is judged: [`walk_main_header`] finds
11//! every marker segment without caring what the decoder supports, and
12//! [`parse_main_header`] then interprets them. That split is what lets a
13//! codestream be traversed past a feature we cannot decode, and is what makes
14//! the reserved segment-less markers and unknown segments handleable at all.
15
16pub mod markers;
17
18use std::borrow::Cow;
19use std::cell::OnceCell;
20use std::collections::{HashMap, HashSet};
21
22use crate::report::ReportEntry;
23use crate::{Error, Result};
24use markers::{
25 Ccap15, Cod, Coding, ComponentParams, Cpf, PocVolume, Progression, Qcd, QuantStyle, Siz,
26 SizComponent, TlmEntry, Transform, marker,
27};
28
29/// Parsed main-header decode parameters. COD/QCD carry the codestream-wide
30/// defaults; [`components`](Self::components) carries each component's effective
31/// parameters after any COC/QCC override and any RGN maxshift — the main
32/// header's, replaced by the tile-part header's where one appears (A.6.3).
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct MainHeader {
35 pub siz: Siz,
36 pub cod: Cod,
37 pub qcd: Qcd,
38 /// Effective coding and quantization parameters per component, in SIZ order:
39 /// COD/QCD's defaults with any COC/QCC override already applied. Every stage
40 /// past the header reads these rather than [`cod`](Self::cod) or
41 /// [`qcd`](Self::qcd), which hold the codestream-wide defaults.
42 pub components: Vec<ComponentParams>,
43 /// The progression volumes of any `POC` marker, in order; empty when the
44 /// codestream carries none, in which case the packet order is [`cod`]'s
45 /// single progression over every axis (A.6.6). A `POC` in a tile's first
46 /// tile-part replaces this for its tile, the same way a tile COD replaces
47 /// the coding style.
48 ///
49 /// [`cod`]: Self::cod
50 pub poc: Vec<PocVolume>,
51 /// `(Xcrg, Ycrg)` sub-pixel registration offsets per component, in SIZ
52 /// order, from a `CRG` marker; empty when the codestream carries none
53 /// (A.9.1). Informational: the offsets say how a display should register the
54 /// components against one another, in units of `1/65536` of the reference-grid
55 /// step, and do not change the decoded samples — so they are recorded for a
56 /// caller to act on, not resampled here (OpenJPEG likewise reads past them).
57 pub crg: Vec<(u16, u16)>,
58 /// The `Ccap15` word of a `CAP` marker that signals Part 15 (HTJ2K);
59 /// `None` when the codestream carries no `CAP`, or one that signals no
60 /// Part 15 capability. It is read for MULTIHT, which is refused, and does
61 /// not decide the block coder: each component's code-block style does.
62 pub ccap15: Option<Ccap15>,
63 /// The `CPF` marker, when the codestream carries one (ISO/IEC 15444-15
64 /// A.6). Informational.
65 pub cpf: Option<Cpf>,
66}
67
68impl MainHeader {
69 /// A header whose components all take the COD/QCD defaults — the shape of
70 /// every codestream that carries no COC and no QCC.
71 pub fn new(siz: Siz, cod: Cod, qcd: Qcd) -> Self {
72 let components = vec![
73 ComponentParams {
74 coding: cod.coding.clone(),
75 quant: qcd.clone(),
76 roi_shift: 0,
77 };
78 siz.components.len()
79 ];
80 MainHeader {
81 siz,
82 cod,
83 qcd,
84 components,
85 poc: Vec::new(),
86 crg: Vec::new(),
87 ccap15: None,
88 cpf: None,
89 }
90 }
91}
92
93#[cfg(test)]
94impl MainHeader {
95 /// A single-component header for unit tests: a `width` x `height` image at
96 /// the origin in one tile, unit sub-sampling, LRCP, one layer, 64 x 64
97 /// code-blocks, no precincts, and the given depth, wavelet and `qcd`.
98 pub(crate) fn single_component(
99 size: (u32, u32),
100 depth: (u8, bool),
101 wavelet: (u8, Transform),
102 qcd: Qcd,
103 ) -> Self {
104 MainHeader::single_component_blocks(size, depth, wavelet, 6, qcd)
105 }
106
107 /// [`single_component`](Self::single_component) with code-blocks of
108 /// `1 << block_exp` samples square; the stored exponent is `block_exp - 2`.
109 pub(crate) fn single_component_blocks(
110 (width, height): (u32, u32),
111 (bit_depth, signed): (u8, bool),
112 (decomposition_levels, transform): (u8, Transform),
113 block_exp: u8,
114 qcd: Qcd,
115 ) -> Self {
116 MainHeader::new(
117 Siz {
118 x_size: width,
119 y_size: height,
120 x_offset: 0,
121 y_offset: 0,
122 tile_width: width,
123 tile_height: height,
124 tile_x_offset: 0,
125 tile_y_offset: 0,
126 components: vec![SizComponent {
127 bit_depth,
128 signed,
129 x_sampling: 1,
130 y_sampling: 1,
131 }],
132 },
133 Cod {
134 progression: Progression::Lrcp,
135 layers: 1,
136 use_sop: false,
137 use_eph: false,
138 multiple_component_transform: false,
139 coding: Coding {
140 decomposition_levels,
141 code_block_width: block_exp - 2,
142 code_block_height: block_exp - 2,
143 code_block_style: 0,
144 transform,
145 precinct_sizes: vec![],
146 },
147 },
148 qcd,
149 )
150 }
151}
152
153/// One tile of the image: its index in the tile grid, the decode parameters in
154/// force inside it, and its packet data.
155///
156/// A tile can be split across several tile-parts, interleaved with other tiles'
157/// (A.4.2). They are gathered here: `data` is every one of this tile's
158/// tile-parts' packet bytes, concatenated in `TPsot` order. Concatenation is
159/// exact, not an approximation — a tile-part holds a whole number of packets
160/// (B.9), so no packet straddles the seam — and it is what OpenJPEG does
161/// (`opj_j2k_read_sod` appends each tile-part into the tile's buffer). It stays
162/// borrowed for the overwhelmingly common single-part tile, and only copies when
163/// there is more than one part to join.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct Tile<'a> {
166 pub index: u32,
167 /// This tile's own tile-part-header markers, as parsed. Resolve them against
168 /// the main header with [`Codestream::tile_header`] to get the parameters the
169 /// tile decodes under.
170 ///
171 /// They are *not* resolved into a whole header here, because a header is
172 /// sized by the component count and there can be tens of thousands of tiles:
173 /// materializing one per tile would cost `tiles × components` in memory and
174 /// in time, which a header under 50 KB can drive into gigabytes and minutes.
175 /// Instead, [`parse_tiles_with`] checks each tile's markers against a summary of
176 /// the main header, in time proportional to the tile's own markers. At
177 /// decode, a tile with no markers runs under the main header itself,
178 /// borrowed; a tile with markers is resolved in full, in time and memory
179 /// proportional to the component count, and the decode then spends at least
180 /// that much on the tile's components anyway: it builds every
181 /// component's geometry before it reads a packet. That holds with
182 /// `strict` off too, where the decode goes on past a tile whose data runs
183 /// out: a tile with no tile-part at all is never resolved, and every
184 /// tile that is resolved builds its geometry. A tile-component holds at
185 /// least one sample (SIZ refuses an empty one), so the copies cost at most
186 /// `tiles × components`, no more than the image's samples (under a window
187 /// or a tile, the samples of the tiles read, as only those are resolved).
188 pub header: TileHeader,
189 pub data: Cow<'a, [u8]>,
190 /// Where each tile-part's data ends in [`data`](Self::data), in `TPsot`
191 /// order, so a report can name the tile-part a byte offset falls in.
192 pub part_ends: Vec<usize>,
193 /// The tile's packed packet headers (`PPT`), concatenated across its
194 /// tile-parts; empty when the headers are inline with the bodies. When
195 /// non-empty, Tier-2 reads every packet header from here and every packet
196 /// body from [`data`](Self::data) (A.7.5).
197 pub packed_headers: Vec<u8>,
198}
199
200/// A parsed codestream: the main header plus every tile, in tile-index order.
201///
202/// A strict walk refuses a codestream that lacks a tile, so it holds them
203/// all. With `strict` off a missing tile is left out of `tiles` and reported
204/// in `entries`, with whatever else the walk found missing.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct Codestream<'a> {
207 pub header: MainHeader,
208 pub tiles: Vec<Tile<'a>>,
209 /// What a walk with `strict` off found missing; always empty when strict.
210 pub entries: Vec<ReportEntry>,
211}
212
213impl Tile<'_> {
214 /// The tile-part that byte `offset` of [`data`](Self::data) falls in, or
215 /// the last one for an offset at or past the end.
216 pub fn part_at(&self, offset: usize) -> u8 {
217 let part = self.part_ends.partition_point(|&end| end <= offset);
218 part.min(self.part_ends.len().saturating_sub(1)) as u8
219 }
220}
221
222impl Codestream<'_> {
223 /// The parameters tile `index` decodes under: the main header with that
224 /// tile's tile-part-header markers resolved over it (A.6.1).
225 ///
226 /// Every stage past the codestream takes one of these, so nothing downstream
227 /// has to know that a tile header exists — a tile is just a header, a
228 /// rectangle, and some bytes. A tile with no tile-part-header markers of its
229 /// own decodes under the main header itself, borrowed, not copied.
230 pub fn tile_header(&self, index: usize) -> Result<Cow<'_, MainHeader>> {
231 let tile = self
232 .tiles
233 .get(index)
234 .ok_or_else(|| Error::inconsistent(format!("no tile {index}")))?;
235 resolve_tile_header(&self.header, &tile.header)
236 }
237}
238
239/// Parse a raw codestream (must start with SOC, end with EOC).
240///
241/// Rejects anything outside the decoded feature set, such as a mixed-mode
242/// HTJ2K code-block style, Part 2 extensions or unknown markers, with
243/// [`Error::Unsupported`]. A JP2 file is
244/// unwrapped before it gets here (see `crate::jp2`).
245///
246/// [`Error::Unsupported`]: crate::Error::Unsupported
247#[cfg(test)]
248pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
249 parse_tiles(bytes, parse_header(bytes)?)
250}
251
252/// A codestream's main header, parsed, with what the tile walk needs to carry
253/// on from it. It reads nothing past the first `SOT` marker.
254#[derive(Debug, Clone, PartialEq, Eq)]
255pub struct ParsedHeader {
256 pub header: MainHeader,
257 /// Offset of the first `SOT` marker, where the tile walk starts.
258 sot_offset: usize,
259 /// The main header's `PPM` packet headers, one chunk per tile-part.
260 ppm: Vec<Vec<u8>>,
261}
262
263/// Parse a codestream's main header, from `SOC` up to the first `SOT` marker,
264/// and stop there: no tile-part header or packet byte is read. `parse` is
265/// this followed by `parse_tiles`.
266pub fn parse_header(bytes: &[u8]) -> Result<ParsedHeader> {
267 let (header, sot_offset, ppm) = parse_main_header(bytes)?;
268 Ok(ParsedHeader {
269 header,
270 sot_offset,
271 ppm,
272 })
273}
274
275/// Walk the tile-parts of the codestream whose main header `parsed` holds, and
276/// check every tile's header.
277#[cfg(test)]
278pub fn parse_tiles(bytes: &[u8], parsed: ParsedHeader) -> Result<Codestream<'_>> {
279 parse_tiles_with(bytes, parsed, true)
280}
281
282/// `parse_tiles`, or with `strict` false, the walk that takes missing data
283/// as missing rather than refusing it (see [`walk_tiles`]).
284pub fn parse_tiles_with(
285 bytes: &[u8],
286 parsed: ParsedHeader,
287 strict: bool,
288) -> Result<Codestream<'_>> {
289 let codestream = split_tiles_with(bytes, parsed, strict)?;
290
291 // Check every tile's header once, here, so a malformed tile-part header is
292 // a parse error rather than a surprise partway through a decode. A header is
293 // sized by the component count and a codestream can declare tens of
294 // thousands of tiles, so each tile's own markers are checked against a
295 // summary of the main header instead of resolving a header per tile. Only
296 // a tile found at fault is resolved in full, so that the fault is reported
297 // in the full check's words.
298 let main = &codestream.header;
299 let summary = OnceCell::new();
300 for (index, tile) in codestream.tiles.iter().enumerate() {
301 if !tile_header_is_valid(main, &summary, &tile.header) {
302 // The two checks agree, so the full one fails here. Were it ever
303 // to pass, its verdict would stand.
304 let full = check_tile_in_full(main, &tile.header, index);
305 debug_assert!(
306 full.is_err(),
307 "tile {index}: the quick check refused a valid tile"
308 );
309 full?;
310 }
311 }
312
313 Ok(codestream)
314}
315
316/// Resolve a tile's header in full and check it: every invariant
317/// [`resolve_tile_header`] holds it to, then the wavelet rule below. This is
318/// what a valid tile header is; [`tile_header_is_valid`] decides the same
319/// without resolving one.
320fn check_tile_in_full(main: &MainHeader, tile: &TileHeader, index: usize) -> Result<()> {
321 let resolved = resolve_tile_header(main, tile)?;
322
323 // Every tile writes into one buffer per component, and that buffer's
324 // arithmetic follows the component's wavelet: 5/3 reconstructs exact
325 // integers, 9/7 reals. A tile-part COD may legally give a component a
326 // different wavelet than the main header does, which would ask one buffer
327 // to hold both. Nothing in Part 4 encodes that and no real encoder emits
328 // it, so it is rejected rather than given a widened container.
329 let pairs = resolved.components.iter().zip(&main.components);
330 for (component, (in_tile, in_main)) in pairs.enumerate() {
331 if in_tile.coding.transform != in_main.coding.transform {
332 return Err(Error::unsupported(format!(
333 "tile {index} codes component {component} with the {:?} wavelet where the \
334 main header uses {:?}; tiles that disagree on a component's wavelet are \
335 not decoded",
336 in_tile.coding.transform, in_main.coding.transform,
337 )));
338 }
339 }
340 Ok(())
341}
342
343/// The main header's components, sorted by what a tile COD or QCD can fall
344/// short of. Either marker lands on every component the tile does not name in
345/// a COC or QCC, so checking it a component at a time would cost the
346/// component count per tile; against this it costs the tile's own markers.
347struct ComponentSummary {
348 /// `(step entries, component)` for each component whose quantization is
349 /// not derived, fewest entries first. The first a tile does not name is
350 /// the tightest test of a tile COD's decomposition levels.
351 by_steps: Vec<(usize, usize)>,
352 /// `(decomposition levels, component)` for every component, most first.
353 /// The first a tile does not name is the tightest test of a tile QCD's
354 /// step entries.
355 by_levels: Vec<(u8, usize)>,
356 /// How many components use the 9/7 wavelet.
357 irreversible: usize,
358}
359
360impl ComponentSummary {
361 fn of(main: &MainHeader) -> Self {
362 let mut by_steps: Vec<(usize, usize)> = main
363 .components
364 .iter()
365 .enumerate()
366 .filter(|(_, params)| params.quant.style != QuantStyle::ScalarDerived)
367 .map(|(index, params)| (params.quant.steps.len(), index))
368 .collect();
369 by_steps.sort_unstable();
370 let mut by_levels: Vec<(u8, usize)> = main
371 .components
372 .iter()
373 .enumerate()
374 .map(|(index, params)| (params.coding.decomposition_levels, index))
375 .collect();
376 by_levels.sort_unstable_by(|a, b| b.cmp(a));
377 let irreversible = main
378 .components
379 .iter()
380 .filter(|params| params.coding.transform == Transform::Irreversible97)
381 .count();
382 ComponentSummary {
383 by_steps,
384 by_levels,
385 irreversible,
386 }
387 }
388}
389
390/// Whether `quant` can quantize a component of `levels` decomposition levels
391/// under `transform`: the per-component half of [`validate_resolved`].
392fn quant_fits(levels: u8, transform: Transform, quant: &Qcd) -> bool {
393 let needed = 3 * usize::from(levels) + 1;
394 (quant.style == QuantStyle::ScalarDerived || quant.steps.len() >= needed)
395 && !(transform == Transform::Irreversible97 && quant.style == QuantStyle::None)
396}
397
398/// Whether [`check_tile_in_full`] accepts `tile` over `main`, decided in time
399/// proportional to the tile's own markers, not to the component count. `main`
400/// must be a header [`parse_main_header`] accepted, so that the components a
401/// tile leaves alone are valid already.
402///
403/// A component the tile names in a COC or QCC is resolved and checked on its
404/// own. Every other one takes the tile COD's coding if there is one, else its
405/// main-header coding, and likewise the tile QCD's quantization. So a tile COD
406/// or QCD is checked once, against the extreme of the components it lands on:
407/// the first entry of `summary` the tile does not name.
408fn tile_header_is_valid(
409 main: &MainHeader,
410 summary: &OnceCell<ComponentSummary>,
411 tile: &TileHeader,
412) -> bool {
413 if resolved_poc_len(main, tile) > MAX_POC_VOLUMES {
414 return false;
415 }
416 let own = &tile.overrides;
417 if !own.codes_or_quantizes() {
418 // RGN and POC change no invariant checked here.
419 return true;
420 }
421
422 // `OverrideReader` refused a second COC or QCC for one component,
423 // and `decode_coc`/`decode_qcc` bounded each index by the component count.
424 let coc: HashMap<usize, &Coding> = own.coc.iter().map(|(i, c)| (*i, c)).collect();
425 let qcc: HashMap<usize, &Qcd> = own.qcc.iter().map(|(i, q)| (*i, q)).collect();
426 let named = || {
427 coc.keys()
428 .chain(qcc.keys().filter(|index| !coc.contains_key(index)))
429 .copied()
430 };
431 let is_named = |index: usize| coc.contains_key(&index) || qcc.contains_key(&index);
432 let in_main = |index: usize| &main.components[index];
433 // The decomposition levels and wavelet component `index` takes in the tile,
434 // and its quantization.
435 let coding = |index: usize| match (coc.get(&index), &own.cod) {
436 (Some(coding), _) => (coding.decomposition_levels, coding.transform),
437 (None, Some(cod)) => (cod.coding.decomposition_levels, cod.coding.transform),
438 (None, None) => {
439 let coding = &in_main(index).coding;
440 (coding.decomposition_levels, coding.transform)
441 }
442 };
443 let quant = |index: usize| match (qcc.get(&index), &own.qcd) {
444 (Some(quant), _) => *quant,
445 (None, Some(qcd)) => qcd,
446 (None, None) => &in_main(index).quant,
447 };
448
449 // The components the tile names, each on its own.
450 for index in named() {
451 let (levels, transform) = coding(index);
452 if !quant_fits(levels, transform, quant(index))
453 || transform != in_main(index).coding.transform
454 {
455 return false;
456 }
457 }
458
459 // The rest, if any, against the summary.
460 let total = main.components.len();
461 if named().count() < total {
462 let summary = summary.get_or_init(|| ComponentSummary::of(main));
463 match (&own.cod, &own.qcd) {
464 (None, None) => {}
465 (Some(cod), qcd) => {
466 // Each keeps its main-header wavelet, so none may differ from
467 // the tile COD's.
468 let differ = match cod.coding.transform {
469 Transform::Irreversible97 => total - summary.irreversible,
470 Transform::Reversible53 => summary.irreversible,
471 };
472 let differ_named = named()
473 .filter(|&index| in_main(index).coding.transform != cod.coding.transform)
474 .count();
475 if differ != differ_named {
476 return false;
477 }
478 match qcd {
479 Some(qcd) => {
480 if !quant_fits(cod.coding.decomposition_levels, cod.coding.transform, qcd) {
481 return false;
482 }
483 }
484 // Their own quantization under the tile COD's levels. Each
485 // has the tile COD's wavelet (checked above) and passed the
486 // main header's checks under it, so the 9/7 rule holds.
487 None => {
488 let needed = 3 * usize::from(cod.coding.decomposition_levels) + 1;
489 let fewest = summary.by_steps.iter().find(|&&(_, i)| !is_named(i));
490 if fewest.is_some_and(|&(steps, _)| steps < needed) {
491 return false;
492 }
493 }
494 }
495 }
496 // Their own coding under the tile QCD.
497 (None, Some(qcd)) => {
498 if qcd.style != QuantStyle::ScalarDerived {
499 let most = summary.by_levels.iter().find(|&&(_, i)| !is_named(i));
500 if most
501 .is_some_and(|&(levels, _)| qcd.steps.len() < 3 * usize::from(levels) + 1)
502 {
503 return false;
504 }
505 }
506 if qcd.style == QuantStyle::None {
507 let irreversible_named = named()
508 .filter(|&index| {
509 in_main(index).coding.transform == Transform::Irreversible97
510 })
511 .count();
512 if summary.irreversible != irreversible_named {
513 return false;
514 }
515 }
516 }
517 }
518 }
519
520 // The color transform, over the first three components (skipped on an
521 // image of fewer, see `mct::applies`).
522 let cod = own.cod.as_ref().unwrap_or(&main.cod);
523 if crate::mct::applies(cod.multiple_component_transform, main.siz.components.len()) {
524 if crate::mct::check_geometry(&main.siz.components).is_err() {
525 return false;
526 }
527 let first = coding(0).1;
528 if (1..3).any(|index| coding(index).1 != first) {
529 return false;
530 }
531 }
532 true
533}
534
535/// [`parse_tiles_with`] (strict) without resolving every tile's header, for a caller that
536/// reads one tile and resolves just that one with [`Codestream::tile_header`].
537/// Resolving them all costs `tiles × components`.
538pub(crate) fn split_tiles(bytes: &[u8], parsed: ParsedHeader) -> Result<Codestream<'_>> {
539 split_tiles_with(bytes, parsed, true)
540}
541
542/// [`split_tiles`], strict or not (see [`walk_tiles`]).
543fn split_tiles_with(bytes: &[u8], parsed: ParsedHeader, strict: bool) -> Result<Codestream<'_>> {
544 let ParsedHeader {
545 header,
546 sot_offset,
547 ppm,
548 } = parsed;
549 let mut entries = Vec::new();
550 let tiles = walk_tiles(bytes, sot_offset, &header, &ppm, strict, &mut entries)?;
551 Ok(Codestream {
552 header,
553 tiles,
554 entries,
555 })
556}
557
558/// A tile-part header's own markers (A.4.2): the tile-level overrides of the
559/// main header's coding parameters, and any progression volumes. Only the
560/// *first* tile-part of a tile may carry the overrides, so one per tile is
561/// enough however many parts the tile is split into. (A later tile-part that
562/// restates a value already in force is accepted and dropped; see
563/// [`check_restatement`].)
564#[derive(Debug, Default, Clone, PartialEq, Eq)]
565pub struct TileHeader {
566 overrides: Overrides,
567 /// A tile-part `POC`'s progression volumes; empty when the tile carries none,
568 /// in which case the main header's `POC` (or its single COD order) governs.
569 poc: Vec<PocVolume>,
570 /// Whether the tile's first tile-part carries a `POC`. Only then do the
571 /// tile's volumes replace the main header's (see `resolve_tile_header`).
572 poc_in_first_part: bool,
573}
574
575/// The COD, QCD, COC, QCC and RGN markers of one header, main or tile-part:
576/// a COD/QCD default and the per-component overrides that layer over it.
577///
578/// The per-component overrides are **sparse**: only the components a marker
579/// actually names. Almost every tile carries none at all, and a dense vector per
580/// tile would cost `tiles × components` for nothing.
581#[derive(Debug, Default, Clone, PartialEq, Eq)]
582struct Overrides {
583 cod: Option<Cod>,
584 qcd: Option<Qcd>,
585 coc: Vec<(usize, Coding)>,
586 qcc: Vec<(usize, Qcd)>,
587 rgn: Vec<(usize, u8)>,
588}
589
590impl Overrides {
591 /// Whether the header carries a COD, QCD, COC or QCC. RGN is left out: it
592 /// changes no coding or quantization parameter.
593 fn codes_or_quantizes(&self) -> bool {
594 self.cod.is_some() || self.qcd.is_some() || !self.coc.is_empty() || !self.qcc.is_empty()
595 }
596
597 /// Lay these markers over `components`, lowest precedence first: a COD or
598 /// QCD lands on every component, then each COC, QCC and RGN on the one
599 /// component it names, outranking the COD or QCD (A.6.1 to A.6.5).
600 ///
601 /// `decode_coc`, `decode_qcc` and `decode_rgn` bounded each index by the
602 /// SIZ component count, and `components` holds one entry per SIZ
603 /// component, so no index lands outside it.
604 fn lay_over(&self, components: &mut [ComponentParams]) {
605 if let Some(cod) = &self.cod {
606 for params in components.iter_mut() {
607 params.coding.clone_from(&cod.coding);
608 }
609 }
610 if let Some(qcd) = &self.qcd {
611 for params in components.iter_mut() {
612 params.quant.clone_from(qcd);
613 }
614 }
615 for (index, coding) in &self.coc {
616 components[*index].coding.clone_from(coding);
617 }
618 for (index, quant) in &self.qcc {
619 components[*index].quant.clone_from(quant);
620 }
621 for (index, shift) in &self.rgn {
622 components[*index].roi_shift = *shift;
623 }
624 }
625}
626
627/// Which header an [`OverrideReader`] reads.
628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
629enum Place {
630 Main,
631 /// A tile-part header, and whether it is its tile's first tile-part.
632 TilePart {
633 first: bool,
634 },
635}
636
637/// Reads the COD, QCD, COC, QCC and RGN markers of one header into
638/// [`Overrides`], refusing a duplicate. The main header and every tile-part
639/// header read them through this one routine, which is also where each
640/// COD's and COC's block coder meets [`check_block_coder`].
641///
642/// A.6 allows one COD and one QCD per header, and one COC, QCC and RGN per
643/// component per header. A second one is not a later-wins override; it is a
644/// malformed header, and guessing which wins would decode an image the encoder
645/// never described. OpenJPEG is silently last-wins here; rejecting is stricter,
646/// and no conformant codestream carries two. Each header is tallied apart: a
647/// tile-part marker over a main-header one for the same component is the legal
648/// override, not a duplicate.
649struct OverrideReader<'s> {
650 siz: &'s Siz,
651 place: Place,
652 overrides: Overrides,
653 /// The `(marker, component)` pairs met so far, so that a header naming
654 /// every component is checked in time proportional to its markers.
655 named: HashSet<(u16, usize)>,
656 /// Whether the codestream's `CAP` says it holds no `RGN` (`Ccap15` bit
657 /// 12 is 0), so that an `RGN` read here is refused.
658 rgn_free: bool,
659}
660
661impl<'s> OverrideReader<'s> {
662 fn new(siz: &'s Siz, place: Place) -> Self {
663 OverrideReader {
664 siz,
665 place,
666 overrides: Overrides::default(),
667 named: HashSet::new(),
668 rgn_free: false,
669 }
670 }
671
672 /// Hold this header to a `CAP` that says the codestream holds no `RGN`
673 /// (ISO/IEC 15444-15 A.3.4): refuse an `RGN` already read, and any read
674 /// later. The main header can carry its `CAP` after an `RGN`, so the
675 /// check runs at both reads.
676 fn forbid_rgn(&mut self) -> Result<()> {
677 self.rgn_free = true;
678 match self.overrides.rgn.first() {
679 Some(&(index, _)) => Err(rgn_without_cap_bit(index)),
680 None => Ok(()),
681 }
682 }
683
684 /// Read marker `code` if it is a COD, QCD, COC, QCC or RGN, and say
685 /// whether it was. `body` yields the marker's segment body. It is called
686 /// only for one of those markers, so for any other the caller's cursor is
687 /// left where it was.
688 fn read<'b>(&mut self, code: u16, body: impl FnOnce() -> Result<Cursor<'b>>) -> Result<bool> {
689 let suffix = match self.place {
690 Place::Main => "",
691 Place::TilePart { .. } => " in the tile-part header",
692 };
693 let duplicate =
694 |name: &str| Error::codestream(format!("duplicate `{name}` marker{suffix}"));
695 match code {
696 marker::COD => {
697 let seen = self.overrides.cod.is_some();
698 // The main header refuses a second COD before reading it; a
699 // tile-part header reads it first, so a malformed second COD
700 // reports its own fault there.
701 if seen && self.place == Place::Main {
702 return Err(duplicate("COD"));
703 }
704 let cod = decode_cod(body()?)?;
705 check_block_coder(&cod.coding, "`COD`")?;
706 if seen {
707 return Err(duplicate("COD"));
708 }
709 self.overrides.cod = Some(cod);
710 }
711 marker::QCD => {
712 // In the same order as COD.
713 let seen = self.overrides.qcd.is_some();
714 if seen && self.place == Place::Main {
715 return Err(duplicate("QCD"));
716 }
717 let qcd = decode_quant(body()?, "`QCD`")?;
718 if seen {
719 return Err(duplicate("QCD"));
720 }
721 self.overrides.qcd = Some(qcd);
722 }
723 marker::COC => {
724 let (index, coding) = decode_coc(body()?, self.siz)?;
725 check_block_coder(&coding, "`COC`")?;
726 self.first_for(code, "COC", index, suffix)?;
727 self.overrides.coc.push((index, coding));
728 }
729 marker::QCC => {
730 let (index, quant) = decode_qcc(body()?, self.siz)?;
731 self.first_for(code, "QCC", index, suffix)?;
732 self.overrides.qcc.push((index, quant));
733 }
734 marker::RGN => {
735 // A later tile-part's COD, COC, QCD and QCC are read for the
736 // caller to hold to the values in force (`check_restatement`);
737 // its RGN is refused here, as a malformed codestream rather
738 // than an unsupported one.
739 if self.place == (Place::TilePart { first: false }) {
740 return Err(Error::codestream(format!(
741 "marker {code:#06X} appears in a tile-part header other than the first; \
742 the coding-parameter overrides belong to the first tile-part of a tile"
743 )));
744 }
745 let (index, shift) = decode_rgn(body()?, self.siz)?;
746 self.first_for(code, "RGN", index, suffix)?;
747 if self.rgn_free {
748 return Err(rgn_without_cap_bit(index));
749 }
750 self.overrides.rgn.push((index, shift));
751 }
752 _ => return Ok(false),
753 }
754 Ok(true)
755 }
756
757 /// Refuse a second `name` marker for component `index` in this header.
758 fn first_for(&mut self, code: u16, name: &str, index: usize, suffix: &str) -> Result<()> {
759 if self.named.insert((code, index)) {
760 Ok(())
761 } else {
762 Err(Error::codestream(format!(
763 "duplicate `{name}` marker for component {index}{suffix}"
764 )))
765 }
766 }
767
768 fn finish(self) -> Overrides {
769 self.overrides
770 }
771}
772
773/// The refusal of an `RGN` for component `index` in a codestream whose
774/// `Ccap15` bit 12 says it holds none (ISO/IEC 15444-15 A.3.4).
775fn rgn_without_cap_bit(index: usize) -> Error {
776 Error::codestream(format!(
777 "`RGN` marker for component {index}, but `CAP` says the codestream has none \
778 (`Ccap15` bit 12 is 0)"
779 ))
780}
781
782/// What has been seen of one tile so far while the tile-parts are walked.
783#[derive(Debug)]
784struct TileParts<'a> {
785 /// Each tile-part's packet data, in `TPsot` order (which is the order they
786 /// must appear in, enforced below).
787 parts: Vec<&'a [u8]>,
788 /// `TNsot` from whichever tile-part stated it, plus one once the
789 /// `TPsot == TNsot` correction is on (see [`count_is_one_short`]); `None`
790 /// while every part so far left it 0 ("not yet known", A.4.2).
791 declared_parts: Option<u16>,
792 /// The tile's own header, from its first tile-part.
793 header: TileHeader,
794 /// What a later tile-part may restate (see [`check_restatement`]), built
795 /// the first time one does.
796 restated: Option<Restated>,
797 /// The tile's packed packet headers from any `PPT` markers, concatenated
798 /// across its tile-parts in `TPsot` order (and within a tile-part in `Zppt`
799 /// order). Empty when the tile carries none, in which case the packet headers
800 /// are inline with the bodies (A.7.5).
801 packed_headers: Vec<u8>,
802}
803
804/// Walk every tile-part from the first `SOT` to the closing `EOC` (A.4.2,
805/// A.4.4) and gather them into one [`Tile`] per tile index.
806///
807/// Tile-parts of different tiles may interleave freely, so this accumulates by
808/// `Isot` and joins each tile's parts at the end. Within one tile they must
809/// arrive in `TPsot` order, and every tile of the grid must be present: a
810/// codestream that skips one describes an image it does not carry, which is a
811/// truncation, not a feature to decode around.
812///
813/// A `Psot` overrun, an out-of-range or out-of-order `TPsot`, a `TNsot` that
814/// disagrees with the parts that arrive, a missing tile, or a missing `EOC` all
815/// reject with [`Error::Codestream`].
816///
817/// With `strict` false, missing data is taken as missing and recorded in
818/// `entries`, and only that: the input may end anywhere after the first
819/// `SOT` (inside a tile-part, its header or the next `SOT`), with or without
820/// an `EOC`; a tile with no tile-part is left out; and `TNsot` is advisory, so
821/// a tile may carry fewer or more tile-parts than it declares. Every other
822/// fault is refused as in a strict walk, including a `TPsot` out of order or
823/// with a gap, since the packets after a gap cannot be placed.
824fn walk_tiles<'a>(
825 bytes: &'a [u8],
826 sot_offset: usize,
827 main: &MainHeader,
828 ppm: &[Vec<u8>],
829 strict: bool,
830 entries: &mut Vec<ReportEntry>,
831) -> Result<Vec<Tile<'a>>> {
832 let tile_count = main.siz.num_tiles() as usize;
833 // `PPM` (main header) supplies one packet-header chunk per tile-part in
834 // codestream order; this counter walks them as the tile-parts are read.
835 let mut ppm_seq = 0usize;
836 let mut tiles: Vec<TileParts<'a>> = (0..tile_count)
837 .map(|_| TileParts {
838 parts: Vec::new(),
839 declared_parts: None,
840 header: TileHeader::default(),
841 restated: None,
842 packed_headers: Vec::new(),
843 })
844 .collect();
845 // OpenJPEG's `TPsot == TNsot` correction (see `count_is_one_short`): looked
846 // for once, when the first tile has all its declared parts, and from then
847 // on added to every `TNsot`.
848 let mut count_checked = false;
849 let mut count_correction = 0u16;
850 // Whether every main-header component codes and quantizes as the main
851 // COD and QCD say, for `check_restatement`; worked out on first use.
852 let uniform = OnceCell::new();
853
854 let mut part_offset = sot_offset;
855 loop {
856 // Not strict: input that ends inside the `SOT` marker segment ends the
857 // codestream there. `SOT` is always 12 bytes (Lsot = 10).
858 if !strict && bytes.len().saturating_sub(part_offset) < 12 {
859 entries.push(ReportEntry::MissingEoc);
860 break;
861 }
862 let mut cur = Cursor::at(bytes, part_offset);
863 // `parse_main_header` stopped on the first SOT and the loop below only
864 // continues when it has just read one, so this is always present.
865 if cur.u16()? != marker::SOT {
866 return Err(Error::codestream("tile-part does not start with `SOT`"));
867 }
868 let sot = decode_sot(segment(&mut cur)?)?;
869
870 let index = usize::from(sot.tile_index);
871 let tile = tiles.get_mut(index).ok_or_else(|| {
872 Error::codestream(format!(
873 "tile-part names tile {index}, but the grid holds {tile_count} tiles"
874 ))
875 })?;
876
877 // A tile's parts are numbered from 0 and shall appear in order (A.4.2),
878 // so TPsot is exactly how many of this tile's parts have already been
879 // seen. That single equality catches a duplicate, a gap, and a
880 // reordering at once.
881 if usize::from(sot.tile_part_index) != tile.parts.len() {
882 return Err(Error::codestream(format!(
883 "tile {index} tile-part index is {}, but {} of its tile-parts have been read",
884 sot.tile_part_index,
885 tile.parts.len(),
886 )));
887 }
888 // TNsot is 0 in a tile-part that does not yet know the count; any part
889 // that does state one must agree with every other that does.
890 if sot.num_tile_parts != 0 {
891 let stated = u16::from(sot.num_tile_parts) + count_correction;
892 // Not strict, the count is advisory: a part past it is read, and
893 // the difference reported once the walk ends.
894 if strict && u16::from(sot.tile_part_index) >= stated {
895 return Err(Error::codestream(format!(
896 "tile {index} tile-part {} of a declared {stated} tile-parts",
897 sot.tile_part_index,
898 )));
899 }
900 match tile.declared_parts {
901 Some(declared) if declared != stated => {
902 return Err(Error::codestream(format!(
903 "tile {index} declares {stated} tile-parts in one `SOT` and {declared} in another",
904 )));
905 }
906 _ => tile.declared_parts = Some(stated),
907 }
908 }
909
910 let first_part = sot.tile_part_index == 0;
911 // Not strict, a tile-part the input ends inside (its `Psot` runs past
912 // the end, or it has none) may end inside its header too. Then the
913 // codestream ends at this tile-part, and none of it is read.
914 let cut = !strict
915 && (sot.psot == 0
916 || part_offset
917 .checked_add(sot.psot as usize)
918 .is_none_or(|end| end > bytes.len()));
919 let (tile_header, packed) = match read_tile_part_header(&mut cur, main, first_part) {
920 Ok(read) => read,
921 Err(_) if cut => {
922 if sot.psot != 0 {
923 entries.push(ReportEntry::TruncatedTilePart {
924 tile: u32::from(sot.tile_index),
925 tile_part: sot.tile_part_index,
926 declared: u64::from(sot.psot),
927 present: (bytes.len() - part_offset) as u64,
928 });
929 }
930 entries.push(ReportEntry::MissingEoc);
931 break;
932 }
933 Err(error) => return Err(error),
934 };
935 if first_part {
936 tile.header = tile_header;
937 } else {
938 // A later tile-part may restate the coding-style values already in
939 // force, which changes nothing; one that differs is refused here.
940 // Its POC volumes are legal and append to the tile's, so the
941 // progression can be split across the tile's parts (A.6.6). Each
942 // part's list is capped, so the accumulation across parts must be
943 // re-checked.
944 check_restatement(main, &uniform, tile, &tile_header, index)?;
945 check_poc_budget(tile.header.poc.len() + tile_header.poc.len())?;
946 tile.header.poc.extend(tile_header.poc);
947 }
948 // Packed packet headers append across the tile's parts in TPsot order
949 // (which is arrival order, enforced above), matching the body order.
950 // They come from `PPT` (this tile-part's own markers) or `PPM` (the main
951 // header, one chunk per tile-part in codestream order) — never both for
952 // the same packets, so a codestream carrying each is out of subset.
953 if ppm.is_empty() {
954 tile.packed_headers.extend(packed);
955 } else {
956 if !packed.is_empty() {
957 return Err(Error::unsupported(
958 "a codestream carrying both `PPM` and `PPT` packed headers is not decoded",
959 ));
960 }
961 let chunk = ppm.get(ppm_seq).ok_or_else(|| {
962 Error::codestream(
963 "`PPM` carries fewer packet-header chunks than the codestream has tile-parts",
964 )
965 })?;
966 ppm_seq += 1;
967 tile.packed_headers.extend_from_slice(chunk);
968 }
969 let data_start = cur.pos;
970
971 // Psot counts from the SOT marker's first byte to the end of the
972 // tile-part. Psot == 0 marks the *last* tile-part (A.4.2). Like
973 // OpenJPEG, give it everything up to the last two bytes of the buffer,
974 // the room for an EOC, without checking that those bytes are FF D9. A
975 // stream with no EOC therefore loses its last two data bytes, as it
976 // does in OpenJPEG, and fails later when the tile's packets run short.
977 // Scanning for the first FF D9 instead would be unsound: bit stuffing
978 // keeps packet data and headers clear of it, but an SOP segment's Nsop
979 // counter is two raw bytes and can spell FF D9 (packet 65497, or a 0xFF
980 // low byte abutting 0xD9), which would silently truncate a valid tile.
981 // The asymmetry with the Psot != 0 arm (which ignores bytes after its
982 // EOC) is therefore deliberate: with no declared length there is nothing
983 // else to anchor to.
984 let data_end = if sot.psot == 0 {
985 match bytes.len().checked_sub(2).filter(|&end| end >= data_start) {
986 Some(end) => end,
987 // Not strict, the codestream ends within two bytes of the
988 // header: the tile-part has no data, and its packets are
989 // missing.
990 None if !strict => data_start,
991 None => {
992 return Err(Error::codestream(format!(
993 "tile {} tile-part {} has `Psot` 0 and fewer than two bytes after its \
994 header",
995 sot.tile_index, sot.tile_part_index
996 )));
997 }
998 }
999 } else {
1000 let end = match part_offset
1001 .checked_add(sot.psot as usize)
1002 .filter(|&end| end <= bytes.len())
1003 {
1004 Some(end) => end,
1005 // Not strict, a tile-part cut short is read as far as it goes,
1006 // and the codestream ends there.
1007 None if !strict => {
1008 entries.push(ReportEntry::TruncatedTilePart {
1009 tile: u32::from(sot.tile_index),
1010 tile_part: sot.tile_part_index,
1011 declared: u64::from(sot.psot),
1012 present: (bytes.len() - part_offset) as u64,
1013 });
1014 bytes.len()
1015 }
1016 None => {
1017 return Err(Error::codestream(format!(
1018 "tile {} tile-part {} declares `Psot` {}, but only {} bytes are left in \
1019 the codestream",
1020 sot.tile_index,
1021 sot.tile_part_index,
1022 sot.psot,
1023 bytes.len() - part_offset
1024 )));
1025 }
1026 };
1027 if end < data_start {
1028 return Err(Error::codestream(format!(
1029 "tile {} tile-part {} declares `Psot` {}, shorter than its {}-byte header",
1030 sot.tile_index,
1031 sot.tile_part_index,
1032 sot.psot,
1033 data_start - part_offset
1034 )));
1035 }
1036 end
1037 };
1038 let tile = &mut tiles[index];
1039 tile.parts.push(&bytes[data_start..data_end]);
1040
1041 // The first time a tile has every part it declares, look ahead for one
1042 // more part of it, as OpenJPEG does (`count_is_one_short`). If there is
1043 // one, every count is one short: raise each one stated so far, and
1044 // each one stated from here on.
1045 if !count_checked && tile.declared_parts == Some(u16::from(sot.tile_part_index) + 1) {
1046 count_checked = true;
1047 if sot.psot != 0 && count_is_one_short(bytes, data_end, sot.tile_index) {
1048 count_correction = 1;
1049 for tile in &mut tiles {
1050 if let Some(declared) = &mut tile.declared_parts {
1051 *declared += 1;
1052 }
1053 }
1054 }
1055 }
1056
1057 // A Psot = 0 tile-part is the last one: the walk ends there, whatever
1058 // the two bytes after its data are.
1059 if sot.psot == 0 {
1060 break;
1061 }
1062 // Not strict, a tile-part cut short ends the codestream.
1063 if data_end == bytes.len() && !strict {
1064 entries.push(ReportEntry::MissingEoc);
1065 break;
1066 }
1067
1068 // Another SOT continues the walk; EOC ends it. Anything else — or
1069 // nothing at all — means the tile-part chain does not close.
1070 match read_u16(bytes, data_end) {
1071 Some(marker::EOC) => break,
1072 Some(marker::SOT) => part_offset = data_end,
1073 Some(other) => {
1074 return Err(Error::codestream(format!(
1075 "expected `SOT` or `EOC` after a tile-part, found {other:#06X}"
1076 )));
1077 }
1078 // Not strict, the input may end after any tile-part.
1079 None if !strict => {
1080 entries.push(ReportEntry::MissingEoc);
1081 break;
1082 }
1083 None => {
1084 return Err(Error::codestream("missing `EOC` after the tile-part"));
1085 }
1086 }
1087 }
1088
1089 // Every PPM chunk maps to one tile-part; leftover chunks mean the main header
1090 // packed headers for tile-parts the codestream never carried. Not strict,
1091 // a codestream that ends early may not reach the last of them.
1092 let ended_early = entries.last() == Some(&ReportEntry::MissingEoc);
1093 if ppm_seq != ppm.len() && !(ended_early && ppm_seq < ppm.len()) {
1094 return Err(Error::codestream(format!(
1095 "`PPM` carries {} packet-header chunk(s) but the codestream has {ppm_seq} tile-part(s)",
1096 ppm.len(),
1097 )));
1098 }
1099
1100 let mut found = Vec::with_capacity(tiles.len());
1101 // Not strict: the run of missing tiles being gathered, as (first, end).
1102 let mut missing: Option<(u32, u32)> = None;
1103 for (index, tile) in tiles.into_iter().enumerate() {
1104 if tile.parts.is_empty() {
1105 if strict {
1106 return Err(Error::codestream(format!(
1107 "the codestream carries no tile-part for tile {index}"
1108 )));
1109 }
1110 let index = index as u32;
1111 missing = Some(missing.map_or((index, index + 1), |(first, _)| (first, index + 1)));
1112 continue;
1113 }
1114 if let Some((first, end)) = missing.take() {
1115 entries.push(ReportEntry::MissingTiles { tiles: first..end });
1116 }
1117 if let Some(declared) = tile.declared_parts {
1118 if usize::from(declared) != tile.parts.len() {
1119 if strict {
1120 return Err(Error::codestream(format!(
1121 "tile {index} declares {declared} tile-parts but carries {}",
1122 tile.parts.len()
1123 )));
1124 }
1125 entries.push(ReportEntry::TilePartCountMismatch {
1126 tile: index as u32,
1127 declared,
1128 found: tile.parts.len() as u16,
1129 });
1130 }
1131 }
1132 found.push((index, tile));
1133 }
1134 if let Some((first, end)) = missing {
1135 entries.push(ReportEntry::MissingTiles { tiles: first..end });
1136 }
1137
1138 found
1139 .into_iter()
1140 .map(|(index, tile)| {
1141 // One part: borrow it. Several: join them, which is exact — a
1142 // tile-part holds a whole number of packets (B.9), so nothing
1143 // straddles the seam.
1144 let data = match <[&[u8]; 1]>::try_from(tile.parts.as_slice()) {
1145 Ok([only]) => Cow::Borrowed(only),
1146 Err(_) => Cow::Owned(tile.parts.concat()),
1147 };
1148 let part_ends = tile
1149 .parts
1150 .iter()
1151 .scan(0, |end, part| {
1152 *end += part.len();
1153 Some(*end)
1154 })
1155 .collect();
1156 Ok(Tile {
1157 index: index as u32,
1158 header: tile.header,
1159 data,
1160 part_ends,
1161 packed_headers: tile.packed_headers,
1162 })
1163 })
1164 .collect()
1165}
1166
1167/// Whether the tile-part chain from `from` holds another part of tile `tile`
1168/// whose `TPsot` equals its `TNsot`, so that every `TNsot` in the codestream
1169/// is one short of the parts it carries.
1170///
1171/// Some encoders (Adobe Photoshop's plug-in is one) number a tile's parts
1172/// 0 to N and declare N of them. OpenJPEG 2.5.0 corrects this on purpose
1173/// (`opj_j2k_need_nb_tile_parts_correction`, its issue 254: "Non conformant
1174/// codestream TPsot==TNsot"), and this copies its test. Once, when the first
1175/// tile has every part it declares, it walks the `SOT` chain onward, stepping
1176/// over other tiles' parts by `Psot`, to the next part of the same tile. If
1177/// that part has `TPsot == TNsot`, every tile's count is raised by one. The
1178/// walk gives up, finding nothing, at anything other than an `SOT`, at a
1179/// `Psot` below 14 (`0` included) on another tile's part, or at a `Psot` past
1180/// the end, as OpenJPEG's does.
1181///
1182/// The raised counts are held to the parts that arrive, as any count is, and
1183/// the parts are still read in `TPsot` order.
1184fn count_is_one_short(bytes: &[u8], from: usize, tile: u16) -> bool {
1185 let mut at = from;
1186 loop {
1187 if read_u16(bytes, at) != Some(marker::SOT) {
1188 return false;
1189 }
1190 // A malformed SOT ends the look-ahead; the walk reaches the same SOT
1191 // and refuses it there.
1192 let mut cur = Cursor::at(bytes, at + 2);
1193 let Ok(sot) = segment(&mut cur).and_then(decode_sot) else {
1194 return false;
1195 };
1196 if sot.tile_index == tile {
1197 return sot.tile_part_index == sot.num_tile_parts;
1198 }
1199 if sot.psot < 14 {
1200 return false;
1201 }
1202 match at.checked_add(sot.psot as usize) {
1203 Some(next) if next <= bytes.len() => at = next,
1204 _ => return false,
1205 }
1206 }
1207}
1208
1209/// Whether every main-header component codes and quantizes as the main COD and
1210/// QCD say, so that no main COC or QCC changes anything.
1211#[derive(Debug, Clone, Copy)]
1212struct Uniform {
1213 coding: bool,
1214 quant: bool,
1215}
1216
1217impl Uniform {
1218 fn of(main: &MainHeader) -> Self {
1219 Uniform {
1220 coding: main.components.iter().all(|p| p.coding == main.cod.coding),
1221 quant: main.components.iter().all(|p| p.quant == main.qcd),
1222 }
1223 }
1224}
1225
1226/// What [`check_restatement`] knows about one tile: where its own COC and QCC
1227/// markers are, by component, and the COD and QCD a later part has already
1228/// been found to restate.
1229#[derive(Debug, Default)]
1230struct Restated {
1231 coc: HashMap<usize, usize>,
1232 qcc: HashMap<usize, usize>,
1233 cod: Option<Cod>,
1234 qcd: Option<Qcd>,
1235}
1236
1237/// Accept a later tile-part's COD, COC, QCD and QCC only when each restates
1238/// the value already in force for the tile; refuse one that differs.
1239///
1240/// A.4.2 puts these markers in a tile's first tile-part. Some encoders (BAP
1241/// Image Systems is one) repeat the main header's COD and QCD in every
1242/// tile-part. OpenJPEG 2.5.0 reads a COD or QCD in any tile-part header
1243/// (`J2K_STATE_TPH` in its marker table) and applies it to the whole tile; it
1244/// dropped its "one COD per tile" check on purpose so that files like these
1245/// decode (`opj_j2k_read_cod`, its issue 1043, a BAP bulk-scanner file).
1246///
1247/// Here a restatement must change nothing, in this decoder's reading or in
1248/// OpenJPEG's, and it is then dropped. OpenJPEG writes a COD over every
1249/// component of the tile, and a QCD likewise, so a COD is accepted only when
1250/// it equals the tile's COD in force and every component of the tile already
1251/// codes as it says, and a QCD the same way. A COC or QCC must equal what its
1252/// component already has. Anything else is refused: the tile's earlier parts
1253/// are read under one set of values and its later parts would name another,
1254/// and which one the encoder meant is not in the file.
1255///
1256/// The cost is bounded by the markers read: a tile's COC and QCC are indexed
1257/// once, a COD or QCD found to restate is remembered, and whether the main
1258/// header's components are uniform is worked out once per codestream.
1259fn check_restatement(
1260 main: &MainHeader,
1261 uniform: &OnceCell<Uniform>,
1262 tile: &mut TileParts<'_>,
1263 later: &TileHeader,
1264 index: usize,
1265) -> Result<()> {
1266 let later = &later.overrides;
1267 if !later.codes_or_quantizes() {
1268 return Ok(());
1269 }
1270 let own = &tile.header.overrides;
1271 let restated = tile.restated.get_or_insert_with(|| Restated {
1272 coc: own
1273 .coc
1274 .iter()
1275 .enumerate()
1276 .map(|(at, (c, _))| (*c, at))
1277 .collect(),
1278 qcc: own
1279 .qcc
1280 .iter()
1281 .enumerate()
1282 .map(|(at, (c, _))| (*c, at))
1283 .collect(),
1284 ..Restated::default()
1285 });
1286 let differs = |what: String| {
1287 Error::codestream(format!(
1288 "a later tile-part of tile {index} carries a {what} that differs from the one \
1289 in force; the coding-parameter overrides belong to the first tile-part of a tile"
1290 ))
1291 };
1292
1293 if let Some(cod) = &later.cod {
1294 if restated.cod.as_ref() != Some(cod) {
1295 let coding = &cod.coding;
1296 let same = cod == own.cod.as_ref().unwrap_or(&main.cod)
1297 && own.coc.iter().all(|(_, c)| c == coding)
1298 && (own.cod.is_some() || uniform.get_or_init(|| Uniform::of(main)).coding);
1299 if !same {
1300 return Err(differs("`COD`".into()));
1301 }
1302 restated.cod = Some(cod.clone());
1303 }
1304 }
1305 if let Some(qcd) = &later.qcd {
1306 if restated.qcd.as_ref() != Some(qcd) {
1307 let same = qcd == own.qcd.as_ref().unwrap_or(&main.qcd)
1308 && own.qcc.iter().all(|(_, q)| q == qcd)
1309 && (own.qcd.is_some() || uniform.get_or_init(|| Uniform::of(main)).quant);
1310 if !same {
1311 return Err(differs("`QCD`".into()));
1312 }
1313 restated.qcd = Some(qcd.clone());
1314 }
1315 }
1316 for (component, coding) in &later.coc {
1317 let same = match (restated.coc.get(component), &own.cod) {
1318 (Some(&at), _) => own.coc[at].1 == *coding,
1319 (None, Some(cod)) => cod.coding == *coding,
1320 (None, None) => main.components[*component].coding == *coding,
1321 };
1322 if !same {
1323 return Err(differs(format!("`COC` for component {component}")));
1324 }
1325 }
1326 for (component, quant) in &later.qcc {
1327 let same = match (restated.qcc.get(component), &own.qcd) {
1328 (Some(&at), _) => own.qcc[at].1 == *quant,
1329 (None, Some(qcd)) => qcd == quant,
1330 (None, None) => main.components[*component].quant == *quant,
1331 };
1332 if !same {
1333 return Err(differs(format!("`QCC` for component {component}")));
1334 }
1335 }
1336 Ok(())
1337}
1338
1339/// Read one tile-part header: the markers between its `SOT` segment and its
1340/// `SOD` (A.4.2). The cursor is left on the first byte of the packet data.
1341///
1342/// Only the *first* tile-part of a tile may carry the coding-parameter overrides
1343/// (COD/COC/QCD/QCC/RGN): they say how to read the tile's packets. A later
1344/// part's COD, COC, QCD and QCC are returned for the caller to hold to the
1345/// values in force ([`check_restatement`]); [`OverrideReader`] refuses a later
1346/// RGN, as a malformed codestream rather than an unsupported one.
1347fn read_tile_part_header(
1348 cur: &mut Cursor<'_>,
1349 main: &MainHeader,
1350 first_part: bool,
1351) -> Result<(TileHeader, Vec<u8>)> {
1352 let siz = &main.siz;
1353 let mut tile = TileHeader::default();
1354 let mut overrides = OverrideReader::new(siz, Place::TilePart { first: first_part });
1355 if main.ccap15.is_some_and(|c| !c.rgn()) {
1356 // Nothing is read yet, so this cannot fail.
1357 overrides.forbid_rgn()?;
1358 }
1359 // `PPT` packet headers for this tile-part, collected as `(Zppt, bytes)` and
1360 // concatenated in `Zppt` order below.
1361 let mut ppt: Vec<(u8, Vec<u8>)> = Vec::new();
1362
1363 loop {
1364 let m = cur.u16()?;
1365 if overrides.read(m, || segment(cur))? {
1366 continue;
1367 }
1368 match m {
1369 marker::SOD => break,
1370 marker::COM => {
1371 segment(cur)?;
1372 }
1373 // Packet lengths (A.7.3): informational, so the structure is
1374 // validated and the lengths discarded — the packets are read from
1375 // the data itself, and decoding must not depend on the hint.
1376 marker::PLT => {
1377 decode_plt(segment(cur)?)?;
1378 }
1379 // A tile-part POC sets the progression for this tile, replacing the
1380 // main header's (see `resolve_tile_header`). Unlike the coding-style
1381 // overrides, it is legal in *any* tile-part, not just the first
1382 // (B.12.3, OpenJPEG's `J2K_STATE_TPH`), and volumes accumulate
1383 // across every one of the tile's parts — so a later tile-part may
1384 // carry one.
1385 marker::POC => {
1386 decode_poc(segment(cur)?, siz, &mut tile.poc)?;
1387 }
1388 // Packed packet headers (A.7.5): this tile-part's packet headers,
1389 // moved out of the bitstream into the marker. `Zppt` orders the
1390 // markers of one tile-part; the bytes after it are `Ippt`. Legal in
1391 // any tile-part (the headers span all of them). Collected here and
1392 // stitched into the tile's packed buffer by the caller; a decoder
1393 // that ignored them would read packet headers off the packet bodies
1394 // and decode garbage.
1395 marker::PPT => {
1396 let mut body = segment(cur)?;
1397 let zppt = body.u8()?;
1398 if ppt.iter().any(|&(z, _)| z == zppt) {
1399 return Err(Error::codestream(format!(
1400 "duplicate `PPT` index `Zppt` {zppt} in one tile-part header"
1401 )));
1402 }
1403 let ippt = body.take(body.remaining())?;
1404 ppt.push((zppt, ippt.to_vec()));
1405 }
1406 // These are legal markers, but not here: TLM and PLM are
1407 // main-header-only (A.7.1, A.7.2), and SOP/EPH delimit packets
1408 // after SOD. In a tile-part header they are a malformed
1409 // codestream, not a missing feature.
1410 marker::TLM | marker::PLM | marker::SOP | marker::EPH => {
1411 return Err(Error::codestream(format!(
1412 "marker {m:#06X} is not permitted in a tile-part header"
1413 )));
1414 }
1415 // CAP and CPF describe the whole codestream, so they belong in the
1416 // main header only (ISO/IEC 15444-1 A.5.2, ISO/IEC 15444-15 A.6);
1417 // OpenJPEG reads both there only. Here, like a misplaced TLM, they
1418 // are a malformed codestream.
1419 marker::CAP | marker::CPF => {
1420 return Err(Error::codestream(format!(
1421 "{} is a main-header marker; it is not permitted in a tile-part header",
1422 marker::describe(m)
1423 )));
1424 }
1425 other => {
1426 return Err(Error::codestream(format!(
1427 "unexpected marker {other:#06X} in tile-part header"
1428 )));
1429 }
1430 }
1431 }
1432 // Stitch this tile-part's PPT markers into one buffer, ordered by Zppt.
1433 ppt.sort_by_key(|&(z, _)| z);
1434 let packed = ppt.into_iter().flat_map(|(_, bytes)| bytes).collect();
1435 tile.overrides = overrides.finish();
1436 // `parse_tiles` reads this flag from the first tile-part only; the
1437 // `first_part` test is defensive.
1438 tile.poc_in_first_part = first_part && !tile.poc.is_empty();
1439 Ok((tile, packed))
1440}
1441
1442/// Resolve one tile's effective parameters: the main header with the tile-part
1443/// header's markers laid over it, in the standard's precedence order (A.6.1).
1444///
1445/// For each component the winner is the first of
1446///
1447/// ```text
1448/// tile COC > tile COD > main COC > main COD
1449/// ```
1450///
1451/// and likewise QCC > QCD down the same two levels. The middle two are the trap:
1452/// a **tile COD outranks a main-header COC**. So it is not enough to lay the
1453/// tile's markers over the main header's resolved components — the main COC
1454/// would win a contest it lost, and the tile would decode on a pyramid no marker
1455/// described.
1456///
1457/// The ladder falls out instead: the main header's resolved components already
1458/// encode `main COC > main COD`, so a tile COD overwrites *every* component's
1459/// coding (beating any main COC), and a tile COC then overwrites the one
1460/// component it names (beating the tile COD). An RGN in a tile-part header
1461/// likewise *replaces* the main header's for that component (A.6.3).
1462///
1463/// A tile with no markers of its own decodes under the main header unchanged,
1464/// so that is returned borrowed: the main header already passed every check
1465/// below. Any other tile is a copy, sized by the component count.
1466fn resolve_tile_header<'m>(main: &'m MainHeader, tile: &TileHeader) -> Result<Cow<'m, MainHeader>> {
1467 if *tile == TileHeader::default() {
1468 return Ok(Cow::Borrowed(main));
1469 }
1470 let mut header = main.clone();
1471
1472 // A tile COD/QCD is the tile's new default: it displaces the main header's
1473 // COD/QCD *and* any main-header COC/QCC, so `lay_over` lands it on every
1474 // component, then lays the tile's own per-component markers over that.
1475 let overrides = &tile.overrides;
1476 if let Some(cod) = &overrides.cod {
1477 header.cod.clone_from(cod);
1478 }
1479 if let Some(qcd) = &overrides.qcd {
1480 header.qcd.clone_from(qcd);
1481 }
1482 overrides.lay_over(&mut header.components);
1483
1484 // A tile-part POC *overrides* the main header's for this tile (A.6.6:
1485 // "Tile-part POC > Main POC > Tile-part COD > Main COD", the greater
1486 // overriding the lesser; B.12.3 likewise). A.6.6 also requires that POC to
1487 // be in the tile's first tile-part. So a tile whose first tile-part has a
1488 // POC walks only its own volumes, accumulated across its tile-parts in
1489 // order. OpenJPEG 2.5.0 instead seeds each tile from the main header, POC
1490 // included, and `opj_j2k_read_poc` appends the tile-part's volumes after
1491 // it, so a file carrying both decodes wrong there (docs/openjpeg-departures.md).
1492 //
1493 // A tile whose first POC is in a later tile-part breaks A.6.6. Its first
1494 // packets can only follow the main header's order, so it is read as
1495 // OpenJPEG reads it: the main volumes, then the tile's. A tile with no POC
1496 // keeps the main header's from `main.clone()` above.
1497 check_poc_budget(resolved_poc_len(main, tile))?;
1498 if tile.poc_in_first_part {
1499 header.poc.clone_from(&tile.poc);
1500 } else {
1501 header.poc.extend(tile.poc.iter().copied());
1502 }
1503
1504 // The tile's resolved parameters must hold every invariant the main header's
1505 // do: a tile COD/QCD pair can break one the main header kept.
1506 validate_resolved(&header)?;
1507 Ok(Cow::Owned(header))
1508}
1509
1510/// SOT fields (A.4.2): the tile index, tile-part length, part index, and part
1511/// count. The packet-data extent is derived from `psot` by the caller.
1512struct Sot {
1513 tile_index: u16,
1514 psot: u32,
1515 tile_part_index: u8,
1516 num_tile_parts: u8,
1517}
1518
1519/// Decode the SOT marker segment body (everything after `Lsot`): Isot, Psot,
1520/// TPsot, TNsot. `expect_consumed` enforces the fixed `Lsot == 10` layout.
1521fn decode_sot(mut b: Cursor<'_>) -> Result<Sot> {
1522 let tile_index = b.u16()?;
1523 let psot = b.u32()?;
1524 let tile_part_index = b.u8()?;
1525 let num_tile_parts = b.u8()?;
1526 b.expect_consumed("`SOT`")?;
1527 Ok(Sot {
1528 tile_index,
1529 psot,
1530 tile_part_index,
1531 num_tile_parts,
1532 })
1533}
1534
1535/// Read a big-endian `u16` marker at `pos`, or `None` if it would run past the
1536/// end. Used to peek the marker that follows a tile-part without disturbing the
1537/// segment cursor.
1538fn read_u16(bytes: &[u8], pos: usize) -> Option<u16> {
1539 let hi = *bytes.get(pos)?;
1540 let lo = *bytes.get(pos + 1)?;
1541 Some(u16::from_be_bytes([hi, lo]))
1542}
1543
1544/// One marker segment located by the structural walk: its code and its body
1545/// (empty for the segment-less markers).
1546struct Segment<'a> {
1547 code: u16,
1548 body: &'a [u8],
1549}
1550
1551/// Upper bound on the marker segments a main header may carry.
1552///
1553/// A segment-less marker costs two input bytes but one `Segment` record, so a
1554/// run of them would grow the located-segment list several times faster than the
1555/// input it came from. The largest conformant header is far smaller than this:
1556/// `Csiz` tops out at 16384, and even a COC *and* a QCC per component is 32768
1557/// segments, so this bound cannot reject a real codestream.
1558const MAX_MAIN_HEADER_SEGMENTS: usize = 1 << 16;
1559
1560/// Walk the main header's marker segments from just after `SOC` to the first
1561/// `SOT`, without judging any of them (A.6).
1562///
1563/// This is deliberately subset-agnostic: it establishes *where every segment
1564/// is*, and leaves "can we decode this?" to the caller. Running the whole walk
1565/// before any segment is interpreted is what lets a codestream carrying an
1566/// out-of-subset feature still be traversed end to end — which is the only way
1567/// a marker sitting *after* the offending one gets exercised at all.
1568///
1569/// Two shapes a naive walker gets wrong, both present in the corpus:
1570///
1571/// - the reserved range `0xFF30..=0xFF3F` carries **no** length field; reading
1572/// one consumes the bytes that follow (`p0_02` has `0xFF30` after its `COM`);
1573/// - a marker this decoder does not recognize still has a length, so the walk
1574/// can step over it. Whether the *decoder* may proceed past it is a different
1575/// question, and `parse_main_header` answers it with `Unsupported`.
1576///
1577/// Returns the segments in codestream order and the offset of the `SOT` that
1578/// ended the header. When the input ends after `SOC` and before the first
1579/// `SOT` marker is whole, the offset is [`Error::Incomplete`] instead and the
1580/// segments are those the input holds in full, so the caller can judge them
1581/// before it reports the cut: the walk reads only marker codes and lengths
1582/// here, so running out of input means the input was cut short (or a length
1583/// was damaged to reach past it, which looks the same). A non-marker where a
1584/// marker must be, a length below 2, and `SOD`/`EOC` before any tile-part are
1585/// [`Error::Codestream`].
1586fn walk_main_header(bytes: &[u8]) -> Result<(Vec<Segment<'_>>, Result<usize>)> {
1587 let mut cur = Cursor::new(bytes);
1588
1589 // 0 bytes, or `FF` alone, may still become `SOC`.
1590 if bytes.len() < 2 && marker::SOC.to_be_bytes().starts_with(bytes) {
1591 return Err(Error::incomplete(
1592 "the input ends before the codestream's `SOC` marker is whole",
1593 ));
1594 }
1595 if cur.u16().ok() != Some(marker::SOC) {
1596 return Err(Error::codestream("does not start with the `SOC` marker"));
1597 }
1598
1599 let mut segments = Vec::new();
1600 let sot_offset = loop {
1601 let Ok(code) = cur.u16() else {
1602 break Err(cut_short("before its first `SOT` marker"));
1603 };
1604 match code {
1605 // The first SOT ends the main header; point the offset back at it.
1606 marker::SOT => break Ok(cur.pos - 2),
1607
1608 // A second SOC, or a delimiter that belongs to a tile-part, means
1609 // the header is malformed rather than merely unfamiliar.
1610 marker::SOC | marker::SOD | marker::EOC => {
1611 return Err(Error::codestream(format!(
1612 "unexpected marker {code:#06X} before any tile-part"
1613 )));
1614 }
1615
1616 _ if !marker::is_marker(code) => {
1617 return Err(Error::codestream(format!(
1618 "expected a marker in the main header, found {code:#06X}"
1619 )));
1620 }
1621
1622 // Everything else is located, not interpreted.
1623 _ => {
1624 // A segment-less marker advances only two bytes, so a run of
1625 // them would grow `segments` at ~12x the input. Bound it: no
1626 // conformant main header comes close, and the cap keeps a hostile
1627 // input's allocation proportional to nothing but this constant.
1628 if segments.len() == MAX_MAIN_HEADER_SEGMENTS {
1629 return Err(Error::codestream(format!(
1630 "main header has more than {MAX_MAIN_HEADER_SEGMENTS} marker segments"
1631 )));
1632 }
1633 let body = if marker::has_segment(code) {
1634 match main_header_segment(&mut cur)? {
1635 Some(body) => body,
1636 None => {
1637 break Err(cut_short(&format!(
1638 "in its {} segment",
1639 marker::describe(code)
1640 )));
1641 }
1642 }
1643 } else {
1644 &[][..]
1645 };
1646 segments.push(Segment { code, body });
1647 }
1648 }
1649 };
1650
1651 Ok((segments, sot_offset))
1652}
1653
1654/// The body of the main-header segment whose marker the walk just read, as
1655/// [`segment`] reads it, or `None` when the input ends inside its length or
1656/// its body: a cut, not a malformed segment.
1657fn main_header_segment<'a>(cur: &mut Cursor<'a>) -> Result<Option<&'a [u8]>> {
1658 let Ok(len) = cur.u16() else {
1659 return Ok(None);
1660 };
1661 if len < 2 {
1662 return Err(Error::codestream("marker segment length below 2"));
1663 }
1664 Ok(cur.take(usize::from(len) - 2).ok())
1665}
1666
1667/// The input ends inside the main header, at `place`.
1668fn cut_short(place: &str) -> Error {
1669 Error::incomplete(format!("the input ends inside the main header, {place}"))
1670}
1671
1672/// Parse the main header up to (but not into) the first `SOT`.
1673///
1674/// Returns the decoded [`MainHeader`] and the byte offset of that `SOT` marker,
1675/// which is where tile-part walking (issue #6) begins. Stops before any
1676/// entropy-coded data, so it never touches packet bytes.
1677///
1678/// The header is walked in full by [`walk_main_header`] first, then each
1679/// located segment is interpreted in codestream order.
1680fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize, Vec<Vec<u8>>)> {
1681 // A cut header is judged on the segments the input holds in full, in the
1682 // order a whole one is, so a damaged segment before the cut is reported
1683 // as it would be in the whole file; `end` reports the cut only once those
1684 // all pass.
1685 let (segments, end) = walk_main_header(bytes)?;
1686
1687 // SIZ shall be the first marker segment after SOC (A.6).
1688 let Some(first) = segments.first() else {
1689 end?;
1690 return Err(Error::codestream("main header has no marker segments"));
1691 };
1692 if first.code != marker::SIZ {
1693 return Err(Error::codestream(
1694 "`SIZ` must be the first marker after `SOC`",
1695 ));
1696 }
1697 let siz = decode_siz(Cursor::new(first.body))?;
1698
1699 // Judge the image before its coding parameters, so a codestream outside the
1700 // subset reports the *image* feature that blocks it (an origin, a tile grid)
1701 // rather than whichever coding-style bit COD happens to trip on first. Both
1702 // are `Unsupported`; this is about which reason is useful to read.
1703 validate_geometry(&siz)?;
1704 check_sample_container(&siz)?;
1705
1706 let mut overrides = OverrideReader::new(&siz, Place::Main);
1707 // TLM entries met so far, which is the tile index an `ST = 0` entry
1708 // implies.
1709 let mut tlm_entries = 0usize;
1710 let mut poc: Vec<PocVolume> = Vec::new();
1711 let mut crg: Option<Vec<(u16, u16)>> = None;
1712 // `CAP` and `CPF`, each at most once: `Some(ccap15)` once a CAP is read.
1713 let mut cap: Option<Option<Ccap15>> = None;
1714 let mut cpf: Option<Cpf> = None;
1715 // Packed packet headers (A.7.4), collected as `(Zppm, Ippm)` and split into
1716 // per-tile-part chunks after the walk by `decode_ppm_chunks`.
1717 let mut ppm: Vec<(u8, Vec<u8>)> = Vec::new();
1718
1719 for seg in &segments[1..] {
1720 let body = || Cursor::new(seg.body);
1721 if overrides.read(seg.code, || Ok(body()))? {
1722 continue;
1723 }
1724 match seg.code {
1725 marker::SIZ => {
1726 return Err(Error::codestream("duplicate `SIZ` marker"));
1727 }
1728 // Comment: recognized, carries nothing the decoder needs.
1729 marker::COM => {}
1730
1731 // Length markers (A.7): pointers into the codestream, not decode
1732 // parameters — the packet and tile-part structures they describe
1733 // are read from the codestream itself, so decoding is identical
1734 // with them present or absent. TLM's entries are validated and
1735 // dropped, since no decode step reads them and a header can hold
1736 // millions; PLM's packet lengths are skipped as OpenJPEG skips
1737 // them (`opj_j2k_read_plm` reads nothing past `Zplm`).
1738 marker::TLM => decode_tlm(body(), &siz, &mut tlm_entries, |_| {})?,
1739 marker::PLM => decode_plm(body())?,
1740
1741 // Progression-order change (A.6.6): a sequence of progression volumes
1742 // that replaces COD's single order for the whole codestream. Volumes
1743 // accumulate across markers.
1744 marker::POC => decode_poc(body(), &siz, &mut poc)?,
1745
1746 // Component registration (A.9.1): sub-pixel display offsets, recorded
1747 // but not applied. One CRG per codestream (main-header only).
1748 marker::CRG => {
1749 if crg.replace(decode_crg(body(), &siz)?).is_some() {
1750 return Err(Error::codestream("duplicate `CRG` marker"));
1751 }
1752 }
1753
1754 // PLT is the tile-part-header form of PLM (A.7.3); in the main
1755 // header it is a malformed codestream, not a missing feature.
1756 marker::PLT => {
1757 return Err(Error::codestream(
1758 "`PLT` is a tile-part-header marker; it is not permitted in the main header",
1759 ));
1760 }
1761
1762 // Packed packet headers in the main header (A.7.4): `Zppm` orders
1763 // this marker among the header's PPM markers, and the rest is `Ippm`.
1764 // Collected here and split per tile-part after the walk; a tile-part
1765 // then sources its packet headers from its chunk (see `walk_tiles`).
1766 marker::PPM => {
1767 let mut b = body();
1768 let zppm = b.u8()?;
1769 let ippm = b.take(b.remaining())?;
1770 ppm.push((zppm, ippm.to_vec()));
1771 }
1772
1773 // Extended capabilities (ISO/IEC 15444-1 A.5.2) and the
1774 // corresponding profile (ISO/IEC 15444-15 A.6): one of each per
1775 // codestream.
1776 marker::CAP => {
1777 let ccap15 = decode_cap(body())?;
1778 if cap.replace(ccap15).is_some() {
1779 return Err(Error::codestream("duplicate `CAP` marker"));
1780 }
1781 if ccap15.is_some_and(|c| !c.rgn()) {
1782 overrides.forbid_rgn()?;
1783 }
1784 }
1785 marker::CPF => {
1786 if cpf.replace(decode_cpf(body())?).is_some() {
1787 return Err(Error::codestream("duplicate `CPF` marker"));
1788 }
1789 }
1790
1791 // Valid markers the decoded subset does not yet cover. Rejected
1792 // rather than skipped: each one changes how the codestream is
1793 // interpreted, so ignoring it would silently decode the wrong
1794 // image. PPT/SOP/EPH belong after SOD or in a tile-part header,
1795 // not the main one.
1796 marker::PPT | marker::SOP | marker::EPH => {
1797 return Err(Error::unsupported(format!(
1798 "marker {} is outside the decoded subset",
1799 marker::describe(seg.code)
1800 )));
1801 }
1802
1803 // A JPEG 2000 Part 2 codestream marker (ISO/IEC 15444-2). Named so
1804 // the rejection says which Part 2 feature blocks the decode —
1805 // multiple-component transforms, non-linearity, extra bit depths —
1806 // rather than reading as a bare unknown code.
1807 code if marker::PART2.contains(&code) => {
1808 return Err(Error::unsupported(format!(
1809 "{} is a JPEG 2000 Part 2 marker, outside the Part 1 subset",
1810 marker::describe(seg.code)
1811 )));
1812 }
1813
1814 // The reserved segment-less range is *defined* to carry nothing, so
1815 // it is the one thing that can be passed over safely.
1816 code if marker::RESERVED_NO_SEGMENT.contains(&code) => {}
1817
1818 // Any other marker this decoder does not know. The walk stepped over
1819 // its segment — that is what lets the header be traversed at all —
1820 // but we will not decode past it: every marker code is allocated by
1821 // some part of the standard, and an unknown one may well change what
1822 // the packet data means. Guessing that it is ignorable would trade
1823 // a clean rejection for a silently wrong image.
1824 other => {
1825 return Err(Error::unsupported(format!(
1826 "unrecognized marker {other:#06X} in the main header"
1827 )));
1828 }
1829 }
1830 }
1831
1832 // Every segment the input holds is valid. What is left needs the whole
1833 // header: whether COD and QCD are there, the resolved components (a later
1834 // COC can change a component's levels, and so the subbands its
1835 // quantization must cover), and the PPM chunk order.
1836 let sot_offset = end?;
1837 let mut overrides = overrides.finish();
1838 let cod =
1839 (overrides.cod.take()).ok_or_else(|| Error::codestream("missing required `COD` marker"))?;
1840 let qcd =
1841 (overrides.qcd.take()).ok_or_else(|| Error::codestream("missing required `QCD` marker"))?;
1842
1843 // Start from COD/QCD's defaults, then lay each override over its component.
1844 // That is the whole of A.6.2's and A.6.5's resolution rule at the main
1845 // header's level; `resolve_tile_header` continues the ladder for a tile.
1846 let mut header = MainHeader::new(siz, cod, qcd);
1847 header.poc = poc;
1848 header.crg = crg.unwrap_or_default();
1849 header.ccap15 = cap.flatten();
1850 header.cpf = cpf;
1851 overrides.lay_over(&mut header.components);
1852
1853 validate_resolved(&header)?;
1854 let ppm_chunks = decode_ppm_chunks(ppm)?;
1855 Ok((header, sot_offset, ppm_chunks))
1856}
1857
1858/// Check the invariants that only hold once a header's per-component parameters
1859/// are resolved — whichever header level resolved them. A tile-part COD/QCD pair
1860/// can break one the main header kept, so this runs for every tile header too,
1861/// not just the main one.
1862fn validate_resolved(header: &MainHeader) -> Result<()> {
1863 // A `CAP` that says each tile-component holds one kind of code-block
1864 // (HTDECLARED, ISO/IEC 15444-15 A.3.2) rules out a MIXED style. The
1865 // style is per tile-component and `CAP` may follow COD or COC in the
1866 // main header, so this is checked on the resolved parameters.
1867 if header.ccap15.is_some_and(|c| c.ht_declared()) {
1868 use markers::code_block_style::HT_MIXED;
1869 if let Some(index) = header
1870 .components
1871 .iter()
1872 .position(|p| p.coding.code_block_style & HT_MIXED != 0)
1873 {
1874 return Err(Error::codestream(format!(
1875 "component {index} has a MIXED code-block style, but `CAP` says each \
1876 tile-component holds one kind of code-block (`Ccap15` bits 15-14 are 10)"
1877 )));
1878 }
1879 }
1880 // A quantization default or override must cover every subband its
1881 // component decomposes into: 3·NL + 1 entries for the none/expounded
1882 // styles (derived's single entry is enforced in `decode_quant`, and excess
1883 // entries are ignored, as OpenJPEG does). NL is only known here, after the
1884 // overrides are resolved; discovering the shortfall per subband at decode
1885 // time would misreport a malformed marker as a geometry inconsistency.
1886 for (index, params) in header.components.iter().enumerate() {
1887 let needed = 3 * usize::from(params.coding.decomposition_levels) + 1;
1888 if params.quant.style != QuantStyle::ScalarDerived && params.quant.steps.len() < needed {
1889 return Err(Error::marker(format!(
1890 "component {index} carries {} quantization step entries but its {} \
1891 decomposition levels need {needed}",
1892 params.quant.steps.len(),
1893 params.coding.decomposition_levels
1894 )));
1895 }
1896 // The wavelet constrains the quantization style (E.1 ties reversible
1897 // to no quantization, irreversible to scalar). OpenJPEG decodes both
1898 // non-conformant pairings: style-0 entries still carry exponents, so
1899 // it derives 9/7 steps with mantissa 0 and reconstructs. This crate
1900 // accepts the 5/3-with-scalar direction to match the oracle (the
1901 // reversible path ignores the mantissas — same output) but rejects
1902 // 9/7-with-none rather than adopt the oracle's zero-mantissa
1903 // interpretation of a stream the standard forbids — a documented
1904 // stricter-than-oracle call (docs/openjpeg-departures.md), relaxed if a real
1905 // file ever trips it.
1906 if params.coding.transform == Transform::Irreversible97
1907 && params.quant.style == QuantStyle::None
1908 {
1909 return Err(Error::marker(format!(
1910 "component {index} pairs the 9/7 wavelet with the no-quantization style"
1911 )));
1912 }
1913 }
1914
1915 // The color transform is signaled by COD but constrains SIZ, so it can
1916 // only be checked once both are read. On an image of fewer than three
1917 // components it is skipped, as OpenJPEG skips it (`mct::applies`).
1918 if crate::mct::applies(
1919 header.cod.multiple_component_transform,
1920 header.siz.components.len(),
1921 ) {
1922 crate::mct::check_geometry(&header.siz.components)?;
1923 // Which color transform applies follows from the wavelet, and the
1924 // wavelet is per component once COC is in play: 5/3 is RCT (integers),
1925 // 9/7 is ICT (floats). The three components must share it — a mix
1926 // reconstructs some as integers and some as floats and describes a
1927 // transform that does not exist. OpenJPEG reads the type off component 0.
1928 let transform = header.components[0].coding.transform;
1929 for (index, params) in header.components.iter().take(3).enumerate() {
1930 if params.coding.transform != transform {
1931 return Err(Error::unsupported(format!(
1932 "`COD` signals the color transform but component {index} uses a different \
1933 wavelet than component 0; the transform is undefined over a mix"
1934 )));
1935 }
1936 }
1937 }
1938
1939 Ok(())
1940}
1941
1942/// Refuse a component whose sample range does not fit the `i32` container
1943/// (unsigned 32 bits, or more than 32), from SIZ alone. It is a header fault,
1944/// so it is found before any tile is read. OpenJPEG 2.5.0 is stricter: it
1945/// refuses every depth over 31 bits at SIZ, signed 32 included. This decoder
1946/// accepts signed 32 on purpose, since it fits `i32` (a deliberate
1947/// deviation, #167; see `docs/openjpeg-departures.md`); unsigned 32 and anything above 32
1948/// are refused. `image::assemble` repeats the check for headers built by hand.
1949fn check_sample_container(siz: &Siz) -> Result<()> {
1950 for (index, comp) in siz.components.iter().enumerate() {
1951 let fits = if comp.signed {
1952 comp.bit_depth <= 32
1953 } else {
1954 comp.bit_depth <= 31
1955 };
1956 if !fits {
1957 return Err(Error::unsupported(format!(
1958 "component {index} depth {} ({}) exceeds the i32 sample container",
1959 comp.bit_depth,
1960 if comp.signed { "signed" } else { "unsigned" }
1961 )));
1962 }
1963 }
1964 Ok(())
1965}
1966
1967/// Enforce the decoded geometry subset on the SIZ fields: a well-formed image
1968/// and tile grid, bounded in tile count. The image and tile origins may be
1969/// non-zero (Annex B's reference grid), so this checks the Table A-9
1970/// constraints that a non-zero origin makes load-bearing, then bounds the tile
1971/// count before it reaches the buffer allocations. The image area is held to
1972/// the caller's sample limit later, once the options are known
1973/// (`samples::check_codestream`).
1974fn validate_geometry(siz: &Siz) -> Result<()> {
1975 if siz.x_size == 0 || siz.y_size == 0 {
1976 return Err(Error::marker("`SIZ` declares a zero-size image"));
1977 }
1978 // Table A-9: `0 <= XOsiz < Xsiz`. An origin at or past the far edge encloses
1979 // no image, so it is a malformed field, not an undecoded feature.
1980 if siz.x_offset >= siz.x_size || siz.y_offset >= siz.y_size {
1981 return Err(Error::marker(format!(
1982 "image offset ({}, {}) is not inside the image {}x{}",
1983 siz.x_offset, siz.y_offset, siz.x_size, siz.y_size
1984 )));
1985 }
1986 if siz.tile_width == 0 || siz.tile_height == 0 {
1987 return Err(Error::marker("`SIZ` declares a zero-size tile"));
1988 }
1989 // Table A-9: `XTOsiz <= XOsiz` and `XTOsiz + XTsiz > XOsiz`. The first keeps
1990 // the tile grid from starting to the right of the image; the second keeps
1991 // the first tile column non-empty (its rect clips to `[XOsiz, …)`), without
1992 // which `tile_rect` would hand `resolution_geoms` an empty leading tile.
1993 if siz.tile_x_offset > siz.x_offset || siz.tile_y_offset > siz.y_offset {
1994 return Err(Error::marker(format!(
1995 "tile offset ({}, {}) is past the image offset ({}, {})",
1996 siz.tile_x_offset, siz.tile_y_offset, siz.x_offset, siz.y_offset
1997 )));
1998 }
1999 if u64::from(siz.tile_x_offset) + u64::from(siz.tile_width) <= u64::from(siz.x_offset)
2000 || u64::from(siz.tile_y_offset) + u64::from(siz.tile_height) <= u64::from(siz.y_offset)
2001 {
2002 return Err(Error::marker(format!(
2003 "tile ({}x{} at offset ({}, {})) does not reach the image offset ({}, {})",
2004 siz.tile_width,
2005 siz.tile_height,
2006 siz.tile_x_offset,
2007 siz.tile_y_offset,
2008 siz.x_offset,
2009 siz.y_offset,
2010 )));
2011 }
2012 // `Isot` is a `u16` running 0..=65534 (Table A-10), so a grid finer than
2013 // that has tiles no tile-part can name. The bound also caps the per-tile
2014 // bookkeeping — one resolved header and one geometry walk each — that the
2015 // sample budget alone does not: a 1×1 tile costs a header but almost no
2016 // samples.
2017 const MAX_TILES: u32 = 65535;
2018 let tiles = siz.num_tiles();
2019 if tiles > MAX_TILES {
2020 return Err(Error::marker(format!(
2021 "tile grid is {}x{} = {tiles} tiles, past the {MAX_TILES}-tile limit on `Isot`",
2022 siz.tile_grid().0,
2023 siz.tile_grid().1,
2024 )));
2025 }
2026 Ok(())
2027}
2028
2029/// Decode SIZ — image and tile geometry plus every component's depth, sign, and
2030/// sub-sampling (A.5.1).
2031///
2032/// Parses all `Csiz` components. Whether the decoder can *reconstruct* them is
2033/// a separate question, enforced by [`validate_geometry`] once the whole main
2034/// header is read, and by the sample limit after it, so a
2035/// multi-component codestream still parses cleanly here.
2036///
2037/// `Ssiz` is a depth-minus-one in the low 7 bits with the sign in bit 7, so the
2038/// declared depth is `1..=128`; the standard caps it at 38 (Table A-11) and
2039/// anything above that is a malformed field, not an unsupported feature.
2040fn decode_siz(mut b: Cursor<'_>) -> Result<Siz> {
2041 let _rsiz = b.u16()?; // capabilities / profile — not needed by the decoder
2042 let x_size = b.u32()?;
2043 let y_size = b.u32()?;
2044 let x_offset = b.u32()?;
2045 let y_offset = b.u32()?;
2046 let tile_width = b.u32()?;
2047 let tile_height = b.u32()?;
2048 let tile_x_offset = b.u32()?;
2049 let tile_y_offset = b.u32()?;
2050 let csiz = b.u16()?;
2051
2052 if csiz == 0 {
2053 return Err(Error::marker("`SIZ` declares zero components"));
2054 }
2055 if csiz > markers::MAX_COMPONENTS {
2056 return Err(Error::marker(format!(
2057 "`SIZ` declares {csiz} components, above the limit of {}",
2058 markers::MAX_COMPONENTS
2059 )));
2060 }
2061 // Each component record is 3 bytes. Check the segment can actually hold them
2062 // before reserving, so a lying `Csiz` cannot steer the allocation.
2063 if b.remaining() != 3 * csiz as usize {
2064 return Err(Error::codestream(format!(
2065 "`SIZ` has {} bytes for {csiz} component records, expected {}",
2066 b.remaining(),
2067 3 * csiz as usize,
2068 )));
2069 }
2070
2071 let mut components = Vec::with_capacity(csiz as usize);
2072 for index in 0..csiz {
2073 let ssiz = b.u8()?;
2074 let x_sampling = b.u8()?;
2075 let y_sampling = b.u8()?;
2076 let bit_depth = (ssiz & 0x7F) + 1;
2077 if bit_depth > 38 {
2078 return Err(Error::marker(format!(
2079 "component {index} declares bit depth {bit_depth}, above the limit of 38"
2080 )));
2081 }
2082 if x_sampling == 0 || y_sampling == 0 {
2083 return Err(Error::marker(format!(
2084 "component {index} declares a zero sub-sampling factor ({x_sampling}, {y_sampling})"
2085 )));
2086 }
2087 components.push(SizComponent {
2088 bit_depth,
2089 signed: ssiz & 0x80 != 0,
2090 x_sampling,
2091 y_sampling,
2092 });
2093 }
2094 b.expect_consumed("`SIZ`")?;
2095
2096 let siz = Siz {
2097 x_size,
2098 y_size,
2099 x_offset,
2100 y_offset,
2101 tile_width,
2102 tile_height,
2103 tile_x_offset,
2104 tile_y_offset,
2105 components,
2106 };
2107 // Geometry legality (`validate_geometry`) and the sample limit
2108 // (`samples::check_codestream`) are the callers' to apply, in that order,
2109 // so this function stays a pure reader of the marker segment.
2110 Ok(siz)
2111}
2112
2113/// Decode COD — default coding style (A.6.1): transform, decomposition depth,
2114/// progression, layers, code-block size/style, precinct sizes. All six Part 1
2115/// style flags and both color transforms are accepted, and Part 2's array MCT
2116/// is rejected. The HTJ2K style bits are kept for [`check_block_coder`].
2117fn decode_cod(mut b: Cursor<'_>) -> Result<Cod> {
2118 // Scod bit 0: user-defined precincts in SPcod. Bit 1: SOP may precede each
2119 // packet. Bit 2: EPH follows each packet header. Bits 3-7 are reserved.
2120 let scod = b.u8()?;
2121 if scod & 0xF8 != 0 {
2122 return Err(Error::marker(format!(
2123 "`COD` sets reserved `Scod` bits {:#04X}",
2124 scod & 0xF8
2125 )));
2126 }
2127 let explicit_precincts = scod & 0x01 != 0;
2128 let use_sop = scod & 0x02 != 0;
2129 let use_eph = scod & 0x04 != 0;
2130
2131 let code = b.u8()?;
2132 let progression = Progression::from_u8(code)
2133 .ok_or_else(|| Error::marker(format!("reserved progression order {code}")))?;
2134
2135 // Every packet costs at least one byte, so a layer count is bounded by the
2136 // tile-part in practice; a declared zero is malformed (ISO Table A-16).
2137 let layers = b.u16()?;
2138 if layers == 0 {
2139 return Err(Error::marker("`COD` declares zero quality layers"));
2140 }
2141
2142 // SGcod multiple-component transform: 0 = none, 1 = the Part 1 color
2143 // transform over the first three components. 2 selects Part 2's array MCT,
2144 // which is a different feature entirely.
2145 let mct = b.u8()?;
2146 let multiple_component_transform = match mct {
2147 0 => false,
2148 1 => true,
2149 other => {
2150 return Err(Error::unsupported(format!(
2151 "multiple-component transform type {other}; only the Part 1 color transform is decoded"
2152 )));
2153 }
2154 };
2155
2156 // Maximal precincts (PPx=PPy=15) when Scod bit 0 is clear, signaled by an
2157 // empty list.
2158 let coding = decode_coding(&mut b, "`COD`", explicit_precincts)?;
2159 b.expect_consumed("`COD`")?;
2160
2161 Ok(Cod {
2162 progression,
2163 layers,
2164 use_sop,
2165 use_eph,
2166 multiple_component_transform,
2167 coding,
2168 })
2169}
2170
2171/// The most progression volumes a tile's walk will honor. This is a decode
2172/// guard one volume above OpenJPEG's limit: its `opj_tcp_t::pocs` array has
2173/// 32 entries, and `opj_j2k_read_poc` refuses ("Too many POCs") a count of 32
2174/// or more, so it reads at most 31. The standard sets
2175/// no limit, but each volume re-enumerates the packet space and a duplicate
2176/// emission consumes no bitstream bytes, so an uncapped list is a quadratic
2177/// work bomb: `V` volumes over `P` one-byte packets cost `V·P` dedup probes
2178/// while the input pays for `P + 7V` bytes. The cap is enforced wherever
2179/// volumes accumulate — per marker and across a tile's parts — and again on the
2180/// list a tile resolves to ([`resolved_poc_len`]).
2181const MAX_POC_VOLUMES: usize = 32;
2182
2183/// How many progression volumes `tile` walks over `main`: its own when its
2184/// first tile-part has a POC, which replaces the main header's, and otherwise
2185/// the main header's followed by any from later tile-parts (see
2186/// `resolve_tile_header`).
2187fn resolved_poc_len(main: &MainHeader, tile: &TileHeader) -> usize {
2188 if tile.poc_in_first_part {
2189 tile.poc.len()
2190 } else {
2191 main.poc.len() + tile.poc.len()
2192 }
2193}
2194
2195/// Reject a progression-volume count past [`MAX_POC_VOLUMES`].
2196fn check_poc_budget(volumes: usize) -> Result<()> {
2197 if volumes > MAX_POC_VOLUMES {
2198 return Err(Error::limit_fixed(
2199 crate::LimitKind::PocVolumes,
2200 format!(
2201 "the `POC` markers declare {volumes} progression volumes for a tile, over the \
2202 limit of {MAX_POC_VOLUMES}"
2203 ),
2204 ));
2205 }
2206 Ok(())
2207}
2208
2209/// Decode a POC marker (A.6.6, Table A-32): a sequence of progression volumes.
2210///
2211/// Each volume is `RSpoc`(1) `CSpoc`(1 or 2) `LYEpoc`(2) `REpoc`(1) `CEpoc`(1 or
2212/// 2) `Ppoc`(1). The component fields are two bytes once the image has 257 or
2213/// more components (like `Ccoc`/`Cqcc`), so the whole volume is `7` or `9` bytes,
2214/// and the marker body must be a whole number of them. `CSpoc`/`CEpoc` are read
2215/// against the component count; `LYEpoc` is clamped to the layer count later,
2216/// where it is known for certain.
2217///
2218/// Volumes append to any already in `into`: several POC markers in one header,
2219/// or in the tile-parts of one tile, form one sequence, as in OpenJPEG's
2220/// `opj_j2k_read_poc`. A tile's sequence then replaces the main header's when
2221/// it starts in the tile's first tile-part (see `resolve_tile_header`).
2222fn decode_poc(mut b: Cursor<'_>, siz: &Siz, into: &mut Vec<PocVolume>) -> Result<()> {
2223 let comp_room = if siz.components.len() < 257 { 1 } else { 2 };
2224 let volume_size = 5 + 2 * comp_room;
2225 let body_len = b.remaining();
2226 if body_len == 0 || !body_len.is_multiple_of(volume_size) {
2227 return Err(Error::marker(format!(
2228 "`POC` body is {body_len} bytes, not a whole number of {volume_size}-byte volumes"
2229 )));
2230 }
2231 check_poc_budget(into.len() + body_len / volume_size)?;
2232 let read_comp = |b: &mut Cursor<'_>| -> Result<u16> {
2233 if comp_room == 1 {
2234 Ok(u16::from(b.u8()?))
2235 } else {
2236 b.u16()
2237 }
2238 };
2239 for _ in 0..body_len / volume_size {
2240 let res_start = b.u8()?;
2241 let comp_start = read_comp(&mut b)?;
2242 let layer_end = b.u16()?;
2243 let res_end = b.u8()?;
2244 let comp_end = read_comp(&mut b)?;
2245 let progression = Progression::from_u8(b.u8()?)
2246 .ok_or_else(|| Error::marker("`POC` volume sets a reserved progression order"))?;
2247 // A volume that encloses nothing would consume no packets and desync
2248 // nothing, but it is a malformed field, not a no-op the encoder meant.
2249 // `LYEpoc` shares the rule: Table A-33 gives it the range 1–65535, so a
2250 // zero-layer volume is a malformed field too, rejected here rather than
2251 // surfacing later as a less precise desync error.
2252 if res_end <= res_start || comp_end <= comp_start || layer_end == 0 {
2253 return Err(Error::marker(format!(
2254 "`POC` volume has an empty range: resolutions [{res_start}, {res_end}), \
2255 components [{comp_start}, {comp_end}), layers [0, {layer_end})"
2256 )));
2257 }
2258 into.push(PocVolume {
2259 res_start,
2260 res_end,
2261 comp_start,
2262 comp_end,
2263 layer_end,
2264 progression,
2265 });
2266 }
2267 Ok(())
2268}
2269
2270/// Decode the `SPcod`/`SPcoc` tail shared by COD and COC (Tables A-12, A-14):
2271/// decomposition levels, the two code-block exponents, the style byte, the
2272/// wavelet, and — when `explicit_precincts` — the per-resolution precinct sizes.
2273/// `origin` names the marker for error messages.
2274///
2275/// The precinct flag lives in `Scod`/`Scoc`, not here, so the caller reads it and
2276/// passes it down. When it is clear the partition is maximal and
2277/// `precinct_sizes` comes back empty.
2278fn decode_coding(b: &mut Cursor<'_>, origin: &str, explicit_precincts: bool) -> Result<Coding> {
2279 let decomposition_levels = b.u8()?;
2280 // Table A-15: 0–32 decomposition levels; 33–255 are reserved. A reserved
2281 // field encoding rejects at parse, like the wavelet and style bytes below.
2282 if decomposition_levels > 32 {
2283 return Err(Error::marker(format!(
2284 "{origin} sets reserved decomposition level count {decomposition_levels} (max 32)"
2285 )));
2286 }
2287 let code_block_width = b.u8()?;
2288 let code_block_height = b.u8()?;
2289 // Every bit is allocated (Table A-19, ISO/IEC 15444-15 A.4), so the byte
2290 // is kept whole; `check_block_coder` refuses the coders not yet decoded.
2291 let code_block_style = b.u8()?;
2292 let transform = match b.u8()? {
2293 0 => Transform::Irreversible97,
2294 1 => Transform::Reversible53,
2295 other => {
2296 return Err(Error::marker(format!(
2297 "{origin} sets reserved wavelet transform {other}"
2298 )));
2299 }
2300 };
2301 // One `SPcod` precinct byte per resolution — `NL + 1` of them, coarsest
2302 // first — each packing `PPx` in the low nibble and `PPy` in the high one
2303 // (Table A-21). They are exponents on that *resolution's* grid, so the same
2304 // byte means a different span at every level.
2305 let precinct_sizes = if explicit_precincts {
2306 let mut sizes = Vec::with_capacity(usize::from(decomposition_levels) + 1);
2307 for resolution in 0..=usize::from(decomposition_levels) {
2308 let byte = b.u8()?;
2309 let (ppx, ppy) = (byte & 0x0F, byte >> 4);
2310 // A 2^0 precinct is legal only at the coarsest resolution (Table
2311 // A-21). Above it the precinct is halved onto the subband grid, so a
2312 // zero exponent would ask for a 2^-1 code-block partition — the
2313 // geometry is not merely unusual, it does not exist.
2314 if resolution > 0 && (ppx == 0 || ppy == 0) {
2315 return Err(Error::marker(format!(
2316 "{origin} sets precinct 2^{ppx} x 2^{ppy} at resolution {resolution}; \
2317 a zero exponent is permitted only at resolution 0"
2318 )));
2319 }
2320 sizes.push((ppx, ppy));
2321 }
2322 sizes
2323 } else {
2324 Vec::new()
2325 };
2326
2327 // The standard bounds each code-block exponent at 2^10 and their sum at
2328 // 2^12 (Table A-18). OpenJPEG refuses the field when it reads the header
2329 // ("Invalid cblkw/cblkh combination"), so a header-only read does too.
2330 let (xcb, ycb) = (
2331 u32::from(code_block_width) + 2,
2332 u32::from(code_block_height) + 2,
2333 );
2334 if xcb > 10 || ycb > 10 || xcb + ycb > 12 {
2335 return Err(Error::marker(format!(
2336 "code-block size 2^{xcb} x 2^{ycb} is over the 4096-sample limit"
2337 )));
2338 }
2339
2340 Ok(Coding {
2341 decomposition_levels,
2342 code_block_width,
2343 code_block_height,
2344 code_block_style,
2345 transform,
2346 precinct_sizes,
2347 })
2348}
2349
2350/// The component index a COC or QCC applies to (`Ccoc`, `Cqcc`). One byte while
2351/// `Csiz < 257`, two bytes otherwise (A.6.2, A.6.5) — the width depends on the
2352/// component count, so SIZ must already be parsed.
2353fn component_index(b: &mut Cursor<'_>, siz: &Siz, origin: &str) -> Result<usize> {
2354 let count = siz.components.len();
2355 let index = if count < 257 {
2356 usize::from(b.u8()?)
2357 } else {
2358 usize::from(b.u16()?)
2359 };
2360 if index >= count {
2361 return Err(Error::marker(format!(
2362 "{origin} targets component {index}, but `SIZ` declares {count}"
2363 )));
2364 }
2365 Ok(index)
2366}
2367
2368/// Decode COC — a coding-style override for one component (A.6.2).
2369///
2370/// Returns the component index and the coding parameters that replace COD's for
2371/// it. `Scoc` carries only the precinct flag; every other bit is reserved.
2372fn decode_coc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Coding)> {
2373 let index = component_index(&mut b, siz, "`COC`")?;
2374 let scoc = b.u8()?;
2375 let explicit_precincts = scoc & 0x01 != 0;
2376 // Only bit 0 is defined in `Scoc` (Table A-21). SOP and EPH are signaled
2377 // once for the tile, in COD's `Scod`, and have no per-component form — so
2378 // unlike `Scod` there is nothing else here to read. OpenJPEG stores the byte
2379 // without validating it and consults only bit 0.
2380 if scoc & 0xFE != 0 {
2381 return Err(Error::marker(format!(
2382 "`COC` sets reserved `Scoc` bits {:#04X}",
2383 scoc & 0xFE
2384 )));
2385 }
2386 let coding = decode_coding(&mut b, "`COC`", explicit_precincts)?;
2387 b.expect_consumed("`COC`")?;
2388 Ok((index, coding))
2389}
2390
2391/// Decode QCC — a quantization override for one component (A.6.5). The body
2392/// after `Cqcc` is a `QCD` body, byte for byte.
2393fn decode_qcc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Qcd)> {
2394 let index = component_index(&mut b, siz, "`QCC`")?;
2395 let quant = decode_quant(b, "`QCC`")?;
2396 Ok((index, quant))
2397}
2398
2399/// Decode RGN — a region of interest for one component (A.6.3).
2400///
2401/// Returns the component index and its maxshift. `Srgn` selects the ROI style,
2402/// and `0` (implicit — the maxshift of Annex H) is the only style Part 1
2403/// defines. OpenJPEG reads the byte and never looks at it, so a codestream using
2404/// a Part 2 style decodes there as though it were maxshift.
2405fn decode_rgn(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, u8)> {
2406 let index = component_index(&mut b, siz, "`RGN`")?;
2407 let srgn = b.u8()?;
2408 if srgn != 0 {
2409 return Err(Error::unsupported(format!(
2410 "region-of-interest style {srgn}; only the implicit maxshift (`Srgn` = 0) is decoded"
2411 )));
2412 }
2413 let shift = b.u8()?;
2414 b.expect_consumed("`RGN`")?;
2415 Ok((index, shift))
2416}
2417
2418/// Decode TLM — tile-part lengths (A.7.1) — appending onto `entries`.
2419///
2420/// `Stlm` packs two field widths: `ST` (bits 4–5) is the tile-index width in
2421/// bytes, where 0 means the index is implied by entry order across all TLM
2422/// markers, and `SP` (bit 6) selects 16- or 32-bit lengths. `ST = 3` and the
2423/// reserved bits (0–3 and 7) are illegal encodings; OpenJPEG warns and ignores
2424/// the whole TLM chain on `ST = 3` or a bad entry size and never looks at the
2425/// reserved bits, but as with `Scoc` rejecting is stricter and no conformant
2426/// codestream carries them.
2427///
2428/// An entry may only name a tile the grid actually holds. OpenJPEG makes the
2429/// same range check against its grid.
2430///
2431/// `seen` counts the entries of every TLM marker read so far, across markers;
2432/// each valid entry is handed to `entry`.
2433fn decode_tlm(
2434 mut b: Cursor<'_>,
2435 siz: &Siz,
2436 seen: &mut usize,
2437 mut entry: impl FnMut(TlmEntry),
2438) -> Result<()> {
2439 b.u8()?; // Ztlm: this marker's position among the TLMs
2440 let stlm = b.u8()?;
2441 if stlm & 0x8F != 0 {
2442 return Err(Error::marker(format!(
2443 "`TLM` sets reserved `Stlm` bits {:#04X}",
2444 stlm & 0x8F
2445 )));
2446 }
2447 let st = (stlm >> 4) & 0x3;
2448 if st == 3 {
2449 return Err(Error::marker(
2450 "`TLM` tile-index width `ST` = 3 is not defined",
2451 ));
2452 }
2453 let sp = (stlm >> 6) & 0x1;
2454
2455 let entry_size = usize::from(st) + 2 * (usize::from(sp) + 1);
2456 if !b.remaining().is_multiple_of(entry_size) {
2457 return Err(Error::codestream(format!(
2458 "`TLM` carries {} entry bytes, not a multiple of its {entry_size}-byte entries",
2459 b.remaining()
2460 )));
2461 }
2462
2463 while b.remaining() > 0 {
2464 let tile_index = match st {
2465 0 => u32::try_from(*seen).unwrap_or(u32::MAX),
2466 1 => u32::from(b.u8()?),
2467 _ => u32::from(b.u16()?),
2468 };
2469 if tile_index >= siz.num_tiles() {
2470 return Err(Error::marker(format!(
2471 "`TLM` names tile {tile_index}, but the grid holds {} tiles",
2472 siz.num_tiles()
2473 )));
2474 }
2475 let length = match sp {
2476 0 => u32::from(b.u16()?),
2477 _ => b.u32()?,
2478 };
2479 *seen += 1;
2480 entry(TlmEntry { tile_index, length });
2481 }
2482 Ok(())
2483}
2484
2485/// Decode CRG — component registration (A.9.1): one `(Xcrg, Ycrg)` sub-pixel
2486/// offset per component, each a `u16` in units of `1/65536` of the reference-grid
2487/// step. The body is exactly `4 · Csiz` bytes.
2488///
2489/// The offsets are recorded, not applied. CRG is informational — it registers
2490/// the components for display, not for decoding — so the reconstructed samples
2491/// are the same with it present or absent, and the class-1 references are made
2492/// without resampling (issue #74). OpenJPEG reads past the body without keeping
2493/// the values at all; recording them is the one place this is deliberately more
2494/// than the oracle, so a caller that does care about registration can act on them.
2495fn decode_crg(mut b: Cursor<'_>, siz: &Siz) -> Result<Vec<(u16, u16)>> {
2496 let count = siz.components.len();
2497 if b.remaining() != count * 4 {
2498 return Err(Error::marker(format!(
2499 "`CRG` carries {} bytes, not the {} its {count} components need",
2500 b.remaining(),
2501 count * 4
2502 )));
2503 }
2504 let mut offsets = Vec::with_capacity(count);
2505 for _ in 0..count {
2506 let x = b.u16()?;
2507 let y = b.u16()?;
2508 offsets.push((x, y));
2509 }
2510 Ok(offsets)
2511}
2512
2513/// `Pcap` bit 15, counted from the MSB: the codestream uses Part 15 (HTJ2K)
2514/// capabilities (ISO/IEC 15444-15 A.3.1).
2515const PCAP_PART15: u32 = 1 << (32 - 15);
2516
2517/// Decode CAP — extended capabilities (ISO/IEC 15444-1 A.5.2): `Pcap`, then
2518/// one `Ccap` word for each bit `Pcap` sets, in bit order from the MSB. Bit
2519/// `i` (from 1 at the MSB) says the codestream uses capabilities of Part `i`.
2520///
2521/// Returns the Part 15 word when `Pcap` sets that bit. A capability of any
2522/// other part is `Unsupported`, as is MULTIHT (`Ccap15` bit 13), which no
2523/// conformance codestream sets. OpenJPEG reads no field of CAP.
2524fn decode_cap(mut b: Cursor<'_>) -> Result<Option<Ccap15>> {
2525 let len = b.remaining();
2526 let pcap = if len >= 4 { b.u32()? } else { 0 };
2527 let needed = 4 + 2 * pcap.count_ones() as usize;
2528 if len != needed {
2529 return Err(Error::marker(format!(
2530 "`CAP` carries {len} bytes, not the {needed} its `Pcap` needs"
2531 )));
2532 }
2533 if let Some(bit) = (1..=32).find(|&i| i != 15 && pcap & (1 << (32 - i)) != 0) {
2534 // Part 1 is the baseline and has no extended capabilities, and no
2535 // part past 17 exists. Such a bit names no capability this decoder
2536 // knows; it is still `Unsupported`, not `Marker`, since a later
2537 // edition may assign it.
2538 let message = if (2..=17).contains(&bit) {
2539 format!("`CAP` signals capabilities of ISO/IEC 15444-{bit}, outside the decoded subset")
2540 } else {
2541 format!(
2542 "`CAP` sets `Pcap` bit {bit}, counted from the MSB, which names no part \
2543 of ISO/IEC 15444 with capabilities this decoder knows"
2544 )
2545 };
2546 return Err(Error::unsupported(message));
2547 }
2548 if pcap & PCAP_PART15 == 0 {
2549 return Ok(None);
2550 }
2551 // The `Ccap` words follow `Pcap`'s bits from the MSB, so `Ccap15` is the
2552 // first word only because every other part's bit was refused above. Once
2553 // a Part 2 capability is read, `Ccap2` comes before it.
2554 let ccap15 = Ccap15(b.u16()?);
2555 if ccap15.multiht() {
2556 return Err(Error::unsupported(
2557 "`CAP` signals more than one HT set per code-block (MULTIHT), outside the decoded subset",
2558 ));
2559 }
2560 Ok(Some(ccap15))
2561}
2562
2563/// Decode CPF — the corresponding profile (ISO/IEC 15444-15 A.6): one or
2564/// more 16-bit `Pcpf` words. Kept, not checked against `Rsiz` or the
2565/// profile: it changes nothing about decoding, and OpenJPEG reads none of
2566/// it. A body that is not whole words is malformed.
2567fn decode_cpf(mut b: Cursor<'_>) -> Result<Cpf> {
2568 let len = b.remaining();
2569 if len == 0 || !len.is_multiple_of(2) {
2570 return Err(Error::marker(format!(
2571 "`CPF` carries {len} bytes, not one or more 16-bit `Pcpf` words"
2572 )));
2573 }
2574 let words = (0..len / 2).map(|_| b.u16()).collect::<Result<_>>()?;
2575 Ok(Cpf { words })
2576}
2577
2578/// The one guard on which block coder a COD or COC selects, run as each is
2579/// read in the main header or a tile-part header ([`OverrideReader`]).
2580///
2581/// The style bits decide each tile-component's coder (ISO/IEC 15444-15
2582/// A.4); `CAP` does not override them. `0x40` alone selects the HT block
2583/// coder. `0x40` with `0x80` is MIXED: each code-block is an HT block or a
2584/// Part 1 block, which tier-2 tells apart. A.4 allows the Part 1 blocks
2585/// there neither bypass nor termination on each pass, so a MIXED style with
2586/// either bit is malformed. `0x80` without `0x40` is a Part 1 style with a
2587/// reserved bit set, and is refused as outside the decoded subset. Because it
2588/// runs per segment, a cut header that already holds such a COD or COC is
2589/// refused, not reported as incomplete.
2590fn check_block_coder(coding: &Coding, origin: &str) -> Result<()> {
2591 use markers::code_block_style::{HT, HT_MIXED, LAZY, TERMALL};
2592 let style = coding.code_block_style;
2593 if style & (HT | HT_MIXED) == HT_MIXED {
2594 return Err(Error::unsupported(format!(
2595 "{origin} code-block style ({}) is outside the decoded subset",
2596 markers::code_block_style::describe(HT_MIXED),
2597 )));
2598 }
2599 let terminating = style & (LAZY | TERMALL);
2600 if style & HT_MIXED != 0 && terminating != 0 {
2601 return Err(Error::marker(format!(
2602 "{origin} code-block style is MIXED with {}, which ISO/IEC 15444-15 A.4 \
2603 does not allow its Part 1 code-blocks",
2604 markers::code_block_style::describe(terminating),
2605 )));
2606 }
2607 Ok(())
2608}
2609
2610/// Decode PLM — main-header packet lengths (A.7.2).
2611///
2612/// Validated for presence and otherwise skipped, exactly as OpenJPEG's
2613/// `opj_j2k_read_plm` does: an `Nplm`/`Iplm` chain may split across PLM
2614/// markers mid-entry, so per-marker structural validation would reject
2615/// codestreams the oracle accepts. The packets themselves are read from the
2616/// codestream, so nothing here is needed to decode.
2617fn decode_plm(mut b: Cursor<'_>) -> Result<()> {
2618 b.u8()?; // Zplm: this marker's position among the PLMs
2619 Ok(())
2620}
2621
2622/// Decode PLT — tile-part packet lengths (A.7.3).
2623///
2624/// Each packet length is a base-128 chain of bytes, high bit meaning "another
2625/// byte follows". The lengths are informational and discarded; what is checked
2626/// is that the last chain is whole — a final byte with its continuation bit
2627/// set is a truncated entry. OpenJPEG rejects the same way unless every
2628/// payload bit of the dangling chain is zero (`opj_j2k_read_plt` tests the
2629/// accumulated *value* at segment end, and `0 << 7` stays 0); rejecting the
2630/// all-zero dangle too is stricter, the same documented stance as the TLM
2631/// encodings above.
2632fn decode_plt(mut b: Cursor<'_>) -> Result<()> {
2633 b.u8()?; // Zplt: this marker's position among the tile-part's PLTs
2634 // The chains are self-delimiting, so whole-ness is one property: the last
2635 // byte must not claim a continuation.
2636 let chains = b.take(b.remaining())?;
2637 if chains.last().is_some_and(|&last| last & 0x80 != 0) {
2638 return Err(Error::codestream(
2639 "`PLT` ends in the middle of a packet-length entry",
2640 ));
2641 }
2642 Ok(())
2643}
2644
2645/// Split the main header's packed packet headers (`PPM`, A.7.4) into one chunk
2646/// per tile-part, in codestream order.
2647///
2648/// Each `PPM` marker carries `Zppm` (its position) and `Ippm` (payload). Joined
2649/// across every marker in `Zppm` order, the payload is a run of `(Nppm, bytes)`
2650/// records — `Nppm` a 4-byte length, `bytes` that tile-part's packet headers —
2651/// one record per tile-part. `Nppm` may straddle a marker boundary, so the
2652/// payloads are concatenated before the records are read, matching OpenJPEG's
2653/// `opj_j2k_merge_ppm`. Each returned chunk feeds a tile-part's packet-header
2654/// stream in [`walk_tiles`], the same role `PPT` plays for a single tile-part.
2655fn decode_ppm_chunks(mut markers: Vec<(u8, Vec<u8>)>) -> Result<Vec<Vec<u8>>> {
2656 if markers.is_empty() {
2657 return Ok(Vec::new());
2658 }
2659 // `Zppm` orders the markers; a repeated index is a malformed main header.
2660 markers.sort_by_key(|&(z, _)| z);
2661 if markers.windows(2).any(|w| w[0].0 == w[1].0) {
2662 return Err(Error::codestream(
2663 "duplicate `PPM` index `Zppm` in the main header",
2664 ));
2665 }
2666 let joined: Vec<u8> = markers.into_iter().flat_map(|(_, bytes)| bytes).collect();
2667
2668 let mut cur = Cursor::new(&joined);
2669 let mut chunks = Vec::new();
2670 while cur.remaining() > 0 {
2671 // Nppm: the byte count of this tile-part's packet headers (may be 0).
2672 let nppm = cur.u32()? as usize;
2673 chunks.push(cur.take(nppm)?.to_vec());
2674 }
2675 Ok(chunks)
2676}
2677
2678/// Decode the quantization body shared by QCD (A.6.4) and QCC (A.6.5): style,
2679/// guard bits, and the per-subband (exponent, mantissa) step parameters. QCC's
2680/// body after `Cqcc` is a QCD body byte for byte, so `origin` only names the
2681/// marker for error messages — a malformed override must not report as a fault
2682/// in the codestream-wide default.
2683fn decode_quant(mut b: Cursor<'_>, origin: &str) -> Result<Qcd> {
2684 let sqcd = b.u8()?;
2685 let guard_bits = sqcd >> 5;
2686 let style = match sqcd & 0x1F {
2687 0 => QuantStyle::None,
2688 1 => QuantStyle::ScalarDerived,
2689 2 => QuantStyle::ScalarExpounded,
2690 other => {
2691 return Err(Error::marker(format!(
2692 "{origin} sets reserved quantization style {other}"
2693 )));
2694 }
2695 };
2696
2697 // A step table covers at most the 3·NL + 1 subbands of a 32-level
2698 // decomposition (A.6.4, with NL ≤ 32 per Table A-15), so 97 entries.
2699 // Entries past that are kept out of the table — but still consumed — the
2700 // way OpenJPEG caps at J2K_MAXBANDS and decodes (verified empirically:
2701 // a 120-entry QCD decodes without a warning). Dropping rather than
2702 // rejecting also keeps a hostile 65535-byte Lqcd from inflating the
2703 // per-component `Qcd` clones in [`MainHeader::new`].
2704 const MAX_STEP_ENTRIES: usize = 3 * 32 + 1;
2705
2706 let mut steps = Vec::new();
2707 match style {
2708 // No quantization (reversible): one byte per subband, high 5 bits are
2709 // the exponent, mantissa is 0.
2710 QuantStyle::None => {
2711 if b.remaining() == 0 {
2712 return Err(Error::codestream(format!(
2713 "{origin} carries no step entries"
2714 )));
2715 }
2716 while b.remaining() > 0 {
2717 let v = b.u8()?;
2718 if steps.len() < MAX_STEP_ENTRIES {
2719 steps.push((v >> 3, 0));
2720 }
2721 }
2722 }
2723 // Scalar: 16-bit per entry, high 5 bits exponent, low 11 bits mantissa.
2724 // Derived signals one entry (LL); expounded one per subband.
2725 QuantStyle::ScalarDerived | QuantStyle::ScalarExpounded => {
2726 if b.remaining() == 0 || !b.remaining().is_multiple_of(2) {
2727 return Err(Error::codestream(format!(
2728 "{origin} step table is truncated"
2729 )));
2730 }
2731 if style == QuantStyle::ScalarDerived && b.remaining() != 2 {
2732 return Err(Error::codestream(format!(
2733 "derived {origin} must carry exactly one step entry"
2734 )));
2735 }
2736 while b.remaining() > 0 {
2737 let v = b.u16()?;
2738 if steps.len() < MAX_STEP_ENTRIES {
2739 steps.push((((v >> 11) & 0x1F) as u8, v & 0x07FF));
2740 }
2741 }
2742 }
2743 }
2744
2745 Ok(Qcd {
2746 style,
2747 guard_bits,
2748 steps,
2749 })
2750}
2751
2752/// Read a marker segment's length field and return a [`Cursor`] over its body.
2753///
2754/// `Lmarker` (A.4) counts the two length bytes but not the two marker bytes, so
2755/// the body is `Lmarker - 2` bytes. A length below 2 or past the buffer end is a
2756/// malformed codestream.
2757fn segment<'a>(cur: &mut Cursor<'a>) -> Result<Cursor<'a>> {
2758 let len = cur.u16()? as usize;
2759 if len < 2 {
2760 return Err(Error::codestream("marker segment length below 2"));
2761 }
2762 let body = cur.take(len - 2)?;
2763 Ok(Cursor::new(body))
2764}
2765
2766/// Bounds-checked big-endian byte cursor. Every read maps an overrun to
2767/// [`Error::Codestream`] so truncation is a typed error, never a panic.
2768struct Cursor<'a> {
2769 buf: &'a [u8],
2770 pos: usize,
2771}
2772
2773impl<'a> Cursor<'a> {
2774 fn new(buf: &'a [u8]) -> Self {
2775 Self { buf, pos: 0 }
2776 }
2777
2778 /// A cursor over `buf` starting at an absolute offset, for resuming a walk
2779 /// (e.g. tile-parts) from a position the main-header pass returned.
2780 fn at(buf: &'a [u8], pos: usize) -> Self {
2781 Self { buf, pos }
2782 }
2783
2784 fn remaining(&self) -> usize {
2785 self.buf.len() - self.pos
2786 }
2787
2788 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
2789 if self.remaining() < n {
2790 return Err(Error::codestream("truncated marker segment"));
2791 }
2792 let slice = &self.buf[self.pos..self.pos + n];
2793 self.pos += n;
2794 Ok(slice)
2795 }
2796
2797 fn u8(&mut self) -> Result<u8> {
2798 Ok(self.take(1)?[0])
2799 }
2800
2801 fn u16(&mut self) -> Result<u16> {
2802 let b = self.take(2)?;
2803 Ok(u16::from_be_bytes([b[0], b[1]]))
2804 }
2805
2806 fn u32(&mut self) -> Result<u32> {
2807 let b = self.take(4)?;
2808 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
2809 }
2810
2811 /// Assert the whole segment body was consumed; a trailing remainder means
2812 /// the declared length and the field layout disagree.
2813 fn expect_consumed(&self, marker: &str) -> Result<()> {
2814 if self.remaining() != 0 {
2815 return Err(Error::codestream(format!(
2816 "{marker} segment has {} unexpected trailing byte(s)",
2817 self.remaining()
2818 )));
2819 }
2820 Ok(())
2821 }
2822}
2823
2824#[cfg(test)]
2825mod tests;