Skip to main content

rust_j2k/tier2/
mod.rs

1//! Stage 2 — Tier-2 packet decoding (ISO/IEC 15444-1 Annex B).
2//!
3//! Tile-part data is a sequence of *packets*, one per (resolution, layer,
4//! component, precinct) in the header's progression order. Each packet header
5//! says, via [tag trees](tagtree), which code-blocks are included, how many
6//! bit-planes are all-zero, how many coding passes each contributes, and the
7//! byte length of each contribution. This stage parses that structure and
8//! hands Tier-1 the coded byte segments per code-block — it does **not** run
9//! the arithmetic decoder.
10//!
11//! This stage runs once per **tile**: a tile's packets are its own, in its own
12//! progression, and nothing about them crosses a tile boundary. The packet
13//! stream walks four axes — layer, resolution, component, and *position* (the
14//! precinct) — in the order that tile's `COD` names, or, when a `POC` marker is
15//! present, through the sequence of progression volumes it prescribes. The
16//! tile's data is then `header₀ body₀ header₁ body₁ …` with no padding, and the
17//! packets must tile it exactly; a leftover byte means a misread field.
18//!
19//! A code-block's contributions accumulate across the layers that include it,
20//! so a precinct's tag trees and per-block state outlive any one packet. See
21//! [`for_each_packet`] for the orders and [`BlockState`] for what persists.
22//!
23//! `decode_packets_metered` also computes the resolution / subband /
24//! code-block geometry from the [`MainHeader`], so it is the single source of
25//! truth the assembly stage reuses.
26
27pub mod bio;
28mod geometry;
29mod progression;
30pub(crate) mod resume;
31pub mod spans;
32pub mod tagtree;
33
34use crate::codestream::markers::Rect;
35use crate::codestream::markers::marker;
36use crate::codestream::{MainHeader, Tile};
37use crate::{Error, Result};
38use bio::BitReader;
39use spans::UnreadSpans;
40use std::borrow::Cow;
41use std::cell::Cell;
42use std::ops::Range;
43use tagtree::{Saved, TagTree};
44
45pub(crate) use geometry::{
46    BandGeom, MAX_CODE_BLOCKS, MAX_PRECINCTS, PrecinctGeom, ResolutionGeom, resolution_geoms,
47};
48pub(crate) use progression::{PacketWalk, for_each_packet};
49
50/// The four subband orientations. Kept Tier-2-local so this stage stays
51/// independent of Tier-1; the assembly stage maps it to the Tier-1
52/// `Orientation` that selects the zero-coding context table.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum BandKind {
55    /// Low-pass both axes (the coarsest resolution only).
56    Ll,
57    /// High-pass horizontally, low-pass vertically.
58    Hl,
59    /// Low-pass horizontally, high-pass vertically.
60    Lh,
61    /// High-pass both axes.
62    Hh,
63}
64
65/// Which block coder a code-block was coded with.
66///
67/// A tile-component's code-block style fixes it for every block, except
68/// under MIXED (style bits `0x40` and `0x80`, ISO/IEC 15444-15 A.4), where
69/// each block is an HT block or a Part 1 one. Tier-2 tells them apart by the
70/// block's first nonzero length field (see [`mixed_first_length`]), since the
71/// two read their later length fields differently.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Coder {
74    /// The Part 1 block coder (ISO/IEC 15444-1 Annex D).
75    Part1,
76    /// The HTJ2K block coder (ISO/IEC 15444-15).
77    Ht,
78}
79
80impl Coder {
81    /// The coder of every code-block of a tile-component with code-block
82    /// style `style`, or `None` under MIXED, where each block has its own.
83    /// `ccap15` is the codestream's `Ccap15` word: when it says every
84    /// code-block is an HT block (bits 15-14 are `00`, A.3.2), a MIXED style
85    /// holds only HT blocks, as A.3.2's note allows.
86    pub(crate) fn of_style(
87        style: u8,
88        ccap15: Option<crate::codestream::markers::Ccap15>,
89    ) -> Option<Coder> {
90        use crate::codestream::markers::code_block_style::{HT, HT_MIXED};
91        if style & HT == 0 {
92            Some(Coder::Part1)
93        } else if style & HT_MIXED == 0 || ccap15.is_some_and(|c| c.ht_only()) {
94            Some(Coder::Ht)
95        } else {
96            None
97        }
98    }
99}
100
101/// One code-block's coded contribution within its subband. `num_passes` is the
102/// coding-pass count from the packet headers (0 if no layer the decode keeps
103/// includes the block) and `zero_bit_planes` the all-zero most-significant
104/// bit-plane count from the zero-bitplane tag tree. `segments` are the raw
105/// coded byte slices Tier-1 decodes (none when the block is not included).
106///
107/// An HT block's placeholder passes are in none of these: they code no bytes,
108/// and each three of them add one to `zero_bit_planes` instead (ISO/IEC
109/// 15444-15 B.3). Its segments are a cleanup segment, then, if it has
110/// refinement passes, a refinement segment.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct CodeBlock<'a> {
113    /// Top-left of the block within its subband, in band-relative samples.
114    pub x: usize,
115    pub y: usize,
116    pub width: usize,
117    pub height: usize,
118    /// Coding passes accumulated over every layer the decode keeps that
119    /// contributed.
120    pub num_passes: u32,
121    pub zero_bit_planes: u32,
122    /// The block's codeword segments, in order. Tier-1 restarts the MQ decoder
123    /// at each one and carries its bit-plane state across them.
124    pub segments: Vec<CodedSegment<'a>>,
125    /// Whether the last segment may be cut short: a layer the decode drops
126    /// adds coding passes to it, or, with `strict` off, a later packet of the
127    /// block's precinct, which may add some, is missing: the data ends
128    /// before it or the `POC` volumes leave it out. Either
129    /// way the encoder may have terminated it past the passes and bytes kept
130    /// here, so Tier-1 does not hold it to `predictable termination`. Only
131    /// the last segment can be cut, since a layer adds passes and bytes to
132    /// the last segment or to new ones.
133    pub cut: bool,
134    /// The placeholder passes of an HT block in the layers the decode keeps,
135    /// which `num_passes` leaves out. Always 0 for a Part 1 block.
136    pub placeholders: u32,
137    /// The block's coder. A block of a MIXED tile-component whose length
138    /// fields are all zero is an HT block of placeholder passes only, which
139    /// codes nothing (see [`mixed_first_length`]).
140    pub coder: Coder,
141    /// With `strict` off, the first layer whose packet of the block's
142    /// precinct was not read whole; `None` when every packet of it was read,
143    /// and always when strict.
144    pub missing_from: Option<u32>,
145}
146
147/// One codeword segment: the coding passes it carries and the bytes coding
148/// them, which a multi-layer codestream may deliver in several chunks.
149///
150/// Without per-pass termination a block has exactly one segment, and the MQ
151/// codeword runs continuously across every layer that contributed to it. Under
152/// `restart` (`termall`) each coding pass is terminated separately, so each is
153/// its own segment and Tier-1 must re-initialize the MQ decoder for it.
154#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct CodedSegment<'a> {
156    pub passes: u32,
157    pub chunks: Vec<&'a [u8]>,
158}
159
160impl<'a> CodedSegment<'a> {
161    /// The segment's bytes, concatenated across the layers that carried them.
162    /// A segment of one chunk is borrowed from the codestream, not copied.
163    pub fn bytes(&self) -> Cow<'a, [u8]> {
164        match self.chunks[..] {
165            [] => Cow::Borrowed(&[]),
166            [chunk] => Cow::Borrowed(chunk),
167            _ => Cow::Owned(self.chunks.concat()),
168        }
169    }
170}
171
172/// One subband: its orientation, tile-component origin, sample geometry, and the
173/// code-block grid carrying the coded segments. Blocks are row-major, so block
174/// `(i, j)` is `blocks[j * block_cols + i]`.
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct Subband<'a> {
177    pub kind: BandKind,
178    /// Tile-component coordinate of the band's top-left sample.
179    pub origin: (u32, u32),
180    pub width: usize,
181    pub height: usize,
182    pub block_cols: usize,
183    pub block_rows: usize,
184    pub blocks: Vec<CodeBlock<'a>>,
185}
186
187/// One resolution level's subbands, in packet order: `[Ll]` at the coarsest
188/// level, `[Hl, Lh, Hh]` at every finer level, or none when the resolution
189/// holds no precinct.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct Resolution<'a> {
192    pub subbands: Vec<Subband<'a>>,
193}
194
195/// One component's coded data, grouped by resolution (coarsest first, index 0
196/// the `NLLL` band) so Tier-1 can decode each block independently and the
197/// assembly stage can place it back.
198///
199/// A resolution that holds no precinct lists no subbands: each is empty and
200/// owns no code-block. The inverse DWT still needs their origins and sizes,
201/// which [`band`](Self::band) gives from `rect`.
202#[derive(Debug, Clone, Default, PartialEq, Eq)]
203pub struct ComponentCoded<'a> {
204    pub resolutions: Vec<Resolution<'a>>,
205    /// The tile-component's rectangle on its own grid, as the walk saw it.
206    /// `None` for coded data built by hand.
207    pub rect: Option<Rect>,
208}
209
210/// Where a subband sits and how big it is: [`Subband`] without its blocks.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct BandExtent {
213    pub origin: (u32, u32),
214    pub width: usize,
215    pub height: usize,
216}
217
218impl BandExtent {
219    /// The extent of a band on `[x0, x1) x [y0, y1)`, empty where the bounds
220    /// meet or cross.
221    fn of_bounds(x0: i64, x1: i64, y0: i64, y1: i64) -> Self {
222        BandExtent {
223            origin: (x0.max(0) as u32, y0.max(0) as u32),
224            width: (x1 - x0).max(0) as usize,
225            height: (y1 - y0).max(0) as usize,
226        }
227    }
228}
229
230impl ComponentCoded<'_> {
231    /// The origin and size of the `kind` band of resolution `r`: what the
232    /// resolution lists or, when it lists none because it holds no precinct,
233    /// what its rectangle gives (see [`geometry::band_rects`]). `None` for a
234    /// band that does not exist.
235    pub fn band(&self, r: usize, kind: BandKind) -> Option<BandExtent> {
236        let resolution = self.resolutions.get(r)?;
237        if let Some(sb) = resolution.subbands.iter().find(|s| s.kind == kind) {
238            return Some(BandExtent {
239                origin: sb.origin,
240                width: sb.width,
241                height: sb.height,
242            });
243        }
244        if !resolution.subbands.is_empty() {
245            return None;
246        }
247        let nl = u32::try_from(self.resolutions.len() - 1).ok()?;
248        geometry::band_rects(self.rect?, nl, u32::try_from(r).ok()?)
249            .find(|b| b.0 == kind)
250            .map(|(_, x0, x1, y0, y1)| BandExtent::of_bounds(x0, x1, y0, y1))
251    }
252
253    /// The `HL`, `LH` and `HH` bands of resolution `r` when it lists none
254    /// (see [`band`](Self::band)) and is not the coarsest.
255    pub fn detail_extents(&self, r: usize) -> Option<[BandExtent; 3]> {
256        if r == 0 || !self.resolutions.get(r)?.subbands.is_empty() {
257            return None;
258        }
259        let nl = u32::try_from(self.resolutions.len() - 1).ok()?;
260        let mut bands = geometry::band_rects(self.rect?, nl, u32::try_from(r).ok()?)
261            .map(|(_, x0, x1, y0, y1)| BandExtent::of_bounds(x0, x1, y0, y1));
262        Some([bands.next()?, bands.next()?, bands.next()?])
263    }
264}
265
266/// The coded byte segments for every code-block of every component, in SIZ
267/// component order.
268#[derive(Debug, Clone, Default, PartialEq, Eq)]
269pub struct CodedData<'a> {
270    pub components: Vec<ComponentCoded<'a>>,
271}
272
273/// Parse all packets of one tile into per-code-block coded segments.
274///
275/// `header` is the tile's resolved header (`Codestream::tile_header`), so a
276/// tile-part COD/QCD override is already in force and nothing below needs to know
277/// a main header exists. The geometry is the tile's own too: every
278/// tile-component bound is the *tile*'s rect on that component's grid, not the
279/// image's.
280///
281/// There is one packet per (layer, resolution, component, precinct) the tile
282/// carries, enumerated in `COD`'s progression order — see [`for_each_packet`].
283/// Each component carries its own tile-component geometry, so a sub-sampled
284/// component's subbands are smaller at the same resolution, and its precinct
285/// lattice is coarser on the reference grid.
286///
287/// The walk spends `meter`, what is left of the decode's work bound (see
288/// [`decode_visits`]), and fails with [`Error::Limit`] once it is gone. A
289/// POC sequence's packets are held in a bitmap of at most `poc_bitmap`
290/// bits, and no more than the visits left, and past it as a count per
291/// precinct (see [`for_each_packet`]). The code-blocks of the resolutions that
292/// `reduction` drops are charged to `meter` too (see
293/// [`Budget::reduction`]). The packets of the layers past `layers` are read
294/// but add nothing to their code-blocks (see [`Budget::layers`]).
295pub(crate) fn decode_packets_metered<'a>(
296    header: &MainHeader,
297    tile: &'a Tile<'a>,
298    meter: &Meter,
299    poc_bitmap: u64,
300    reduction: u8,
301    layers: Option<u16>,
302) -> std::result::Result<CodedData<'a>, Refused> {
303    meter.clear_refusal();
304    let mut budget = Budget {
305        reduction,
306        layers,
307        ..Budget::decode(meter.left(), poc_bitmap)
308    };
309    decode_packets_within(header, tile, &mut budget, meter).map_err(|error| refused(meter, error))
310}
311
312/// [`decode_packets_metered`] on a meter of `visits` that is read back into
313/// it, for tests that walk a tile on its own.
314#[cfg(test)]
315pub fn decode_packets<'a>(
316    header: &MainHeader,
317    tile: &'a Tile<'a>,
318    visits: &mut u64,
319    poc_bitmap: u64,
320    reduction: u8,
321) -> std::result::Result<CodedData<'a>, Refused> {
322    let meter = Meter::new(*visits);
323    let coded = decode_packets_metered(header, tile, &meter, poc_bitmap, reduction, None);
324    *visits = meter.left();
325    coded
326}
327
328/// How a walk that failed with `error` was refused: for work when `meter`
329/// recorded why, otherwise as the error it is.
330fn refused(meter: &Meter, error: Error) -> Refused {
331    match (meter.refusal(), error) {
332        (Some(work), Error::Limit(_)) => Refused::Work(work),
333        (_, error) => Refused::Other(error),
334    }
335}
336
337/// The fewest visits (see [`Meter`]) a decode may spend walking its
338/// tiles' packets. A visit costs about 1 to 55 ns (see
339/// [`DECODE_VISITS_PER_BYTE`]), so this is under a second. A packet a POC
340/// marker's volumes reach again is skipped from a bitmap without a visit, in
341/// about 4 ns; skipped by the per-precinct counts a sequence past the bitmap
342/// keeps, it is charged 12 visits (see `progression::for_each_packet`).
343pub(crate) const DECODE_VISITS_MIN: u64 = 1 << 24;
344
345/// The visits a decode may spend per byte of its tiles' data, when that comes
346/// to more than [`DECODE_VISITS_MIN`]. The cheapest visits, the layer
347/// orders' steps over resolutions with no precinct, refuse a file at about
348/// 0.02 to 0.06 µs a byte, 1 to 2 ns a visit. The costliest measured are a
349/// positional walk's points over 16384 components and 200 tiles, each with
350/// a packet to read: 24 to 28 ns a visit over 32 `POC` volumes and 33 to
351/// 55 ns with none, the packet reads included. So the bound comes to between
352/// about 0.02 and 1.8 µs a byte, against the 0.19 to 0.73 µs a byte the
353/// conformance codestreams past 100 KB take to decode (the best of five
354/// release-build decodes of each). At most, a file past the floor is refused
355/// in about 2.5 times the slowest conformance decode per byte.
356///
357/// Setting up a tile's geometry is counted only for the code-blocks of the
358/// resolutions a reduction drops (see [`Budget::reduction`]). A resolution with no precinct
359/// gets no band or code-block geometry and lists no subband, so its setup
360/// allocates nothing. The costliest shape measured, 64 tiles of 16384
361/// components with one byte of packet data each, decodes at about 6 µs a
362/// byte, about 1.2 times what OpenJPEG takes.
363pub(crate) const DECODE_VISITS_PER_BYTE: u64 = 32;
364
365/// The visits a decode may spend walking the packets of tiles that hold
366/// `bytes` bytes of data in all, packed packet headers included.
367///
368/// A code-block entry that reads a bit of its packet header is paid for by
369/// the header's bytes and is not counted. What is counted is the work that
370/// reads none: each packet, each step over code-blocks whose inclusion is
371/// already known to lie past the layer (see [`parse_band_header`]), and each
372/// point of the progression order's loops. Encoder output spends 0.04 to 88
373/// visits per byte, the high end only in files of a few hundred bytes,
374/// under the floor; the largest share of the bound seen is 12.8%, from
375/// `opj_compress` on a sparse 2048^2 image in 4x4 code-blocks and 64
376/// layers. A packet header of one byte
377/// can still make the walk step over each row of code-blocks of its
378/// precinct, and a positional sweep can check millions of positions that
379/// hold no packet, so without a bound a small file could make the walk run
380/// for minutes. The one bound covers every tile of the decode, so many small
381/// tiles cannot each spend the floor.
382pub(crate) fn decode_visits(bytes: u64) -> u64 {
383    DECODE_VISITS_MIN.max(bytes.saturating_mul(DECODE_VISITS_PER_BYTE))
384}
385
386/// What one walk of a tile's packets may hold: the geometry guards, the
387/// POC packet storage and the reduction. The visits it spends are the
388/// [`Meter`]'s. Running out of a guard fails the walk with [`Error::Limit`]
389/// before the work or the allocation is done.
390#[derive(Debug, Clone, Copy, PartialEq, Eq)]
391pub(crate) struct Budget {
392    /// Precincts across the tile's components (see [`resolution_geoms`]).
393    pub(crate) precincts: usize,
394    /// Code-blocks across the tile's components (see [`resolution_geoms`]).
395    pub(crate) blocks: usize,
396    /// The most bits a POC sequence's packets are held in a bitmap of (see
397    /// [`for_each_packet`]).
398    pub(crate) poc_bitmap: u64,
399    /// Whether a POC sequence whose packets are more than
400    /// [`poc_bitmap`](Self::poc_bitmap) holds them as a count per precinct;
401    /// if not, its walk fails.
402    pub(crate) poc_counts: bool,
403    /// Whether a POC sequence that leaves out packets of the tile is refused
404    /// before the walk (see `progression::check_poc_coverage`). The decode
405    /// sets it. `read_header`'s walk of a `Psot = 0` tile does not: it asks
406    /// only where the packets the volumes reach end, and the decode refuses
407    /// the tile anyway.
408    pub(crate) poc_coverage: bool,
409    /// The decode's resolution reduction. Each code-block of a resolution it
410    /// drops costs a visit once the geometry is built, since every tile builds
411    /// its geometry at full resolution whatever the reduction. Nothing else is
412    /// charged for the geometry: each precinct is paid for by its packets'
413    /// visits, and the code-blocks of the kept resolutions are no more than
414    /// the reduced tile's samples, which the sample limit bounds, and the
415    /// per-tile cap. Without
416    /// the charge, many tiles of next to no data, each building close to the
417    /// per-tile code-block cap, would make a small file take minutes to decode
418    /// at a reduction. It is 0 for `read_header`'s walk.
419    pub(crate) reduction: u8,
420    /// The decode's layer cap (`DecodeOptions::max_quality_layers`): the
421    /// packets of layer `layers` on are still read, since they frame the
422    /// packets after them and their headers carry each code-block's state
423    /// into the next layer, but their coding passes and bytes are not added
424    /// to the code-blocks. Reading them costs the visits it does without a
425    /// cap. `None` keeps every layer, as `read_header`'s walk does.
426    pub(crate) layers: Option<u16>,
427}
428
429impl Budget {
430    /// The decode's budget for one tile: the geometry guards, and a POC
431    /// bitmap of no more bits than `visits`, the visits left on the decode's
432    /// [`Meter`], or `poc_bitmap`, then a count per precinct. A walk that
433    /// reads every packet takes a visit for each, so a bitmap of more bits
434    /// than the visits left would be wasted. `poc_bitmap` is the decode's
435    /// default bound, so a raised bound does not raise the bitmap's memory.
436    pub(crate) const fn decode(visits: u64, poc_bitmap: u64) -> Budget {
437        Budget {
438            precincts: MAX_PRECINCTS,
439            blocks: MAX_CODE_BLOCKS,
440            poc_bitmap: if visits < poc_bitmap {
441                visits
442            } else {
443                poc_bitmap
444            },
445            poc_counts: true,
446            poc_coverage: true,
447            reduction: 0,
448            layers: None,
449        }
450    }
451}
452
453/// What a walk with `strict` off found of a tile's packets: which were never
454/// read, and what was left over.
455#[derive(Debug, Clone, Default, PartialEq, Eq)]
456pub(crate) struct Reach {
457    /// Per component, per resolution: the first layer with a packet that was
458    /// not read, or `None` when every packet of it was read.
459    pub(crate) missing_from: Vec<Vec<Option<u32>>>,
460    /// Bytes of tile data not read: where they start and how many.
461    pub(crate) leftover: Option<(usize, usize)>,
462    /// Bytes of packed packet headers not read.
463    pub(crate) leftover_packed: Option<usize>,
464}
465
466impl Reach {
467    /// Note that packet (`layer`, `res`, `comp`) was not read.
468    fn miss(&mut self, comp: usize, res: usize, layer: u32) {
469        if let Some(from) = self.missing_from.get_mut(comp).and_then(|c| c.get_mut(res)) {
470            *from = Some(from.map_or(layer, |f| f.min(layer)));
471        }
472    }
473}
474
475/// [`decode_packets_metered`] with `strict` off: the tile's data may end
476/// anywhere, and what was not read comes back as a [`Reach`] beside the coded
477/// data (see [`walk_packets`]).
478pub fn decode_packets_partial<'a>(
479    header: &MainHeader,
480    tile: &'a Tile<'a>,
481    meter: &Meter,
482    poc_bitmap: u64,
483    reduction: u8,
484    layers: Option<u16>,
485) -> std::result::Result<(CodedData<'a>, Reach), Refused> {
486    meter.clear_refusal();
487    let mut budget = Budget {
488        reduction,
489        layers,
490        ..Budget::decode(meter.left(), poc_bitmap)
491    };
492    let mut reach = Reach::default();
493    walk_packets(header, tile, &mut budget, meter, Some(&mut reach))
494        .map(|coded| (coded, reach))
495        .map_err(|error| refused(meter, error))
496}
497
498/// [`decode_packets_metered`] under `budget`, spending `meter`, which is left
499/// holding what was not spent, also when the walk fails.
500pub(crate) fn decode_packets_within<'a>(
501    header: &MainHeader,
502    tile: &'a Tile<'a>,
503    budget: &mut Budget,
504    meter: &Meter,
505) -> Result<CodedData<'a>> {
506    walk_packets(header, tile, budget, meter, None)
507}
508
509/// The packet walk behind [`decode_packets_within`] and
510/// [`decode_packets_partial`]: strict when `reach` is `None`.
511///
512/// Not strict, the walk reads packets until the data ends (see
513/// [`parse_packet`]), then goes on through the rest of the progression
514/// without reading, to note each packet not read in `reach`. That costs a
515/// visit a packet, from the same meter, and the end of the data costs
516/// [`END_VISITS`] for each resolution of each component, for the setup no
517/// byte paid for. Packets the `POC` volumes leave out are noted the same way
518/// rather than refused, and bytes left after the last packet are noted
519/// rather than refused. Every other fault, the work bound included, fails as
520/// it does when strict.
521fn walk_packets<'a>(
522    header: &MainHeader,
523    tile: &'a Tile<'a>,
524    budget: &mut Budget,
525    meter: &Meter,
526    mut reach: Option<&mut Reach>,
527) -> Result<CodedData<'a>> {
528    let data: &'a [u8] = &tile.data;
529
530    // Precincts are bounded *as the geometry is built*, not after: a precinct's
531    // grid dimensions are cheap to compute but each precinct then costs a
532    // `PrecinctGeom` per band and a pair of tag trees, each tree a heap
533    // allocation, and the block count does not bound them — a band empty in
534    // one axis has no blocks while its resolution still has a full column of
535    // precincts. A 1 × 2^26 image under a 2^1 precinct is the shape that
536    // exploits it: ~2^25 precincts, built before any after-the-fact check
537    // could fire. So the cap is threaded through `resolution_geoms` and
538    // enforced before the allocation, across every component of the tile
539    // (`resolution_geoms` mutates the running total).
540    //
541    // The code-block count is bounded the same way and for the same reason:
542    // the per-block `BlockState`s and tag-tree leaves below, and the
543    // `CodeBlock`s after them, are sized by it, and legal 4×4 blocks push the
544    // count toward samples/16, so the cap has to bite before they are
545    // allocated rather than summing them afterwards. Both running totals are
546    // threaded through `resolution_geoms`; the geometry itself holds nothing
547    // per block.
548    //
549    // The code-blocks of the resolutions the reduction drops are charged to
550    // `meter` as each component is built (see [`Budget::reduction`]), so a
551    // tile can pass the bound by at most one component's geometry, which the
552    // caps bound.
553    let geoms = tile_geometry(header, tile.index, budget, |dropped| {
554        meter.spend(
555            dropped,
556            WorkRefusal::DroppedBlocks {
557                blocks: dropped as u64,
558            },
559        )
560    })?;
561    let mut states = band_states(header, &geoms);
562
563    let walk = PacketWalk {
564        siz: &header.siz,
565        tile: header
566            .siz
567            .tile_rect(tile.index)
568            .ok_or_else(|| Error::inconsistent(format!("no tile {} in `SIZ`", tile.index)))?,
569        geoms: &geoms,
570    };
571    let delimiters = Delimiters {
572        sop: header.cod.use_sop,
573        eph: header.cod.use_eph,
574    };
575    // When the tile carries PPT packed headers, packet headers come from that
576    // buffer and only the bodies stay inline; otherwise both are `data` and the
577    // two cursors move together.
578    let packed = !tile.packed_headers.is_empty();
579    let mut streams = PacketStreams {
580        header: if packed { &tile.packed_headers } else { data },
581        header_pos: 0,
582        data,
583        body_pos: 0,
584        packed,
585        tile: tile.index,
586    };
587    if let Some(reach) = reach.as_deref_mut() {
588        reach.missing_from = geoms.iter().map(|c| vec![None; c.len()]).collect();
589        progression::poc_gaps(header, &walk, |comp, res, layer| {
590            reach.miss(comp, res, u32::from(layer));
591            // The packets left out may add passes to the last segment of
592            // any code-block of the resolution, as packets the data never
593            // reached may.
594            mark_gap(&mut states[comp][res], u32::from(layer));
595            Ok(())
596        })?;
597    } else if budget.poc_coverage {
598        progression::check_poc_coverage(header, &walk, tile.index)?;
599    }
600    let strict = reach.is_none();
601    let end_visits = geoms
602        .iter()
603        .map(Vec::len)
604        .sum::<usize>()
605        .saturating_mul(END_VISITS);
606    let mut log = Vec::new();
607    let mut scratch = Scratch::default();
608    // Not strict: whether the data has ended.
609    let mut ended = false;
610    let mut packet_index = 0u32;
611    for_each_packet(
612        header,
613        &walk,
614        meter,
615        budget.poc_bitmap,
616        budget.poc_counts,
617        |layer, resolution, component, precinct| {
618            if let Some(reach) = reach.as_deref_mut() {
619                if ended {
620                    // Past the end of the data: count the packet, not read.
621                    meter.spend(1, WorkRefusal::PacketWalk)?;
622                    reach.miss(component, resolution, layer);
623                    mark_unread(&mut states[component][resolution], precinct, layer);
624                    return Ok(());
625                }
626            }
627            let geom = &geoms[component][resolution];
628            let packet = parse_packet(
629                &mut streams,
630                meter,
631                layer,
632                packet_index,
633                delimiters,
634                header.components[component].coding.code_block_style,
635                &geom.bands,
636                precinct,
637                &mut states[component][resolution],
638                &mut scratch,
639                budget.layers.is_none_or(|cap| layer < u32::from(cap)),
640                if strict { None } else { Some(&mut log) },
641                None,
642            )?;
643            if packet != Packet::Read {
644                ended = true;
645                mark_unread(&mut states[component][resolution], precinct, layer);
646                meter.spend(end_visits, WorkRefusal::PacketWalk)?;
647                if let Some(reach) = reach.as_deref_mut() {
648                    reach.miss(component, resolution, layer);
649                }
650            }
651            packet_index += 1;
652            Ok(())
653        },
654    )?;
655
656    let mut components = Vec::with_capacity(states.len());
657    for (comp, (component_states, component_geoms)) in states.iter().zip(&geoms).enumerate() {
658        let rect = header
659            .siz
660            .tile_component_rect(tile.index, comp)
661            .ok_or_else(|| Error::inconsistent(format!("no component {comp} in `SIZ`")))?;
662        let mut resolutions = Vec::with_capacity(component_states.len());
663        for (band_states, level) in component_states.iter().zip(component_geoms) {
664            let subbands = if level.bands.is_empty() {
665                Vec::new()
666            } else {
667                build_subbands(&level.bands, band_states, data)
668            };
669            resolutions.push(Resolution { subbands });
670        }
671        components.push(ComponentCoded {
672            resolutions,
673            rect: Some(rect),
674        });
675    }
676
677    // Not strict, bytes left after the last packet are noted rather than
678    // refused. Data that ran out leaves none.
679    if let Some(reach) = reach {
680        if !ended {
681            if streams.body_pos < data.len() {
682                reach.leftover = Some((streams.body_pos, data.len() - streams.body_pos));
683            }
684            if packed && streams.header_pos < streams.header.len() {
685                reach.leftover_packed = Some(streams.header.len() - streams.header_pos);
686            }
687        }
688        return Ok(CodedData { components });
689    }
690
691    // The packets tile the tile-part data exactly, with no padding, up to the
692    // closing EOC. Any remainder means a misread field — a dropped layer shows up
693    // here as leftover bytes (this doubles as the parse self-check).
694    if streams.body_pos != data.len() {
695        return Err(Error::codestream(format!(
696            "tile {} has {} byte(s) left after the last packet",
697            tile.index,
698            data.len() - streams.body_pos
699        )));
700    }
701    // The packed headers must be exhausted too: a leftover header byte is the
702    // same kind of misread, caught on the header stream instead of the body.
703    if packed && streams.header_pos != streams.header.len() {
704        return Err(Error::codestream(format!(
705            "tile {} has {} byte(s) of packed packet headers left after the last packet",
706            tile.index,
707            streams.header.len() - streams.header_pos
708        )));
709    }
710
711    Ok(CodedData { components })
712}
713
714/// The geometry of each component of tile `tile`, built under `budget`'s
715/// caps. After each component, `dropped` is called with the code-blocks of
716/// the resolutions `budget`'s reduction drops (see [`Budget::reduction`]),
717/// and an error from it ends the build.
718fn tile_geometry(
719    header: &MainHeader,
720    tile: u32,
721    budget: &mut Budget,
722    mut dropped: impl FnMut(usize) -> Result<()>,
723) -> Result<Vec<Vec<ResolutionGeom>>> {
724    let component_count = header.siz.components.len();
725    let mut geoms = Vec::with_capacity(component_count);
726    for c in 0..component_count {
727        let resolutions =
728            resolution_geoms(header, tile, c, &mut budget.precincts, &mut budget.blocks)?;
729        let kept = resolutions
730            .len()
731            .saturating_sub(usize::from(budget.reduction));
732        dropped(
733            resolutions[kept..]
734                .iter()
735                .flat_map(|resolution| &resolution.bands)
736                .map(BandGeom::block_count)
737                .sum(),
738        )?;
739        geoms.push(resolutions);
740    }
741    Ok(geoms)
742}
743
744/// One state per (component, resolution, band) of `geoms`, carried across
745/// every layer. The tag trees decode incrementally and there is a pair per
746/// *precinct*, so they must outlive the packet that starts them.
747fn band_states(header: &MainHeader, geoms: &[Vec<ResolutionGeom>]) -> Vec<Vec<Vec<BandState>>> {
748    geoms
749        .iter()
750        .zip(&header.components)
751        .map(|(component, params)| {
752            let coder = Coder::of_style(params.coding.code_block_style, header.ccap15);
753            component
754                .iter()
755                .map(|level| {
756                    level
757                        .bands
758                        .iter()
759                        .map(|band| BandState::new(band, coder))
760                        .collect()
761                })
762                .collect()
763        })
764        .collect()
765}
766
767/// Ceiling on the zero-bitplane count: a single read above this resolves any
768/// real value, while rejecting a malformed run of zero bits rather than
769/// looping on it. The count is bounded by the *raised* plane count
770/// `Kmax = Mb + SPrgn` (ISO H.2), not by `Mb` alone — a background-only block
771/// under a maxshift legitimately signals more zero bit-planes than the band
772/// has magnitude planes. `Mb` is at most 37 (7 guard bits + exponent 31 − 1)
773/// and the maxshift byte at most 255, so 292 is the largest value a
774/// conformant stream can signal and this threshold resolves every one.
775const ZBP_LIMIT: u32 = 293;
776
777/// Upper bound on the Lblock length-indicator before a malformed packet is
778/// rejected. The length field is `Lblock + floor(log2(num_passes))` bits and
779/// `num_passes ≤ 164` (so `floor(log2) ≤ 7`); capping Lblock at 24 keeps that
780/// read at most 31 bits, inside the `u32` [`BitReader::read`] accepts.
781const LBLOCK_MAX: u32 = 24;
782
783/// What a codeword segment codes. It decides how many passes the segment may
784/// hold and what the next segment is.
785#[derive(Debug, Clone, Copy, PartialEq, Eq)]
786enum SegmentKind {
787    /// Part 1 passes the MQ coder codes: every segment of a block without
788    /// `bypass`, and the cleanup segments of one with it.
789    Mq,
790    /// The raw segment of a `bypass` block: a significance and a refinement
791    /// pass coded as raw bits.
792    Raw,
793    /// An HT cleanup segment (ISO/IEC 15444-15 B.2). A block's first one
794    /// holds `placeholders` passes before its cleanup pass, a multiple of
795    /// three; every later one holds its cleanup pass alone. `None` while every
796    /// pass read is a placeholder pass: the cleanup pass, and so the segment's
797    /// end, is still to come (B.3 NOTE 4). See [`ht_first_cleanup`].
798    HtCleanup { placeholders: Option<u32> },
799    /// An HT refinement segment: a SigProp pass and, if present, a MagRef
800    /// pass.
801    HtRefinement,
802}
803
804/// The kind of the *next* codeword segment, and how many coding passes it may
805/// hold, given the block's coder, the code-block style and the last segment
806/// opened (`opj_t2_init_seg`).
807///
808/// `termall` terminates the MQ coder after every pass, so each pass is its own
809/// segment. `bypass` (lazy) terminates at every raw/MQ boundary: the first
810/// segment holds the ten MQ passes of the four most significant bit-planes, then
811/// each lower plane splits into a two-pass raw segment (significance +
812/// refinement) and a one-pass MQ segment (cleanup) — the `10, 2, 1, 2, 1, …`
813/// pattern OpenJPEG spells with `prev.maxpasses in {1, 10} ? 2 : 1`. Otherwise a
814/// segment takes up to 109 passes — `3 * Mb - 2` with `Mb` capped at 37 — which a
815/// code-block can never exceed, so the default never splits.
816///
817/// An HT block's segments alternate by ISO/IEC 15444-15 B.2: after a cleanup
818/// segment comes a refinement segment of up to two passes, then a one-pass
819/// cleanup segment. Its first segment is opened by [`ht_first_cleanup`]
820/// instead, since where it ends depends on the placeholder passes of the
821/// contribution that holds the cleanup pass. The other style bits mean nothing
822/// to an HT block.
823fn next_segment(coder: Coder, style: u8, last: Option<&SegmentState>) -> (SegmentKind, u32) {
824    use crate::codestream::markers::code_block_style::{LAZY, TERMALL};
825    let last = last.map(|s| s.kind);
826    if coder == Coder::Ht {
827        match last {
828            Some(SegmentKind::HtCleanup { .. }) => (SegmentKind::HtRefinement, 2),
829            _ => (
830                SegmentKind::HtCleanup {
831                    placeholders: Some(0),
832                },
833                1,
834            ),
835        }
836    } else if style & TERMALL != 0 {
837        // Every pass ends its segment, so nothing turns on the kind.
838        (SegmentKind::Mq, 1)
839    } else if style & LAZY != 0 {
840        match last {
841            None => (SegmentKind::Mq, 10),
842            Some(SegmentKind::Mq) => (SegmentKind::Raw, 2),
843            Some(_) => (SegmentKind::Mq, 1),
844        }
845    } else {
846        (SegmentKind::Mq, 109)
847    }
848}
849
850/// The width of a length field: `Lblock + floor(log2(n))` bits for a codeword
851/// segment of `n` passes from one packet (ISO B.10.7.1). An HT block uses the
852/// same rule for each codeword segment (ISO/IEC 15444-15 B.3), so the field of
853/// its first cleanup segment counts the placeholder passes in it too.
854fn length_bits(lblock: u32, passes: u32) -> u32 {
855    lblock + passes.ilog2()
856}
857
858/// The longest HT cleanup segment, `Lcup < 65535`, and HT refinement segment,
859/// `Lref < 2047` (ISO/IEC 15444-15 7.1.1, 7.1.2).
860const HT_CLEANUP_MAX: u64 = 65534;
861const HT_REFINEMENT_MAX: u64 = 2046;
862
863/// Add a length field's `bytes` to `segment`, which an HT segment may hold
864/// only within its limit. An HT segment's bytes are those of its codeword
865/// segments over the layers (B.3), so the limit is on the sum.
866fn add_length(segment: &mut SegmentState, bytes: u32) -> Result<()> {
867    segment.length += u64::from(bytes);
868    let (what, max) = match segment.kind {
869        SegmentKind::HtCleanup { .. } => ("cleanup", HT_CLEANUP_MAX),
870        SegmentKind::HtRefinement => ("refinement", HT_REFINEMENT_MAX),
871        SegmentKind::Mq | SegmentKind::Raw => return Ok(()),
872    };
873    if segment.length > max {
874        return Err(Error::codestream(format!(
875            "HT {what} segment is {} bytes, over the limit of {max}",
876            segment.length
877        )));
878    }
879    Ok(())
880}
881
882/// What the first length field of an HT block's contribution is, while the
883/// block's cleanup pass is still to come. See [`ht_first_cleanup`].
884#[derive(Debug, Clone, Copy, PartialEq, Eq)]
885enum FirstCleanup {
886    /// Every pass of the contribution is a placeholder pass.
887    Placeholders,
888    /// The contribution holds the cleanup pass, `placeholders` passes from
889    /// the block's first, and its first codeword segment has `passes` passes,
890    /// up to the cleanup pass, and `length` bytes.
891    Cleanup {
892        placeholders: u32,
893        passes: u32,
894        length: u32,
895    },
896}
897
898/// Read the first length field of an HT block's contribution of `new` passes,
899/// after `prior` passes that were all placeholders, and say whether the
900/// contribution holds the cleanup pass (ISO/IEC 15444-15 B.1 to B.3).
901///
902/// The packet with a block's first cleanup pass holds no other cleanup pass
903/// and at most two refinement passes after it (B.3). If this contribution
904/// holds it, it is pass `3 P0` (from 0), `P0 = floor((prior + new - 1) / 3)`,
905/// and the contribution's first codeword segment ends there. A contribution
906/// of placeholder passes only (NOTE 4) is one codeword segment of all `new`
907/// passes, whose length is zero, since placeholder passes carry no bytes.
908///
909/// The pass counts cannot tell the two apart, but the length can. The first
910/// cleanup segment is at least 2 bytes long (B.3), so the field read at the
911/// cleanup reading's width is nonzero exactly when the contribution holds the
912/// cleanup pass. That width is never more than the placeholder reading's, so
913/// a zero is the leading bits of an all-zero field, and the rest of it is read
914/// next. When `3 P0` falls before `prior`, the contribution cannot hold the
915/// cleanup pass, and its field is read at the placeholder width at once.
916fn ht_first_cleanup(
917    lblock: u32,
918    prior: u32,
919    new: u32,
920    bio: &mut BitReader,
921) -> Result<FirstCleanup> {
922    let placeholders = 3 * ((prior + new - 1) / 3);
923    let mut read = 0;
924    if placeholders >= prior {
925        let passes = placeholders + 1 - prior;
926        let bits = length_bits(lblock, passes);
927        match bio.read(bits) {
928            0 => read = bits,
929            1 => {
930                return Err(Error::codestream(
931                    "HT code-block's first cleanup segment is 1 byte long; it must be at least 2",
932                ));
933            }
934            length => {
935                return Ok(FirstCleanup::Cleanup {
936                    placeholders,
937                    passes,
938                    length,
939                });
940            }
941        }
942    }
943    if bio.read(length_bits(lblock, new) - read) != 0 {
944        return Err(Error::codestream(
945            "HT code-block placeholder passes carry bytes",
946        ));
947    }
948    Ok(FirstCleanup::Placeholders)
949}
950
951/// What the first length field of a contribution says about a code-block of
952/// a MIXED tile-component whose earlier length fields were all zero. See
953/// [`mixed_first_length`].
954#[derive(Debug, Clone, Copy, PartialEq, Eq)]
955enum MixedFirst {
956    /// The field is zero: the contribution codes no bytes, and the block's
957    /// coder is still open.
958    Empty,
959    /// The block is an HT block, and the contribution holds its cleanup pass.
960    Ht(FirstCleanup),
961    /// The block is a Part 1 block, and its one codeword segment takes
962    /// `length` bytes from the contribution.
963    Part1 { length: u32 },
964}
965
966/// Read the first length field of a contribution of `new` passes to a
967/// code-block of a MIXED tile-component, after `prior` passes whose length
968/// fields were all zero, and say which coder the block uses (ISO/IEC
969/// 15444-15 A.4).
970///
971/// The two coders read the field at different widths when the contribution
972/// holds an HT cleanup pass and refinement passes after it: an HT block's
973/// first field ends at its cleanup pass (see [`ht_first_cleanup`]), a Part 1
974/// block's one field spans all `new` passes, since A.4 allows a Part 1 block
975/// here neither bypass nor termination on each pass. Both fields start at
976/// the same bit, and A.4 requires of an HT block that the first bit of its
977/// first nonzero length field be 0 and that `Lblock` be above 3 there. So a
978/// nonzero field with `Lblock` at 3 or a leading 1 is a Part 1 block's.
979/// Otherwise the field is read as an HT block's, and a value an HT block
980/// cannot have (a cleanup length of 1 or over `HT_CLEANUP_MAX`, or bytes on
981/// placeholder passes) makes it a Part 1 block's: that is the A.4 note's "processing the code-block
982/// assuming it conforms to Annex B", and it fails here, in the length field,
983/// or not at all.
984///
985/// The bits read are the same whichever reading wins: a zero field is
986/// `Lblock + floor(log2(new))` bits in both, and a Part 1 field is read to
987/// that width. So the choice is made once, here, and the walk never holds
988/// two readings of a block.
989fn mixed_first_length(
990    lblock: u32,
991    prior: u32,
992    new: u32,
993    bio: &mut BitReader,
994) -> Result<MixedFirst> {
995    let width = length_bits(lblock, new);
996    // The HT reading's first field, when the contribution can hold the
997    // cleanup pass: its width, and its `placeholders` before the pass.
998    let placeholders = 3 * ((prior + new - 1) / 3);
999    let cleanup = (placeholders >= prior)
1000        .then(|| (length_bits(lblock, placeholders + 1 - prior), placeholders));
1001    // The Part 1 reading of the field, whose first `read` bits, of value
1002    // `top`, are read already.
1003    let part1 = |top: u32, read: u32, bio: &mut BitReader| match (top << (width - read))
1004        | bio.read(width - read)
1005    {
1006        0 => MixedFirst::Empty,
1007        length => MixedFirst::Part1 { length },
1008    };
1009    if lblock <= 3 {
1010        return Ok(part1(0, 0, bio));
1011    }
1012    if bio.read_bit() == 1 {
1013        return Ok(part1(1, 1, bio));
1014    }
1015    let Some((bits, placeholders)) = cleanup else {
1016        return Ok(part1(0, 1, bio));
1017    };
1018    match bio.read(bits - 1) {
1019        top @ (0 | 1) => Ok(part1(top, bits, bio)),
1020        // A cleanup segment over its limit (7.1.1) is not an HT block's.
1021        top if u64::from(top) > HT_CLEANUP_MAX => Ok(part1(top, bits, bio)),
1022        length => Ok(MixedFirst::Ht(FirstCleanup::Cleanup {
1023            placeholders,
1024            passes: placeholders + 1 - prior,
1025            length,
1026        })),
1027    }
1028}
1029
1030/// Settle a code-block of a MIXED tile-component as a Part 1 block. Its
1031/// earlier passes, held as placeholder passes of no bytes, become passes of
1032/// its one MQ codeword segment. A.4 allows a Part 1 block there neither
1033/// bypass nor termination on each pass, so all its passes, in every layer,
1034/// are one codeword segment with one length field per contribution
1035/// (ISO/IEC 15444-1 B.10.7.1). The segment has no pass limit: OpenJPEG's
1036/// 109-pass split ([`next_segment`]) is for the Part 1 tile-components it
1037/// decodes. A block of more passes than tier-1 can decode is refused there.
1038fn become_part1(block: &mut BlockState) {
1039    block.coder = Some(Coder::Part1);
1040    match block.segments.first_mut() {
1041        Some(segment) => {
1042            segment.kind = SegmentKind::Mq;
1043            segment.max_passes = u32::MAX;
1044            block.num_passes += segment.kept;
1045        }
1046        None => block
1047            .segments
1048            .push(SegmentState::new(SegmentKind::Mq, u32::MAX)),
1049    }
1050}
1051
1052/// Which packet delimiters `COD` signals (`Scod` bits 1 and 2).
1053#[derive(Debug, Clone, Copy)]
1054struct Delimiters {
1055    /// SOP *may* precede each packet.
1056    sop: bool,
1057    /// EPH *shall* follow each packet header.
1058    eph: bool,
1059}
1060
1061/// The two byte streams a packet is read from, with a cursor into each.
1062///
1063/// A packet is a header followed by its body. Normally both are inline in the
1064/// tile data and the two cursors move in lockstep. When the tile carries `PPT`
1065/// packed headers, the header stream is that separate buffer and the body stream
1066/// is still the tile data, so the cursors advance independently (A.7.5). SOP
1067/// stays in the body stream; EPH moves with the headers.
1068struct PacketStreams<'a> {
1069    /// Where packet *headers* are read: the `PPT` buffer, or `data` when inline.
1070    header: &'a [u8],
1071    header_pos: usize,
1072    /// Where packet *bodies* (and SOP markers) are read: always the tile data.
1073    data: &'a [u8],
1074    body_pos: usize,
1075    /// Whether the header stream is separate from the body stream.
1076    packed: bool,
1077    /// The tile's index, for an error message.
1078    tile: u32,
1079}
1080
1081/// Why a packet walk was refused for work, with the numbers a caller needs to
1082/// name a [`WorkLimit`](crate::WorkLimit) factor. It travels beside the
1083/// [`Error`] the walk fails with (see [`Refused`]), so nothing reads it back
1084/// out of the message. A new work refusal (the sample-area one, say) is a new
1085/// variant here, a line in [`WorkRefusal::why`], and a function in
1086/// `limit_hint`.
1087#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1088pub(crate) enum WorkRefusal {
1089    /// The walk ran out of visits.
1090    PacketWalk,
1091    /// A POC sequence's volumes reach `reached` packets, more than the visits
1092    /// left.
1093    PocReach { reached: u64 },
1094    /// A component's geometry holds `blocks` code-blocks in the resolutions
1095    /// the reduction drops, more than the visits left (see
1096    /// [`Budget::reduction`]).
1097    DroppedBlocks { blocks: u64 },
1098}
1099
1100impl WorkRefusal {
1101    /// The plain message of the [`Error::Limit`] for this refusal, without
1102    /// the tile or a retry factor. [`decode`](crate::decode) replaces it with
1103    /// the full message from `limit_hint`.
1104    pub(crate) fn why(&self) -> String {
1105        match self {
1106            WorkRefusal::PacketWalk => "reading the packet headers goes past the packet work \
1107                                        bound (see `DecodeOptions::packet_work_limit`)"
1108                .into(),
1109            WorkRefusal::PocReach { reached } => format!(
1110                "the `POC` volumes reach {reached} packets, a step each, more than \
1111                 the steps left of the packet work bound (see \
1112                 `DecodeOptions::packet_work_limit`)"
1113            ),
1114            WorkRefusal::DroppedBlocks { blocks } => format!(
1115                "the resolutions the reduction drops hold {blocks} code-blocks in \
1116                 one component, a step each, more than the steps left of the \
1117                 packet work bound (see `DecodeOptions::packet_work_limit`)"
1118            ),
1119        }
1120    }
1121}
1122
1123/// How [`decode_packets_metered`] fails: for work, with the typed reason, or
1124/// for anything else, as the [`Error`] it is.
1125#[derive(Debug)]
1126pub(crate) enum Refused {
1127    /// The tile went past the packet work bound.
1128    Work(WorkRefusal),
1129    /// Any other failure.
1130    Other(Error),
1131}
1132
1133impl From<Refused> for Error {
1134    fn from(refused: Refused) -> Error {
1135        match refused {
1136            Refused::Work(work) => Error::limit_unhinted(crate::LimitKind::PacketWork, work.why()),
1137            Refused::Other(error) => error,
1138        }
1139    }
1140}
1141
1142/// A decode's packet work count: the visits it started with, what is left,
1143/// and, once a walk is refused for work, why. The decode owns one and every
1144/// tile's walk spends it, so there is a single count to read afterwards.
1145///
1146/// A visit is a step of a walk that reads no bit: packets read, steps over
1147/// code-blocks a packet header does not name a bit for, and the points of
1148/// the progression order's loops, such as each position of a positional
1149/// sweep for each (component, resolution) it checks. A packet header can
1150/// be a single byte and still pass over every row of code-blocks of its
1151/// precinct, and a sweep can check millions of points that hold no
1152/// packet, so this bounds the work where the other limits cannot.
1153pub(crate) struct Meter {
1154    first: u64,
1155    left: Cell<u64>,
1156    refusal: Cell<Option<WorkRefusal>>,
1157}
1158
1159impl Meter {
1160    /// A meter with `first` visits to spend.
1161    pub(crate) fn new(first: u64) -> Self {
1162        Meter {
1163            first,
1164            left: Cell::new(first),
1165            refusal: Cell::new(None),
1166        }
1167    }
1168
1169    /// The visits it started with.
1170    pub(crate) fn first(&self) -> u64 {
1171        self.first
1172    }
1173
1174    /// The visits left.
1175    pub(crate) fn left(&self) -> u64 {
1176        self.left.get()
1177    }
1178
1179    /// The visits spent so far.
1180    pub(crate) fn spent(&self) -> u64 {
1181        self.first.saturating_sub(self.left.get())
1182    }
1183
1184    /// Why the walk was refused for work, once it is.
1185    fn refusal(&self) -> Option<WorkRefusal> {
1186        self.refusal.get()
1187    }
1188
1189    /// Forget a refusal an earlier walk recorded, so that it cannot label
1190    /// this walk's other limit errors as work.
1191    fn clear_refusal(&self) {
1192        self.refusal.set(None);
1193    }
1194
1195    /// Spend `n` visits, or leave the count as it is and say whether they
1196    /// were there. For a charge whose refusal is not a [`WorkRefusal`].
1197    pub(crate) fn try_spend(&self, n: u64) -> bool {
1198        match self.left.get().checked_sub(n) {
1199            Some(rest) => {
1200                self.left.set(rest);
1201                true
1202            }
1203            None => false,
1204        }
1205    }
1206
1207    /// Spend `n` visits, or refuse the walk for `why` when fewer are left.
1208    pub(crate) fn spend(&self, n: usize, why: WorkRefusal) -> Result<()> {
1209        if self.try_spend(n as u64) {
1210            Ok(())
1211        } else {
1212            Err(self.refuse(why))
1213        }
1214    }
1215
1216    /// Record `why` as the reason the walk is refused, and give the [`Error`]
1217    /// to fail it with.
1218    pub(crate) fn refuse(&self, why: WorkRefusal) -> Error {
1219        self.refusal.set(Some(why));
1220        Error::limit_unhinted(crate::LimitKind::PacketWork, why.why())
1221    }
1222}
1223
1224/// What the end of a tile's data costs with `strict` off, in visits, for
1225/// each resolution of each of the tile's components.
1226///
1227/// A strict decode stops at the first tile whose data runs out; one with
1228/// `strict` off goes on to the next. The geometry built for a tile and the
1229/// decode after its walk cost about a microsecond for each resolution of
1230/// each component, which the bytes of its packets pay for when they are
1231/// there. When they are not, a tile-part of 14 bytes would buy that setup
1232/// for thousands of components, so this charges it: at 32 visits, the
1233/// default bound's 2^24 visits hold about half a second of it. The data of
1234/// a codestream a strict decode reads never ends early, so this costs that
1235/// decode nothing.
1236const END_VISITS: usize = 32;
1237
1238/// The error for a packed packet header that reads past the end of the
1239/// `PPM` or `PPT` bytes it is packed in.
1240fn packed_overrun() -> Error {
1241    Error::codestream("a packet header runs past the end of its `PPM` or `PPT` packed headers")
1242}
1243
1244/// The two-byte marker at `pos`, or `None` if it would run past the end.
1245fn peek_marker(data: &[u8], pos: usize) -> Option<u16> {
1246    let hi = *data.get(pos)?;
1247    let lo = *data.get(pos + 1)?;
1248    Some(u16::from_be_bytes([hi, lo]))
1249}
1250
1251/// Consume the SOP marker segment at `pos` and return the offset of the packet
1252/// header that follows (ISO A.8.1).
1253///
1254/// `Lsop` is fixed at 4 and `Nsop` counts packets from zero **within the tile**,
1255/// continuing across that tile's tile-parts: OpenJPEG's encoder writes
1256/// `tile->packno`, which lives on the tile and is never reset per tile-part. The
1257/// corpus agrees — every single-tile entry that carries SOP numbers its packets
1258/// sequentially from zero, every multi-tile one restarts.
1259///
1260/// The counter therefore lives in [`decode_packets_metered`], which runs once
1261/// per tile over that tile's tile-parts joined end to end: it starts at zero
1262/// for each tile and does not restart at a tile-part boundary.
1263///
1264/// OpenJPEG leaves `Nsop` unchecked — `/* TODO : check the Nsop value */` — so
1265/// this is stricter than the oracle. Validating the sequence number is the whole
1266/// point of a resynchronization marker.
1267fn read_sop(data: &[u8], pos: usize, packet_index: u32) -> Result<usize> {
1268    let end = pos + 6;
1269    if end > data.len() {
1270        return Err(Error::codestream("truncated `SOP` marker segment"));
1271    }
1272    let lsop = u16::from_be_bytes([data[pos + 2], data[pos + 3]]);
1273    if lsop != 4 {
1274        return Err(Error::codestream(format!(
1275            "`SOP` declares `Lsop` {lsop}, expected 4"
1276        )));
1277    }
1278    let nsop = u16::from_be_bytes([data[pos + 4], data[pos + 5]]);
1279    // Nsop is 16 bits and wraps; a tile with more than 65536 packets restarts it.
1280    let expected = (packet_index % 65536) as u16;
1281    if nsop != expected {
1282        return Err(Error::codestream(format!(
1283            "`SOP` sequence number {nsop} for packet {packet_index}, expected {expected}"
1284        )));
1285    }
1286    Ok(end)
1287}
1288
1289/// One code-block's decode state, carried across the quality layers of its
1290/// precinct (ISO/IEC 15444-1 B.10).
1291///
1292/// A block is included in the packets of one layer onward, never in isolation:
1293/// once the inclusion tag tree resolves it, later layers signal a contribution
1294/// with a single bit. `lblock` and `zero_bit_planes` are read once and then
1295/// persist, and `num_passes` and `segments` accumulate. Rebuilding any of this
1296/// per packet — which a single-layer decoder can get away with — desynchronizes
1297/// the header bit-reader on the second layer.
1298struct BlockState {
1299    /// The block's coder: the tile-component's, or, under MIXED, `None`
1300    /// until the block's first nonzero length field settles it (see
1301    /// [`mixed_first_length`]). While it is `None` every length field read
1302    /// was zero, which both coders read alike: the block's passes sit in one
1303    /// open HT cleanup segment of no bytes, as placeholder passes, and become
1304    /// passes of its one MQ segment if the block turns out to be a Part 1
1305    /// block.
1306    coder: Option<Coder>,
1307    included: bool,
1308    /// Length-indicator width, grown by a unary run of 1s and never reset.
1309    lblock: u32,
1310    /// The zero bit-planes the tag tree gives, without an HT block's skipped
1311    /// ones (see [`skipped_planes`](Self::skipped_planes)).
1312    zero_bit_planes: u32,
1313    /// Coding passes summed over every contributing layer the decode keeps
1314    /// (see [`Budget::layers`]), an HT block's placeholder passes left out.
1315    num_passes: u32,
1316    /// Codeword segments in order; the last one may still take passes.
1317    segments: Vec<SegmentState>,
1318}
1319
1320/// A codeword segment while it is being filled from successive layers.
1321struct SegmentState {
1322    kind: SegmentKind,
1323    /// Coding passes from every layer read, which decide where the next
1324    /// segment starts. An HT block's first cleanup segment counts its
1325    /// placeholder passes.
1326    passes: u32,
1327    /// The passes of [`passes`](Self::passes) from the layers the decode
1328    /// keeps: all of them without a layer cap. The layers past the cap only
1329    /// add passes after these, and add no chunks.
1330    kept: u32,
1331    /// How many passes this segment may hold before the next one starts:
1332    /// 1 under `termall`, the `10, 2, 1, 2, 1, …` pattern under `bypass`,
1333    /// otherwise 109 — the most a code-block can carry (`3 * Mb - 2` with
1334    /// `Mb <= 37`), so the default never splits. See [`next_segment`],
1335    /// which mirrors OpenJPEG's `opj_t2_init_seg`. A Part 1 block of a MIXED
1336    /// tile-component has one segment of any number of passes
1337    /// ([`become_part1`]). An HT block's first
1338    /// cleanup segment holds its placeholder passes and the cleanup pass,
1339    /// and until the cleanup pass comes it takes any number.
1340    max_passes: u32,
1341    /// The bytes the length fields gave it, over every layer read.
1342    length: u64,
1343    /// Where each layer's bytes of it lie in the tile data, in layer order.
1344    /// They are offsets, not slices, so that the state can outlive the
1345    /// bytes it was read from and go on over a longer copy of them.
1346    chunks: Vec<Range<usize>>,
1347}
1348
1349impl SegmentState {
1350    fn new(kind: SegmentKind, max_passes: u32) -> Self {
1351        SegmentState {
1352            kind,
1353            passes: 0,
1354            kept: 0,
1355            max_passes,
1356            length: 0,
1357            chunks: Vec::new(),
1358        }
1359    }
1360
1361    /// The placeholder passes of [`kept`](Self::kept): all of them while the
1362    /// cleanup pass is still to come.
1363    fn kept_placeholders(&self) -> u32 {
1364        match self.kind {
1365            SegmentKind::HtCleanup {
1366                placeholders: Some(p),
1367            } => self.kept.min(p),
1368            SegmentKind::HtCleanup { placeholders: None } => self.kept,
1369            _ => 0,
1370        }
1371    }
1372
1373    /// The kept passes Tier-1 decodes: [`kept`](Self::kept) without the
1374    /// placeholder passes, which code nothing.
1375    fn coded_kept(&self) -> u32 {
1376        self.kept - self.kept_placeholders()
1377    }
1378}
1379
1380impl BlockState {
1381    fn new(coder: Option<Coder>) -> Self {
1382        BlockState {
1383            coder,
1384            included: false,
1385            lblock: 3,
1386            zero_bit_planes: 0,
1387            num_passes: 0,
1388            segments: Vec::new(),
1389        }
1390    }
1391
1392    /// The magnitude bit-planes an HT block skips past those the tag tree
1393    /// gives: one per three placeholder passes (`P0`, ISO/IEC 15444-15 B.3),
1394    /// counted only when the decode keeps the cleanup pass after them. A
1395    /// block without its cleanup pass decodes to zeros whatever the count.
1396    fn skipped_planes(&self) -> u32 {
1397        match self.segments.first() {
1398            Some(
1399                s @ SegmentState {
1400                    kind:
1401                        SegmentKind::HtCleanup {
1402                            placeholders: Some(p),
1403                        },
1404                    ..
1405                },
1406            ) if s.coded_kept() > 0 => p / 3,
1407            _ => 0,
1408        }
1409    }
1410}
1411
1412/// One subband's decode state across the layers: a tag-tree pair **per
1413/// precinct**, plus a state per code-block of the whole band.
1414///
1415/// The trees are per precinct because a packet is per precinct — each one
1416/// decodes incrementally at a rising threshold over its own precinct's block
1417/// grid, and knows nothing of the blocks next door. The block states stay
1418/// band-indexed so that [`build_subbands`] can hand the band back whole; a block
1419/// is touched by exactly one precinct's packets, so the two indexings never
1420/// collide.
1421struct BandState {
1422    precincts: Vec<PrecinctState>,
1423    blocks: Vec<BlockState>,
1424}
1425
1426/// The two tag trees one precinct runs over one subband: which code-blocks the
1427/// packet includes, and how many of their leading bit-planes are all zero.
1428struct PrecinctState {
1429    inclusion: TagTree,
1430    zero_bits: TagTree,
1431    /// With `strict` off: the first layer of the precinct whose packet the
1432    /// `POC` volumes leave out. It stays missing however much data comes.
1433    gap: Option<u32>,
1434    /// With `strict` off: the first layer whose packet of the precinct was
1435    /// not read, or read only in part, because the data ended. More data
1436    /// may bring it.
1437    ended: Option<u32>,
1438}
1439
1440impl PrecinctState {
1441    /// The first layer of the precinct whose packet was not read whole,
1442    /// for either reason. Its code-blocks may then lack passes a later layer
1443    /// adds to their last segment.
1444    fn unread(&self) -> Option<u32> {
1445        match (self.gap, self.ended) {
1446            (Some(a), Some(b)) => Some(a.min(b)),
1447            (a, b) => a.or(b),
1448        }
1449    }
1450}
1451
1452impl BandState {
1453    /// The bytes the band's state holds on the heap.
1454    fn heap_bytes(&self) -> usize {
1455        use std::mem::size_of;
1456        let precincts = self.precincts.capacity() * size_of::<PrecinctState>()
1457            + self
1458                .precincts
1459                .iter()
1460                .map(|p| p.inclusion.heap_bytes() + p.zero_bits.heap_bytes())
1461                .sum::<usize>();
1462        let blocks = self.blocks.capacity() * size_of::<BlockState>()
1463            + self
1464                .blocks
1465                .iter()
1466                .map(|b| {
1467                    b.segments.capacity() * size_of::<SegmentState>()
1468                        + b.segments
1469                            .iter()
1470                            .map(|s| s.chunks.capacity() * size_of::<Range<usize>>())
1471                            .sum::<usize>()
1472                })
1473                .sum::<usize>();
1474        precincts + blocks
1475    }
1476
1477    /// Free each precinct's tag trees, once no packet is left to read
1478    /// them, and forget where the data ended.
1479    fn drop_trees(&mut self) {
1480        for precinct in &mut self.precincts {
1481            precinct.inclusion = TagTree::new(1, 1);
1482            precinct.zero_bits = TagTree::new(1, 1);
1483            precinct.ended = None;
1484        }
1485        self.precincts.shrink_to_fit();
1486    }
1487
1488    /// `coder` is the tile-component's coder, `None` under MIXED.
1489    fn new(band: &BandGeom, coder: Option<Coder>) -> Self {
1490        BandState {
1491            precincts: band
1492                .precincts
1493                .iter()
1494                .map(|precinct| PrecinctState {
1495                    inclusion: TagTree::new(precinct.cols as u32, precinct.rows as u32),
1496                    zero_bits: TagTree::new(precinct.cols as u32, precinct.rows as u32),
1497                    gap: None,
1498                    ended: None,
1499                })
1500                .collect(),
1501            blocks: (0..band.block_count())
1502                .map(|_| BlockState::new(coder))
1503                .collect(),
1504        }
1505    }
1506}
1507
1508/// The tag-tree nodes a packet's reads changed, as they were before, per
1509/// band of its resolution: the inclusion tree's and the zero bit-plane
1510/// tree's. With the block log (see [`Undo`]) and the stream positions, it
1511/// undoes a packet whole, so that a walk can stop inside a packet the data
1512/// cuts and read it again once more data comes.
1513#[derive(Debug, Default)]
1514pub(crate) struct Journal {
1515    trees: Vec<[Vec<Saved>; 2]>,
1516}
1517
1518impl Journal {
1519    /// The bytes the notes hold on the heap, capacity included.
1520    fn heap_bytes(&self) -> usize {
1521        use std::mem::size_of;
1522        self.trees.capacity() * size_of::<[Vec<Saved>; 2]>()
1523            + self
1524                .trees
1525                .iter()
1526                .flatten()
1527                .map(|notes| notes.capacity() * size_of::<Saved>())
1528                .sum::<usize>()
1529    }
1530
1531    /// Forget what the last packet noted.
1532    fn clear(&mut self) {
1533        for [inclusion, zero_bits] in &mut self.trees {
1534            inclusion.clear();
1535            zero_bits.clear();
1536        }
1537    }
1538
1539    /// The two trees' notes for band `band`.
1540    fn band(&mut self, band: usize) -> &mut [Vec<Saved>; 2] {
1541        if self.trees.len() <= band {
1542            self.trees.resize_with(band + 1, Default::default);
1543        }
1544        &mut self.trees[band]
1545    }
1546
1547    /// Put back the trees of `precinct` in `states` as they were before the
1548    /// packet that noted them.
1549    fn restore(&self, states: &mut [BandState], precinct: usize) {
1550        for (state, [inclusion, zero_bits]) in states.iter_mut().zip(&self.trees) {
1551            if let Some(trees) = state.precincts.get_mut(precinct) {
1552                trees.zero_bits.restore(zero_bits);
1553                trees.inclusion.restore(inclusion);
1554            }
1555        }
1556    }
1557}
1558
1559/// What one codeword segment takes from *this* packet: the length of the byte
1560/// range that follows the header, and where to file it.
1561struct Contribution {
1562    band: usize,
1563    block: usize,
1564    segment: usize,
1565    seg_len: usize,
1566}
1567
1568/// The buffers a packet read fills and empties again, kept across the
1569/// packets of a walk so that a packet allocates nothing of its own.
1570#[derive(Default)]
1571struct Scratch {
1572    /// The packet's contributions, in header order.
1573    contributions: Vec<Contribution>,
1574    /// The unread spans of one band's inclusion pass.
1575    unread: UnreadSpans,
1576}
1577
1578impl Scratch {
1579    /// The bytes the buffers hold on the heap, capacity included.
1580    fn heap_bytes(&self) -> usize {
1581        self.contributions.capacity() * std::mem::size_of::<Contribution>()
1582            + self.unread.heap_bytes()
1583    }
1584}
1585
1586/// How a packet read ended, when the walk is not strict.
1587#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1588enum Packet {
1589    /// The packet was read whole.
1590    Read,
1591    /// The data ended at or inside the packet. What it holds of whole
1592    /// code-blocks is kept; the rest of it is undone.
1593    Ended,
1594}
1595
1596/// A code-block's state before a packet added to it, so that the packet can
1597/// be undone (see [`undo`]).
1598struct Undo {
1599    band: usize,
1600    block: usize,
1601    coder: Option<Coder>,
1602    included: bool,
1603    lblock: u32,
1604    zero_bit_planes: u32,
1605    num_passes: u32,
1606    /// How many segments the block had, and the state of the last of them.
1607    segments: usize,
1608    last: Option<LastSegment>,
1609}
1610
1611/// The state of a block's last segment before a packet, which the packet may
1612/// add passes and bytes to, or, for an HT block's first cleanup segment, end.
1613struct LastSegment {
1614    kind: SegmentKind,
1615    passes: u32,
1616    kept: u32,
1617    max_passes: u32,
1618    length: u64,
1619    chunks: usize,
1620}
1621
1622impl LastSegment {
1623    fn of(segment: &SegmentState) -> Self {
1624        LastSegment {
1625            kind: segment.kind,
1626            passes: segment.passes,
1627            kept: segment.kept,
1628            max_passes: segment.max_passes,
1629            length: segment.length,
1630            chunks: segment.chunks.len(),
1631        }
1632    }
1633}
1634
1635/// Put back the state of every block in `log`, latest first, so that the
1636/// packet that logged them adds nothing to those blocks. Their earlier
1637/// layers stay.
1638fn undo(log: &[Undo], states: &mut [BandState]) {
1639    for entry in log.iter().rev() {
1640        let block = &mut states[entry.band].blocks[entry.block];
1641        block.coder = entry.coder;
1642        block.included = entry.included;
1643        block.lblock = entry.lblock;
1644        block.zero_bit_planes = entry.zero_bit_planes;
1645        block.num_passes = entry.num_passes;
1646        block.segments.truncate(entry.segments);
1647        if let (Some(last), Some(was)) = (block.segments.last_mut(), &entry.last) {
1648            last.kind = was.kind;
1649            last.passes = was.passes;
1650            last.kept = was.kept;
1651            last.max_passes = was.max_passes;
1652            last.length = was.length;
1653            last.chunks.truncate(was.chunks);
1654        }
1655    }
1656}
1657
1658/// Parse one packet — one precinct of one resolution of one component in one
1659/// layer — starting at byte `start` of the tile-part `data`.
1660///
1661/// Folds the packet's contributions into `states` and returns the byte offset
1662/// where the next packet begins. The subbands are built once every layer has
1663/// been read; see [`build_subbands`].
1664///
1665/// With `keep` false (a layer past the decode's cap, see [`Budget::layers`]),
1666/// the packet is read the same way and its header still moves each
1667/// code-block's state on, but its passes and bytes are not added.
1668///
1669/// With `log` given (a walk with `strict` off), running out of data is not a
1670/// fault. A packet that ends past the data adds the code-blocks whose data is
1671/// all there and undoes the rest, from the first code-block whose data runs
1672/// out on, back to their earlier layers; a packet whose inline header runs out
1673/// adds nothing. Either is [`Packet::Ended`]. Every other fault fails as it
1674/// does when strict, a packed header that runs out included, and a packet the
1675/// strict walk reads is read the same way.
1676#[allow(clippy::too_many_arguments)]
1677fn parse_packet(
1678    streams: &mut PacketStreams<'_>,
1679    meter: &Meter,
1680    layer: u32,
1681    packet_index: u32,
1682    delimiters: Delimiters,
1683    style: u8,
1684    bands: &[BandGeom],
1685    precinct: usize,
1686    states: &mut [BandState],
1687    scratch: &mut Scratch,
1688    keep: bool,
1689    mut log: Option<&mut Vec<Undo>>,
1690    mut journal: Option<&mut Journal>,
1691) -> Result<Packet> {
1692    meter.spend(1, WorkRefusal::PacketWalk)?;
1693    let partial = log.is_some();
1694    if partial
1695        && delimiters.sop
1696        && peek_marker(streams.data, streams.body_pos) == Some(marker::SOP)
1697        && streams.body_pos + 6 > streams.data.len()
1698    {
1699        return Ok(Packet::Ended);
1700    }
1701    // SOP precedes the packet in the *body* stream when COD allows it — but only
1702    // *may* (A.8.1), so its absence is not an error, and it stays inline even
1703    // when the headers are packed. OpenJPEG warns and carries on.
1704    //
1705    // The peek is unambiguous: a packet header can never begin `FF 91`. Its
1706    // first byte may well be `0xFF`, but the header's bit stuffing then forces
1707    // the next byte's most significant bit to zero, so that byte is at most
1708    // `0x7F` and never `0x91`. See [`bio`].
1709    if delimiters.sop && peek_marker(streams.data, streams.body_pos) == Some(marker::SOP) {
1710        streams.body_pos = read_sop(streams.data, streams.body_pos, packet_index)?;
1711    }
1712
1713    // Inline, the header starts where the body cursor now sits (past any SOP);
1714    // packed, it continues in the separate buffer.
1715    if !streams.packed {
1716        streams.header_pos = streams.body_pos;
1717    }
1718    // A packet header occupies at least one byte, so a cursor at or past the end
1719    // of the header stream means the codestream promised more packets than it
1720    // carries.
1721    if streams.header_pos >= streams.header.len() {
1722        if partial {
1723            return Ok(Packet::Ended);
1724        }
1725        return Err(Error::codestream(format!(
1726            "the data of tile {} ends before the last packet",
1727            streams.tile
1728        )));
1729    }
1730
1731    let mut bio = BitReader::new(&streams.header[streams.header_pos..]);
1732    if let Some(log) = log.as_deref_mut() {
1733        log.clear();
1734    }
1735
1736    // The first bit flags an empty packet (no contributions) against a present
1737    // one. An empty packet still costs its layer: the tag trees are untouched,
1738    // not reset.
1739    let present = bio.read_bit() == 1;
1740    let contributions = &mut scratch.contributions;
1741    contributions.clear();
1742    let mut fault = None;
1743    if present {
1744        for (band_index, (band, state)) in bands.iter().zip(states.iter_mut()).enumerate() {
1745            let parsed = parse_band_header(
1746                meter,
1747                band_index,
1748                &band.precincts[precinct],
1749                &mut state.precincts[precinct],
1750                &mut state.blocks,
1751                layer,
1752                style,
1753                keep,
1754                &mut bio,
1755                contributions,
1756                &mut scratch.unread,
1757                log.as_deref_mut(),
1758                journal.as_deref_mut().map(|j| j.band(band_index)),
1759            );
1760            if let Err(error) = parsed {
1761                fault = Some(error);
1762                break;
1763            }
1764        }
1765    }
1766    // A packed header that reads past its bytes is damaged, strict or not:
1767    // the bits it needs are not in the codestream. Its bytes sit in the main
1768    // or tile-part headers, which are there whole or not at all, so this is
1769    // never the data ending. It is checked before any fault, which the fill
1770    // bits may have caused, so the overrun is what is reported.
1771    if streams.packed && bio.overran() {
1772        return Err(packed_overrun());
1773    }
1774    if let Some(error) = fault {
1775        // Not strict, a fault in an inline header that runs past the data is
1776        // the data ending, not damage: the bits past the end are fill.
1777        return match log.as_deref() {
1778            Some(log) if bio.overran() => {
1779                undo(log, states);
1780                Ok(Packet::Ended)
1781            }
1782            _ => Err(error),
1783        };
1784    }
1785
1786    // The header is a whole number of bytes. EPH, when COD signals it, sits
1787    // between the header and the body — after an empty packet's header too — and
1788    // moves into the packed buffer with the headers, so it is read from the
1789    // header stream.
1790    //
1791    // Not strict, an inline header whose bits run past the data is the data
1792    // ending. That is taken before the alignment, which past a last byte of
1793    // 0xFF reads one more byte that a strict decode does not ask for. Packed
1794    // headers are not checked here: their bytes sit in the main or tile-part
1795    // headers, which are there whole or not at all, so one that runs short
1796    // was refused above, as damage, and one the alignment runs past is
1797    // refused below.
1798    let header_overran = bio.overran() && !streams.packed;
1799    bio.align();
1800    // A packed header whose last byte is 0xFF needs the stuffed byte after it
1801    // (B.10.1). Without one the header is damaged, as OpenJPEG's
1802    // `opj_bio_inalign` also finds.
1803    if streams.packed && bio.overran() {
1804        return Err(packed_overrun());
1805    }
1806    streams.header_pos += bio.bytes_consumed();
1807    if let Some(log) = log.as_deref() {
1808        let eph_cut = delimiters.eph && streams.header_pos + 2 > streams.header.len();
1809        if header_overran || eph_cut {
1810            undo(log, states);
1811            return Ok(Packet::Ended);
1812        }
1813    }
1814    if delimiters.eph {
1815        if peek_marker(streams.header, streams.header_pos) != Some(marker::EPH) {
1816            return Err(Error::codestream(
1817                "`COD` signals `EPH` but the packet header is not followed by one",
1818            ));
1819        }
1820        streams.header_pos += 2;
1821    }
1822
1823    // Inline, the body follows the header in the same buffer.
1824    if !streams.packed {
1825        streams.body_pos = streams.header_pos;
1826    }
1827    for contribution in contributions.iter() {
1828        let end = match streams
1829            .body_pos
1830            .checked_add(contribution.seg_len)
1831            .filter(|&e| e <= streams.data.len())
1832        {
1833            Some(end) => end,
1834            None => {
1835                if let Some(log) = log.as_deref() {
1836                    // Keep the blocks before this one; undo this one and every
1837                    // block after it in the header.
1838                    let from = log
1839                        .iter()
1840                        .position(|u| (u.band, u.block) == (contribution.band, contribution.block))
1841                        .unwrap_or(0);
1842                    undo(&log[from..], states);
1843                    return Ok(Packet::Ended);
1844                }
1845                return Err(Error::codestream(format!(
1846                    "a packet body segment overruns the data of tile {}",
1847                    streams.tile
1848                )));
1849            }
1850        };
1851        if keep {
1852            states[contribution.band].blocks[contribution.block].segments[contribution.segment]
1853                .chunks
1854                .push(streams.body_pos..end);
1855        }
1856        streams.body_pos = end;
1857    }
1858    // Inline, keep the two cursors together for the next packet.
1859    if !streams.packed {
1860        streams.header_pos = streams.body_pos;
1861    }
1862
1863    Ok(Packet::Read)
1864}
1865
1866/// Read one precinct's code-block entries, on one subband, from this layer's
1867/// packet header (ISO B.10): per block its inclusion, and for a contributing
1868/// block the zero-bitplane count (first inclusion only), coding-pass count, and
1869/// the length of its byte contribution.
1870///
1871/// The blocks are visited in raster order **within the precinct**, and the tag
1872/// trees are addressed in the precinct's own coordinates — the packet header
1873/// knows nothing of the band's wider grid, so a band-relative index here would
1874/// address the wrong leaf on every precinct but the first.
1875///
1876/// A block not yet included can sit under an inclusion-tree node already
1877/// known to lie past this layer. Its entry then reads no bit, nor does any
1878/// other entry under that node, so the walk steps over that node's blocks at
1879/// once (see [`TagTree::unread_span`]): along the row, or over all of its rows
1880/// when it spans the whole precinct width, and again on each row below that
1881/// it reaches (see [`UnreadSpans`]). Each such step spends a visit. Any
1882/// other entry reads at least one bit, so its work is paid for by the header's
1883/// bytes and is not counted.
1884///
1885/// With `keep` false the entries are read the same way, and the passes still
1886/// fill the segments so that the next layer's lengths are read at the right
1887/// width, but they are not counted as kept (see [`SegmentState::kept`]).
1888#[allow(clippy::too_many_arguments)]
1889fn parse_band_header(
1890    meter: &Meter,
1891    band_index: usize,
1892    precinct: &PrecinctGeom,
1893    trees: &mut PrecinctState,
1894    blocks: &mut [BlockState],
1895    layer: u32,
1896    style: u8,
1897    keep: bool,
1898    bio: &mut BitReader,
1899    contributions: &mut Vec<Contribution>,
1900    unread: &mut UnreadSpans,
1901    mut log: Option<&mut Vec<Undo>>,
1902    mut saved: Option<&mut [Vec<Saved>; 2]>,
1903) -> Result<()> {
1904    let cols = precinct.cols as u32;
1905    let threshold = layer + 1;
1906
1907    unread.clear();
1908    let mut entry = 0;
1909    while entry < precinct.cols * precinct.rows {
1910        let bx = entry as u32 % cols;
1911        let by = entry as u32 / cols;
1912        let block_index = precinct.block(bx as usize, by as usize);
1913        entry += 1;
1914
1915        let was_included = blocks[block_index].included;
1916        let span = if was_included {
1917            None
1918        } else {
1919            unread.find(&trees.inclusion, bx, by, threshold)
1920        };
1921        if let Some(span) = span {
1922            meter.spend(1, WorkRefusal::PacketWalk)?;
1923            entry = span.next_entry(by, cols);
1924            continue;
1925        }
1926        let contributes = if was_included {
1927            // Already included: one bit says whether this layer adds passes.
1928            bio.read_bit() == 1
1929        } else {
1930            // Not yet included: the inclusion tree resolves to the first layer
1931            // that carries this block. Reading at `layer + 1` asks "is that
1932            // layer at most this one?" and leaves the tree part-decoded when it
1933            // is not, so the next layer resumes where this one stopped.
1934            let saved = saved.as_deref_mut().map(|[inclusion, _]| inclusion);
1935            match trees.inclusion.read_saving(bx, by, threshold, bio, saved) {
1936                Some(_) => {
1937                    blocks[block_index].included = true;
1938                    true
1939                }
1940                None => false,
1941            }
1942        };
1943        if !contributes {
1944            continue;
1945        }
1946        if let Some(log) = log.as_deref_mut() {
1947            let block = &blocks[block_index];
1948            log.push(Undo {
1949                band: band_index,
1950                block: block_index,
1951                coder: block.coder,
1952                included: was_included,
1953                lblock: block.lblock,
1954                zero_bit_planes: block.zero_bit_planes,
1955                num_passes: block.num_passes,
1956                segments: block.segments.len(),
1957                last: block.segments.last().map(LastSegment::of),
1958            });
1959        }
1960
1961        // The zero-bitplane tree is resolved in full the first time a block is
1962        // included, so a single read at the ceiling settles it. Later layers
1963        // never read it again.
1964        if !was_included {
1965            let saved = saved.as_deref_mut().map(|[_, zero_bits]| zero_bits);
1966            blocks[block_index].zero_bit_planes = trees
1967                .zero_bits
1968                .read_saving(bx, by, ZBP_LIMIT, bio, saved)
1969                .ok_or_else(|| {
1970                    Error::codestream(format!(
1971                        "code-block zero-bitplane count is over {}, the most a valid stream \
1972                         can signal",
1973                        ZBP_LIMIT - 1
1974                    ))
1975                })?;
1976        }
1977
1978        // `read_num_passes` always returns >= 1, so the `ilog2` below never hits
1979        // the zero case.
1980        let num_passes = read_num_passes(bio);
1981
1982        // Lblock grows by a unary run of 1s and carries into later layers; the
1983        // length field is then `Lblock + floor(log2(num_passes))` bits wide
1984        // (ISO B.10.7.5), over *this* contribution's passes, not the running
1985        // total. OpenJPEG spells the same thing `numlenbits +
1986        // floorlog2(seg->numnewpasses)`.
1987        //
1988        // One length field, because one codeword segment. A contribution splits
1989        // into several segments only under a code-block style that terminates
1990        // (`termall`, `bypass`); there OpenJPEG's `do { ... } while (n > 0)`
1991        // reads a length per segment, which the loop below mirrors.
1992        let block = &mut blocks[block_index];
1993        while bio.read_bit() == 1 {
1994            block.lblock += 1;
1995            if block.lblock > LBLOCK_MAX {
1996                return Err(Error::codestream(format!(
1997                    "code-block `Lblock` grows past the limit of {LBLOCK_MAX}"
1998                )));
1999            }
2000        }
2001        // The passes are handed to codeword segments in turn, each with its own
2002        // length field. Without termination one segment swallows them all;
2003        // under `restart` each pass terminates, so each gets a segment and a
2004        // length of its own. OpenJPEG spells this `do { ... } while (n > 0)`.
2005        //
2006        // An HT block's segments follow ISO/IEC 15444-15 B.2 instead (see
2007        // [`next_segment`]), once its first cleanup segment has ended. Until
2008        // then a contribution may be placeholder passes only, or end that
2009        // segment at its cleanup pass, which [`ht_first_cleanup`] tells apart.
2010        let mut remaining = num_passes;
2011        let mut placeholders = 0;
2012        let open = SegmentKind::HtCleanup { placeholders: None };
2013        let first_open = block.segments.first().is_none_or(|s| s.kind == open);
2014        let prior = block.segments.first().map_or(0, |s| s.passes);
2015        // A Part 1 block's length field, when reading it settled the coder
2016        // of a MIXED block.
2017        let mut part1_length = None;
2018        let first = match block.coder {
2019            Some(Coder::Ht) if first_open => {
2020                Some(ht_first_cleanup(block.lblock, prior, num_passes, bio)?)
2021            }
2022            Some(_) => None,
2023            None => match mixed_first_length(block.lblock, prior, num_passes, bio)? {
2024                MixedFirst::Empty => Some(FirstCleanup::Placeholders),
2025                MixedFirst::Ht(first) => {
2026                    block.coder = Some(Coder::Ht);
2027                    Some(first)
2028                }
2029                MixedFirst::Part1 { length } => {
2030                    become_part1(block);
2031                    part1_length = Some(length);
2032                    None
2033                }
2034            },
2035        };
2036        if let Some(first) = first {
2037            if block.segments.is_empty() {
2038                block.segments.push(SegmentState::new(open, u32::MAX));
2039            }
2040            let segment = &mut block.segments[0];
2041            let passes = match first {
2042                FirstCleanup::Placeholders => {
2043                    placeholders = num_passes;
2044                    num_passes
2045                }
2046                FirstCleanup::Cleanup {
2047                    placeholders: before,
2048                    passes,
2049                    length,
2050                } => {
2051                    placeholders = before - prior;
2052                    segment.kind = SegmentKind::HtCleanup {
2053                        placeholders: Some(before),
2054                    };
2055                    segment.max_passes = before + 1;
2056                    add_length(segment, length)?;
2057                    contributions.push(Contribution {
2058                        band: band_index,
2059                        block: block_index,
2060                        segment: 0,
2061                        seg_len: length as usize,
2062                    });
2063                    passes
2064                }
2065            };
2066            segment.passes += passes;
2067            if keep {
2068                segment.kept += passes;
2069            }
2070            remaining -= passes;
2071        }
2072        if keep {
2073            block.num_passes += num_passes - placeholders;
2074        }
2075        while remaining > 0 {
2076            if block
2077                .segments
2078                .last()
2079                .is_none_or(|s| s.passes >= s.max_passes)
2080            {
2081                let coder = block.coder.unwrap_or(Coder::Ht);
2082                let (kind, max_passes) = next_segment(coder, style, block.segments.last());
2083                block.segments.push(SegmentState::new(kind, max_passes));
2084            }
2085            let segment_index = block.segments.len() - 1;
2086            let segment = &mut block.segments[segment_index];
2087            let new_passes = remaining.min(segment.max_passes - segment.passes);
2088
2089            // The length field's width uses *this* segment's new passes.
2090            let seg_len = match part1_length.take() {
2091                Some(length) => length,
2092                None => bio.read(length_bits(block.lblock, new_passes)),
2093            };
2094            add_length(segment, seg_len)?;
2095            let seg_len = seg_len as usize;
2096
2097            // A layer may add coding passes and no bytes (B.10.7 sets no
2098            // lower bound on the length). The MQ codeword is continuous
2099            // within a segment, so the encoder's rate split can put passes in
2100            // one layer and the bytes carrying them in the next. A segment
2101            // that never gets a byte is decoded from the `0xFF` fill (D.4.1),
2102            // as OpenJPEG decodes it. The passes still count and still fill
2103            // the segment, so a later layer's passes land in the right one.
2104            // A zero length files no chunk, and reading it took at least the
2105            // header bits above, so it costs no more than one with bytes.
2106            let segment = &mut block.segments[segment_index];
2107            segment.passes += new_passes;
2108            if keep {
2109                segment.kept += new_passes;
2110            }
2111            if seg_len > 0 {
2112                contributions.push(Contribution {
2113                    band: band_index,
2114                    block: block_index,
2115                    segment: segment_index,
2116                    seg_len,
2117                });
2118            }
2119
2120            remaining -= new_passes;
2121        }
2122    }
2123    Ok(())
2124}
2125
2126/// Note that the packet of `precinct` in `layer` was not read whole because
2127/// the data ended (see [`PrecinctState::ended`]). A packet spans every band
2128/// of the resolution.
2129fn mark_unread(bands: &mut [BandState], precinct: usize, layer: u32) {
2130    for band in bands {
2131        if let Some(state) = band.precincts.get_mut(precinct) {
2132            state.ended = Some(state.ended.map_or(layer, |from| from.min(layer)));
2133        }
2134    }
2135}
2136
2137/// Note that the `POC` volumes leave out the packets of every precinct of
2138/// a resolution from `layer` on (see [`PrecinctState::gap`]).
2139fn mark_gap(bands: &mut [BandState], layer: u32) {
2140    for band in bands {
2141        for state in &mut band.precincts {
2142            state.gap = Some(state.gap.map_or(layer, |from| from.min(layer)));
2143        }
2144    }
2145}
2146
2147/// Turn the accumulated per-layer state of one resolution into its subbands.
2148///
2149/// A block may end up with coding passes and no bytes, in one codeword segment
2150/// or in all of them, since B.10.7 lets a contribution's length be zero. Tier-1
2151/// decodes such a segment from the `0xFF` bytes D.4.1 appends, as OpenJPEG
2152/// does.
2153///
2154/// `data` is the tile data the segments' chunks are offsets into. The state
2155/// is left as it was, so a walk can go on from it.
2156fn build_subbands<'a>(
2157    bands: &[BandGeom],
2158    states: &[BandState],
2159    data: &'a [u8],
2160) -> Vec<Subband<'a>> {
2161    bands
2162        .iter()
2163        .zip(states)
2164        .map(|(band, state)| {
2165            // The rectangles come from a nested loop, which gives no exact
2166            // length, so the vector is sized up front rather than grown.
2167            debug_assert_eq!(
2168                state.blocks.len(),
2169                band.block_count(),
2170                "one block state per code-block of the band"
2171            );
2172            // The code-blocks of the precincts the data ended in or before.
2173            // A precinct owns a rectangle of the band's blocks, and each
2174            // block lies in one precinct, so this visits each block at most
2175            // once. A walk that read every packet allocates nothing here.
2176            let mut unread = Vec::new();
2177            for (geom, precinct) in band.precincts.iter().zip(&state.precincts) {
2178                if let Some(from) = precinct.unread() {
2179                    unread.resize(state.blocks.len(), None);
2180                    for by in 0..geom.rows {
2181                        for bx in 0..geom.cols {
2182                            if let Some(flag) = unread.get_mut(geom.block(bx, by)) {
2183                                *flag = Some(from);
2184                            }
2185                        }
2186                    }
2187                }
2188            }
2189            let mut blocks = Vec::with_capacity(state.blocks.len());
2190            blocks.extend(band.block_rects().zip(&state.blocks).enumerate().map(
2191                |(index, ((x, y, width, height), block))| {
2192                    let missing_from = unread.get(index).copied().flatten();
2193                    let unread = missing_from.is_some();
2194                    // Under a layer cap, the segments the kept layers never
2195                    // reached are left out, and the last one kept may hold
2196                    // only some of its passes. Without a cap every pass is
2197                    // kept. The filter is what keeps a cut segment last:
2198                    // Tier-1 exempts only the last segment from `predictable
2199                    // termination`, so an empty segment left after the cut
2200                    // one would have it checked and refused.
2201                    //
2202                    // An HT block's placeholder passes code nothing, so they
2203                    // count as neither passes nor a segment (see
2204                    // [`SegmentState::coded_kept`]); they skip bit-planes
2205                    // instead.
2206                    //
2207                    // With `strict` off, a block whose precinct the data
2208                    // ended in may have lost later passes of its last
2209                    // segment, unless that segment holds all the passes it
2210                    // can: then the next pass opens a new segment, and this
2211                    // one is whole.
2212                    let mut cut = false;
2213                    let coder = block.coder.unwrap_or(Coder::Ht);
2214                    let zero_bit_planes = block.zero_bit_planes + block.skipped_planes();
2215                    let placeholders = block
2216                        .segments
2217                        .first()
2218                        .map_or(0, SegmentState::kept_placeholders);
2219                    let segments = block
2220                        .segments
2221                        .iter()
2222                        .take_while(|s| s.coded_kept() > 0)
2223                        .map(|s| {
2224                            cut = s.kept < s.passes || (unread && s.passes < s.max_passes);
2225                            CodedSegment {
2226                                passes: s.coded_kept(),
2227                                chunks: s.chunks.iter().map(|r| &data[r.clone()]).collect(),
2228                            }
2229                        })
2230                        .collect();
2231                    CodeBlock {
2232                        x,
2233                        y,
2234                        width,
2235                        height,
2236                        num_passes: block.num_passes,
2237                        zero_bit_planes,
2238                        segments,
2239                        cut,
2240                        placeholders,
2241                        coder,
2242                        missing_from,
2243                    }
2244                },
2245            ));
2246            Subband {
2247                kind: band.kind,
2248                origin: band.origin,
2249                width: band.width,
2250                height: band.height,
2251                block_cols: band.block_cols,
2252                block_rows: band.block_rows,
2253                blocks,
2254            }
2255        })
2256        .collect()
2257}
2258
2259/// Decode the number of coding passes (ISO Table B.4 / OpenJPEG
2260/// `opj_t2_getnumpasses`): a prefix code spanning 1 to 164 passes.
2261fn read_num_passes(bio: &mut BitReader) -> u32 {
2262    if bio.read_bit() == 0 {
2263        return 1;
2264    }
2265    if bio.read_bit() == 0 {
2266        return 2;
2267    }
2268    let n = bio.read(2);
2269    if n != 3 {
2270        return 3 + n;
2271    }
2272    let n = bio.read(5);
2273    if n != 31 {
2274        return 6 + n;
2275    }
2276    37 + bio.read(7)
2277}
2278
2279#[cfg(test)]
2280mod partial_tests;
2281#[cfg(test)]
2282mod tests;
2283#[cfg(test)]
2284mod work_bound_tests;