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//! The Phase 1 subset is one tile, one component, one quality layer, LRCP, and
12//! maximal precincts (one precinct per resolution). That collapses the packet
13//! stream to exactly one packet per resolution level, coarsest first, so the
14//! whole tile-part is `header₀ body₀ header₁ body₁ …` with no precinct or layer
15//! nesting. `decode_packets` also computes the resolution / subband /
16//! code-block geometry from the [`MainHeader`](crate::codestream::MainHeader),
17//! so it is the single source of truth the assembly stage reuses.
18
19pub mod bio;
20pub mod tagtree;
21
22use crate::codestream::{Codestream, MainHeader};
23use crate::{Error, Result};
24use bio::BitReader;
25use tagtree::TagTree;
26
27/// The four subband orientations. Kept Tier-2-local so this stage stays
28/// independent of Tier-1; the assembly stage maps it to the Tier-1
29/// `Orientation` that selects the zero-coding context table.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum BandKind {
32    /// Low-pass both axes (the coarsest resolution only).
33    Ll,
34    /// High-pass horizontally, low-pass vertically.
35    Hl,
36    /// Low-pass horizontally, high-pass vertically.
37    Lh,
38    /// High-pass both axes.
39    Hh,
40}
41
42/// One code-block's coded contribution within its subband. `num_passes` is the
43/// coding-pass count from the packet header (0 if the block is never included
44/// in the single layer) and `zero_bit_planes` the all-zero most-significant
45/// bit-plane count from the zero-bitplane tag tree. `segment` is the raw
46/// MQ-coded byte slice Tier-1 decodes (empty when the block is not included).
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct CodeBlock<'a> {
49    /// Top-left of the block within its subband, in band-relative samples.
50    pub x: usize,
51    pub y: usize,
52    pub width: usize,
53    pub height: usize,
54    pub num_passes: u32,
55    pub zero_bit_planes: u32,
56    pub segment: &'a [u8],
57}
58
59/// One subband: its orientation, tile-component origin, sample geometry, and the
60/// code-block grid carrying the coded segments. Blocks are row-major, so block
61/// `(i, j)` is `blocks[j * block_cols + i]`.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Subband<'a> {
64    pub kind: BandKind,
65    /// Tile-component coordinate of the band's top-left sample.
66    pub origin: (u32, u32),
67    pub width: usize,
68    pub height: usize,
69    pub block_cols: usize,
70    pub block_rows: usize,
71    pub blocks: Vec<CodeBlock<'a>>,
72}
73
74/// One resolution level's subbands, in packet order: `[Ll]` at the coarsest
75/// level, `[Hl, Lh, Hh]` at every finer level.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct Resolution<'a> {
78    pub subbands: Vec<Subband<'a>>,
79}
80
81/// The coded byte segments for every code-block in every subband, grouped by
82/// resolution (coarsest first, index 0 the `NLLL` band) so Tier-1 can decode
83/// each block independently and the assembly stage can place it back.
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct CodedData<'a> {
86    pub resolutions: Vec<Resolution<'a>>,
87}
88
89/// Parse all packets in the codestream's single tile-part into per-code-block
90/// coded segments, following the LRCP order over the one tile / component /
91/// layer with maximal precincts: one packet per resolution, coarsest first.
92pub fn decode_packets<'a>(cs: &Codestream<'a>) -> Result<CodedData<'a>> {
93    let tile = cs
94        .tile_parts
95        .first()
96        .ok_or_else(|| Error::Codestream("codestream carries no tile-part".into()))?;
97    let data = tile.data;
98
99    let geoms = resolution_geoms(&cs.header)?;
100    let mut cursor = 0usize;
101    let mut resolutions = Vec::with_capacity(geoms.len());
102    for bands in &geoms {
103        let (subbands, next) = parse_packet(data, cursor, bands)?;
104        cursor = next;
105        resolutions.push(Resolution { subbands });
106    }
107
108    // Single-layer LRCP with maximal precincts packs the tile-part with no
109    // padding: the packets must tile it exactly up to the closing EOC. Any
110    // remainder means a misread field (this doubles as the parse self-check).
111    if cursor != data.len() {
112        return Err(Error::Codestream(format!(
113            "tile-part has {} byte(s) left after the last packet",
114            data.len() - cursor
115        )));
116    }
117
118    Ok(CodedData { resolutions })
119}
120
121/// Geometry of one subband before its segments are parsed: orientation, origin,
122/// sample dimensions, and the code-block grid (each block's band-relative
123/// position and size).
124struct BandGeom {
125    kind: BandKind,
126    origin: (u32, u32),
127    width: usize,
128    height: usize,
129    block_cols: usize,
130    block_rows: usize,
131    /// `(x, y, width, height)` per block, row-major.
132    blocks: Vec<(usize, usize, usize, usize)>,
133}
134
135/// `ceil(a / b)` for any integers with `b > 0` (Rust's `/` truncates toward
136/// zero, so the subband formula's negative numerators need this floor-based
137/// form).
138fn ceil_div(a: i64, b: i64) -> i64 {
139    debug_assert!(b > 0, "ceil_div needs a positive divisor");
140    let q = a.div_euclid(b);
141    if a.rem_euclid(b) != 0 { q + 1 } else { q }
142}
143
144/// Compute the resolution → subband → code-block geometry for the single
145/// tile-component, coarsest resolution first (ISO B.5–B.7, Eq. B-15). Maximal
146/// precincts mean one precinct per resolution, so the code-block grid tiles each
147/// whole subband.
148fn resolution_geoms(header: &MainHeader) -> Result<Vec<Vec<BandGeom>>> {
149    let siz = &header.siz;
150    let cod = &header.cod;
151
152    let nl = cod.decomposition_levels as i64;
153    if nl > 32 {
154        return Err(Error::Unsupported(format!(
155            "{nl} decomposition levels exceeds the 32-level maximum"
156        )));
157    }
158
159    // Tile-component bounds: the single tile clipped to the image, divided by
160    // the component sub-sampling (Annex B.3, Eq. B-7/B-12). The Phase 1 subset
161    // uses zero offsets and unit sub-sampling, but the general form costs
162    // nothing — provided the tile origin is clamped up to the image offset.
163    let comp = siz
164        .components
165        .first()
166        .ok_or_else(|| Error::Codestream("SIZ declares no components".into()))?;
167    let xr = (comp.x_sampling.max(1)) as i64;
168    let yr = (comp.y_sampling.max(1)) as i64;
169    let tx0 = (siz.tile_x_offset as i64).max(siz.x_offset as i64);
170    let ty0 = (siz.tile_y_offset as i64).max(siz.y_offset as i64);
171    let tx1 = (siz.tile_x_offset as i64 + siz.tile_width as i64).min(siz.x_size as i64);
172    let ty1 = (siz.tile_y_offset as i64 + siz.tile_height as i64).min(siz.y_size as i64);
173    if tx1 <= tx0 || ty1 <= ty0 {
174        return Err(Error::Codestream("tile has empty area".into()));
175    }
176    let (tcx0, tcx1) = (ceil_div(tx0, xr), ceil_div(tx1, xr));
177    let (tcy0, tcy1) = (ceil_div(ty0, yr), ceil_div(ty1, yr));
178
179    // Code-block exponents (COD stores `log2(size) - 2`). The standard bounds
180    // each at 2^10 and their sum at 2^12 (ISO Table A-18); reject anything
181    // larger so the grid shifts below stay well-defined and a malformed COD is
182    // a typed error, not a silently clamped mis-decode.
183    let xcb = cod.code_block_width as u32 + 2;
184    let ycb = cod.code_block_height as u32 + 2;
185    if xcb > 10 || ycb > 10 || xcb + ycb > 12 {
186        return Err(Error::Marker(format!(
187            "code-block size 2^{xcb}×2^{ycb} exceeds the 2^10 / xcb+ycb≤12 limit"
188        )));
189    }
190
191    // With maximal precincts (PPx = PPy = 15), the precinct never shrinks the
192    // block at level 0 and caps it one below the precinct at finer levels
193    // (ISO B.6); for the subset's 2^6 blocks neither cap bites.
194
195    let mut levels = Vec::with_capacity((nl + 1) as usize);
196    for r in 0..=nl {
197        let bands = if r == 0 {
198            // The coarsest resolution carries only the NLLL band.
199            let pow = 1i64 << nl;
200            vec![band_geom(
201                BandKind::Ll,
202                ceil_div(tcx0, pow),
203                ceil_div(tcx1, pow),
204                ceil_div(tcy0, pow),
205                ceil_div(tcy1, pow),
206                xcb.min(15),
207                ycb.min(15),
208            )]
209        } else {
210            // Finer levels add HL, LH, HH at decomposition level `nb = NL-r+1`.
211            let nb = nl - r + 1;
212            let pow = 1i64 << nb;
213            let half = 1i64 << (nb - 1);
214            [
215                (BandKind::Hl, 1, 0),
216                (BandKind::Lh, 0, 1),
217                (BandKind::Hh, 1, 1),
218            ]
219            .into_iter()
220            .map(|(kind, xob, yob)| {
221                band_geom(
222                    kind,
223                    ceil_div(tcx0 - xob * half, pow),
224                    ceil_div(tcx1 - xob * half, pow),
225                    ceil_div(tcy0 - yob * half, pow),
226                    ceil_div(tcy1 - yob * half, pow),
227                    xcb.min(14),
228                    ycb.min(14),
229                )
230            })
231            .collect()
232        };
233        levels.push(bands);
234    }
235    Ok(levels)
236}
237
238/// Build one subband's geometry from its sample bounds `[bx0, bx1) × [by0, by1)`
239/// and the effective code-block exponents, tiling it with the code-block grid
240/// anchored at the canvas origin (ISO B.7).
241fn band_geom(
242    kind: BandKind,
243    bx0: i64,
244    bx1: i64,
245    by0: i64,
246    by1: i64,
247    xcb: u32,
248    ycb: u32,
249) -> BandGeom {
250    let width = (bx1 - bx0).max(0) as usize;
251    let height = (by1 - by0).max(0) as usize;
252    let cbw = 1i64 << xcb;
253    let cbh = 1i64 << ycb;
254
255    let (block_cols, first_col) = grid_span(bx0, bx1, cbw);
256    let (block_rows, first_row) = grid_span(by0, by1, cbh);
257
258    let mut blocks = Vec::with_capacity(block_cols * block_rows);
259    for j in 0..block_rows {
260        let gy0 = (first_row + j as i64) * cbh;
261        let cy0 = gy0.max(by0);
262        let cy1 = (gy0 + cbh).min(by1);
263        for i in 0..block_cols {
264            let gx0 = (first_col + i as i64) * cbw;
265            let cx0 = gx0.max(bx0);
266            let cx1 = (gx0 + cbw).min(bx1);
267            blocks.push((
268                (cx0 - bx0) as usize,
269                (cy0 - by0) as usize,
270                (cx1 - cx0) as usize,
271                (cy1 - cy0) as usize,
272            ));
273        }
274    }
275
276    BandGeom {
277        kind,
278        origin: (bx0.max(0) as u32, by0.max(0) as u32),
279        width,
280        height,
281        block_cols,
282        block_rows,
283        blocks,
284    }
285}
286
287/// Number of code-block grid cells spanning `[lo, hi)` and the index of the
288/// first cell, with the grid anchored at multiples of `cell` from the origin.
289fn grid_span(lo: i64, hi: i64, cell: i64) -> (usize, i64) {
290    if hi <= lo {
291        return (0, 0);
292    }
293    let first = lo.div_euclid(cell);
294    let last = ceil_div(hi, cell);
295    ((last - first) as usize, first)
296}
297
298/// Ceiling on the zero-bitplane count: a single read above this resolves any
299/// real value (the count is bounded by the magnitude bit-planes — at most the
300/// sample depth plus guard bits, well under 64 for the ≤32-bit subset), while
301/// rejecting a malformed run of zero bits rather than looping on it.
302const ZBP_LIMIT: u32 = 64;
303
304/// Upper bound on the Lblock length-indicator before a malformed packet is
305/// rejected. The length field is `Lblock + floor(log2(num_passes))` bits and
306/// `num_passes ≤ 164` (so `floor(log2) ≤ 7`); capping Lblock at 24 keeps that
307/// read at most 31 bits, inside the `u32` [`BitReader::read`] accepts.
308const LBLOCK_MAX: u32 = 24;
309
310/// Per-block metadata read from a packet header, before body bytes are sliced.
311struct BlockMeta {
312    num_passes: u32,
313    zero_bit_planes: u32,
314    seg_len: usize,
315}
316
317/// Parse one packet (the single precinct of one resolution) starting at byte
318/// `start` of the tile-part `data`. Returns the resolution's subbands with their
319/// segments and the byte offset where the next packet begins.
320fn parse_packet<'a>(
321    data: &'a [u8],
322    start: usize,
323    bands: &[BandGeom],
324) -> Result<(Vec<Subband<'a>>, usize)> {
325    let mut bio = BitReader::new(&data[start..]);
326
327    // The first bit flags an empty packet (no contributions) vs. a present one.
328    let present = bio.read_bit() == 1;
329    let mut metas: Vec<Vec<BlockMeta>> = Vec::with_capacity(bands.len());
330    for band in bands {
331        if !present {
332            metas.push(band.blocks.iter().map(|_| BlockMeta::absent()).collect());
333            continue;
334        }
335        metas.push(parse_band_header(band, &mut bio)?);
336    }
337
338    // The header is a whole number of bytes; the body follows immediately.
339    bio.align();
340    let mut body = start + bio.bytes_consumed();
341
342    let mut subbands = Vec::with_capacity(bands.len());
343    for (band, band_meta) in bands.iter().zip(&metas) {
344        let mut blocks = Vec::with_capacity(band.blocks.len());
345        for (&(x, y, width, height), meta) in band.blocks.iter().zip(band_meta) {
346            // An included block (passes > 0) must carry coded bytes; a zero
347            // length there is malformed and would hand Tier-1 an empty MQ
348            // stream, so reject it here where the context is known.
349            if meta.num_passes > 0 && meta.seg_len == 0 {
350                return Err(Error::Codestream(
351                    "included code-block has coding passes but zero length".into(),
352                ));
353            }
354            let segment = if meta.seg_len == 0 {
355                &[][..]
356            } else {
357                let end = body
358                    .checked_add(meta.seg_len)
359                    .filter(|&e| e <= data.len())
360                    .ok_or_else(|| {
361                        Error::Codestream("packet body segment overruns the tile-part".into())
362                    })?;
363                let slice = &data[body..end];
364                body = end;
365                slice
366            };
367            blocks.push(CodeBlock {
368                x,
369                y,
370                width,
371                height,
372                num_passes: meta.num_passes,
373                zero_bit_planes: meta.zero_bit_planes,
374                segment,
375            });
376        }
377        subbands.push(Subband {
378            kind: band.kind,
379            origin: band.origin,
380            width: band.width,
381            height: band.height,
382            block_cols: band.block_cols,
383            block_rows: band.block_rows,
384            blocks,
385        });
386    }
387
388    Ok((subbands, body))
389}
390
391impl BlockMeta {
392    /// A block that contributes nothing to this packet.
393    fn absent() -> Self {
394        BlockMeta {
395            num_passes: 0,
396            zero_bit_planes: 0,
397            seg_len: 0,
398        }
399    }
400}
401
402/// Read one subband's code-block entries from the packet header: per block, its
403/// inclusion (inclusion tag tree at layer 0), and for an included block the
404/// zero-bitplane count, coding-pass count, and contribution length.
405fn parse_band_header(band: &BandGeom, bio: &mut BitReader) -> Result<Vec<BlockMeta>> {
406    let cols = band.block_cols as u32;
407    let rows = band.block_rows as u32;
408    let mut inclusion = TagTree::new(cols, rows);
409    let mut zero_bits = TagTree::new(cols, rows);
410
411    let mut metas = Vec::with_capacity(band.blocks.len());
412    for idx in 0..band.blocks.len() {
413        let bx = idx as u32 % cols;
414        let by = idx as u32 / cols;
415
416        // Single layer: a block is included now iff its inclusion value is 0
417        // (it never appears in a later layer), so read at threshold 1.
418        if inclusion.read(bx, by, 1, bio).is_none() {
419            metas.push(BlockMeta::absent());
420            continue;
421        }
422
423        // Zero bit-planes: unlike inclusion (read once per layer at a rising
424        // threshold), the zero-bitplane tree is resolved in full the first time
425        // a block is included, so a single read at the ceiling resolves it.
426        let zero_bit_planes = zero_bits
427            .read(bx, by, ZBP_LIMIT, bio)
428            .ok_or_else(|| Error::Codestream("zero-bitplane count exceeds the limit".into()))?;
429
430        // `read_num_passes` always returns ≥ 1, so the `ilog2` below never hits
431        // the zero case.
432        let num_passes = read_num_passes(bio);
433
434        // Lblock grows by a unary run of 1s; the length field is then
435        // `Lblock + floor(log2(num_passes))` bits wide (ISO B.10.7.5).
436        let mut lblock = 3u32;
437        while bio.read_bit() == 1 {
438            lblock += 1;
439            if lblock > LBLOCK_MAX {
440                return Err(Error::Codestream("Lblock indicator runs too long".into()));
441            }
442        }
443        let length_bits = lblock + num_passes.ilog2();
444        let seg_len = bio.read(length_bits) as usize;
445
446        metas.push(BlockMeta {
447            num_passes,
448            zero_bit_planes,
449            seg_len,
450        });
451    }
452    Ok(metas)
453}
454
455/// Decode the number of coding passes (ISO Table B.4 / OpenJPEG
456/// `opj_t2_getnumpasses`): a prefix code spanning 1 to 164 passes.
457fn read_num_passes(bio: &mut BitReader) -> u32 {
458    if bio.read_bit() == 0 {
459        return 1;
460    }
461    if bio.read_bit() == 0 {
462        return 2;
463    }
464    let n = bio.read(2);
465    if n != 3 {
466        return 3 + n;
467    }
468    let n = bio.read(5);
469    if n != 31 {
470        return 6 + n;
471    }
472    37 + bio.read(7)
473}
474
475#[cfg(test)]
476mod tests;