rust_j2k/lib.rs
1//! Pure-Rust JPEG 2000 codec, built GRIB2-decode-first toward OpenJPEG-level
2//! coverage. No C dependency, so it cross-compiles cleanly to every target.
3//!
4//! The decoder reads a **raw codestream** (ISO/IEC 15444-1 Annex A, not yet
5//! the JP2 file format) into **integer** samples: one grid per component,
6//! signed up to 32 bits, unsigned up to 31 (an `i32` container), each with its
7//! own bit depth, sign, and sub-sampling. Both wavelet paths decode — the
8//! reversible 5/3 bit-exactly, the irreversible 9/7 within the standard's
9//! compliance bounds — as do tiling and tile-parts, precincts, quality layers,
10//! all five progression orders and POC changes between them, packed packet
11//! headers (PPM/PPT), every Part 1 code-block coding style, region of interest
12//! (maxshift), non-zero canvas offsets, resolution-reduced decoding, and the
13//! reversible (RCT) and irreversible (ICT) colour transforms.
14//!
15//! JP2 boxes, HTJ2K, and an encoder are later work, not permanent non-goals.
16//! See `docs/roadmap.md` and `docs/scope.md`.
17//!
18//! # Pipeline
19//!
20//! ```text
21//! bytes ─▶ codestream ─▶ tier-2 ─▶ tier-1 ─▶ dequant ─▶ inverse DWT ─▶ Image
22//! (markers) (packets) (MQ+EBCOT) (quant) (5/3 | 9/7)
23//! ```
24//!
25//! Each stage is a module below. [`decode`] wires them together.
26//!
27//! # Example
28//!
29//! The entire public surface is [`decode`]: codestream bytes in, an [`Image`]
30//! out. An [`Image`] is the image area on the reference grid plus one
31//! [`Component`] per codestream component; a sub-sampled component holds fewer
32//! samples than that area, so size sample buffers from the component, not from
33//! the image. Malformed input never panics; it comes back as a typed [`Error`].
34//!
35//! ```
36//! use rust_j2k::{decode, Error};
37//!
38//! // In real use these are the bytes of a `.j2k` codestream, or the GRIB2 §7
39//! // data section of a `grid_jpeg` message. Invalid input is rejected cleanly:
40//! match decode(b"not a codestream") {
41//! Ok(image) => {
42//! let first = image.component(0).expect("at least one component");
43//! println!(
44//! "image area {}x{}, first component {}x{}",
45//! image.width, image.height, first.width, first.height,
46//! );
47//! }
48//! Err(Error::Unsupported(what)) => println!("outside the decoded subset: {what}"),
49//! Err(e) => println!("decode failed: {e}"),
50//! }
51//! ```
52//!
53//! # Status
54//!
55//! All 23 entries of the ISO/IEC 15444-4 conformance suite decode within their
56//! class-1 error bounds, and that gate runs in `tests/` against committed
57//! oracle snapshots, with no external tools. Correctness is defined by
58//! cross-checking a reference decoder (OpenJPEG / eccodes), not by
59//! self-consistency. A codestream using a feature outside the decoded set — a
60//! JP2 wrapper, HTJ2K, a Part 2 extension — is rejected with
61//! [`Error::Unsupported`], never half-decoded. GRIB2 §5.40 (`grid_jpeg`)
62//! payloads, the crate's original target, are raw codestreams and decode
63//! directly. See each module's docs for the ISO §reference and what it owns;
64//! the feature map is in `docs/scope.md`.
65#![warn(missing_docs)]
66
67// The pipeline modules are crate-internal: the public API is `decode`, `Image`,
68// `Error`, and `Result`. Keeping the stages private lets each one evolve freely
69// (the roadmap widens all of them) without churning the crate's committed
70// surface, and keeps the docs.rs page to what a caller can actually use.
71pub(crate) mod codestream;
72pub(crate) mod dwt;
73pub(crate) mod error;
74pub(crate) mod image;
75pub(crate) mod mct;
76pub(crate) mod quant;
77pub(crate) mod tier1;
78pub(crate) mod tier2;
79
80// Structured fuzz entry points for the detached fuzz/ workspace. Compiled
81// unconditionally so that workspace builds under plain cargo (rust-analyzer,
82// `cargo check` in fuzz/), but hidden from docs and exempt from semver: this
83// is a test seam, not public API.
84#[doc(hidden)]
85pub mod fuzz;
86
87pub use error::{Error, Result};
88pub use image::{Component, Image};
89
90/// Decode a JPEG 2000 **codestream** (Annex A, no JP2 wrapper) into an
91/// [`Image`]: the reference-grid image area plus one [`Component`] per SIZ
92/// component, each on its own sample grid.
93///
94/// This is the whole public surface for the GRIB2 use case: the §7 data
95/// section of a `grid_jpeg` message is exactly such a codestream. That subset is
96/// single-component, so its images carry one component; a codestream declaring
97/// more decodes each component onto its own grid, independently.
98///
99/// Pass the bare codestream, not a `.jp2` file: a JP2 wrapper is valid JPEG 2000
100/// but is rejected with [`Error::Unsupported`] rather than unwrapped. Anything
101/// else outside the decoded subset is rejected the same way, never half-decoded.
102pub fn decode(codestream: &[u8]) -> Result<Image> {
103 decode_with(codestream, DecodeOptions::default())
104}
105
106/// Options for [`decode_with`]. The default decodes at full resolution —
107/// [`decode`] is exactly that.
108///
109/// Start from [`DecodeOptions::default`] and set what differs, with the
110/// `with_*` methods or the fields directly. The struct is `#[non_exhaustive]`,
111/// so a new option is not a breaking change.
112#[derive(Debug, Clone, Copy, Default)]
113#[non_exhaustive]
114pub struct DecodeOptions {
115 /// How many of the finest resolution levels to discard. Each level halves
116 /// the output in both axes (rounding up), so `1` decodes a half-size image,
117 /// `2` a quarter-size, and so on — the wavelet pyramid's own lower
118 /// resolutions, not a resample. Every component must keep at least one
119 /// resolution: a reduction that consumes some component's whole pyramid is
120 /// rejected as [`Error::Unsupported`].
121 pub resolution_reduction: u8,
122}
123
124impl DecodeOptions {
125 /// These options with
126 /// [`resolution_reduction`](Self::resolution_reduction) set to `levels`.
127 #[must_use]
128 pub fn with_resolution_reduction(mut self, levels: u8) -> Self {
129 self.resolution_reduction = levels;
130 self
131 }
132}
133
134/// Decode a JPEG 2000 codestream like [`decode`], governed by `options`.
135pub fn decode_with(codestream: &[u8], options: DecodeOptions) -> Result<Image> {
136 let cs = codestream::parse(codestream)?;
137
138 let reduction = options.resolution_reduction;
139
140 // Each tile is a whole decode of its own: its own header, its own packets,
141 // its own wavelet pyramid in its own coordinate frame. Nothing crosses a
142 // tile boundary — that is what tiling is for — so the tiles meet only at the
143 // end, when each writes its rectangle of the canvas.
144 let mut canvas = image::Canvas::new(&cs.header, reduction)?;
145 for (index, tile) in cs.tiles.iter().enumerate() {
146 // The tile's own parameters: the main header with this tile's tile-part
147 // header resolved over it. Held for one tile at a time — a header is
148 // sized by the component count, and a codestream can declare tens of
149 // thousands of tiles.
150 let header = cs.tile_header(index)?;
151
152 // A reduction must leave every component a resolution to decode, checked
153 // against each component's own decomposition count: a COC can give one
154 // component a shallower pyramid than the rest (p0_08 does exactly that),
155 // and a tile COD can give one tile a shallower pyramid than the rest — so
156 // this is per tile, not once for the image.
157 for (component, params) in header.components.iter().enumerate() {
158 let resolutions = u32::from(params.coding.decomposition_levels) + 1;
159 if u32::from(reduction) >= resolutions {
160 return Err(Error::Unsupported(format!(
161 "resolution reduction {reduction} discards all {resolutions} resolutions \
162 of component {component} in tile {index}"
163 )));
164 }
165 }
166
167 // Tier-2: parse packets into per-code-block coded segments, per
168 // component. The walk covers every resolution whatever the reduction:
169 // packet order is the codestream's framing, so the dropped levels'
170 // packets must still be stepped over to reach the kept ones.
171 let coded = tier2::decode_packets(&header, tile)?;
172 // Tier-1: MQ + EBCOT bit-plane decode each code block into subband
173 // coeffs. The dropped resolutions' code-blocks are skipped, never
174 // decoded.
175 let coeffs = tier1::decode_code_blocks(&header, &coded, reduction)?;
176
177 // Dequantize, then invert the DWT per resolution level into samples.
178 let mut samples = coeffs
179 .into_iter()
180 .enumerate()
181 .map(|(component, coeffs)| {
182 let dequant = quant::dequantize(&header, component, coeffs)?;
183 dwt::inverse(&header, component, dequant)
184 })
185 .collect::<Result<Vec<_>>>()?;
186
187 // Undo the inter-component decorrelation, if any, before the DC level
188 // shift (ISO/IEC 15444-1 G.1). It is a per-tile transform: the flag
189 // lives in COD, which a tile-part header can override. Components past
190 // the third are untouched.
191 if header.cod.multiple_component_transform {
192 // The wavelet picks the transform (G.1): 5/3 reconstructs integers
193 // and inverts with the reversible RCT, 9/7 reconstructs floats and
194 // inverts with the irreversible ICT. All three colour components
195 // share the wavelet (checked at parse), so component 0's decides.
196 match header.components[0].coding.transform {
197 codestream::markers::Transform::Reversible53 => mct::inverse_rct(&mut samples)?,
198 codestream::markers::Transform::Irreversible97 => mct::inverse_ict(&mut samples)?,
199 }
200 }
201
202 for (component, samples) in samples.into_iter().enumerate() {
203 let rect = cs
204 .header
205 .siz
206 .tile_component_rect(tile.index, component)
207 .ok_or_else(|| {
208 Error::Inconsistent(format!(
209 "no tile {} or no component {component} in SIZ",
210 tile.index
211 ))
212 })?;
213 canvas.place(component, rect.reduced(reduction), samples)?;
214 }
215 }
216
217 image::assemble(&cs.header, canvas.into_planes(), reduction)
218}