Skip to main content

rust_j2k/codestream/
mod.rs

1//! Stage 1 — codestream parsing (ISO/IEC 15444-1 Annex A).
2//!
3//! Walks the marker segments of a raw J2K codestream: the main header
4//! (SIZ / COD / QCD, plus optional COC / QCC / RGN / POC / COM), then the
5//! tile-parts (SOT … SOD … data). Produces a [`MainHeader`] of decode
6//! parameters and the byte ranges of each tile's packet data — everything the
7//! later stages need, with no interpretation of the entropy-coded bytes yet.
8
9pub mod markers;
10
11use crate::{Error, Result};
12use markers::{Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform, marker};
13
14/// Parsed main-header decode parameters. COC/QCC/RGN component overrides will
15/// live here too once needed; for the single-component subset the defaults
16/// usually suffice.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MainHeader {
19    pub siz: Siz,
20    pub cod: Cod,
21    pub qcd: Qcd,
22}
23
24/// One tile-part: its tile index and the slice of packet data between SOD and
25/// the next marker. Multiple tile-parts can carry one tile; the GRIB2 common
26/// case is a single tile in a single part.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TilePart<'a> {
29    pub tile_index: u16,
30    pub data: &'a [u8],
31}
32
33/// A parsed codestream: main header plus the tile-part data ranges.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Codestream<'a> {
36    pub header: MainHeader,
37    pub tile_parts: Vec<TilePart<'a>>,
38}
39
40/// Parse a raw codestream (must start with SOC, end with EOC).
41///
42/// Rejects the JP2 box wrapper (callers pass the bare codestream) and anything
43/// outside the single-component subset with [`Error::Unsupported`].
44///
45/// [`Error::Unsupported`]: crate::Error::Unsupported
46pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
47    let (header, sot_offset) = parse_main_header(bytes)?;
48    let tile_parts = walk_tile_parts(bytes, sot_offset)?;
49    Ok(Codestream { header, tile_parts })
50}
51
52/// Walk the tile-parts from the first `SOT` to the closing `EOC` (A.4.2, A.4.4).
53///
54/// The GRIB2 subset is exactly one tile carried in one tile-part, so this reads
55/// a single `SOT … SOD … packet-data` run and requires `EOC` to follow it.
56/// Multiple tiles or tile-parts reject with [`Error::Unsupported`]; a `Psot`
57/// overrun, a truncated `SOT`, or a missing `EOC` reject with
58/// [`Error::Codestream`].
59fn walk_tile_parts(bytes: &[u8], sot_offset: usize) -> Result<Vec<TilePart<'_>>> {
60    let mut cur = Cursor::at(bytes, sot_offset);
61
62    // `parse_main_header` stopped on this SOT, so it is present; re-read it here
63    // so this function owns the whole tile-part structure.
64    if cur.u16()? != marker::SOT {
65        return Err(Error::Codestream(
66            "tile-part does not start with SOT".into(),
67        ));
68    }
69    let sot = decode_sot(segment(&mut cur)?)?;
70
71    // Single tile, single tile-part. Isot is the tile index, TPsot the part
72    // index within the tile, TNsot the part count (0 = "not stated").
73    if sot.tile_index != 0 {
74        return Err(Error::Unsupported(format!(
75            "tile index {}; the subset is a single tile",
76            sot.tile_index
77        )));
78    }
79    if sot.tile_part_index != 0 || sot.num_tile_parts > 1 {
80        return Err(Error::Unsupported(
81            "multiple tile-parts; the subset is a single tile-part".into(),
82        ));
83    }
84
85    // Tile-part header: only SOD (and a skippable COM) belong here in the
86    // subset; tile-level coding/quant overrides are a later phase.
87    loop {
88        let m = cur.u16()?;
89        match m {
90            marker::SOD => break,
91            marker::COM => {
92                segment(&mut cur)?;
93            }
94            marker::COD
95            | marker::COC
96            | marker::QCD
97            | marker::QCC
98            | marker::RGN
99            | marker::POC
100            | marker::TLM
101            | marker::PLT
102            | marker::SOP
103            | marker::EPH => {
104                return Err(Error::Unsupported(format!(
105                    "tile-part header marker {m:#06X} is outside the Phase 1 subset"
106                )));
107            }
108            other => {
109                return Err(Error::Codestream(format!(
110                    "unexpected marker {other:#06X} in tile-part header"
111                )));
112            }
113        }
114    }
115    let data_start = cur.pos;
116
117    // Psot counts from the SOT marker's first byte to the end of the tile-part.
118    // Psot == 0 marks the last tile-part: it runs to the closing EOC (A.4.2).
119    let data_end = if sot.psot == 0 {
120        bytes
121            .len()
122            .checked_sub(2)
123            .filter(|&end| end >= data_start && read_u16(bytes, end) == Some(marker::EOC))
124            .ok_or_else(|| Error::Codestream("Psot=0 tile-part is not terminated by EOC".into()))?
125    } else {
126        let end = sot_offset
127            .checked_add(sot.psot as usize)
128            .filter(|&end| end <= bytes.len())
129            .ok_or_else(|| Error::Codestream("Psot overruns the codestream".into()))?;
130        if end < data_start {
131            return Err(Error::Codestream(
132                "Psot is shorter than the tile-part header".into(),
133            ));
134        }
135        end
136    };
137
138    let data = &bytes[data_start..data_end];
139
140    // A single tile-part must be followed by EOC. A second SOT means more than
141    // one tile-part, which the subset does not decode.
142    match read_u16(bytes, data_end) {
143        Some(marker::EOC) => {}
144        Some(marker::SOT) => {
145            return Err(Error::Unsupported(
146                "multiple tile-parts; the subset is a single tile-part".into(),
147            ));
148        }
149        Some(other) => {
150            return Err(Error::Codestream(format!(
151                "expected EOC after the tile-part, found {other:#06X}"
152            )));
153        }
154        None => return Err(Error::Codestream("missing EOC after the tile-part".into())),
155    }
156
157    Ok(vec![TilePart {
158        tile_index: sot.tile_index,
159        data,
160    }])
161}
162
163/// SOT fields (A.4.2): the tile index, tile-part length, part index, and part
164/// count. The packet-data extent is derived from `psot` by the caller.
165struct Sot {
166    tile_index: u16,
167    psot: u32,
168    tile_part_index: u8,
169    num_tile_parts: u8,
170}
171
172/// Decode the SOT marker segment body (everything after `Lsot`): Isot, Psot,
173/// TPsot, TNsot. `expect_consumed` enforces the fixed `Lsot == 10` layout.
174fn decode_sot(mut b: Cursor<'_>) -> Result<Sot> {
175    let tile_index = b.u16()?;
176    let psot = b.u32()?;
177    let tile_part_index = b.u8()?;
178    let num_tile_parts = b.u8()?;
179    b.expect_consumed("SOT")?;
180    Ok(Sot {
181        tile_index,
182        psot,
183        tile_part_index,
184        num_tile_parts,
185    })
186}
187
188/// Read a big-endian `u16` marker at `pos`, or `None` if it would run past the
189/// end. Used to peek the marker that follows a tile-part without disturbing the
190/// segment cursor.
191fn read_u16(bytes: &[u8], pos: usize) -> Option<u16> {
192    let hi = *bytes.get(pos)?;
193    let lo = *bytes.get(pos + 1)?;
194    Some(u16::from_be_bytes([hi, lo]))
195}
196
197/// Parse the main header up to (but not into) the first `SOT`.
198///
199/// Returns the decoded [`MainHeader`] and the byte offset of that `SOT` marker,
200/// which is where tile-part walking (issue #6) begins. Stops before any
201/// entropy-coded data, so it never touches packet bytes.
202fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize)> {
203    let mut cur = Cursor::new(bytes);
204
205    if cur.u16()? != marker::SOC {
206        return Err(Error::Codestream(
207            "does not start with the SOC marker".into(),
208        ));
209    }
210    // SIZ shall be the first marker segment after SOC (A.6).
211    if cur.u16()? != marker::SIZ {
212        return Err(Error::Codestream(
213            "SIZ must be the first marker after SOC".into(),
214        ));
215    }
216    let siz = decode_siz(segment(&mut cur)?)?;
217
218    let mut cod = None;
219    let mut qcd = None;
220
221    let sot_offset = loop {
222        let m = cur.u16()?;
223        match m {
224            // First SOT ends the main header; point the offset back at it.
225            marker::SOT => break cur.pos - 2,
226
227            marker::COD => {
228                if cod.is_some() {
229                    return Err(Error::Codestream("duplicate COD marker".into()));
230                }
231                cod = Some(decode_cod(segment(&mut cur)?)?);
232            }
233            marker::QCD => {
234                if qcd.is_some() {
235                    return Err(Error::Codestream("duplicate QCD marker".into()));
236                }
237                qcd = Some(decode_qcd(segment(&mut cur)?)?);
238            }
239            // Comment: recognised, length-skipped.
240            marker::COM => {
241                segment(&mut cur)?;
242            }
243
244            // Valid markers a later phase owns — reject cleanly, do not half-parse.
245            marker::COC
246            | marker::QCC
247            | marker::RGN
248            | marker::POC
249            | marker::TLM
250            | marker::PLT
251            | marker::SOP
252            | marker::EPH => {
253                return Err(Error::Unsupported(format!(
254                    "marker {m:#06X} is outside the Phase 1 subset"
255                )));
256            }
257
258            // SOD/EOC have no place in a main header.
259            marker::SOD | marker::EOC => {
260                return Err(Error::Codestream(format!(
261                    "unexpected marker {m:#06X} before any tile-part"
262                )));
263            }
264            other => {
265                return Err(Error::Codestream(format!(
266                    "unknown marker {other:#06X} in main header"
267                )));
268            }
269        }
270    };
271
272    let cod = cod.ok_or_else(|| Error::Codestream("missing required COD marker".into()))?;
273    let qcd = qcd.ok_or_else(|| Error::Codestream("missing required QCD marker".into()))?;
274
275    Ok((MainHeader { siz, cod, qcd }, sot_offset))
276}
277
278/// Upper bound on the declared image area (`Xsiz * Ysiz`), a robustness guard
279/// against a malformed SIZ steering the per-subband and DWT buffers into an
280/// overflowing or out-of-memory allocation. Sized for Phase 1 GRIB2 grids: 2^26
281/// samples is 256 MiB as `i32`, well above operational grids (HRRR ~1.9M, MRMS
282/// ~24.5M) and below anything that threatens the decode. Not a format limit —
283/// raise it as later phases take larger imagery.
284const MAX_IMAGE_SAMPLES: u64 = 1 << 26;
285
286/// Enforce the Phase 1 geometry subset on the SIZ fields: a single tile at the
287/// canvas origin, bounded in area. The general canvas (nonzero image/tile
288/// offsets, a multi-tile grid) is valid JPEG 2000 but Phase 2+ work, so reject
289/// it cleanly here rather than let an out-of-subset origin reach the DWT (whose
290/// interleaving assumes even, canvas-anchored subband origins) or an unbounded
291/// area reach the buffer allocations.
292fn validate_geometry(siz: &Siz) -> Result<()> {
293    if siz.x_size == 0 || siz.y_size == 0 {
294        return Err(Error::Marker("SIZ declares a zero-size image".into()));
295    }
296    if siz.x_offset != 0 || siz.y_offset != 0 {
297        return Err(Error::Unsupported(format!(
298            "image offset ({}, {}); the Phase 1 subset is canvas-origin only",
299            siz.x_offset, siz.y_offset
300        )));
301    }
302    if siz.tile_x_offset != 0 || siz.tile_y_offset != 0 {
303        return Err(Error::Unsupported(format!(
304            "tile offset ({}, {}); the Phase 1 subset is canvas-origin only",
305            siz.tile_x_offset, siz.tile_y_offset
306        )));
307    }
308    if siz.tile_width == 0 || siz.tile_height == 0 {
309        return Err(Error::Marker("SIZ declares a zero-size tile".into()));
310    }
311    // A single tile must span the whole image; a smaller tile means a multi-tile
312    // grid, which is Phase 2.
313    if (siz.tile_width as u64) < siz.x_size as u64 || (siz.tile_height as u64) < siz.y_size as u64 {
314        return Err(Error::Unsupported(
315            "tile smaller than the image (multi-tile grid); the Phase 1 subset is single-tile"
316                .into(),
317        ));
318    }
319    if siz.x_size as u64 * siz.y_size as u64 > MAX_IMAGE_SAMPLES {
320        return Err(Error::Unsupported(format!(
321            "image area {}×{} exceeds the Phase 1 decode guard of {MAX_IMAGE_SAMPLES} samples",
322            siz.x_size, siz.y_size
323        )));
324    }
325    Ok(())
326}
327
328/// Decode SIZ — image and tile geometry plus the per-component depth/sign
329/// (A.5.1). Enforces the single-component subset.
330fn decode_siz(mut b: Cursor<'_>) -> Result<Siz> {
331    let _rsiz = b.u16()?; // capabilities / profile — not needed by the decoder
332    let x_size = b.u32()?;
333    let y_size = b.u32()?;
334    let x_offset = b.u32()?;
335    let y_offset = b.u32()?;
336    let tile_width = b.u32()?;
337    let tile_height = b.u32()?;
338    let tile_x_offset = b.u32()?;
339    let tile_y_offset = b.u32()?;
340    let csiz = b.u16()?;
341
342    if csiz == 0 {
343        return Err(Error::Marker("SIZ declares zero components".into()));
344    }
345    if csiz != 1 {
346        return Err(Error::Unsupported(format!(
347            "{csiz} components; the Phase 1 subset is single-component"
348        )));
349    }
350
351    let mut components = Vec::with_capacity(csiz as usize);
352    for _ in 0..csiz {
353        let ssiz = b.u8()?;
354        let x_sampling = b.u8()?;
355        let y_sampling = b.u8()?;
356        components.push(SizComponent {
357            bit_depth: (ssiz & 0x7F) + 1,
358            signed: ssiz & 0x80 != 0,
359            x_sampling,
360            y_sampling,
361        });
362    }
363    b.expect_consumed("SIZ")?;
364
365    let siz = Siz {
366        x_size,
367        y_size,
368        x_offset,
369        y_offset,
370        tile_width,
371        tile_height,
372        tile_x_offset,
373        tile_y_offset,
374        components,
375    };
376    validate_geometry(&siz)?;
377    Ok(siz)
378}
379
380/// Decode COD — default coding style (A.6.1): transform, decomposition depth,
381/// progression, layers, code-block size/style. Enforces LRCP, a single layer,
382/// no precincts, no multi-component transform.
383fn decode_cod(mut b: Cursor<'_>) -> Result<Cod> {
384    let scod = b.u8()?;
385    // Scod bit 0: user-defined precincts present in SPcod; bits 1/2: SOP/EPH.
386    if scod & 0x01 != 0 {
387        return Err(Error::Unsupported(
388            "explicit precinct partition; the subset uses maximal precincts".into(),
389        ));
390    }
391    if scod & 0x06 != 0 {
392        return Err(Error::Unsupported(
393            "SOP/EPH error-resilience markers are out of the Phase 1 subset".into(),
394        ));
395    }
396
397    let progression = match b.u8()? {
398        0 => Progression::Lrcp,
399        p @ 1..=4 => {
400            return Err(Error::Unsupported(format!(
401                "progression order {p}; the subset is LRCP only"
402            )));
403        }
404        other => {
405            return Err(Error::Marker(format!("reserved progression order {other}")));
406        }
407    };
408
409    let layers = b.u16()?;
410    if layers != 1 {
411        return Err(Error::Unsupported(format!(
412            "{layers} quality layers; the subset is single-layer"
413        )));
414    }
415
416    let mct = b.u8()?;
417    if mct != 0 {
418        return Err(Error::Unsupported(
419            "multiple-component transform is out of the single-component subset".into(),
420        ));
421    }
422
423    let decomposition_levels = b.u8()?;
424    let code_block_width = b.u8()?;
425    let code_block_height = b.u8()?;
426    let code_block_style = b.u8()?;
427    let transform = match b.u8()? {
428        0 => Transform::Irreversible97,
429        1 => Transform::Reversible53,
430        other => return Err(Error::Marker(format!("reserved wavelet transform {other}"))),
431    };
432    b.expect_consumed("COD")?;
433
434    Ok(Cod {
435        progression,
436        layers,
437        decomposition_levels,
438        code_block_width,
439        code_block_height,
440        code_block_style,
441        transform,
442        // Maximal precincts (PPx=PPy=15) when Scod bit 0 is clear, signalled by
443        // an empty list; explicit precincts were rejected above.
444        precinct_sizes: Vec::new(),
445    })
446}
447
448/// Decode QCD — default quantization (A.6.4): style, guard bits, and the
449/// per-subband (exponent, mantissa) step parameters.
450fn decode_qcd(mut b: Cursor<'_>) -> Result<Qcd> {
451    let sqcd = b.u8()?;
452    let guard_bits = sqcd >> 5;
453    let style = match sqcd & 0x1F {
454        0 => QuantStyle::None,
455        1 => QuantStyle::ScalarDerived,
456        2 => QuantStyle::ScalarExpounded,
457        other => {
458            return Err(Error::Marker(format!(
459                "reserved quantization style {other}"
460            )));
461        }
462    };
463
464    let mut steps = Vec::new();
465    match style {
466        // No quantization (reversible): one byte per subband, high 5 bits are
467        // the exponent, mantissa is 0.
468        QuantStyle::None => {
469            if b.remaining() == 0 {
470                return Err(Error::Codestream("QCD carries no step entries".into()));
471            }
472            while b.remaining() > 0 {
473                let v = b.u8()?;
474                steps.push((v >> 3, 0));
475            }
476        }
477        // Scalar: 16-bit per entry, high 5 bits exponent, low 11 bits mantissa.
478        // Derived signals one entry (LL); expounded one per subband.
479        QuantStyle::ScalarDerived | QuantStyle::ScalarExpounded => {
480            if b.remaining() == 0 || !b.remaining().is_multiple_of(2) {
481                return Err(Error::Codestream("QCD step table is truncated".into()));
482            }
483            if style == QuantStyle::ScalarDerived && b.remaining() != 2 {
484                return Err(Error::Codestream(
485                    "derived QCD must carry exactly one step entry".into(),
486                ));
487            }
488            while b.remaining() > 0 {
489                let v = b.u16()?;
490                steps.push((((v >> 11) & 0x1F) as u8, v & 0x07FF));
491            }
492        }
493    }
494
495    Ok(Qcd {
496        style,
497        guard_bits,
498        steps,
499    })
500}
501
502/// Read a marker segment's length field and return a [`Cursor`] over its body.
503///
504/// `Lmarker` (A.4) counts the two length bytes but not the two marker bytes, so
505/// the body is `Lmarker - 2` bytes. A length below 2 or past the buffer end is a
506/// malformed codestream.
507fn segment<'a>(cur: &mut Cursor<'a>) -> Result<Cursor<'a>> {
508    let len = cur.u16()? as usize;
509    if len < 2 {
510        return Err(Error::Codestream("marker segment length below 2".into()));
511    }
512    let body = cur.take(len - 2)?;
513    Ok(Cursor::new(body))
514}
515
516/// Bounds-checked big-endian byte cursor. Every read maps an overrun to
517/// [`Error::Codestream`] so truncation is a typed error, never a panic.
518struct Cursor<'a> {
519    buf: &'a [u8],
520    pos: usize,
521}
522
523impl<'a> Cursor<'a> {
524    fn new(buf: &'a [u8]) -> Self {
525        Self { buf, pos: 0 }
526    }
527
528    /// A cursor over `buf` starting at an absolute offset, for resuming a walk
529    /// (e.g. tile-parts) from a position the main-header pass returned.
530    fn at(buf: &'a [u8], pos: usize) -> Self {
531        Self { buf, pos }
532    }
533
534    fn remaining(&self) -> usize {
535        self.buf.len() - self.pos
536    }
537
538    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
539        if self.remaining() < n {
540            return Err(Error::Codestream("truncated marker segment".into()));
541        }
542        let slice = &self.buf[self.pos..self.pos + n];
543        self.pos += n;
544        Ok(slice)
545    }
546
547    fn u8(&mut self) -> Result<u8> {
548        Ok(self.take(1)?[0])
549    }
550
551    fn u16(&mut self) -> Result<u16> {
552        let b = self.take(2)?;
553        Ok(u16::from_be_bytes([b[0], b[1]]))
554    }
555
556    fn u32(&mut self) -> Result<u32> {
557        let b = self.take(4)?;
558        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
559    }
560
561    /// Assert the whole segment body was consumed; a trailing remainder means
562    /// the declared length and the field layout disagree.
563    fn expect_consumed(&self, marker: &str) -> Result<()> {
564        if self.remaining() != 0 {
565            return Err(Error::Codestream(format!(
566                "{marker} segment has {} unexpected trailing byte(s)",
567                self.remaining()
568            )));
569        }
570        Ok(())
571    }
572}
573
574#[cfg(test)]
575mod tests;