rust_j2k/lib.rs
1//! A pure-Rust JPEG 2000 decoder. It has no C dependency, so cross-compiling it
2//! needs no C toolchain.
3//!
4//! The decoder reads a **raw codestream** (ISO/IEC 15444-1 Annex A) or a
5//! **JP2 file** (Annex I) 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 and 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) color transforms.
14//!
15//! A JP2 file's codestream decodes the same way, and the file's header comes
16//! back on [`Image::jp2`]. A palettized JP2 file decodes to the palette's
17//! channels, and a file with channel definitions puts its color channels in
18//! color order. [`read_header`] and [`read_header_with`] read the same header
19//! without decoding any tile data. Samples come out as coded by default;
20//! [`ColorOutput::Srgb`] converts sYCC and restricted ICC profiles to sRGB.
21//! The [feature scope](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/scope.md)
22//! maps what is decoded and what is not.
23//!
24//! # Pipeline
25//!
26//! ```text
27//! bytes ─▶ [jp2 boxes] ─▶ codestream ─▶ tier-2 ─▶ tier-1 ─▶ dequant
28//! (Annex I) (markers) (packets) (MQ+EBCOT) (quant)
29//!
30//! ─▶ inverse DWT ─▶ inverse MCT ─▶ [palette, cdef, sRGB] ─▶ Image
31//! (5/3 | 9/7) (RCT | ICT) (JP2 only)
32//! ```
33//!
34//! [`decode`] runs these stages in order.
35//!
36//! # Example
37//!
38//! The core of the public surface is [`decode`]: codestream or JP2 bytes in,
39//! an [`Image`] out, with one [`Component`] per output channel. Malformed
40//! input never panics; it comes back as a typed [`Error`].
41//!
42//! ```
43//! use rust_j2k::{decode, Error};
44//!
45//! // In real use these are the bytes of a `.j2k` codestream or `.jp2` file, or the GRIB2 §7
46//! // data section of a `grid_jpeg` message. Invalid input is rejected cleanly:
47//! match decode(b"not a codestream") {
48//! Ok(image) => {
49//! let first = image.component(0).expect("at least one component");
50//! println!(
51//! "image area {}x{}, first component {}x{}",
52//! image.width, image.height, first.width, first.height,
53//! );
54//! }
55//! Err(Error::Unsupported(what)) => println!("outside the decoded subset: {what}"),
56//! Err(e) => println!("decode failed: {e}"),
57//! }
58//! ```
59//!
60//! A JP2 file's header says how to read its samples. To get sRGB instead of
61//! the samples as coded, ask for it in the options:
62//!
63//! ```no_run
64//! use rust_j2k::{ColorOutput, ColorSpace, DecodeOptions, decode_with};
65//!
66//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
67//! let bytes = std::fs::read("photo.jp2")?;
68//! let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
69//! let image = decode_with(&bytes, &options)?;
70//! if let Some(jp2) = &image.jp2 {
71//! // After a conversion the color space says sRGB, or grayscale for a
72//! // monochrome profile; a file left as coded keeps the space it
73//! // declares. `channels` labels each component (color 1, 2, 3, opacity).
74//! if jp2.color == ColorSpace::Srgb {
75//! println!("sRGB, channels {:?}", jp2.channels);
76//! }
77//! }
78//! # Ok(())
79//! # }
80//! ```
81//!
82//! # Damaged input
83//!
84//! Decoding is strict by default. Truncated or inconsistent data is an
85//! error, and no partial image comes back with it. A raw codestream cut
86//! short fails as [`Error::Codestream`], a JP2 file cut short as `Codestream` or
87//! [`Error::FileFormat`], depending on where the cut falls. A codestream
88//! whose last tile-part states its length is refused without its closing
89//! `EOC` marker. A last tile-part of length 0 (`Psot = 0`, "to the end")
90//! takes the data up to the final two bytes without checking that they are
91//! `EOC`, as OpenJPEG does, so a missing `EOC` there costs the tile its last
92//! two bytes and usually fails the tile instead; in a JP2 file such a
93//! tile-part can also end where its `jp2c` box ends. Input that is not
94//! JPEG 2000 at all, empty input and plain text included, is `Codestream`
95//! too.
96//!
97//! Damage can show up as any variant, not only those two. A flipped bit in
98//! a header field can read as an absurd image size ([`Error::Limit`]) or an
99//! unknown marker or a feature the decoder does not read
100//! ([`Error::Unsupported`]). Do not retry a file with
101//! [`WorkLimit::Unlimited`] on that evidence alone.
102//!
103//! JPEG 2000 carries no checksum, so damage inside the entropy-coded data is
104//! not always detected: a flipped byte in a code-block can decode without an
105//! error and give a wrong image. If that matters, check the file against a
106//! hash you keep. [The correctness notes][strict] list what is refused and
107//! where this decoder is stricter than OpenJPEG.
108//!
109//! ```
110//! use rust_j2k::{Error, decode};
111//!
112//! let bytes = include_bytes!(concat!(
113//! env!("CARGO_MANIFEST_DIR"),
114//! "/tests/fixtures/jpeg2000_regular_latlon.j2k"
115//! ));
116//! assert!(decode(bytes).is_ok());
117//!
118//! // Cut short: an error, not a partial image.
119//! let cut = &bytes[..bytes.len() / 2];
120//! assert!(matches!(decode(cut), Err(Error::Codestream(_))));
121//! // Without its closing `EOC` marker (FF D9): refused.
122//! assert!(decode(&bytes[..bytes.len() - 2]).is_err());
123//! // Not JPEG 2000 at all.
124//! assert!(matches!(decode(b"hello"), Err(Error::Codestream(_))));
125//! ```
126//!
127//! [strict]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/openjpeg-departures.md#stricter-than-the-oracle-on-non-conforming-streams
128//!
129//! With [`DecodeOptions::strict`] off, a codestream cut short, or one with
130//! bytes left after a tile's last packet, decodes to the image the data
131//! holds, and [`Image::report`] says what is missing (a [`DecodeReport`]).
132//! This is what `opj_decompress -allow-partial` does. A codestream that
133//! streams in can be decoded as it arrives: the report's
134//! [`complete_reduction`](DecodeReport::complete_reduction) is the finest
135//! level the data already gives in full. Everything else damaged is refused
136//! as when strict.
137//!
138//! # Limits
139//!
140//! A valid file can still be refused with [`Error::Limit`]. The decoder caps
141//! what a file may declare and how much work it may ask for. Three limits
142//! can be changed, each set with a [`WorkLimit`]:
143//! [`DecodeOptions::sample_limit`] for the image's size,
144//! [`DecodeOptions::packet_work_limit`] for reading the packet headers and
145//! [`DecodeOptions::code_block_work_limit`] for decoding the code-blocks.
146//! The other guards have no option; the list is on [`Error::Limit`]. The
147//! message says which guard the file hit. For one of the three it also
148//! names a [`WorkLimit::Raised`] factor (see [`WorkLimit`] for how far to
149//! trust it).
150//!
151//! For a file from a source you trust, lift all three. [`WorkLimit`] has an
152//! example that retries after an `Error::Limit`.
153//!
154//! # Conformance
155//!
156//! All 23 codestreams of the ISO/IEC 15444-4 conformance suite decode within
157//! their class-1 error bounds, and its nine JP2 files within their compliance
158//! class. That gate runs in `tests/` against committed oracle snapshots, with
159//! no external tools. Correctness is defined by cross-checking OpenJPEG, not
160//! by self-consistency. An input using a
161//! feature outside the decoded set (HTJ2K, a Part 2 extension) is rejected
162//! with [`Error::Unsupported`], never half-decoded. GRIB2 §5.40 (`grid_jpeg`)
163//! payloads, the crate's original target, are raw codestreams and decode
164//! directly. The feature map is in [`docs/scope.md`](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/scope.md).
165#![warn(missing_docs)]
166
167// The pipeline modules are crate-internal: the public API is `decode`,
168// `read_header`, their options and output types, `Error`, and `Result`. Keeping
169// the stages private lets each one evolve freely
170// (the roadmap widens all of them) without churning the crate's committed
171// surface, and keeps the docs.rs page to what a caller can actually use.
172pub(crate) mod codestream;
173pub(crate) mod dwt;
174pub(crate) mod error;
175pub(crate) mod header;
176pub(crate) mod image;
177pub(crate) mod jp2;
178pub(crate) mod limit_hint;
179pub(crate) mod mct;
180pub(crate) mod pipeline;
181pub(crate) mod quant;
182pub(crate) mod report;
183pub(crate) mod samples;
184pub(crate) mod tier1;
185pub(crate) mod tier2;
186
187// Structured fuzz entry points for the detached fuzz/ workspace. Compiled
188// unconditionally so that workspace builds under plain cargo (rust-analyzer,
189// `cargo check` in fuzz/), but hidden from docs and exempt from semver: this
190// is a test seam, not public API.
191#[doc(hidden)]
192pub mod fuzz;
193
194pub use error::{Error, Result};
195pub use header::{ComponentInfo, Header};
196pub use image::{Component, Image};
197pub use jp2::{
198 Association, ChannelDefinition, ChannelDefinitionEntry, ChannelMapping, ChannelType,
199 ColorSpace, ColorSpecification, FileType, ImageHeader, IprBox, Jp2Metadata, MappingKind,
200 Palette, PaletteColumn, Ratio, ReaderRequirements, Res, Resolution, StandardFeature, UuidBox,
201 UuidInfo, VendorFeature, XmlBox,
202};
203pub use report::{DecodeReport, ReportEntry};
204
205/// Decode a JPEG 2000 **codestream** (Annex A) or **JP2 file** (Annex I)
206/// into an [`Image`]: the reference-grid image area plus one [`Component`] per
207/// output channel, each on its own sample grid. For a raw codestream that is
208/// one per SIZ component, in SIZ order. A JP2 file can change the channels:
209/// its palette and channel definitions (below), and, through [`decode_with`],
210/// the sRGB output option.
211///
212/// The input kind is detected from its first bytes. Input that opens with the
213/// `SOC` marker (`FF 4F`) is a codestream. Otherwise, input whose bytes 4..8
214/// are `jP ` (the signature box's type) is a JP2 file, and anything else goes
215/// to the codestream parser, which rejects it for its missing `SOC`. A JP2 file
216/// decodes its codestream (the first `jp2c` box) and reports the file's header
217/// on [`Image::jp2`], which is `None` for a raw codestream.
218///
219/// A JP2 file with a palette (`pclr` and `cmap`) decodes to the palette's
220/// channels, one per palette column, so it can have more components than its
221/// codestream. A `pclr` without a `cmap` is ignored. A file with channel
222/// definitions (`cdef`) moves each color channel to its color's position
223/// (color 1 first) and labels every channel on [`Jp2Metadata::channels`].
224/// [`DecodeOptions::raw_channels`] skips both and returns the codestream's
225/// components as coded.
226///
227/// ```no_run
228/// use rust_j2k::{decode, ColorSpace};
229///
230/// // A `.jp2` file decodes the same way as a raw codestream; the format is
231/// // detected from the first bytes.
232/// let bytes = std::fs::read("photo.jp2")?;
233/// let image = decode(&bytes)?;
234/// if let Some(jp2) = &image.jp2 {
235/// if jp2.color == ColorSpace::Srgb {
236/// println!("{} sRGB channels", image.components.len());
237/// }
238/// }
239/// # Ok::<(), Box<dyn std::error::Error>>(())
240/// ```
241///
242/// This is the whole public surface for the GRIB2 use case: the §7 data
243/// section of a `grid_jpeg` message is a raw codestream. That subset is
244/// single-component, so its images carry one component; a codestream declaring
245/// more decodes each component onto its own grid, independently.
246///
247/// A malformed JP2 box structure is [`Error::FileFormat`]. A file whose File
248/// Type box has `jp2 ` neither as its brand nor in its compatibility list is
249/// valid JPEG 2000 but is rejected with
250/// [`Error::Unsupported`]. Anything else outside the decoded subset is
251/// rejected the same way, never half-decoded.
252///
253/// Three limits bound a decode: the size of the image, and the work of
254/// reading the packet headers and decoding the code-blocks for the file's
255/// size. Past any of them the decode fails with [`Error::Limit`]. OpenJPEG has none of
256/// them.
257///
258/// - The decoded image may hold at most 2^28 samples (1 GiB
259/// as `i32`), summed over its output channels at the decode's
260/// [`resolution_reduction`](DecodeOptions::resolution_reduction): every
261/// component, a palette's expanded channels, and the channels sRGB output
262/// adds. That admits a 10980 x 10980 Sentinel-2 band, or an RGB image of
263/// up to about 89 MP. A larger image is refused from its header alone,
264/// before any tile is read. Peak memory is about 1.35 times the output for
265/// a square tile, an estimated 1.4 GiB at the limit, and more for a tall,
266/// narrow tile or while a palette expands (see [the sample
267/// limit][sample-limit]).
268/// - Reading the packet headers of every tile may take
269/// at most 2^24 steps, or 32 per byte of tile data when that is more. A
270/// step is a packet read, a run of code-blocks a header skips without
271/// reading a bit, or a position a progression order sweeps; [the tier-2
272/// work bound][work-bound] gives the full count. A valid file of many
273/// layers that each include a few scattered code-blocks can exceed it.
274/// - Decoding the code-blocks may take at most
275/// 2^26 sample-passes (passes run times code-block samples), or 2^15 per
276/// byte of tile data when that is more. A tile past it is refused before
277/// any of its code-blocks is decoded. On the slowest data the bound comes
278/// to about 0.5 s, or 0.25 ms a byte (see [the tier-1 work
279/// bound][tier1-bound]).
280///
281/// [`decode_with`] can raise or lift each of the three, for a file from a
282/// source you trust: see [`DecodeOptions::sample_limit`],
283/// [`DecodeOptions::packet_work_limit`] and
284/// [`DecodeOptions::code_block_work_limit`]. The message of an
285/// [`Error::Limit`] from one of them names the option and a
286/// [`WorkLimit::Raised`] factor; [`WorkLimit`] shows a retry and how far to
287/// trust the factor. The guards with no option are listed on
288/// [`Error::Limit`].
289///
290/// Decoding is strict by default: damaged or truncated data is an
291/// [`Error`], not a partial image. With [`DecodeOptions::strict`] off,
292/// missing data and leftover bytes give an image with an [`Image::report`]
293/// of what is missing. A flipped byte in entropy-coded data can go unnoticed,
294/// since the format has no checksum, and damage can show up as any variant
295/// (see the crate docs).
296///
297/// [sample-limit]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/resource-bounds.md#the-sample-limit
298/// [work-bound]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/resource-bounds.md#the-tier-2-work-bound
299/// [tier1-bound]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/resource-bounds.md#the-tier-1-work-bound
300pub fn decode(bytes: &[u8]) -> Result<Image> {
301 decode_with(bytes, &DecodeOptions::default())
302}
303
304/// Read a JPEG 2000 codestream's or JP2 file's [`Header`] without decoding any
305/// tile data: the image area, each output channel's sample format, and, for a
306/// JP2 file, the same [`Jp2Metadata`] that [`decode`] would put on
307/// [`Image::jp2`].
308///
309/// This is [`read_header_with`] at the default [`DecodeOptions`], so a fault in
310/// what it reads is the same [`Error`] that [`decode`] returns for that input.
311/// Use [`read_header_with`] to read the header for other options.
312///
313/// A readable header does not mean [`decode`] will succeed. The tile data is
314/// not read (except the packet headers of the last tile of a JP2 file whose
315/// tile-part has `Psot = 0`, described on [`read_header_with`]), so it can
316/// still be damaged, unsupported, or past a work bound ([`Error::Limit`]).
317///
318/// ```
319/// use rust_j2k::{read_header, Error};
320///
321/// // In real use these are a codestream's or JP2 file's bytes; the tile data
322/// // may be missing. Invalid input is the same typed error `decode` gives.
323/// match read_header(b"not a codestream") {
324/// Ok(header) => println!("{}x{}, {} channels", header.width, header.height, header.components.len()),
325/// Err(Error::Codestream(why)) => println!("malformed: {why}"),
326/// Err(e) => println!("refused: {e}"),
327/// }
328/// ```
329pub fn read_header(bytes: &[u8]) -> Result<Header> {
330 read_header_with(bytes, &DecodeOptions::default())
331}
332
333/// Read a JPEG 2000 codestream's or JP2 file's [`Header`] without decoding any
334/// tile data, for the same `options` as [`decode_with`]: the header describes
335/// the [`Image`] that `decode_with(bytes, options)` would return.
336///
337/// The input is detected as [`decode`] detects it. The read covers a JP2
338/// file's boxes and the codestream's main header, up to the first tile-part
339/// (`SOT` marker), and stops there, so a file whose tile data is cut short or
340/// missing still has a readable header. Nothing is allocated for the samples.
341/// One case reads further: in a JP2 file whose last tile-part has `Psot = 0`
342/// (no length) and whose `jp2c` box ends before the file does, the packet
343/// headers of that tile-part's tile are walked to see whether the codestream
344/// ends at the box's end. No samples are decoded, and every step of the walk
345/// is bounded. A codestream of more than 4096 tiles or 1024 components, or of
346/// fewer than 14 bytes per tile, is not walked, nor is a tile of more than
347/// 16384 code-blocks or precincts. The walk stops after 2^22 steps, or 8 per
348/// byte of the tile's data when that is more, counting the same steps as
349/// the decode's bound (see [`decode`]);
350/// [`packet_work_limit`](DecodeOptions::packet_work_limit) raises or lifts
351/// this bound as it does the decode's. Past a bound the walk gives up, and the
352/// codestream is taken to run to the end of the file, as for any `Psot = 0`
353/// tile-part; [`decode_with`] does the same.
354///
355/// A fault in what it reads is the same [`Error`] that `decode_with(bytes,
356/// options)` returns for that input, since `decode_with` runs the same checks
357/// first. The options matter: a `cmap` that
358/// [`raw_channels`](DecodeOptions::raw_channels) does not check, or an image
359/// or palette that fits the sample limit only once
360/// [`resolution_reduction`](DecodeOptions::resolution_reduction) shrinks the
361/// image or [`sample_limit`](DecodeOptions::sample_limit) raises the limit,
362/// is a fault under some options and not others. A fault in the tile
363/// data (a broken tile-part, a tile header that changes a component's
364/// wavelet, a reduction that a tile-part COD or COC with fewer levels cannot
365/// take) is only found by decoding. So is a POC sequence that leaves out
366/// packets of a tile, even one in the main header: whether it covers a tile
367/// depends on that tile's geometry. A reduction that the main header's own
368/// levels cannot take is [`Error::InvalidOptions`] here, as OpenJPEG has it.
369///
370/// ```
371/// use rust_j2k::{read_header_with, DecodeOptions};
372///
373/// let options = DecodeOptions::default().with_resolution_reduction(1);
374/// // In real use these are a codestream's or JP2 file's bytes.
375/// assert!(read_header_with(b"not a codestream", &options).is_err());
376/// ```
377pub fn read_header_with(bytes: &[u8], options: &DecodeOptions) -> Result<Header> {
378 check_options(options)?;
379 let reduction = options.resolution_reduction;
380 if !bytes.starts_with(&[0xFF, 0x4F]) && jp2::looks_like_jp2(bytes) {
381 let prefix = read_jp2_prefix(bytes, options)?;
382 let siz = &prefix.parsed.header.siz;
383 let (width, height) = siz.image_extent_at(reduction);
384 let mut components = prefix.plans.outputs(siz, reduction)?;
385 if let Some(srgb) = &prefix.srgb {
386 srgb.describe_outputs(&mut components);
387 }
388 return Ok(Header {
389 width,
390 height,
391 components,
392 max_reduction: max_reduction(&prefix.parsed.header),
393 jp2: Some(prefix.metadata),
394 });
395 }
396 let parsed = codestream::parse_header(bytes)?;
397 let siz = &parsed.header.siz;
398 samples::check_codestream(siz, reduction, samples::cap(&options.sample_limit))?;
399 check_raw_color(options, siz.components.len())?;
400 check_reduction(&parsed.header, reduction, None)?;
401 let (width, height) = siz.image_extent_at(reduction);
402 Ok(Header {
403 width,
404 height,
405 components: ComponentInfo::of_siz(siz, reduction),
406 max_reduction: max_reduction(&parsed.header),
407 jp2: None,
408 })
409}
410
411/// The largest reduction [`check_reduction`] lets the main header take: the
412/// fewest decomposition levels of any component.
413fn max_reduction(header: &codestream::MainHeader) -> u8 {
414 header
415 .components
416 .iter()
417 .map(|params| params.coding.decomposition_levels)
418 .min()
419 .unwrap_or(0)
420}
421
422/// What color space a JP2 file's color channels come out in: the
423/// [`DecodeOptions::color`] option.
424#[derive(Debug, Clone, Default, PartialEq, Eq)]
425#[non_exhaustive]
426#[doc(alias = "ColourOutput")]
427pub enum ColorOutput {
428 /// The samples as the codestream coded them, after the palette and the
429 /// channel definitions. [`Jp2Metadata::color`] says how to read them;
430 /// an ICC profile is passed through, not applied.
431 #[default]
432 AsCoded,
433 /// sRGB. A restricted ICC profile (a monochrome or a three-component
434 /// matrix/TRC input profile) is applied at its rendering intent, as
435 /// OpenJPEG applies it with LittleCMS. sYCC is converted to RGB, with
436 /// sub-sampled chroma (2x1 or 2x2) replicated to full resolution first.
437 /// The color channels are the ones the `cdef` box labels color 1, 2 and
438 /// 3, wherever they sit. Other channels (opacity, say) are untouched. No
439 /// conversion changes a channel's bit depth: a 12-bit file comes out as
440 /// 12-bit sRGB, and a caller who wants 8-bit samples scales them (see the
441 /// example below).
442 ///
443 /// These pass through as coded, with the metadata as declared, except a
444 /// three-channel 4:2:0 or 4:2:2 image (below):
445 ///
446 /// - sRGB and grayscale;
447 /// - one or two channels, whatever the color space, as OpenJPEG reads them
448 /// as gray, or gray and opacity; only a monochrome profile converts
449 /// them;
450 /// - an ICC profile that LittleCMS refuses to open or to build a
451 /// transform from, or whose color space is not RGB, gray or YCbCr, as
452 /// OpenJPEG leaves it. [`Jp2Metadata::color`] stays
453 /// [`ColorSpace::RestrictedIcc`], so a caller can tell nothing was
454 /// converted;
455 /// - an RGB profile when any of the first four channels differs from the
456 /// first in depth, sign or sub-sampling (OpenJPEG's "AFL test").
457 ///
458 /// Anything else that cannot be converted is [`Error::Unsupported`]:
459 ///
460 /// - three or more channels with no color space (a raw codestream
461 /// included) or another enumerated color space;
462 /// - a three-channel 4:2:0 or 4:2:2 image (luma at 1x1, both chroma
463 /// channels at 2x2 or both at 2x1) that is not declared sYCC, which
464 /// OpenJPEG converts as sYCC whatever the file declares;
465 /// - color channels that are missing, or that differ in depth, sign or
466 /// sub-sampling outside the cases above;
467 /// - signed sYCC, sYCC in another layout, and samples a profile is not
468 /// applied at (8- or 16-bit unsigned for RGB, 8-bit unsigned for gray);
469 /// - a YCbCr profile, a profile LittleCMS would apply through a lookup
470 /// table or the Lab connection space, and a monochrome profile on more
471 /// than two channels.
472 ///
473 /// Replicated chroma, or a tinted gray channel, past the sample limit is
474 /// [`Error::Limit`]. These errors apply only when `Srgb` is asked for:
475 /// [`ColorOutput::AsCoded`] decodes the same files. The [table of
476 /// outcomes][outcomes] lists every case against what OpenJPEG does, and
477 /// the profiles LittleCMS refuses.
478 ///
479 /// When the samples are converted, [`Jp2Metadata::color`] says what they
480 /// now are: [`ColorSpace::Srgb`], or [`ColorSpace::Grayscale`] for a
481 /// monochrome profile, with no ICC profile. A monochrome profile whose
482 /// output is not neutral (absolute colorimetric with a tinted white
483 /// point) gives three sRGB channels in place of the gray one, as OpenJPEG
484 /// does. [`read_header`] doesn't predict that; [`read_header_with`] with
485 /// the same options does.
486 ///
487 /// An ICC conversion matches `opj_decompress -force-rgb` (OpenJPEG 2.5.0
488 /// with LittleCMS 2.14 on x86-64 Linux, glibc 2.39) sample for sample.
489 /// The output is the same on every platform whose `fma` is correctly
490 /// rounded; CI checks this on x86-64 Linux, macOS on aarch64 and
491 /// wasm32-wasip1. MinGW's `fma` (`*-pc-windows-gnu`) may not be correctly
492 /// rounded (rust-lang/rust#140515), and i586 targets use x87 arithmetic,
493 /// which is not exact IEEE, so the output there can differ. The sYCC
494 /// conversion uses the IEC 61966-2-1 constants and rounds, and is within
495 /// an MSE of 0.03 of the ISO references. OpenJPEG shortens the constants
496 /// and truncates, so the two differ by an MSE of about 0.38 to 0.49 a
497 /// channel.
498 ///
499 /// # Example: an 8-bit RGBA buffer
500 ///
501 /// Samples are `i32` at each channel's own depth and sign, so a caller
502 /// that wants 8-bit RGBA does three things. It scales each sample to
503 /// 8 bits, adding half the range first when the channel is signed. It
504 /// finds the opacity channel by its [`ChannelType`] on
505 /// [`Jp2Metadata::channels`], not by position. And it repeats a gray
506 /// (one color channel) image's value for red, green and blue. This
507 /// handles those three for a JP2 file whose channels share one grid; an
508 /// image without opacity gets 255, and so does one whose opacity is
509 /// [`ChannelType::PremultipliedOpacity`], which this recipe does not
510 /// handle.
511 ///
512 /// ```
513 /// use rust_j2k::{ChannelType, ColorOutput, DecodeOptions, Image, decode_with};
514 ///
515 /// /// One sample at its channel's depth and sign, as 8 bits.
516 /// fn to_u8(sample: i32, bit_depth: u8, signed: bool) -> u8 {
517 /// let max = (1i64 << bit_depth) - 1;
518 /// let offset = if signed { 1i64 << (bit_depth - 1) } else { 0 };
519 /// let unsigned = (i64::from(sample) + offset).clamp(0, max);
520 /// ((unsigned * 255 + max / 2) / max) as u8
521 /// }
522 ///
523 /// /// Interleaved RGBA, or `None` when the channels do not fit that shape
524 /// /// (two colors, or channels on different grids).
525 /// fn rgba8(image: &Image) -> Option<Vec<u8>> {
526 /// let first = image.components.first()?;
527 /// let same_grid = image
528 /// .components
529 /// .iter()
530 /// .all(|c| (c.width, c.height) == (first.width, first.height));
531 /// // A raw codestream has no labels: take every channel as a color.
532 /// let kinds: Vec<ChannelType> = match &image.jp2 {
533 /// Some(jp2) => jp2.channels.iter().map(|c| c.kind).collect(),
534 /// None => vec![ChannelType::Color; image.components.len()],
535 /// };
536 /// let colors: Vec<usize> = (0..kinds.len())
537 /// .filter(|&i| kinds[i] == ChannelType::Color)
538 /// .collect();
539 /// let alpha = kinds.iter().position(|&k| k == ChannelType::Opacity);
540 /// let (r, g, b) = match colors.as_slice() {
541 /// [gray] => (*gray, *gray, *gray),
542 /// [r, g, b, ..] => (*r, *g, *b),
543 /// _ => return None,
544 /// };
545 /// if !same_grid {
546 /// return None;
547 /// }
548 /// let mut out = Vec::with_capacity(first.samples.len() * 4);
549 /// for i in 0..first.samples.len() {
550 /// for channel in [Some(r), Some(g), Some(b), alpha] {
551 /// out.push(match channel {
552 /// Some(c) => {
553 /// let c = &image.components[c];
554 /// to_u8(c.samples[i], c.bit_depth, c.signed)
555 /// }
556 /// None => 255,
557 /// });
558 /// }
559 /// }
560 /// Some(out)
561 /// }
562 ///
563 /// let bytes = include_bytes!(concat!(
564 /// env!("CARGO_MANIFEST_DIR"),
565 /// "/tests/fixtures/jp2_cdef_rgba.jp2"
566 /// ));
567 /// let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
568 /// let image = decode_with(bytes, &options).expect("a 16x12 RGBA file");
569 /// let rgba = rgba8(&image).expect("red, green, blue and opacity");
570 /// assert_eq!(rgba.len(), 16 * 12 * 4);
571 ///
572 /// // A gray image repeats its value, and has no opacity channel.
573 /// use rust_j2k::Component;
574 /// let gray = Image::new(2, 1, vec![Component::new(2, 1, 12, false, 1, 1, vec![0, 4095])]);
575 /// assert_eq!(rgba8(&gray), Some(vec![0, 0, 0, 255, 255, 255, 255, 255]));
576 /// ```
577 ///
578 /// [outcomes]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/srgb-output.md#every-input-and-its-result
579 Srgb,
580}
581
582/// Options for [`decode_with`]. [`decode`] is `decode_with` at
583/// [`DecodeOptions::default`].
584///
585/// Start from [`DecodeOptions::default`] and set what differs with its
586/// `with_*` method, or the field directly. The struct is `#[non_exhaustive]`,
587/// so a new option is not a breaking change.
588#[derive(Debug, Clone)]
589#[non_exhaustive]
590pub struct DecodeOptions {
591 /// How many of the finest resolution levels to discard. Each level about
592 /// halves the output in both axes, so `1` decodes a half-size image, `2`
593 /// a quarter-size, and so on: the wavelet pyramid's own lower
594 /// resolutions, not a resample. The exact size depends on the image
595 /// origin; [`Image`] and [`ComponentInfo::width`] give the formula. Every
596 /// component must keep at least one resolution: a reduction that consumes
597 /// some component's whole pyramid is rejected as
598 /// [`Error::InvalidOptions`]. [`Header::max_reduction`] gives the largest
599 /// the main header allows.
600 pub resolution_reduction: u8,
601 /// Return a JP2 file's codestream components as coded, without applying
602 /// the file's palette (`pclr` + `cmap`) or channel definitions (`cdef`):
603 /// the file decodes exactly as its codestream does on its own, in SIZ
604 /// order, and [`Jp2Metadata::palette_applied`] is `false`. It means no
605 /// color conversion either, so it cannot be combined with
606 /// [`ColorOutput::Srgb`] ([`Error::InvalidOptions`]). Each index
607 /// plane is reported on [`Jp2Metadata::channels`] as
608 /// [`ChannelType::Unspecified`] with [`Association::None`], since it is
609 /// not a color until it goes through the palette; every other channel
610 /// is labeled as a file without a `cdef` is (see
611 /// [`Jp2Metadata::channels`]), whatever the `cdef` box says. The
612 /// boxes' layout is still checked, so a malformed `pclr`, `cmap` or
613 /// `cdef` is still [`Error::FileFormat`]; the palette mapping and column
614 /// depths, and the channel definitions' entries, are not.
615 ///
616 /// The metadata carries what the decode left out, so a caller can rebuild
617 /// the default decode, in order, from the raw one:
618 ///
619 /// 1. Expand the index planes. For each entry of
620 /// [`Jp2Metadata::channel_mapping`], in order, take the raw channel
621 /// `component`; a [`MappingKind::Direct`] entry is used as it is, and a
622 /// [`MappingKind::Palette`] entry looks each sample up as an index into
623 /// that column of [`Jp2Metadata::palette`] (an index past the table
624 /// reads its last entry, a negative one its first). Each channel
625 /// takes its bit depth and sign from its palette column: column
626 /// `column` for a palette entry, and column `i` for a direct entry at
627 /// position `i`, as OpenJPEG has it. Without a palette the raw
628 /// channels are used as they are.
629 /// 2. Put the channels in color order with
630 /// [`Jp2Metadata::channel_definitions`], by the rule documented there
631 /// (each swap looks up where the entry's channel has moved to, not its
632 /// original position). Without a `cdef` the order from step 1 stands.
633 ///
634 /// The result is the channels of the default decode. No effect on a raw
635 /// codestream. Default `false`.
636 pub raw_channels: bool,
637 /// What color space the color channels come out in. Default
638 /// [`ColorOutput::AsCoded`].
639 pub color: ColorOutput,
640 /// How much work reading the packet headers may take, against the bound
641 /// described on [`decode`]. Default [`WorkLimit::Default`].
642 ///
643 /// This also bounds the walk of a `Psot = 0` tile that [`read_header_with`]
644 /// describes, so [`read_header_with`] takes the same option.
645 pub packet_work_limit: WorkLimit,
646 /// How much work decoding the code-blocks may take, against the bound
647 /// described on [`decode`]. Default [`WorkLimit::Default`].
648 pub code_block_work_limit: WorkLimit,
649 /// How many samples the decoded image may hold, against the limit
650 /// described on [`decode`]: 2^28 samples (1 GiB as `i32`) by default,
651 /// summed over the output channels at
652 /// [`resolution_reduction`](Self::resolution_reduction). Default
653 /// [`WorkLimit::Default`].
654 ///
655 /// `Raised(n)` allows `n` times 2^28 samples. `Unlimited` lifts the
656 /// limit: the decode allocates what the header declares, 4 bytes per
657 /// sample for the output, and about 1.35 to 3.2 times that in all at its
658 /// peak (see [the sample limit](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/resource-bounds.md#the-sample-limit)), so a small hostile file can ask
659 /// for many gigabytes. If
660 /// the allocation fails the process aborts, as Rust's allocation
661 /// failures do. Only an image too large for this target to
662 /// address (`isize::MAX` bytes of samples) is still refused, with
663 /// [`Error::Limit`]. Use it only for files from a source you trust.
664 ///
665 /// [`read_header_with`] checks the same limit, so it refuses what the
666 /// decode would.
667 pub sample_limit: WorkLimit,
668 /// Refuse missing data with an [`Error`] (`true`, the default), or decode
669 /// what is there and say what is missing on [`Image::report`] (`false`).
670 /// It is the same switch as OpenJPEG's strict mode
671 /// (`opj_decoder_set_strict_mode`, `opj_decompress -allow-partial`) and
672 /// GDAL's `STRICT` option.
673 ///
674 /// `false` relaxes these two things and no others; any other relaxation
675 /// is a separate option:
676 ///
677 /// - The input may end anywhere after the first `SOT`
678 /// marker, which ends the main header: inside a tile-part, its header or
679 /// its packets, with or without the `EOC` marker. Tiles with no
680 /// tile-part are filled with 0, and packets that were never read (cut
681 /// off, or left out by the `POC` volumes) add nothing to their
682 /// code-blocks. A tile-part count (`TNsot`) that
683 /// disagrees with the tile-parts found is taken as advisory.
684 /// - Bytes left after a tile's last packet are skipped
685 /// rather than refused, and the tile is reported as possibly wrong.
686 ///
687 /// Everything else is refused as a strict decode refuses it: a damaged
688 /// packet header, coded data that fails to decode, a marker fault, tile-parts
689 /// out of order or with a gap, and every [`Error::Limit`]. The work bounds
690 /// and the sample limit hold as they do when strict, counted on the data
691 /// that is there. A missing tile is not walked, but each of its
692 /// tile-components is charged against the packet work bound, as are the
693 /// packets after the end of the data, so a short input cannot ask for
694 /// unbounded work.
695 ///
696 /// For a codestream as it streams in: a prefix that holds every packet of
697 /// the resolutions a reduction keeps decodes at that reduction to the same
698 /// samples as the whole codestream, and the report's
699 /// [`complete_reduction`](DecodeReport::complete_reduction) says which
700 /// reduction that is.
701 ///
702 /// ```
703 /// use rust_j2k::{DecodeOptions, Error, decode_with, read_header};
704 ///
705 /// let bytes = include_bytes!(concat!(
706 /// env!("CARGO_MANIFEST_DIR"),
707 /// "/tests/fixtures/jpeg2000_regular_latlon.j2k"
708 /// ));
709 /// let prefix = &bytes[..bytes.len() - 20];
710 /// // Strict, the default: a cut codestream is an error.
711 /// assert!(matches!(
712 /// decode_with(prefix, &DecodeOptions::default()),
713 /// Err(Error::Codestream(_))
714 /// ));
715 /// // Not strict: the image, and what it lacks.
716 /// let options = DecodeOptions::default().with_strict(false);
717 /// let image = decode_with(prefix, &options).expect("decodes");
718 /// assert!(!image.report.is_complete());
719 /// // The coarsest level a decode may ask for, and the finest the data holds.
720 /// let max = read_header(prefix).expect("the main header is there").max_reduction;
721 /// if let Some(r) = image.report.complete_reduction.filter(|&r| r <= max) {
722 /// let coarse = decode_with(prefix, &options.with_resolution_reduction(r)).expect("decodes");
723 /// assert!(coarse.report.is_complete());
724 /// }
725 /// ```
726 #[doc(alias = "allow_partial")]
727 #[doc(alias = "allow-partial")]
728 pub strict: bool,
729}
730
731impl Default for DecodeOptions {
732 /// Full resolution, components as the file's boxes shape them, color as
733 /// coded, the default limits, and strict.
734 fn default() -> Self {
735 DecodeOptions {
736 resolution_reduction: 0,
737 raw_channels: false,
738 color: ColorOutput::default(),
739 packet_work_limit: WorkLimit::default(),
740 code_block_work_limit: WorkLimit::default(),
741 sample_limit: WorkLimit::default(),
742 strict: true,
743 }
744 }
745}
746
747/// How far a decode may go against one of its bounds: the
748/// [`DecodeOptions::packet_work_limit`] and
749/// [`DecodeOptions::code_block_work_limit`] work bounds, and the
750/// [`DecodeOptions::sample_limit`] on the image's size.
751///
752/// Each work bound scales with the size of the file, so a small file cannot
753/// ask for minutes of work, and the sample limit holds the memory a file may
754/// ask for to an estimated 1.4 GiB for a square tile, and to a few GiB for a tall,
755/// narrow one (see [the sample limit](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.4.0/docs/resource-bounds.md#the-sample-limit)). A valid file can still go past
756/// a bound, when it codes many samples in very few bytes or is very
757/// large. The decode then fails with [`Error::Limit`], and its message names
758/// the option and a [`Raised`](WorkLimit::Raised) factor. Treat the factor as
759/// a hint, not a measure of the file:
760///
761/// - For the sample limit it is exact for the check it names: the image's
762/// samples are known from its header. Palette expansion or sRGB output is
763/// checked later, against the same limit, and may need a higher factor.
764/// - For the code-block bound it is what the tiles seen so far need, exact
765/// for a file of one tile.
766/// - For the packet bound it is the next factor up from the one that failed
767/// (or, when the refusal comes from a POC sequence's reach or a
768/// reduction's dropped code-blocks, the factor that check needs), and the
769/// file may need more: the walk stops as soon as it runs
770/// out, so it does not know the total. Double `n` on each retry rather than
771/// stepping by one: each retry costs more, and a file can need a factor of
772/// dozens.
773///
774/// Which value to pick:
775///
776/// - For a file from a source you trust, use [`Unlimited`](WorkLimit::Unlimited).
777/// The decode then takes as long as the file asks.
778/// - To keep a ceiling, use `Raised(n)` with an `n` of your own choosing,
779/// the largest cost you will accept. Read the factor from the message to
780/// size it: a file that needs `Raised(3)` is refused under `Raised(2)`. Do
781/// not parse the message in code; it is a diagnostic, not a stable format.
782///
783/// Only these three limits can be changed. The other guards also end in
784/// [`Error::Limit`], and no option here raises them (see [`Error::Limit`]).
785/// A damaged file can hit a guard too, so do not lift a bound on that
786/// evidence alone.
787///
788/// ```
789/// use rust_j2k::{DecodeOptions, Error, WorkLimit, decode, decode_with};
790///
791/// // A valid 1 KB file that asks for far more work than its size allows.
792/// let bytes = include_bytes!(concat!(
793/// env!("CARGO_MANIFEST_DIR"),
794/// "/tests/fixtures/tier1_work_bound/t1bomb_1024_64_88.j2k"
795/// ));
796/// let image = match decode(bytes) {
797/// // The example fails if the bomb is ever admitted by default.
798/// Ok(_) => panic!("expected the work bound to refuse this file"),
799/// // Past a limit. The message says which, and the factor.
800/// Err(Error::Limit(why)) => {
801/// println!("refused: {why}");
802/// // The file is trusted here, so lift all three limits. To keep a
803/// // ceiling, use `WorkLimit::Raised(n)` for the one named instead.
804/// let options = DecodeOptions::default()
805/// .with_sample_limit(WorkLimit::Unlimited)
806/// .with_code_block_work_limit(WorkLimit::Unlimited)
807/// .with_packet_work_limit(WorkLimit::Unlimited);
808/// decode_with(bytes, &options).expect("a valid file decodes once the limits are lifted")
809/// }
810/// Err(e) => panic!("not a work-bound failure: {e}"),
811/// };
812/// assert_eq!((image.width, image.height), (1024, 1024));
813/// ```
814#[derive(Debug, Clone, Default, PartialEq, Eq)]
815#[non_exhaustive]
816pub enum WorkLimit {
817 /// The bound as [`decode`] describes it.
818 #[default]
819 Default,
820 /// The default bound times this factor: for a work bound, both its floor
821 /// and the work it allows per byte. `Raised(1)` sets the same bound as
822 /// `Default`, though the two do not compare equal. `Raised(0)` is
823 /// [`Error::InvalidOptions`].
824 Raised(u32),
825 /// No bound. For a work bound, the decode does all the work the file
826 /// asks for, however long that takes; for the sample limit, it allocates
827 /// all the memory the file asks for (see [`DecodeOptions::sample_limit`]).
828 /// The other two limits keep their own settings, and the guards with no
829 /// option (listed on [`Error::Limit`]) stay in force.
830 Unlimited,
831}
832
833impl WorkLimit {
834 /// The bound this limit sets, from the default bound `bound`.
835 pub(crate) fn apply(&self, bound: u64) -> u64 {
836 match self {
837 WorkLimit::Default => bound,
838 WorkLimit::Raised(factor) => bound.saturating_mul(u64::from(*factor)),
839 WorkLimit::Unlimited => u64::MAX,
840 }
841 }
842}
843
844impl DecodeOptions {
845 /// These options with
846 /// [`resolution_reduction`](Self::resolution_reduction) set to `levels`.
847 ///
848 /// ```
849 /// use rust_j2k::DecodeOptions;
850 ///
851 /// let options = DecodeOptions::default().with_resolution_reduction(1);
852 /// assert_eq!(options.resolution_reduction, 1);
853 /// ```
854 #[must_use]
855 pub fn with_resolution_reduction(mut self, levels: u8) -> Self {
856 self.resolution_reduction = levels;
857 self
858 }
859
860 /// These options with [`raw_channels`](Self::raw_channels) set to `raw`.
861 ///
862 /// ```
863 /// use rust_j2k::DecodeOptions;
864 ///
865 /// let options = DecodeOptions::default().with_raw_channels(true);
866 /// assert!(options.raw_channels);
867 /// ```
868 #[must_use]
869 pub fn with_raw_channels(mut self, raw: bool) -> Self {
870 self.raw_channels = raw;
871 self
872 }
873
874 /// These options with [`color`](Self::color) set to `color`.
875 ///
876 /// ```
877 /// use rust_j2k::{ColorOutput, DecodeOptions};
878 ///
879 /// let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
880 /// assert_eq!(options.color, ColorOutput::Srgb);
881 /// ```
882 #[must_use]
883 #[doc(alias = "with_colour")]
884 pub fn with_color(mut self, color: ColorOutput) -> Self {
885 self.color = color;
886 self
887 }
888
889 /// These options with [`packet_work_limit`](Self::packet_work_limit)
890 /// set to `limit`.
891 ///
892 /// ```
893 /// use rust_j2k::{DecodeOptions, WorkLimit};
894 ///
895 /// let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(4));
896 /// assert_eq!(options.packet_work_limit, WorkLimit::Raised(4));
897 /// ```
898 #[must_use]
899 pub fn with_packet_work_limit(mut self, limit: WorkLimit) -> Self {
900 self.packet_work_limit = limit;
901 self
902 }
903
904 /// These options with
905 /// [`code_block_work_limit`](Self::code_block_work_limit) set to `limit`.
906 ///
907 /// ```
908 /// use rust_j2k::{DecodeOptions, WorkLimit};
909 ///
910 /// let options = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
911 /// assert_eq!(options.code_block_work_limit, WorkLimit::Unlimited);
912 /// ```
913 #[must_use]
914 pub fn with_code_block_work_limit(mut self, limit: WorkLimit) -> Self {
915 self.code_block_work_limit = limit;
916 self
917 }
918
919 /// These options with [`sample_limit`](Self::sample_limit) set to
920 /// `limit`.
921 ///
922 /// ```
923 /// use rust_j2k::{DecodeOptions, WorkLimit};
924 ///
925 /// // Up to 3 x 2^28 samples, enough for a 16384 x 16384 RGB image.
926 /// let options = DecodeOptions::default().with_sample_limit(WorkLimit::Raised(3));
927 /// assert_eq!(options.sample_limit, WorkLimit::Raised(3));
928 /// ```
929 #[must_use]
930 pub fn with_sample_limit(mut self, limit: WorkLimit) -> Self {
931 self.sample_limit = limit;
932 self
933 }
934
935 /// These options with [`strict`](Self::strict) set to `strict`.
936 ///
937 /// ```
938 /// use rust_j2k::DecodeOptions;
939 ///
940 /// assert!(DecodeOptions::default().strict);
941 /// let options = DecodeOptions::default().with_strict(false);
942 /// assert!(!options.strict);
943 /// ```
944 #[must_use]
945 #[doc(alias = "allow_partial")]
946 pub fn with_strict(mut self, strict: bool) -> Self {
947 self.strict = strict;
948 self
949 }
950}
951
952/// Decode a JPEG 2000 codestream or JP2 file like [`decode`], governed by
953/// `options`.
954///
955/// Every [`DecodeOptions`] field is set with a `with_*` method. This reads
956/// a JP2 file at half size and converts it to sRGB:
957///
958/// ```
959/// use rust_j2k::{ColorOutput, DecodeOptions, Error, decode_with};
960///
961/// let bytes = include_bytes!(concat!(
962/// env!("CARGO_MANIFEST_DIR"),
963/// "/tests/fixtures/jp2_cdef_rgba.jp2"
964/// ));
965/// let options = DecodeOptions::default()
966/// .with_resolution_reduction(1)
967/// .with_color(ColorOutput::Srgb);
968/// match decode_with(bytes, &options) {
969/// Ok(image) => {
970/// // The file is 16x12; one level discarded halves each side.
971/// assert_eq!((image.width, image.height), (8, 6));
972/// // Red, green, blue and opacity.
973/// assert_eq!(image.components.len(), 4);
974/// }
975/// // Options that contradict each other or do not fit the file (a
976/// // reduction past its levels, `raw_channels` with sRGB output), or a
977/// // file the conversion cannot handle (`Unsupported`), are handled
978/// // here in real code. This file is fine, so they fail the example.
979/// Err(Error::InvalidOptions(why) | Error::Unsupported(why)) => panic!("{why}"),
980/// Err(e) => panic!("decode failed: {e}"),
981/// }
982/// ```
983///
984/// Failures are the same [`Error`] variants as [`decode`], plus
985/// [`Error::InvalidOptions`] for options that are invalid on their own
986/// ([`WorkLimit::Raised`]`(0)`), contradict each other, or do not fit the
987/// file.
988pub fn decode_with(bytes: &[u8], options: &DecodeOptions) -> Result<Image> {
989 check_options(options)?;
990 // A codestream opens with SOC; anything else that carries the signature
991 // box's type is read as a JP2 file, so a damaged signature box is reported
992 // as a box fault. The rest falls to the codestream parser, which reports
993 // the missing SOC.
994 if !bytes.starts_with(&[0xFF, 0x4F]) && jp2::looks_like_jp2(bytes) {
995 return decode_jp2(bytes, options);
996 }
997 // The header checks come before the tile walk, as `read_header_with` has it.
998 let parsed = codestream::parse_header(bytes)?;
999 samples::check_codestream(
1000 &parsed.header.siz,
1001 options.resolution_reduction,
1002 samples::cap(&options.sample_limit),
1003 )?;
1004 check_raw_color(options, parsed.header.siz.components.len())?;
1005 check_reduction(&parsed.header, options.resolution_reduction, None)?;
1006 let cs = codestream::parse_tiles_with(bytes, parsed, options.strict)?;
1007 decode_codestream(cs, options)
1008}
1009
1010/// Options that contradict each other, whatever the input.
1011fn check_options(options: &DecodeOptions) -> Result<()> {
1012 if options.color == ColorOutput::Srgb && options.raw_channels {
1013 return Err(Error::InvalidOptions(
1014 "`raw_channels` returns the channels as coded, so it cannot be combined with \
1015 `ColorOutput::Srgb`"
1016 .into(),
1017 ));
1018 }
1019 for (name, limit) in [
1020 ("packet_work_limit", &options.packet_work_limit),
1021 ("code_block_work_limit", &options.code_block_work_limit),
1022 ("sample_limit", &options.sample_limit),
1023 ] {
1024 if *limit == WorkLimit::Raised(0) {
1025 return Err(Error::InvalidOptions(format!(
1026 "`DecodeOptions::{name}` is `WorkLimit::Raised(0)`, but the factor must be \
1027 at least 1"
1028 )));
1029 }
1030 }
1031 Ok(())
1032}
1033
1034/// A reduction must leave every component a resolution to decode, checked
1035/// against each component's own decomposition count: a COC can give one
1036/// component a shallower pyramid than the rest (p0_08 does exactly that).
1037/// `decode_with` and `read_header_with` make this check against the main header
1038/// (COD and COC) before any tile is read, with `tile` of `None`. A tile-part COD
1039/// or COC with fewer levels is only found while decoding, where the same test
1040/// runs per tile with that tile's index.
1041fn check_reduction(
1042 header: &codestream::MainHeader,
1043 reduction: u8,
1044 tile: Option<usize>,
1045) -> Result<()> {
1046 for (component, params) in header.components.iter().enumerate() {
1047 let resolutions = u32::from(params.coding.decomposition_levels) + 1;
1048 if u32::from(reduction) >= resolutions {
1049 let place = tile.map_or_else(String::new, |index| format!(" in tile {index}"));
1050 return Err(Error::InvalidOptions(format!(
1051 "resolution reduction {reduction} discards all {resolutions} resolutions \
1052 of component {component}{place}"
1053 )));
1054 }
1055 }
1056 Ok(())
1057}
1058
1059/// A raw codestream declares no color space. Like OpenJPEG, one or two
1060/// components are read as gray (and gray plus opacity) and pass through; three
1061/// or more have nothing to convert from, so sRGB output refuses them.
1062fn check_raw_color(options: &DecodeOptions, components: usize) -> Result<()> {
1063 if options.color == ColorOutput::Srgb && components > 2 {
1064 return Err(Error::Unsupported(format!(
1065 "sRGB output from a raw codestream of {components} components, which declares \
1066 no color space"
1067 )));
1068 }
1069 Ok(())
1070}
1071
1072/// A JP2 file read up to its tile data: the boxes, the codestream's main
1073/// header, the channel plans and the metadata. Everything here is checked
1074/// before any tile is read, so [`read_header`] and [`decode`] share it and
1075/// report a header fault the same way.
1076struct Jp2Prefix<'a> {
1077 codestream: &'a [u8],
1078 parsed: codestream::ParsedHeader,
1079 plans: jp2::ChannelPlans,
1080 metadata: Jp2Metadata,
1081 /// The sRGB step, when the caller asked for it.
1082 srgb: Option<jp2::SrgbPlan>,
1083}
1084
1085/// Read a JP2 file up to its tile data, in OpenJPEG's order: the box walk,
1086/// the codestream's main header, `ihdr` against SIZ, then the channel plans.
1087/// The header boxes after the codestream, which OpenJPEG reads again once it
1088/// has decoded, are checked next, then the sRGB step is planned; all of it
1089/// before any tile is read.
1090fn read_jp2_prefix<'a>(bytes: &'a [u8], options: &DecodeOptions) -> Result<Jp2Prefix<'a>> {
1091 let file = jp2::parse(bytes, &options.packet_work_limit)?;
1092 let parsed = codestream::parse_header(file.codestream)?;
1093 let siz = &parsed.header.siz;
1094 let cap = samples::cap(&options.sample_limit);
1095 samples::check_codestream(siz, options.resolution_reduction, cap)?;
1096 jp2::check_against_siz(&file.header, siz)?;
1097 let plans = jp2::ChannelPlans::plan(
1098 &file.header,
1099 siz,
1100 options.resolution_reduction,
1101 cap,
1102 options.raw_channels,
1103 )?;
1104 jp2::check_after_codestream(&file, options.raw_channels)?;
1105 let mut metadata = jp2::metadata(&file, &plans, siz)?;
1106 let srgb = match options.color {
1107 ColorOutput::AsCoded => None,
1108 ColorOutput::Srgb => {
1109 let plan = jp2::plan_srgb(&metadata, &plans, siz, options.resolution_reduction, cap)?;
1110 // A converted image is sRGB (or gray) and carries no profile, as
1111 // OpenJPEG reports it.
1112 plan.describe(&mut metadata);
1113 Some(plan)
1114 }
1115 };
1116 check_reduction(&parsed.header, options.resolution_reduction, None)?;
1117 Ok(Jp2Prefix {
1118 codestream: file.codestream,
1119 parsed,
1120 plans,
1121 metadata,
1122 srgb,
1123 })
1124}
1125
1126/// Decode a JP2 file: read it up to its tile data, decode the codestream,
1127/// and apply the channel plans, then any sRGB step, to the samples.
1128fn decode_jp2(bytes: &[u8], options: &DecodeOptions) -> Result<Image> {
1129 let prefix = read_jp2_prefix(bytes, options)?;
1130 let cs = codestream::parse_tiles_with(prefix.codestream, prefix.parsed, options.strict)?;
1131 let image = decode_codestream(cs, options)?;
1132 let mut components = prefix.plans.apply(image.components)?;
1133 if let Some(srgb) = &prefix.srgb {
1134 components = srgb.apply(components)?;
1135 }
1136 Ok(Image {
1137 components,
1138 jp2: Some(prefix.metadata),
1139 ..image
1140 })
1141}
1142
1143/// Decode a parsed codestream into its components.
1144fn decode_codestream(cs: codestream::Codestream<'_>, options: &DecodeOptions) -> Result<Image> {
1145 let reduction = options.resolution_reduction;
1146
1147 // Each tile is a whole decode of its own: its own header, its own packets,
1148 // its own wavelet pyramid in its own coordinate frame. Nothing crosses a
1149 // tile boundary — that is what tiling is for — so the tiles meet only at the
1150 // end, when each writes its rectangle of the canvas.
1151 let mut canvas = image::Canvas::new(&cs.header, reduction)?;
1152 // One work bound for every tile's packet walk, and one for every tile's
1153 // code-blocks, in proportion to the tiles' data, so that many small
1154 // tiles cannot each spend a floor's worth. A POC sequence's bitmap stays
1155 // within the default bound however far the caller raises it.
1156 let bytes = tile_bytes(&cs);
1157 let poc_bitmap = tier2::decode_visits(bytes);
1158 let mut visits = options.packet_work_limit.apply(poc_bitmap);
1159 let first_visits = visits;
1160 let mut block_work = match &options.code_block_work_limit {
1161 WorkLimit::Unlimited => None,
1162 limit => Some(limit.apply(tier1::decode_work(bytes))),
1163 };
1164 let first_work = block_work.unwrap_or(0);
1165 // Not strict: what the codestream walk found missing, then each tile's
1166 // packets, and the smallest reduction every tile is complete at so far.
1167 let mut entries = cs.entries.clone();
1168 let mut complete = Some(0u8);
1169 // A missing tile reads no packet, but setting its samples to 0 visits
1170 // each of its tile-components, and a header of a few kilobytes can
1171 // declare 65535 tiles of 16384 components with none of them present. So
1172 // each tile-component of a missing tile costs a visit, charged here,
1173 // before any tile is decoded.
1174 let missing: u64 = entries
1175 .iter()
1176 .filter_map(|entry| match entry {
1177 ReportEntry::MissingTiles { tiles } => Some(u64::from(tiles.end - tiles.start)),
1178 _ => None,
1179 })
1180 .sum();
1181 let cost = missing.saturating_mul(cs.header.siz.components.len() as u64);
1182 visits = visits
1183 .checked_sub(cost)
1184 .ok_or_else(|| Error::Limit(limit_hint::missing_tiles(cost, first_visits, poc_bitmap)))?;
1185 for (position, tile) in cs.tiles.iter().enumerate() {
1186 // `tiles` holds every tile when strict, so `index` is also its
1187 // position; not strict, a missing tile is left out.
1188 let index = tile.index as usize;
1189 // The tile's own parameters: the main header with this tile's tile-part
1190 // header resolved over it. A tile with no markers of its own borrows the
1191 // main header; any other is a copy, sized by the component count, held
1192 // for this tile alone, as a codestream can declare tens of thousands.
1193 // That copy is paid for by the geometry the packet walk then builds for
1194 // every component, whether or not the tile's data runs out; a tile
1195 // with no data at all is not resolved. So the copies stay within
1196 // `tiles × components`, which SIZ's rule that no tile-component is
1197 // empty holds to the image's samples, with `strict` off as with it on.
1198 let header = cs.tile_header(position)?;
1199
1200 // A tile COD can give one tile a shallower pyramid than the rest, so
1201 // the reduction is checked per tile, not once for the image.
1202 check_reduction(&header, reduction, Some(index))?;
1203
1204 // Tier-2: parse packets into per-code-block coded segments, per
1205 // component. The walk covers every resolution whatever the reduction:
1206 // packet order is the codestream's framing, so the dropped levels'
1207 // packets must still be stepped over to reach the kept ones.
1208 let walked = if options.strict {
1209 tier2::decode_packets(&header, tile, &mut visits, poc_bitmap, reduction)
1210 .map(|coded| (coded, None))
1211 } else {
1212 tier2::decode_packets_partial(&header, tile, &mut visits, poc_bitmap, reduction)
1213 .map(|(coded, reach)| (coded, Some(reach)))
1214 };
1215 let coded = match walked {
1216 Ok((coded, reach)) => {
1217 if let Some(reach) = reach {
1218 let tile_complete = report_tile(&header, tile, &reach, reduction, &mut entries);
1219 complete = complete.zip(tile_complete).map(|(a, b)| a.max(b));
1220 }
1221 coded
1222 }
1223 Err(tier2::Refused::Work(work)) => {
1224 // `visits` holds what is left after the refusal, so this
1225 // counts this tile's charges before it as well as the
1226 // earlier tiles'.
1227 let spent = first_visits.saturating_sub(visits);
1228 return Err(Error::Limit(limit_hint::packet(
1229 work,
1230 index,
1231 spent,
1232 first_visits,
1233 poc_bitmap,
1234 )));
1235 }
1236 Err(tier2::Refused::Other(error)) => return Err(error),
1237 };
1238 // Tier-1: MQ + EBCOT bit-plane decode each code block into subband
1239 // coeffs. The dropped resolutions' code-blocks are skipped, never
1240 // decoded. Their work is counted first, so a tile past the bound is
1241 // refused before any of it is done.
1242 if let Some(left) = &mut block_work {
1243 let work = tier1::work(&header, &coded, reduction);
1244 let Some(rest) = left.checked_sub(work) else {
1245 return Err(Error::Limit(limit_hint::code_blocks(
1246 index,
1247 work,
1248 *left,
1249 first_work.saturating_sub(*left),
1250 tier1::decode_work(bytes),
1251 )));
1252 };
1253 *left = rest;
1254 }
1255 let coeffs = tier1::decode_code_blocks(&header, &coded, reduction)?;
1256
1257 // Invert the DWT per resolution level into samples. Tier-1 has already
1258 // dequantized the 9/7 coefficients as it placed each block.
1259 let mut samples = coeffs
1260 .into_iter()
1261 .enumerate()
1262 .map(|(component, coeffs)| dwt::inverse(&header, component, coeffs))
1263 .collect::<Result<Vec<_>>>()?;
1264
1265 // Undo the inter-component decorrelation, if any, before the DC level
1266 // shift (ISO/IEC 15444-1 G.1). It is a per-tile transform: the flag
1267 // lives in COD, which a tile-part header can override. Components past
1268 // the third are untouched. On an image of fewer than three components
1269 // the flag is ignored, as OpenJPEG ignores it (`mct::applies`).
1270 if mct::applies(
1271 header.cod.multiple_component_transform,
1272 header.components.len(),
1273 ) {
1274 // The wavelet picks the transform (G.1): 5/3 reconstructs integers
1275 // and inverts with the reversible RCT, 9/7 reconstructs floats and
1276 // inverts with the irreversible ICT. All three color components
1277 // share the wavelet (checked at parse), so component 0's decides.
1278 match header.components[0].coding.transform {
1279 codestream::markers::Transform::Reversible53 => mct::inverse_rct(&mut samples)?,
1280 codestream::markers::Transform::Irreversible97 => mct::inverse_ict(&mut samples)?,
1281 }
1282 }
1283
1284 for (component, samples) in samples.into_iter().enumerate() {
1285 let rect = cs
1286 .header
1287 .siz
1288 .tile_component_rect(tile.index, component)
1289 .ok_or_else(|| {
1290 Error::Inconsistent(format!(
1291 "no tile {} or no component {component} in `SIZ`",
1292 tile.index
1293 ))
1294 })?;
1295 canvas.place(component, rect.reduced(reduction), samples)?;
1296 }
1297 }
1298
1299 let mut image = image::assemble(&cs.header, canvas.into_planes(), reduction)?;
1300 if !options.strict {
1301 for entry in &entries {
1302 if let ReportEntry::MissingTiles { tiles } = entry {
1303 complete = None;
1304 for tile in tiles.clone() {
1305 image::zero_tile(&mut image, &cs.header.siz, tile, reduction);
1306 }
1307 }
1308 }
1309 image.report = DecodeReport::new(entries, complete, reduction);
1310 }
1311 Ok(image)
1312}
1313
1314/// Add what a non-strict walk of `tile` found to `entries`, and give the
1315/// smallest reduction at which the tile has every packet.
1316fn report_tile(
1317 header: &codestream::MainHeader,
1318 tile: &codestream::Tile<'_>,
1319 reach: &tier2::Reach,
1320 reduction: u8,
1321 entries: &mut Vec<ReportEntry>,
1322) -> Option<u8> {
1323 let layers = u32::from(header.cod.layers);
1324 let missing = |comp: usize, res: usize| reach.missing_from[comp][res];
1325 let resolutions: Vec<usize> = reach.missing_from.iter().map(Vec::len).collect();
1326 // The smallest reduction at which every resolution kept is whole.
1327 let most = resolutions.iter().min().map_or(0, |&n| n.saturating_sub(1));
1328 let leftover = reach.leftover.is_some() || reach.leftover_packed.is_some();
1329 let tile_complete = (0..=most)
1330 .find(|&r| {
1331 resolutions
1332 .iter()
1333 .enumerate()
1334 .all(|(comp, &n)| (0..n.saturating_sub(r)).all(|res| missing(comp, res).is_none()))
1335 })
1336 .and_then(|r| u8::try_from(r).ok())
1337 .filter(|_| !leftover);
1338 // The leading layers whole at the resolutions this decode keeps.
1339 let mut whole = layers;
1340 for (comp, &n) in resolutions.iter().enumerate() {
1341 for res in 0..n.saturating_sub(usize::from(reduction)) {
1342 if let Some(from) = missing(comp, res) {
1343 whole = whole.min(from);
1344 }
1345 }
1346 }
1347 if whole < layers {
1348 entries.push(ReportEntry::MissingPackets {
1349 tile: tile.index,
1350 complete_layers: whole as u16,
1351 complete_reduction: tile_complete,
1352 });
1353 }
1354 if let Some((at, bytes)) = reach.leftover {
1355 entries.push(ReportEntry::LeftoverBytes {
1356 tile: tile.index,
1357 tile_part: tile.part_at(at),
1358 bytes: bytes as u64,
1359 in_packed_headers: false,
1360 });
1361 }
1362 if let Some(bytes) = reach.leftover_packed {
1363 entries.push(ReportEntry::LeftoverBytes {
1364 tile: tile.index,
1365 tile_part: tile.part_at(tile.data.len()),
1366 bytes: bytes as u64,
1367 in_packed_headers: true,
1368 });
1369 }
1370 tile_complete
1371}
1372
1373/// The bytes of tile data the codestream's packets are read from: every
1374/// tile's packet data and packed packet headers.
1375pub(crate) fn tile_bytes(cs: &codestream::Codestream<'_>) -> u64 {
1376 cs.tiles
1377 .iter()
1378 .map(|tile| (tile.data.len() + tile.packed_headers.len()) as u64)
1379 .fold(0, u64::saturating_add)
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384 use super::*;
1385
1386 /// The reduction check names the component and the resolutions it would
1387 /// discard, and the tile only when it runs per tile.
1388 #[test]
1389 fn check_reduction_message_names_the_tile_only_when_given() {
1390 let bytes = std::fs::read(concat!(
1391 env!("CARGO_MANIFEST_DIR"),
1392 "/tests/fixtures/roi_maxshift_lossless.j2k"
1393 ))
1394 .unwrap();
1395 let mut header = codestream::parse_header(&bytes).unwrap().header;
1396 // One component is shallower than the rest, as a COC or tile COD makes it.
1397 let last = header.components.len() - 1;
1398 header.components[last].coding.decomposition_levels = 1;
1399 assert!(check_reduction(&header, 1, None).is_ok());
1400 let message = |tile| match check_reduction(&header, 2, tile) {
1401 Err(Error::InvalidOptions(m)) => m,
1402 other => panic!("{other:?}"),
1403 };
1404 let tail = format!("resolution reduction 2 discards all 2 resolutions of component {last}");
1405 assert_eq!(message(None), tail);
1406 assert_eq!(message(Some(7)), format!("{tail} in tile 7"));
1407 }
1408}