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, and HTJ2K codestreams and
6//! JPH files (ISO/IEC 15444-15) the same way: one grid per component,
7//! signed up to 32 bits, unsigned up to 31 (an `i32` container), each with its
8//! own bit depth, sign, and sub-sampling. Both wavelet paths decode, the
9//! reversible 5/3 bit-exactly and the irreversible 9/7 within the standard's
10//! compliance bounds, as do tiling and tile-parts, precincts, quality layers,
11//! all five progression orders and POC changes between them, packed packet
12//! headers (PPM/PPT), every Part 1 code-block coding style, region of interest
13//! (maxshift), non-zero canvas offsets, resolution-reduced decoding, and the
14//! reversible (RCT) and irreversible (ICT) color transforms. HTJ2K code-blocks
15//! decode with all three of their coding passes, and a tile-component may mix
16//! HT and Part 1 code-blocks. An HTJ2K file takes the same call and options
17//! as any other. A decode can stop after some quality layers, or
18//! return a window, one tile or some of the components ([`DecodeOptions`]).
19//!
20//! A JP2 file's codestream decodes the same way, and the file's header comes
21//! back on [`Image::jp2`]. A palettized JP2 file decodes to the palette's
22//! channels, and a file with channel definitions puts its color channels in
23//! color order. [`read_header`] and [`read_header_with`] read the same header
24//! without decoding any tile data. Samples come out as coded by default;
25//! [`ColorOutput::Srgb`] converts sYCC and restricted ICC profiles to sRGB.
26//! The [feature scope](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/scope.md)
27//! maps what is decoded and what is not.
28//!
29//! # Pipeline
30//!
31//! ```text
32//! bytes ─▶ [jp2 boxes] ─▶ codestream ─▶ tier-2 ─▶ tier-1 ─▶ dequant
33//! (Annex I) (markers) (packets) (EBCOT|HT) (quant)
34//!
35//! ─▶ inverse DWT ─▶ inverse MCT ─▶ [palette, cdef, sRGB] ─▶ Image
36//! (5/3 | 9/7) (RCT | ICT) (JP2 only)
37//! ```
38//!
39//! [`decode`] runs these stages in order.
40//!
41//! # Example
42//!
43//! The core of the public surface is [`decode`]: codestream or JP2 bytes in,
44//! an [`Image`] out, with one [`Component`] per output channel. Malformed
45//! input never panics; it comes back as a typed [`Error`].
46//!
47//! ```
48//! use rust_j2k::{decode, Error};
49//!
50//! // In real use these are the bytes of a `.j2k` codestream or `.jp2` file, or the GRIB2 §7
51//! // data section of a `grid_jpeg` message. Invalid input is rejected cleanly:
52//! match decode(b"not a codestream") {
53//! Ok(image) => {
54//! let first = image.component(0).expect("at least one component");
55//! println!(
56//! "image area {}x{}, first component {}x{}",
57//! image.width, image.height, first.width, first.height,
58//! );
59//! }
60//! Err(Error::Unsupported(what)) => println!("outside the decoded subset: {what}"),
61//! Err(e) => println!("decode failed: {e}"),
62//! }
63//! ```
64//!
65//! A JP2 file's header says how to read its samples. To get sRGB instead of
66//! the samples as coded, ask for it in the options:
67//!
68//! ```no_run
69//! use rust_j2k::{ColorOutput, ColorSpace, DecodeOptions, decode_with};
70//!
71//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
72//! let bytes = std::fs::read("photo.jp2")?;
73//! let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
74//! let image = decode_with(&bytes, &options)?;
75//! if let Some(jp2) = &image.jp2 {
76//! // After a conversion the color space says sRGB, or grayscale for a
77//! // monochrome profile; a file left as coded keeps the space it
78//! // declares. `channels` labels each component (color 1, 2, 3, opacity).
79//! if jp2.color == ColorSpace::Srgb {
80//! println!("sRGB, channels {:?}", jp2.channels);
81//! }
82//! }
83//! # Ok(())
84//! # }
85//! ```
86//!
87//! # Damaged input
88//!
89//! This section and the API docs use the standard's names for the parts of
90//! a codestream: markers such as `SIZ`, `COD`, `SOT` and `EOC`, tiles and
91//! tile-parts, packets, code-blocks and the reference grid. [What a JPEG 2000
92//! file holds][terms] explains them.
93//!
94//! Decoding is strict by default. Truncated or inconsistent data is an
95//! error, and no partial image comes back with it. Input cut before the
96//! codestream's main header is whole, that is, before its first `SOT` marker,
97//! is [`Error::Incomplete`], so a caller whose input streams in can tell it to
98//! wait for more bytes. That covers every cut from the empty input on,
99//! including a JP2 file's boxes before the codestream. A cut later fails as
100//! [`Error::Codestream`], or as [`Error::FileFormat`] when it falls in a JP2
101//! box after the codestream. A codestream whose last tile-part states its
102//! length is refused without its closing `EOC` marker. A last tile-part of
103//! length 0 (`Psot = 0`, "to the end") takes the data up to the final two
104//! bytes without checking that they are `EOC`, as OpenJPEG does, so a
105//! missing `EOC` there costs the tile its last two bytes and usually fails
106//! the tile instead; in a JP2 file such a tile-part can also end where its
107//! `jp2c` box ends. Input that is not JPEG 2000 at all, plain text included,
108//! is `Codestream` too.
109//!
110//! Damage can show up as any variant, not only the ones named here. A
111//! flipped bit in a header field can read as an absurd image size
112//! ([`Error::Limit`]) or an unknown marker or a feature the decoder does not
113//! read ([`Error::Unsupported`]). Do not retry a file with
114//! [`WorkLimit::Unlimited`] on that evidence alone.
115//!
116//! JPEG 2000 carries no checksum, so damage inside the entropy-coded data is
117//! not always detected: a flipped byte in a code-block can decode without an
118//! error and give a wrong image. If that matters, check the file against a
119//! hash you keep. [The correctness notes][strict] list what is refused and
120//! where this decoder is stricter than OpenJPEG.
121//!
122//! ```
123//! use rust_j2k::{Error, decode};
124//!
125//! # let bytes = include_bytes!(concat!(
126//! # env!("CARGO_MANIFEST_DIR"),
127//! # "/tests/fixtures/jpeg2000_regular_latlon.j2k"
128//! # )).to_vec();
129//! # /*
130//! let bytes = std::fs::read("image.j2k")?;
131//! # */
132//! assert!(decode(&bytes).is_ok());
133//!
134//! // Cut short: an error, not a partial image.
135//! let cut = &bytes[..bytes.len() / 2];
136//! assert!(matches!(decode(cut), Err(Error::Codestream(_))));
137//! // Without its closing `EOC` marker (FF D9): refused.
138//! assert!(decode(&bytes[..bytes.len() - 2]).is_err());
139//! // Not JPEG 2000 at all.
140//! assert!(matches!(decode(b"hello"), Err(Error::Codestream(_))));
141//! # Ok::<(), Box<dyn std::error::Error>>(())
142//! ```
143//!
144//! [terms]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/README.md#what-a-jpeg-2000-file-holds
145//! [strict]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/openjpeg-departures.md#stricter-than-the-oracle-on-non-conforming-streams
146//!
147//! With [`DecodeOptions::strict`] off, a codestream cut short, or one with
148//! bytes left after a tile's last packet, decodes to the image the data
149//! holds, and [`Image::report`] says what is missing (a [`DecodeReport`]).
150//! This is what `opj_decompress -allow-partial` does. A codestream that
151//! streams in can be decoded as it arrives: the report's
152//! [`complete_reduction`](DecodeReport::complete_reduction) is the finest
153//! level the data already gives in full. Until the main header has arrived,
154//! the decode, like [`read_header`], is [`Error::Incomplete`]. Everything else
155//! damaged is refused as when strict.
156//!
157//! For a file that arrives in pieces, use [`IncrementalDecoder`] rather than
158//! decoding each prefix again: [`feed`](IncrementalDecoder::feed) appends
159//! bytes, [`refine`](IncrementalDecoder::refine) decodes them from time to
160//! time and returns the image they hold, with its report, and
161//! [`finish`](IncrementalDecoder::finish) decodes the whole input once it
162//! ends. Each refine goes on from where the last one stopped reading
163//! packets.
164//!
165//! # Limits
166//!
167//! A valid file can still be refused with [`Error::Limit`]. The decoder caps
168//! what a file may declare and how much work it may ask for. Three limits
169//! can be changed, each set with a [`WorkLimit`]:
170//! [`DecodeOptions::sample_limit`] for the image's size,
171//! [`DecodeOptions::packet_work_limit`] for reading the packet headers and
172//! [`DecodeOptions::code_block_work_limit`] for decoding the code-blocks.
173//! The other guards have no option; the list is on [`Error::Limit`]. The
174//! error's [`LimitDetail`] says which guard the file hit, as a
175//! [`LimitKind`]. For one of the three it also gives the [`WorkLimit`] to
176//! retry with (see [`WorkLimit`] for how far to trust it).
177//!
178//! For a file from a source you trust, lift all three. [`WorkLimit`] and
179//! [`LimitDetail`] have examples that retry after an `Error::Limit`.
180//!
181//! # Conformance
182//!
183//! All 23 codestreams of the ISO/IEC 15444-4 conformance suite decode within
184//! their class-1 error bounds, and its nine JP2 files within their compliance
185//! class. So do its 41 HTJ2K codestreams and 20 JPH files. That gate runs in
186//! `tests/` against committed oracle snapshots, with no external tools.
187//! Correctness is defined by cross-checking OpenJPEG, not by self-consistency.
188//! An input using a feature outside the decoded set (an HTJ2K code-block that
189//! needs more than one HT coding pass set, a Part 2 extension) is rejected with [`Error::Unsupported`],
190//! never half-decoded. GRIB2 §5.40 (`grid_jpeg`) payloads, the crate's original
191//! target, are raw codestreams and decode directly. The feature map is in
192//! [`docs/scope.md`](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/scope.md).
193#![warn(missing_docs)]
194
195// The pipeline modules are crate-internal: the public API is `decode`,
196// `read_header`, their options and output types, `Error`, and `Result`. Keeping
197// the stages private lets each one evolve freely
198// (the roadmap widens all of them) without churning the crate's committed
199// surface, and keeps the docs.rs page to what a caller can actually use.
200pub(crate) mod codestream;
201pub(crate) mod dwt;
202pub(crate) mod error;
203pub(crate) mod header;
204pub(crate) mod image;
205pub(crate) mod incremental;
206pub(crate) mod jp2;
207pub(crate) mod limit_hint;
208pub(crate) mod mct;
209pub(crate) mod pipeline;
210pub(crate) mod quant;
211pub(crate) mod report;
212pub(crate) mod samples;
213pub(crate) mod tier1;
214pub(crate) mod tier2;
215pub(crate) mod window;
216
217// Structured fuzz entry points for the detached fuzz/ workspace. Compiled
218// unconditionally so that workspace builds under plain cargo (rust-analyzer,
219// `cargo check` in fuzz/), but hidden from docs and exempt from semver: this
220// is a test seam, not public API.
221#[doc(hidden)]
222pub mod fuzz;
223
224pub use error::{Error, ErrorDetail, LimitDetail, LimitKind, Result};
225pub use header::{ComponentInfo, Header, TileGrid};
226pub use image::{Component, Image};
227pub use incremental::IncrementalDecoder;
228pub use jp2::{
229 Association, ChannelDefinition, ChannelDefinitionEntry, ChannelMapping, ChannelType,
230 ColorSpace, ColorSpecification, FileType, ImageHeader, IprBox, Jp2Metadata, MappingKind,
231 Palette, PaletteColumn, Ratio, ReaderRequirements, Res, Resolution, StandardFeature, UuidBox,
232 UuidInfo, VendorFeature, XmlBox,
233};
234pub use report::{DecodeReport, ReportEntry};
235pub use window::{Region, Window};
236
237/// Decode a JPEG 2000 **codestream** (Annex A) or **JP2 file** (Annex I)
238/// into an [`Image`]: the reference-grid image area plus one [`Component`] per
239/// output channel, each on its own sample grid. For a raw codestream that is
240/// one per component of the `SIZ` marker, in `SIZ` order. [What a JPEG 2000
241/// file holds](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/README.md#what-a-jpeg-2000-file-holds)
242/// explains the codestream's parts. A JP2 file can change the channels:
243/// its palette and channel definitions (below), and, through [`decode_with`],
244/// the sRGB output option.
245///
246/// The input kind is detected from its first bytes. Input that opens with the
247/// `SOC` marker (`FF 4F`) is a codestream. Otherwise, input whose bytes 4..8
248/// are `jP ` (the signature box's type) is a JP2 file, and anything else goes
249/// to the codestream parser, which rejects it for its missing `SOC`. A JP2 file
250/// decodes its codestream (the first `jp2c` box) and reports the file's header
251/// on [`Image::jp2`], which is `None` for a raw codestream.
252///
253/// A JP2 file with a palette (`pclr` and `cmap`) decodes to the palette's
254/// channels, one per palette column, so it can have more components than its
255/// codestream. A `pclr` without a `cmap` is ignored. A file with channel
256/// definitions (`cdef`) moves each color channel to its color's position
257/// (color 1 first) and labels every channel on [`Jp2Metadata::channels`].
258/// [`DecodeOptions::raw_channels`] skips both and returns the codestream's
259/// components as coded.
260///
261/// ```no_run
262/// use rust_j2k::{decode, ColorSpace};
263///
264/// // A `.jp2` file decodes the same way as a raw codestream; the format is
265/// // detected from the first bytes.
266/// let bytes = std::fs::read("photo.jp2")?;
267/// let image = decode(&bytes)?;
268/// if let Some(jp2) = &image.jp2 {
269/// if jp2.color == ColorSpace::Srgb {
270/// println!("{} sRGB channels", image.components.len());
271/// }
272/// }
273/// # Ok::<(), Box<dyn std::error::Error>>(())
274/// ```
275///
276/// This is the whole public surface for the GRIB2 use case: the §7 data
277/// section of a `grid_jpeg` message is a raw codestream. That subset is
278/// single-component, so its images carry one component; a codestream declaring
279/// more decodes each component onto its own grid, independently.
280///
281/// A JPH file (a JP2-family file holding an HTJ2K codestream) decodes as a
282/// JP2 file does. A malformed box structure is [`Error::FileFormat`]. A file
283/// whose File Type box has neither `jp2 ` nor `jph ` as its brand or in its
284/// compatibility list is valid JPEG 2000 but is rejected with
285/// [`Error::Unsupported`]. Anything else outside the decoded subset is
286/// rejected the same way, never half-decoded.
287///
288/// Three limits bound a decode: the size of the image, and the work of
289/// reading the packet headers and decoding the code-blocks for the file's
290/// size. Past any of them the decode fails with [`Error::Limit`]. OpenJPEG has none of
291/// them.
292///
293/// - The decoded image may hold at most 2^29 samples (2 GiB
294/// as `i32`), summed over its output channels at the decode's
295/// [`resolution_reduction`](DecodeOptions::resolution_reduction): every
296/// component, a palette's expanded channels, and the channels sRGB output
297/// adds. That admits a 10980 x 10980 Sentinel-2 true-color image (three
298/// components), or an RGB image of up to about 179 MP. A larger image is refused from its header alone,
299/// before any tile is read. Under a window or a tile, only the tiles read
300/// count (see [`DecodeOptions::sample_limit`]). Peak memory is about 1.35
301/// times the output for a square tile, about 2.7 GiB at the limit,
302/// and more for a tall, narrow tile or while a palette expands (see [the
303/// sample limit][sample-limit]). This is for the one-shot functions; an
304/// [`IncrementalDecoder`] keeps per-tile state and can hold up to about
305/// three times as much.
306/// - Reading the packet headers of every tile may take
307/// at most 2^24 steps, or 32 per byte of tile data when that is more. A
308/// step is a packet read, a run of code-blocks a header skips without
309/// reading a bit, or a position a progression order sweeps; [the tier-2
310/// work bound][work-bound] gives the full count. A valid file of many
311/// layers that each include a few scattered code-blocks can exceed it.
312/// - Decoding the code-blocks may take at most
313/// 2^26 sample-passes (passes run times code-block samples), or 2^15 per
314/// byte of tile data when that is more. A tile past it is refused before
315/// any of its code-blocks is decoded. On the slowest data the bound comes
316/// to about 0.5 s, or 0.25 ms a byte (see [the tier-1 work
317/// bound][tier1-bound]).
318///
319/// [`decode_with`] can raise or lift each of the three, for a file from a
320/// source you trust: see [`DecodeOptions::sample_limit`],
321/// [`DecodeOptions::packet_work_limit`] and
322/// [`DecodeOptions::code_block_work_limit`]. An [`Error::Limit`] from one
323/// of them names the option, as [`LimitDetail::kind`], and the
324/// [`WorkLimit`] to retry with, as [`LimitDetail::retry_with`]; its message
325/// names both too. [`WorkLimit`] shows a retry and how far to trust the
326/// factor. The guards with no option are listed on [`Error::Limit`].
327///
328/// Decoding is strict by default: damaged or truncated data is an
329/// [`Error`], not a partial image. With [`DecodeOptions::strict`] off,
330/// missing data and leftover bytes give an image with an [`Image::report`]
331/// of what is missing. A flipped byte in entropy-coded data can go unnoticed,
332/// since the format has no checksum, and damage can show up as any variant
333/// (see the crate docs).
334///
335/// [sample-limit]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/resource-bounds.md#the-sample-limit
336/// [work-bound]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/resource-bounds.md#the-tier-2-work-bound
337/// [tier1-bound]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/resource-bounds.md#the-tier-1-work-bound
338pub fn decode(bytes: &[u8]) -> Result<Image> {
339 decode_with(bytes, &DecodeOptions::default())
340}
341
342/// Read a JPEG 2000 codestream's or JP2 file's [`Header`] without decoding any
343/// tile data: the image area, each output channel's sample format, and, for a
344/// JP2 file, the same [`Jp2Metadata`] that [`decode`] would put on
345/// [`Image::jp2`].
346///
347/// This is [`read_header_with`] at the default [`DecodeOptions`], so a fault in
348/// what it reads is the same [`Error`] that [`decode`] returns for that input.
349/// Use [`read_header_with`] to read the header for other options.
350///
351/// A readable header does not mean [`decode`] will succeed. The tile data is
352/// not read (except the packet headers of the last tile of a JP2 file whose
353/// tile-part has `Psot = 0`, described on [`read_header_with`]), so it can
354/// still be damaged, unsupported, or past a work bound ([`Error::Limit`]).
355///
356/// ```
357/// use rust_j2k::{read_header, Error};
358///
359/// // In real use these are a codestream's or JP2 file's bytes; the tile data
360/// // may be missing. Invalid input is the same typed error `decode` gives.
361/// match read_header(b"not a codestream") {
362/// Ok(header) => println!("{}x{}, {} channels", header.width, header.height, header.components.len()),
363/// Err(Error::Codestream(why)) => println!("malformed: {why}"),
364/// Err(e) => println!("refused: {e}"),
365/// }
366/// ```
367pub fn read_header(bytes: &[u8]) -> Result<Header> {
368 read_header_with(bytes, &DecodeOptions::default())
369}
370
371/// Read a JPEG 2000 codestream's or JP2 file's [`Header`] without decoding any
372/// tile data, for the same `options` as [`decode_with`]: the header describes
373/// the [`Image`] that `decode_with(bytes, options)` would return.
374///
375/// The input is detected as [`decode`] detects it. The read covers a JP2
376/// file's boxes and the codestream's main header, up to the first tile-part
377/// (`SOT` marker), and stops there, so a file whose tile data is cut short or
378/// missing still has a readable header. Input that ends before the first
379/// `SOT` marker is whole, from the empty input on and in a JP2 file's boxes
380/// too, is [`Error::Incomplete`]: wait for more bytes and try again. Nothing
381/// is allocated for the samples.
382/// One case reads further: in a JP2 file whose last tile-part has `Psot = 0`
383/// (no length) and whose `jp2c` box ends before the file does, the packet
384/// headers of that tile-part's tile are walked to see whether the codestream
385/// ends at the box's end. No samples are decoded, and every step of the walk
386/// is bounded. A codestream of more than 4096 tiles or 1024 components, or of
387/// fewer than 14 bytes per tile, is not walked, nor is a tile of more than
388/// 16384 code-blocks or precincts. The walk stops after 2^22 steps, or 8 per
389/// byte of the tile's data when that is more, counting the same steps as
390/// the decode's bound (see [`decode`]);
391/// [`packet_work_limit`](DecodeOptions::packet_work_limit) raises or lifts
392/// this bound as it does the decode's. Past a bound the walk gives up, and the
393/// codestream is taken to run to the end of the file, as for any `Psot = 0`
394/// tile-part; [`decode_with`] does the same.
395///
396/// A fault in what it reads is the same [`Error`] that `decode_with(bytes,
397/// options)` returns for that input, since `decode_with` runs the same checks
398/// first. The options matter: a `cmap` that
399/// [`raw_channels`](DecodeOptions::raw_channels) does not check, or an image
400/// or palette that fits the sample limit only once
401/// [`resolution_reduction`](DecodeOptions::resolution_reduction) shrinks the
402/// image or [`sample_limit`](DecodeOptions::sample_limit) raises the limit,
403/// is a fault under some options and not others. A fault in the tile
404/// data (a broken tile-part, a tile header that changes a component's
405/// wavelet, a reduction that a tile-part COD or COC with fewer levels cannot
406/// take) is only found by decoding. So is a POC sequence that leaves out
407/// packets of a tile, even one in the main header: whether it covers a tile
408/// depends on that tile's geometry. A reduction that the main header's own
409/// levels cannot take is [`Error::InvalidOptions`] here, as OpenJPEG has it.
410///
411/// ```
412/// use rust_j2k::{read_header_with, DecodeOptions};
413///
414/// let options = DecodeOptions::default().with_resolution_reduction(1);
415/// // In real use these are a codestream's or JP2 file's bytes.
416/// assert!(read_header_with(b"not a codestream", &options).is_err());
417/// ```
418pub fn read_header_with(bytes: &[u8], options: &DecodeOptions) -> Result<Header> {
419 check_options(options)?;
420 let reduction = options.resolution_reduction;
421 if !bytes.starts_with(&[0xFF, 0x4F]) && jp2::looks_like_jp2(bytes) {
422 let prefix = read_jp2_prefix(bytes, options)?;
423 let area = &prefix.selection.area;
424 let (width, height) = area.image_extent_at(reduction);
425 let mut components = if prefix.selection.subset {
426 pick(
427 ComponentInfo::of_siz(area, reduction),
428 &prefix.selection.order,
429 )
430 } else {
431 prefix.plans.outputs(area, reduction)?
432 };
433 if let Some(srgb) = &prefix.srgb {
434 srgb.describe_outputs(&mut components);
435 }
436 return Ok(Header {
437 width,
438 height,
439 components,
440 max_reduction: max_reduction(&prefix.parsed.header),
441 quality_layers: prefix.parsed.header.cod.layers,
442 image_area: header::image_area(&prefix.parsed.header.siz),
443 tiles: TileGrid::of_siz(&prefix.parsed.header.siz),
444 jp2: Some(prefix.metadata),
445 });
446 }
447 let parsed = codestream::parse_header(bytes)?;
448 let siz = &parsed.header.siz;
449 // The selection's refusals come after the checks before it, as the decode
450 // has them. The sample limit counts the tiles the selection reads, so it
451 // is held only to a selection that is valid: a refused one is reported as
452 // such, as no limit raised would help it.
453 let selection = window::select(siz, options);
454 if let Ok(selection) = &selection {
455 samples::check_read(
456 siz,
457 selection,
458 reduction,
459 samples::cap(&options.sample_limit),
460 )?;
461 }
462 check_raw_color(options, siz.components.len())?;
463 check_reduction(&parsed.header, reduction, None)?;
464 let selection = selection?;
465 let (width, height) = selection.area.image_extent_at(reduction);
466 Ok(Header {
467 width,
468 height,
469 components: pick(
470 ComponentInfo::of_siz(&selection.area, reduction),
471 &selection.order,
472 ),
473 max_reduction: max_reduction(&parsed.header),
474 quality_layers: parsed.header.cod.layers,
475 image_area: header::image_area(siz),
476 tiles: TileGrid::of_siz(siz),
477 jp2: None,
478 })
479}
480
481/// The entries of `all` that `order` names, in its order. Each index is in
482/// range and named once ([`window::select`] checked).
483fn pick<T: Clone>(all: Vec<T>, order: &[usize]) -> Vec<T> {
484 if order.len() == all.len() && order.iter().enumerate().all(|(i, &c)| i == c) {
485 return all;
486 }
487 order.iter().filter_map(|&c| all.get(c).cloned()).collect()
488}
489
490/// The largest reduction [`check_reduction`] lets the main header take: the
491/// fewest decomposition levels of any component.
492fn max_reduction(header: &codestream::MainHeader) -> u8 {
493 header
494 .components
495 .iter()
496 .map(|params| params.coding.decomposition_levels)
497 .min()
498 .unwrap_or(0)
499}
500
501/// What color space a JP2 file's color channels come out in: the
502/// [`DecodeOptions::color`] option.
503#[derive(Debug, Clone, Default, PartialEq, Eq)]
504#[non_exhaustive]
505#[doc(alias = "ColourOutput")]
506pub enum ColorOutput {
507 /// The samples as the codestream coded them, after the palette and the
508 /// channel definitions. [`Jp2Metadata::color`] says how to read them;
509 /// an ICC profile is passed through, not applied.
510 #[default]
511 AsCoded,
512 /// sRGB. A restricted ICC profile (a monochrome or a three-component
513 /// matrix/TRC input profile) is applied at its rendering intent, as
514 /// OpenJPEG applies it with LittleCMS. sYCC is converted to RGB, with
515 /// sub-sampled chroma (2x1 or 2x2) replicated to full resolution first.
516 /// The color channels are the ones the `cdef` box labels color 1, 2 and
517 /// 3, wherever they sit. Other channels (opacity, say) are untouched. No
518 /// conversion changes a channel's bit depth: a 12-bit file comes out as
519 /// 12-bit sRGB, and a caller who wants 8-bit samples scales them (see the
520 /// example below).
521 ///
522 /// These pass through as coded, with the metadata as declared, except a
523 /// three-channel 4:2:0 or 4:2:2 image (below):
524 ///
525 /// - sRGB and grayscale;
526 /// - one or two channels, whatever the color space, as OpenJPEG reads them
527 /// as gray, or gray and opacity; only a monochrome profile converts
528 /// them;
529 /// - an ICC profile that LittleCMS refuses to open or to build a
530 /// transform from, or whose color space is not RGB, gray or YCbCr, as
531 /// OpenJPEG leaves it. [`Jp2Metadata::color`] stays
532 /// [`ColorSpace::RestrictedIcc`], so a caller can tell nothing was
533 /// converted;
534 /// - an RGB profile when any of the first four channels differs from the
535 /// first in depth, sign or sub-sampling (OpenJPEG's "AFL test").
536 ///
537 /// Anything else that cannot be converted is [`Error::Unsupported`]:
538 ///
539 /// - three or more channels with no color space (a raw codestream
540 /// included) or another enumerated color space;
541 /// - a three-channel 4:2:0 or 4:2:2 image (luma at 1x1, both chroma
542 /// channels at 2x2 or both at 2x1) that is not declared sYCC, which
543 /// OpenJPEG converts as sYCC whatever the file declares;
544 /// - color channels that are missing, or that differ in depth, sign or
545 /// sub-sampling outside the cases above;
546 /// - signed sYCC, sYCC in another layout, and samples a profile is not
547 /// applied at (8- or 16-bit unsigned for RGB, 8-bit unsigned for gray);
548 /// - a YCbCr profile, a profile LittleCMS would apply through a lookup
549 /// table or the Lab connection space, and a monochrome profile on more
550 /// than two channels.
551 ///
552 /// Replicated chroma, or a tinted gray channel, past the sample limit is
553 /// [`Error::Limit`]. These errors apply only when `Srgb` is asked for:
554 /// [`ColorOutput::AsCoded`] decodes the same files. The [table of
555 /// outcomes][outcomes] lists every case against what OpenJPEG does, and
556 /// the profiles LittleCMS refuses.
557 ///
558 /// When the samples are converted, [`Jp2Metadata::color`] says what they
559 /// now are: [`ColorSpace::Srgb`], or [`ColorSpace::Grayscale`] for a
560 /// monochrome profile, with no ICC profile. A monochrome profile whose
561 /// output is not neutral (absolute colorimetric with a tinted white
562 /// point) gives three sRGB channels in place of the gray one, as OpenJPEG
563 /// does. [`read_header`] doesn't predict that; [`read_header_with`] with
564 /// the same options does.
565 ///
566 /// An ICC conversion matches `opj_decompress -force-rgb` (OpenJPEG 2.5.0
567 /// with LittleCMS 2.14 on x86-64 Linux, glibc 2.39) sample for sample.
568 /// The output is the same on every platform whose `fma` is correctly
569 /// rounded; CI checks this on x86-64 Linux, macOS on aarch64 and
570 /// wasm32-wasip1. MinGW's `fma` (`*-pc-windows-gnu`) may not be correctly
571 /// rounded (rust-lang/rust#140515), and i586 targets use x87 arithmetic,
572 /// which is not exact IEEE, so the output there can differ. The sYCC
573 /// conversion uses the IEC 61966-2-1 constants and rounds, and is within
574 /// an MSE of 0.03 of the ISO references. OpenJPEG shortens the constants
575 /// and truncates, so the two differ by an MSE of about 0.38 to 0.49 a
576 /// channel.
577 ///
578 /// # Example: an 8-bit RGBA buffer
579 ///
580 /// Samples are `i32` at each channel's own depth and sign, so a caller
581 /// that wants 8-bit RGBA does three things. It scales each sample to
582 /// 8 bits, adding half the range first when the channel is signed. It
583 /// finds the opacity channel by its [`ChannelType`] on
584 /// [`Jp2Metadata::channels`], not by position. And it repeats a gray
585 /// (one color channel) image's value for red, green and blue. This
586 /// handles those three for a JP2 file whose channels share one grid; an
587 /// image without opacity gets 255, and so does one whose opacity is
588 /// [`ChannelType::PremultipliedOpacity`], which this recipe does not
589 /// handle.
590 ///
591 /// ```
592 /// use rust_j2k::{ChannelType, ColorOutput, DecodeOptions, Image, decode_with};
593 ///
594 /// /// One sample at its channel's depth and sign, as 8 bits.
595 /// fn to_u8(sample: i32, bit_depth: u8, signed: bool) -> u8 {
596 /// let max = (1i64 << bit_depth) - 1;
597 /// let offset = if signed { 1i64 << (bit_depth - 1) } else { 0 };
598 /// let unsigned = (i64::from(sample) + offset).clamp(0, max);
599 /// ((unsigned * 255 + max / 2) / max) as u8
600 /// }
601 ///
602 /// /// Interleaved RGBA, or `None` when the channels do not fit that shape
603 /// /// (two colors, or channels on different grids).
604 /// fn rgba8(image: &Image) -> Option<Vec<u8>> {
605 /// let first = image.components.first()?;
606 /// let same_grid = image
607 /// .components
608 /// .iter()
609 /// .all(|c| (c.width, c.height) == (first.width, first.height));
610 /// // A raw codestream has no labels: take every channel as a color.
611 /// let kinds: Vec<ChannelType> = match &image.jp2 {
612 /// Some(jp2) => jp2.channels.iter().map(|c| c.kind).collect(),
613 /// None => vec![ChannelType::Color; image.components.len()],
614 /// };
615 /// let colors: Vec<usize> = (0..kinds.len())
616 /// .filter(|&i| kinds[i] == ChannelType::Color)
617 /// .collect();
618 /// let alpha = kinds.iter().position(|&k| k == ChannelType::Opacity);
619 /// let (r, g, b) = match colors.as_slice() {
620 /// [gray] => (*gray, *gray, *gray),
621 /// [r, g, b, ..] => (*r, *g, *b),
622 /// _ => return None,
623 /// };
624 /// if !same_grid {
625 /// return None;
626 /// }
627 /// let mut out = Vec::with_capacity(first.samples.len() * 4);
628 /// for i in 0..first.samples.len() {
629 /// for channel in [Some(r), Some(g), Some(b), alpha] {
630 /// out.push(match channel {
631 /// Some(c) => {
632 /// let c = &image.components[c];
633 /// to_u8(c.samples[i], c.bit_depth, c.signed)
634 /// }
635 /// None => 255,
636 /// });
637 /// }
638 /// }
639 /// Some(out)
640 /// }
641 ///
642 /// # let bytes = include_bytes!(concat!(
643 /// # env!("CARGO_MANIFEST_DIR"),
644 /// # "/tests/fixtures/jp2_cdef_rgba.jp2"
645 /// # )).to_vec();
646 /// # /*
647 /// let bytes = std::fs::read("image.jp2")?;
648 /// # */
649 /// // For a 16x12 RGBA file.
650 /// let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
651 /// let image = decode_with(&bytes, &options).expect("a 16x12 RGBA file");
652 /// let rgba = rgba8(&image).expect("red, green, blue and opacity");
653 /// assert_eq!(rgba.len(), 16 * 12 * 4);
654 ///
655 /// // A gray image repeats its value, and has no opacity channel.
656 /// use rust_j2k::Component;
657 /// let gray = Image::new(2, 1, vec![Component::new(2, 1, 12, false, 1, 1, vec![0, 4095])]);
658 /// assert_eq!(rgba8(&gray), Some(vec![0, 0, 0, 255, 255, 255, 255, 255]));
659 /// # Ok::<(), Box<dyn std::error::Error>>(())
660 /// ```
661 ///
662 /// [outcomes]: https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/srgb-output.md#every-input-and-its-result
663 Srgb,
664}
665
666/// Options for [`decode_with`]. [`decode`] is `decode_with` at
667/// [`DecodeOptions::default`].
668///
669/// Start from [`DecodeOptions::default`] and set what differs with its
670/// `with_*` method, or the field directly. The struct is `#[non_exhaustive]`,
671/// so a new option is not a breaking change.
672#[derive(Debug, Clone)]
673#[non_exhaustive]
674pub struct DecodeOptions {
675 /// How many of the finest resolution levels to discard. Each level about
676 /// halves the output in both axes, so `1` decodes a half-size image, `2`
677 /// a quarter-size, and so on: the wavelet pyramid's own lower
678 /// resolutions, not a resample. The exact size depends on the image
679 /// origin; [`Image`] and [`ComponentInfo::width`] give the formula. Every
680 /// component must keep at least one resolution: a reduction that consumes
681 /// some component's whole pyramid is rejected as
682 /// [`Error::InvalidOptions`]. [`Header::max_reduction`] gives the largest
683 /// the main header allows.
684 pub resolution_reduction: u8,
685 /// How many of the leading quality layers to decode: `Some(n)` decodes
686 /// layers `0..n` of each tile, `None` (the default) every layer. A
687 /// codestream builds its image up in layers, each adding coding passes
688 /// to the code-blocks, so a cap gives a lower-fidelity image at full
689 /// size from fewer passes, and the block decoder does less work. It is
690 /// OpenJPEG's `opj_decompress -l n`.
691 ///
692 /// A cap at or above a tile's layer count decodes that tile whole, as
693 /// OpenJPEG does. `Some(0)` is [`Error::InvalidOptions`]. It combines
694 /// with [`resolution_reduction`](Self::resolution_reduction).
695 ///
696 /// The packets of the later layers are still read, since they frame the
697 /// packets after them, so a fault in one is still an error, and they
698 /// count against [`packet_work_limit`](Self::packet_work_limit) as
699 /// without a cap. Only their coding passes are left out. With
700 /// [`strict`](Self::strict) off, a packet of a layer past the cap that
701 /// the data does not reach is not reported missing.
702 ///
703 /// [`Header::quality_layers`](crate::Header::quality_layers) is the layer
704 /// count the main header declares.
705 ///
706 /// ```
707 /// use rust_j2k::{DecodeOptions, decode, decode_with};
708 ///
709 /// // For a 32x24 file in three quality layers, the last one lossless.
710 /// # let bytes = include_bytes!(concat!(
711 /// # env!("CARGO_MANIFEST_DIR"),
712 /// # "/tests/fixtures/multilayer_lossless.j2k"
713 /// # )).to_vec();
714 /// # /*
715 /// let bytes = std::fs::read("image.j2k")?;
716 /// # */
717 /// let whole = decode(&bytes).expect("decodes");
718 /// let first = decode_with(&bytes, &DecodeOptions::default().with_max_quality_layers(Some(1)))
719 /// .expect("decodes");
720 /// // The same size, from fewer coding passes.
721 /// assert_eq!((first.width, first.height), (whole.width, whole.height));
722 /// assert_ne!(first.components[0].samples, whole.components[0].samples);
723 /// // A cap at or past the layer count is the whole decode.
724 /// let all = decode_with(&bytes, &DecodeOptions::default().with_max_quality_layers(Some(3)))
725 /// .expect("decodes");
726 /// assert_eq!(all.components[0].samples, whole.components[0].samples);
727 /// # Ok::<(), Box<dyn std::error::Error>>(())
728 /// ```
729 #[doc(alias = "layers")]
730 #[doc(alias = "cp_layer")]
731 pub max_quality_layers: Option<u16>,
732 /// The area to decode: [`Region::Whole`] (the default) the whole image,
733 /// [`Region::Window`] a rectangle of the reference grid, and
734 /// [`Region::Tile`] one tile. One field holds all three, so a window and a
735 /// tile cannot be asked for together. A window is OpenJPEG's
736 /// `opj_set_decode_area` (`opj_decompress -d x0,y0,x1,y1`); a tile is its
737 /// `opj_get_decoded_tile` (`opj_decompress -t index`).
738 ///
739 /// # Window
740 ///
741 /// A [`Region::Window`] returns the part of the image inside it. It is in
742 /// reference-grid coordinates, as SIZ declares them, whatever the
743 /// [`resolution_reduction`](Self::resolution_reduction).
744 /// [`Header::image_area`] gives the image area in those coordinates,
745 /// and [`TileGrid::tile`] each tile's rectangle.
746 /// The part of it outside the image area is left out, as OpenJPEG clips
747 /// it. The returned [`Image`] covers what is left, `x0..x1` by `y0..y1`:
748 /// its [`width`](Image::width) is `x1 - x0` at full resolution and
749 /// `ceil(x1 / 2^r) - ceil(x0 / 2^r)` at a reduction of `r`, and each
750 /// component's is the same of `ceil(x0 / dx)` and `ceil(x1 / dx)` for its
751 /// sub-sampling `dx` ([`ComponentInfo::width`] gives the formula for the
752 /// whole image). The samples are those of a whole decode at the same
753 /// position. [`ColorOutput::Srgb`] from sYCC with sub-sampled chroma is
754 /// [`Error::Unsupported`] when the window, cut to the image area, does not
755 /// cover all of it, as the chroma replication depends on where the
756 /// decoded area starts.
757 ///
758 /// Only the tiles the window reaches are decoded, so a small window of a
759 /// large tiled image costs a few tiles. The packets of the other tiles
760 /// are not read, so damage in them is not found, as in OpenJPEG. With
761 /// [`strict`](Self::strict) off, a codestream cut short after the tiles
762 /// the window reaches still gives the window's samples.
763 /// `opj_decompress -allow-partial -d` 2.5.0 refuses such a file, while
764 /// `-t` decodes each tile, the cut one included, as this decoder does. In
765 /// the
766 /// tiles it reaches, only the code-blocks whose wavelet support reaches
767 /// the window are decoded, so damage in the others is not found either.
768 /// Nor is a code-block it skips checked against the bit-plane limit, so
769 /// a window can decode where the whole image is refused as
770 /// [`Error::Limit`].
771 ///
772 /// An empty window, one with no part inside the image area, and one that
773 /// holds no sample of a returned component at the reduction are
774 /// [`Error::InvalidOptions`].
775 ///
776 /// ```
777 /// use rust_j2k::{DecodeOptions, Region, Window, decode, decode_with};
778 ///
779 /// // For a 32x24 file with its image area at the grid's origin.
780 /// # let bytes = include_bytes!(concat!(
781 /// # env!("CARGO_MANIFEST_DIR"),
782 /// # "/tests/fixtures/multilayer_lossless.j2k"
783 /// # )).to_vec();
784 /// # /*
785 /// let bytes = std::fs::read("image.j2k")?;
786 /// # */
787 /// let whole = decode(&bytes).expect("decodes");
788 /// let options = DecodeOptions::default().with_region(Region::Window(Window::new(8, 4, 20, 30)));
789 /// let part = decode_with(&bytes, &options).expect("decodes");
790 /// // The window is cut to the image: rows 4 to 23.
791 /// assert_eq!((part.width, part.height), (12, 20));
792 /// assert_eq!(part.components[0].sample(0, 0), whole.components[0].sample(8, 4));
793 /// # Ok::<(), Box<dyn std::error::Error>>(())
794 /// ```
795 ///
796 /// # Tile
797 ///
798 /// [`Region::Tile`] returns tile `index`'s area of the image. Tiles are
799 /// numbered in raster order from 0, as the codestream's `Isot` numbers
800 /// them. The result is the decode of a [`Region::Window`] set to the
801 /// tile's rectangle on the reference grid: its size, its samples and its
802 /// failures, the refusal of sRGB output from sub-sampled sYCC included
803 /// (unless the image is one tile). [`Header::tiles`] gives the tile grid
804 /// and [`TileGrid::count`] the number of tiles; an index at or past the
805 /// count is [`Error::InvalidOptions`].
806 #[doc(alias = "decode_area")]
807 #[doc(alias = "window")]
808 #[doc(alias = "tile")]
809 pub region: Region,
810 /// Decode only these components, in this order: `Some(list)` returns one
811 /// [`Component`] per entry of `list`, each the component of that SIZ
812 /// index, and `None` (the default) every component. It is OpenJPEG's
813 /// `opj_set_decoded_components` (`opj_decompress -c`), which takes them
814 /// in the given order too.
815 ///
816 /// Each returned component has the samples of a whole decode. The other
817 /// components' packets are still read, as they frame the packets after
818 /// them, but their code-blocks are not decoded. Under the codestream's
819 /// color transform (RCT or ICT), components 0, 1 and 2 are decoded
820 /// together whenever one of them is asked for, since each of them needs
821 /// all three. OpenJPEG skips the color transform instead when the
822 /// components are chosen, so its `-c` returns other samples for those
823 /// three.
824 ///
825 /// On a JP2 file the list names codestream components, which come out
826 /// as coded: the palette and channel definitions are not applied, as
827 /// with [`raw_channels`](Self::raw_channels), and as OpenJPEG has it.
828 /// [`Jp2Metadata::channels`] describes the components returned.
829 ///
830 /// An empty list, an index named twice, an index past SIZ's component
831 /// count, and a list with [`ColorOutput::Srgb`] are
832 /// [`Error::InvalidOptions`]. The last holds even on a gray codestream,
833 /// where sRGB output would pass the samples through, as it does for
834 /// [`raw_channels`](Self::raw_channels).
835 ///
836 /// ```
837 /// use rust_j2k::{DecodeOptions, decode, decode_with};
838 ///
839 /// // For a file of three components under the irreversible color transform.
840 /// # let bytes = include_bytes!(concat!(
841 /// # env!("CARGO_MANIFEST_DIR"),
842 /// # "/tests/fixtures/layers/cprl_irreversible.j2k"
843 /// # )).to_vec();
844 /// # /*
845 /// let bytes = std::fs::read("image.j2k")?;
846 /// # */
847 /// let whole = decode(&bytes).expect("decodes");
848 /// let options = DecodeOptions::default().with_components(Some(vec![2, 0]));
849 /// let some = decode_with(&bytes, &options).expect("decodes");
850 /// assert_eq!(some.components.len(), 2);
851 /// assert_eq!(some.components[0], whole.components[2]);
852 /// assert_eq!(some.components[1], whole.components[0]);
853 /// # Ok::<(), Box<dyn std::error::Error>>(())
854 /// ```
855 #[doc(alias = "opj_set_decoded_components")]
856 pub components: Option<Vec<u16>>,
857 /// Return a JP2 file's codestream components as coded, without applying
858 /// the file's palette (`pclr` + `cmap`) or channel definitions (`cdef`):
859 /// the file decodes exactly as its codestream does on its own, in SIZ
860 /// order, and [`Jp2Metadata::palette_applied`] is `false`. It means no
861 /// color conversion either, so it cannot be combined with
862 /// [`ColorOutput::Srgb`] ([`Error::InvalidOptions`]). Each index
863 /// plane is reported on [`Jp2Metadata::channels`] as
864 /// [`ChannelType::Unspecified`] with [`Association::None`], since it is
865 /// not a color until it goes through the palette; every other channel
866 /// is labeled as a file without a `cdef` is (see
867 /// [`Jp2Metadata::channels`]), whatever the `cdef` box says. The
868 /// boxes' layout is still checked, so a malformed `pclr`, `cmap` or
869 /// `cdef` is still [`Error::FileFormat`]; the palette mapping and column
870 /// depths, and the channel definitions' entries, are not.
871 ///
872 /// The metadata carries what the decode left out, so a caller can rebuild
873 /// the default decode, in order, from the raw one:
874 ///
875 /// 1. Expand the index planes. For each entry of
876 /// [`Jp2Metadata::channel_mapping`], in order, take the raw channel
877 /// `component`; a [`MappingKind::Direct`] entry is used as it is, and a
878 /// [`MappingKind::Palette`] entry looks each sample up as an index into
879 /// that column of [`Jp2Metadata::palette`] (an index past the table
880 /// reads its last entry, a negative one its first). Each channel
881 /// takes its bit depth and sign from its palette column: column
882 /// `column` for a palette entry, and column `i` for a direct entry at
883 /// position `i`, as OpenJPEG has it. Without a palette the raw
884 /// channels are used as they are.
885 /// 2. Put the channels in color order with
886 /// [`Jp2Metadata::channel_definitions`], by the rule documented there
887 /// (each swap looks up where the entry's channel has moved to, not its
888 /// original position). Without a `cdef` the order from step 1 stands.
889 ///
890 /// The result is the channels of the default decode. No effect on a raw
891 /// codestream. Default `false`.
892 pub raw_channels: bool,
893 /// What color space the color channels come out in. Default
894 /// [`ColorOutput::AsCoded`].
895 pub color: ColorOutput,
896 /// How much work reading the packet headers may take, against the bound
897 /// described on [`decode`]. Default [`WorkLimit::Default`].
898 ///
899 /// This also bounds the walk of a `Psot = 0` tile that [`read_header_with`]
900 /// describes, so [`read_header_with`] takes the same option.
901 ///
902 /// That walk, in a JP2 file whose last tile-part has `Psot = 0`, decides
903 /// where the tile ends: at the end of the `jp2c` box if the packets end
904 /// exactly there, otherwise at the end of the file. A walk that stops at
905 /// the default bound reads to the end of the file, so the box's trailing
906 /// bytes count as left after the last packet. Raising the limit can let
907 /// the walk finish. The same file can then decode in full where the
908 /// default gives [`Error::Codestream`] (or, with
909 /// [`strict`](Self::strict) off, a report with a
910 /// [`ReportEntry::LeftoverBytes`]), and no [`Error::Limit`] ever
911 /// suggested the change.
912 pub packet_work_limit: WorkLimit,
913 /// How much work decoding the code-blocks may take, against the bound
914 /// described on [`decode`]. Default [`WorkLimit::Default`].
915 pub code_block_work_limit: WorkLimit,
916 /// How many samples the decoded image may hold, against the limit
917 /// described on [`decode`]: 2^29 samples (2 GiB as `i32`) by default,
918 /// summed over the output channels at
919 /// [`resolution_reduction`](Self::resolution_reduction). Default
920 /// [`WorkLimit::Default`].
921 ///
922 /// Under a window or a tile ([`region`](Self::region)), the count
923 /// is the samples of the tiles the decode reads, in every component, as
924 /// each of those tiles is reconstructed whole; a palette's expanded
925 /// channels and sRGB output count only the returned area. A small window
926 /// of a large tiled image therefore fits the default, but a window of
927 /// one large tile counts the whole tile. A
928 /// [`components`](Self::components) subset does not lower the count, as
929 /// the packets of every component of a tile read are still walked.
930 ///
931 /// `Raised(n)` allows `n` times 2^29 samples. `Unlimited` lifts the
932 /// limit: the decode allocates what the header declares, 4 bytes per
933 /// sample for the output, and about 1.35 to 3.2 times that in all at its
934 /// peak (see [the sample limit](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/resource-bounds.md#the-sample-limit)), so a small hostile file can ask
935 /// for many gigabytes. If
936 /// the allocation fails the process aborts, as Rust's allocation
937 /// failures do. Only an image too large for this target to
938 /// address (`isize::MAX` bytes of samples) is still refused, with
939 /// [`Error::Limit`]. Use it only for files from a source you trust.
940 ///
941 /// [`read_header_with`] checks the same limit, so it refuses what the
942 /// decode would.
943 pub sample_limit: WorkLimit,
944 /// Refuse missing data with an [`Error`] (`true`, the default), or decode
945 /// what is there and say what is missing on [`Image::report`] (`false`).
946 /// It is the same switch as OpenJPEG's strict mode
947 /// (`opj_decoder_set_strict_mode`, `opj_decompress -allow-partial`) and
948 /// GDAL's `STRICT` option.
949 ///
950 /// `false` relaxes these two things and no others; any other relaxation
951 /// is a separate option:
952 ///
953 /// - The input may end anywhere after the first `SOT` marker, which ends
954 /// the main header: inside a tile-part, its header or its packets, with or without the `EOC`
955 /// marker. Input that ends before the first `SOT` is
956 /// [`Error::Incomplete`], as when strict. Tiles with no
957 /// tile-part are filled with 0, and packets that were never read (cut
958 /// off, or left out by the `POC` volumes) add nothing to their
959 /// code-blocks. A tile-part count (`TNsot`) that
960 /// disagrees with the tile-parts found is taken as advisory.
961 /// - Bytes left after a tile's last packet are skipped
962 /// rather than refused, and the tile is reported as possibly wrong.
963 ///
964 /// Everything else is refused as a strict decode refuses it: a damaged
965 /// packet header, coded data that fails to decode, a marker fault, tile-parts
966 /// out of order or with a gap, and every [`Error::Limit`]. The work bounds
967 /// and the sample limit hold as they do when strict, counted on the data
968 /// that is there. A missing tile is not walked, but each of its
969 /// tile-components is charged against the packet work bound (under a
970 /// window or tile, those of the missing tiles it reads), as are the
971 /// packets after the end of the data, so a short input cannot ask for
972 /// unbounded work.
973 ///
974 /// Strict or not, only the data a decode reads is checked. With a
975 /// [`region`](Self::region) of a window or a tile, the tiles outside it
976 /// are not read, with a window the code-blocks of the tiles it reaches
977 /// that the window does not need are not decoded, and with
978 /// [`components`](Self::components) the code-blocks of the components
979 /// left out are not decoded, so damage there goes unseen, as with
980 /// `opj_decompress -t` and `-d`. Nor is a code-block a decode skips
981 /// checked against the bit-plane limit, so it can succeed where the
982 /// whole decode is refused as [`Error::Limit`].
983 ///
984 /// For a codestream as it streams in: a prefix that holds every packet of
985 /// the resolutions a reduction keeps decodes at that reduction to the same
986 /// samples as the whole codestream, and the report's
987 /// [`complete_reduction`](DecodeReport::complete_reduction) says which
988 /// reduction that is. [`IncrementalDecoder`] decodes such prefixes for
989 /// you: each refine goes on from where the last one stopped reading
990 /// packets. The packets it reads again are listed in
991 /// [`docs/incremental-decoding.md`](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/incremental-decoding.md).
992 ///
993 /// ```
994 /// use rust_j2k::{DecodeOptions, Error, decode_with, read_header};
995 ///
996 /// # let bytes = include_bytes!(concat!(
997 /// # env!("CARGO_MANIFEST_DIR"),
998 /// # "/tests/fixtures/jpeg2000_regular_latlon.j2k"
999 /// # )).to_vec();
1000 /// # /*
1001 /// let bytes = std::fs::read("image.j2k")?;
1002 /// # */
1003 /// let prefix = &bytes[..bytes.len() - 20];
1004 /// // Strict, the default: a cut codestream is an error.
1005 /// assert!(matches!(
1006 /// decode_with(prefix, &DecodeOptions::default()),
1007 /// Err(Error::Codestream(_))
1008 /// ));
1009 /// // Not strict: the image, and what it lacks.
1010 /// let options = DecodeOptions::default().with_strict(false);
1011 /// let image = decode_with(prefix, &options).expect("decodes");
1012 /// assert!(!image.report.is_complete());
1013 /// // The coarsest level a decode may ask for, and the finest the data holds.
1014 /// let max = read_header(prefix).expect("the main header is there").max_reduction;
1015 /// if let Some(r) = image.report.complete_reduction.filter(|&r| r <= max) {
1016 /// let coarse = decode_with(prefix, &options.with_resolution_reduction(r)).expect("decodes");
1017 /// assert!(coarse.report.is_complete());
1018 /// }
1019 /// # Ok::<(), Box<dyn std::error::Error>>(())
1020 /// ```
1021 #[doc(alias = "allow_partial")]
1022 #[doc(alias = "allow-partial")]
1023 pub strict: bool,
1024}
1025
1026impl Default for DecodeOptions {
1027 /// Full resolution, every quality layer, the whole image, components as
1028 /// the file's boxes shape them, color as coded, the default limits, and strict.
1029 fn default() -> Self {
1030 DecodeOptions {
1031 resolution_reduction: 0,
1032 max_quality_layers: None,
1033 region: Region::Whole,
1034 components: None,
1035 raw_channels: false,
1036 color: ColorOutput::default(),
1037 packet_work_limit: WorkLimit::default(),
1038 code_block_work_limit: WorkLimit::default(),
1039 sample_limit: WorkLimit::default(),
1040 strict: true,
1041 }
1042 }
1043}
1044
1045/// How far a decode may go against one of its bounds: the
1046/// [`DecodeOptions::packet_work_limit`] and
1047/// [`DecodeOptions::code_block_work_limit`] work bounds, and the
1048/// [`DecodeOptions::sample_limit`] on the image's size.
1049///
1050/// Each work bound scales with the size of the file, so a small file cannot
1051/// ask for minutes of work, and the sample limit holds the memory a file may
1052/// ask for to about 2.7 GiB for a square tile, and to several GiB for a tall,
1053/// narrow one (see [the sample limit](https://github.com/D0ubleD0uble/rust-j2k/blob/v0.5.0/docs/resource-bounds.md#the-sample-limit)). A valid file can still go past
1054/// a bound, when it codes many samples in very few bytes or is very
1055/// large. The decode then fails with [`Error::Limit`]. Its
1056/// [`LimitDetail::kind`] names the option, and [`LimitDetail::retry_with`]
1057/// gives a [`Raised`](WorkLimit::Raised) factor, which the message names
1058/// too. Treat the factor as a hint, not a measure of the file:
1059///
1060/// - For the sample limit it is exact for the check it names: the image's
1061/// samples are known from its header. Palette expansion or sRGB output is
1062/// checked later, against the same limit, and may need a higher factor.
1063/// - For the code-block bound it is what the tiles seen so far need, exact
1064/// for a file of one tile.
1065/// - For the packet bound it is the next factor up from the one that failed
1066/// (or, when the refusal comes from a POC sequence's reach or a
1067/// reduction's dropped code-blocks, the factor that check needs), and the
1068/// file may need more: the walk stops as soon as it runs
1069/// out, so it does not know the total. Double `n` on each retry rather than
1070/// stepping by one: each retry costs more, and a file can need a factor of
1071/// dozens.
1072///
1073/// Which value to pick:
1074///
1075/// - For a file from a source you trust, use [`Unlimited`](WorkLimit::Unlimited).
1076/// The decode then takes as long as the file asks.
1077/// - To keep a ceiling, use `Raised(n)` with an `n` of your own choosing,
1078/// the largest cost you will accept. Read the factor from
1079/// [`LimitDetail::retry_with`] to size it, or let
1080/// [`DecodeOptions::with_retry`] set it: a file that needs `Raised(3)` is
1081/// refused under `Raised(2)`. Do not parse the message; it is a
1082/// diagnostic, not a stable format.
1083///
1084/// Only these three limits can be changed. The other guards also end in
1085/// [`Error::Limit`], and no option here raises them (see [`Error::Limit`]).
1086/// A damaged file can hit a guard too, so do not lift a bound on that
1087/// evidence alone.
1088///
1089/// ```
1090/// use rust_j2k::{DecodeOptions, Error, WorkLimit, decode, decode_with};
1091///
1092/// // A file that asks for far more work than its size allows.
1093/// # let bytes = include_bytes!(concat!(
1094/// # env!("CARGO_MANIFEST_DIR"),
1095/// # "/tests/fixtures/tier1_work_bound/t1bomb_1024_64_88.j2k"
1096/// # )).to_vec();
1097/// # /*
1098/// let bytes = std::fs::read("image.j2k")?;
1099/// # */
1100/// let image = match decode(&bytes) {
1101/// // The example fails if the bomb is ever admitted by default.
1102/// Ok(_) => panic!("expected the work bound to refuse this file"),
1103/// // Past a limit. `limit.kind()` says which, and `limit.retry_with()`
1104/// // the factor.
1105/// Err(Error::Limit(limit)) => {
1106/// println!("refused: {limit}");
1107/// // The file is trusted here, so lift all three limits. To keep a
1108/// // ceiling, use `WorkLimit::Raised(n)` for the one named instead.
1109/// let options = DecodeOptions::default()
1110/// .with_sample_limit(WorkLimit::Unlimited)
1111/// .with_code_block_work_limit(WorkLimit::Unlimited)
1112/// .with_packet_work_limit(WorkLimit::Unlimited);
1113/// decode_with(&bytes, &options).expect("a valid file decodes once the limits are lifted")
1114/// }
1115/// Err(e) => panic!("not a work-bound failure: {e}"),
1116/// };
1117/// assert_eq!((image.width, image.height), (1024, 1024));
1118/// # Ok::<(), Box<dyn std::error::Error>>(())
1119/// ```
1120#[derive(Debug, Clone, Default, PartialEq, Eq)]
1121#[non_exhaustive]
1122pub enum WorkLimit {
1123 /// The bound as [`decode`] describes it.
1124 #[default]
1125 Default,
1126 /// The default bound times this factor: for a work bound, both its floor
1127 /// and the work it allows per byte. `Raised(1)` sets the same bound as
1128 /// `Default`, though the two do not compare equal. `Raised(0)` is
1129 /// [`Error::InvalidOptions`].
1130 Raised(u32),
1131 /// No bound. For a work bound, the decode does all the work the file
1132 /// asks for, however long that takes; for the sample limit, it allocates
1133 /// all the memory the file asks for (see [`DecodeOptions::sample_limit`]).
1134 /// The other two limits keep their own settings, and the guards with no
1135 /// option (listed on [`Error::Limit`]) stay in force.
1136 Unlimited,
1137}
1138
1139impl WorkLimit {
1140 /// The bound this limit sets, from the default bound `bound`.
1141 pub(crate) fn apply(&self, bound: u64) -> u64 {
1142 match self {
1143 WorkLimit::Default => bound,
1144 WorkLimit::Raised(factor) => bound.saturating_mul(u64::from(*factor)),
1145 WorkLimit::Unlimited => u64::MAX,
1146 }
1147 }
1148}
1149
1150impl DecodeOptions {
1151 /// These options with
1152 /// [`resolution_reduction`](Self::resolution_reduction) set to `levels`.
1153 ///
1154 /// ```
1155 /// use rust_j2k::DecodeOptions;
1156 ///
1157 /// let options = DecodeOptions::default().with_resolution_reduction(1);
1158 /// assert_eq!(options.resolution_reduction, 1);
1159 /// ```
1160 #[must_use]
1161 pub fn with_resolution_reduction(mut self, levels: u8) -> Self {
1162 self.resolution_reduction = levels;
1163 self
1164 }
1165
1166 /// These options with
1167 /// [`max_quality_layers`](Self::max_quality_layers) set to `layers`.
1168 /// [`Header::quality_layers`](crate::Header::quality_layers) is how many
1169 /// layers the main header declares.
1170 ///
1171 /// ```
1172 /// use rust_j2k::DecodeOptions;
1173 ///
1174 /// let options = DecodeOptions::default().with_max_quality_layers(Some(2));
1175 /// assert_eq!(options.max_quality_layers, Some(2));
1176 /// ```
1177 #[must_use]
1178 pub fn with_max_quality_layers(mut self, layers: Option<u16>) -> Self {
1179 self.max_quality_layers = layers;
1180 self
1181 }
1182
1183 /// These options with [`region`](Self::region) set to `region`.
1184 ///
1185 /// ```
1186 /// use rust_j2k::{DecodeOptions, Region, Window};
1187 ///
1188 /// let options = DecodeOptions::default().with_region(Region::Tile(3));
1189 /// assert_eq!(options.region, Region::Tile(3));
1190 /// let window = Region::Window(Window::new(0, 0, 64, 64));
1191 /// assert_eq!(DecodeOptions::default().with_region(window.clone()).region, window);
1192 /// ```
1193 #[must_use]
1194 pub fn with_region(mut self, region: Region) -> Self {
1195 self.region = region;
1196 self
1197 }
1198
1199 /// These options with [`components`](Self::components) set to
1200 /// `components`.
1201 ///
1202 /// ```
1203 /// use rust_j2k::DecodeOptions;
1204 ///
1205 /// let options = DecodeOptions::default().with_components(Some(vec![0]));
1206 /// assert_eq!(options.components, Some(vec![0]));
1207 /// ```
1208 #[must_use]
1209 pub fn with_components(mut self, components: Option<Vec<u16>>) -> Self {
1210 self.components = components;
1211 self
1212 }
1213
1214 /// These options with [`raw_channels`](Self::raw_channels) set to `raw`.
1215 ///
1216 /// ```
1217 /// use rust_j2k::DecodeOptions;
1218 ///
1219 /// let options = DecodeOptions::default().with_raw_channels(true);
1220 /// assert!(options.raw_channels);
1221 /// ```
1222 #[must_use]
1223 pub fn with_raw_channels(mut self, raw: bool) -> Self {
1224 self.raw_channels = raw;
1225 self
1226 }
1227
1228 /// These options with [`color`](Self::color) set to `color`.
1229 ///
1230 /// ```
1231 /// use rust_j2k::{ColorOutput, DecodeOptions};
1232 ///
1233 /// let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
1234 /// assert_eq!(options.color, ColorOutput::Srgb);
1235 /// ```
1236 #[must_use]
1237 #[doc(alias = "with_colour")]
1238 pub fn with_color(mut self, color: ColorOutput) -> Self {
1239 self.color = color;
1240 self
1241 }
1242
1243 /// These options with [`packet_work_limit`](Self::packet_work_limit)
1244 /// set to `limit`.
1245 ///
1246 /// ```
1247 /// use rust_j2k::{DecodeOptions, WorkLimit};
1248 ///
1249 /// let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(4));
1250 /// assert_eq!(options.packet_work_limit, WorkLimit::Raised(4));
1251 /// ```
1252 #[must_use]
1253 pub fn with_packet_work_limit(mut self, limit: WorkLimit) -> Self {
1254 self.packet_work_limit = limit;
1255 self
1256 }
1257
1258 /// These options with
1259 /// [`code_block_work_limit`](Self::code_block_work_limit) set to `limit`.
1260 ///
1261 /// ```
1262 /// use rust_j2k::{DecodeOptions, WorkLimit};
1263 ///
1264 /// let options = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
1265 /// assert_eq!(options.code_block_work_limit, WorkLimit::Unlimited);
1266 /// ```
1267 #[must_use]
1268 pub fn with_code_block_work_limit(mut self, limit: WorkLimit) -> Self {
1269 self.code_block_work_limit = limit;
1270 self
1271 }
1272
1273 /// These options with [`sample_limit`](Self::sample_limit) set to
1274 /// `limit`.
1275 ///
1276 /// ```
1277 /// use rust_j2k::{DecodeOptions, WorkLimit};
1278 ///
1279 /// // Up to 3 x 2^29 samples, enough for a 20000 x 20000 RGB image.
1280 /// let options = DecodeOptions::default().with_sample_limit(WorkLimit::Raised(3));
1281 /// assert_eq!(options.sample_limit, WorkLimit::Raised(3));
1282 /// ```
1283 #[must_use]
1284 pub fn with_sample_limit(mut self, limit: WorkLimit) -> Self {
1285 self.sample_limit = limit;
1286 self
1287 }
1288
1289 /// These options with the limit that refused a decode set to the one
1290 /// it gave to retry with, or `None` if no option raises it or the
1291 /// refusal gave none ([`LimitDetail::retry_with`]).
1292 ///
1293 /// ```
1294 /// use rust_j2k::{DecodeOptions, Error, WorkLimit, decode};
1295 ///
1296 /// // A file that asks for far more work than its size allows.
1297 /// # let bytes = include_bytes!(concat!(
1298 /// # env!("CARGO_MANIFEST_DIR"),
1299 /// # "/tests/fixtures/tier1_work_bound/t1bomb_1024_64_88.j2k"
1300 /// # )).to_vec();
1301 /// # /*
1302 /// let bytes = std::fs::read("image.j2k")?;
1303 /// # */
1304 /// let Err(Error::Limit(limit)) = decode(&bytes) else { panic!() };
1305 /// let options = DecodeOptions::default().with_retry(&limit).unwrap();
1306 /// assert_eq!(options.code_block_work_limit, WorkLimit::Raised(2));
1307 /// # Ok::<(), Box<dyn std::error::Error>>(())
1308 /// ```
1309 #[must_use]
1310 pub fn with_retry(&self, limit: &LimitDetail) -> Option<Self> {
1311 let retry = limit.retry_with()?;
1312 let options = self.clone();
1313 match limit.kind() {
1314 LimitKind::Samples => Some(options.with_sample_limit(retry)),
1315 LimitKind::PacketWork => Some(options.with_packet_work_limit(retry)),
1316 LimitKind::CodeBlockWork => Some(options.with_code_block_work_limit(retry)),
1317 _ => None,
1318 }
1319 }
1320
1321 /// These options with [`strict`](Self::strict) set to `strict`.
1322 ///
1323 /// ```
1324 /// use rust_j2k::DecodeOptions;
1325 ///
1326 /// assert!(DecodeOptions::default().strict);
1327 /// let options = DecodeOptions::default().with_strict(false);
1328 /// assert!(!options.strict);
1329 /// ```
1330 #[must_use]
1331 #[doc(alias = "allow_partial")]
1332 pub fn with_strict(mut self, strict: bool) -> Self {
1333 self.strict = strict;
1334 self
1335 }
1336}
1337
1338/// Decode a JPEG 2000 codestream or JP2 file like [`decode`], governed by
1339/// `options`.
1340///
1341/// Every [`DecodeOptions`] field is set with a `with_*` method. This reads
1342/// a JP2 file at half size and converts it to sRGB:
1343///
1344/// ```
1345/// use rust_j2k::{ColorOutput, DecodeOptions, Error, decode_with};
1346///
1347/// # let bytes = include_bytes!(concat!(
1348/// # env!("CARGO_MANIFEST_DIR"),
1349/// # "/tests/fixtures/jp2_cdef_rgba.jp2"
1350/// # )).to_vec();
1351/// # /*
1352/// let bytes = std::fs::read("image.jp2")?;
1353/// # */
1354/// let options = DecodeOptions::default()
1355/// .with_resolution_reduction(1)
1356/// .with_color(ColorOutput::Srgb);
1357/// match decode_with(&bytes, &options) {
1358/// Ok(image) => {
1359/// // For a 16x12 file, one level discarded halves each side.
1360/// assert_eq!((image.width, image.height), (8, 6));
1361/// // Red, green, blue and opacity.
1362/// assert_eq!(image.components.len(), 4);
1363/// }
1364/// // Options that contradict each other or do not fit the file (a
1365/// // reduction past its levels, `raw_channels` with sRGB output), or a
1366/// // file the conversion cannot handle (`Unsupported`), are handled
1367/// // here in real code. This file is fine, so they fail the example.
1368/// Err(Error::InvalidOptions(why) | Error::Unsupported(why)) => panic!("{why}"),
1369/// Err(e) => panic!("decode failed: {e}"),
1370/// }
1371/// # Ok::<(), Box<dyn std::error::Error>>(())
1372/// ```
1373///
1374/// Failures are the same [`Error`] variants as [`decode`], plus
1375/// [`Error::InvalidOptions`] for options that are invalid on their own
1376/// ([`WorkLimit::Raised`]`(0)`, a [`max_quality_layers`](DecodeOptions::max_quality_layers)
1377/// of `Some(0)`), contradict each other, or do not fit the file.
1378pub fn decode_with(bytes: &[u8], options: &DecodeOptions) -> Result<Image> {
1379 decode_metered(bytes, options, None)
1380}
1381
1382/// [`decode_with`], with the code-block work also held to what `ledger`
1383/// has left of its bound, and the packet walks with `strict` off kept on
1384/// it, when there is one (see [`incremental::Ledger`]).
1385fn decode_metered(
1386 bytes: &[u8],
1387 options: &DecodeOptions,
1388 ledger: Option<&incremental::Ledger>,
1389) -> Result<Image> {
1390 check_options(options)?;
1391 // A codestream opens with SOC; anything else that carries the signature
1392 // box's type is read as a JP2 file, so a damaged signature box is reported
1393 // as a box fault. The rest falls to the codestream parser, which reports
1394 // the missing SOC.
1395 if !bytes.starts_with(&[0xFF, 0x4F]) && jp2::looks_like_jp2(bytes) {
1396 return decode_jp2(bytes, options, ledger);
1397 }
1398 // The header checks come before the tile walk, as `read_header_with` has it.
1399 let parsed = codestream::parse_header(bytes)?;
1400 let selection = window::select(&parsed.header.siz, options);
1401 if let Ok(selection) = &selection {
1402 samples::check_read(
1403 &parsed.header.siz,
1404 selection,
1405 options.resolution_reduction,
1406 samples::cap(&options.sample_limit),
1407 )?;
1408 }
1409 check_raw_color(options, parsed.header.siz.components.len())?;
1410 check_reduction(&parsed.header, options.resolution_reduction, None)?;
1411 let selection = selection?;
1412 let cs = codestream::parse_tiles_with(bytes, parsed, options.strict)?;
1413 decode_codestream(cs, options, &selection, ledger)
1414}
1415
1416/// Options that contradict each other, whatever the input.
1417fn check_options(options: &DecodeOptions) -> Result<()> {
1418 if options.color == ColorOutput::Srgb && options.raw_channels {
1419 return Err(Error::invalid_options(
1420 "`raw_channels` returns the channels as coded, so it cannot be combined with \
1421 `ColorOutput::Srgb`",
1422 ));
1423 }
1424 for (name, limit) in [
1425 ("packet_work_limit", &options.packet_work_limit),
1426 ("code_block_work_limit", &options.code_block_work_limit),
1427 ("sample_limit", &options.sample_limit),
1428 ] {
1429 if *limit == WorkLimit::Raised(0) {
1430 return Err(Error::invalid_options(format!(
1431 "`DecodeOptions::{name}` is `WorkLimit::Raised(0)`, but the factor must be \
1432 at least 1"
1433 )));
1434 }
1435 }
1436 if options.max_quality_layers == Some(0) {
1437 return Err(Error::invalid_options(
1438 "`DecodeOptions::max_quality_layers` is `Some(0)`, but a decode keeps at least \
1439 one layer",
1440 ));
1441 }
1442 window::check_options(options)
1443}
1444
1445/// A reduction must leave every component a resolution to decode, checked
1446/// against each component's own decomposition count: a COC can give one
1447/// component a shallower pyramid than the rest (p0_08 does exactly that).
1448/// `decode_with` and `read_header_with` make this check against the main header
1449/// (COD and COC) before any tile is read, with `tile` of `None`. A tile-part COD
1450/// or COC with fewer levels is only found while decoding, where the same test
1451/// runs per tile with that tile's index.
1452fn check_reduction(
1453 header: &codestream::MainHeader,
1454 reduction: u8,
1455 tile: Option<usize>,
1456) -> Result<()> {
1457 for (component, params) in header.components.iter().enumerate() {
1458 let resolutions = u32::from(params.coding.decomposition_levels) + 1;
1459 if u32::from(reduction) >= resolutions {
1460 let place = tile.map_or_else(String::new, |index| format!(" in tile {index}"));
1461 return Err(Error::invalid_options(format!(
1462 "resolution reduction {reduction} discards all {resolutions} resolutions \
1463 of component {component}{place}"
1464 )));
1465 }
1466 }
1467 Ok(())
1468}
1469
1470/// A raw codestream declares no color space. Like OpenJPEG, one or two
1471/// components are read as gray (and gray plus opacity) and pass through; three
1472/// or more have nothing to convert from, so sRGB output refuses them.
1473fn check_raw_color(options: &DecodeOptions, components: usize) -> Result<()> {
1474 if options.color == ColorOutput::Srgb && components > 2 {
1475 return Err(Error::unsupported(format!(
1476 "sRGB output from a raw codestream of {components} components, which declares \
1477 no color space"
1478 )));
1479 }
1480 Ok(())
1481}
1482
1483/// A JP2 file read up to its tile data: the boxes, the codestream's main
1484/// header, the channel plans and the metadata. Everything here is checked
1485/// before any tile is read, so [`read_header`] and [`decode`] share it and
1486/// report a header fault the same way.
1487struct Jp2Prefix<'a> {
1488 codestream: &'a [u8],
1489 parsed: codestream::ParsedHeader,
1490 plans: jp2::ChannelPlans,
1491 metadata: Jp2Metadata,
1492 /// The sRGB step, when the caller asked for it.
1493 srgb: Option<jp2::SrgbPlan>,
1494 /// The area and components the decode returns.
1495 selection: window::Selection,
1496}
1497
1498/// Read a JP2 file up to its tile data, in OpenJPEG's order: the box walk,
1499/// the codestream's main header, `ihdr` against SIZ, then the channel plans.
1500/// The header boxes after the codestream, which OpenJPEG reads again once it
1501/// has decoded, are checked next, then the sRGB step is planned; all of it
1502/// before any tile is read.
1503fn read_jp2_prefix<'a>(bytes: &'a [u8], options: &DecodeOptions) -> Result<Jp2Prefix<'a>> {
1504 let file = jp2::parse(bytes, &options.packet_work_limit)?;
1505 let parsed = codestream::parse_header(file.codestream)?;
1506 let siz = &parsed.header.siz;
1507 let cap = samples::cap(&options.sample_limit);
1508 let selection = window::select(siz, options);
1509 if let Ok(selection) = &selection {
1510 samples::check_read(siz, selection, options.resolution_reduction, cap)?;
1511 }
1512 jp2::check_against_siz(&file.header, siz)?;
1513 // A component subset names codestream components, which come out as
1514 // coded: OpenJPEG bypasses the JP2 channel transforms under `-c`.
1515 let raw_channels = options.raw_channels || options.components.is_some();
1516 // A palette expands the area the decode returns. A refused selection has
1517 // no area, so the plan counts nothing: its other faults are found at the
1518 // same place whatever the image's size, and the selection's refusal
1519 // follows them.
1520 let plan_cap = if selection.is_ok() { cap } else { u64::MAX };
1521 let plans = jp2::ChannelPlans::plan(
1522 &file.header,
1523 selection.as_ref().map_or(siz, |selection| &selection.area),
1524 options.resolution_reduction,
1525 plan_cap,
1526 raw_channels,
1527 jp2::is_jph(&file.file_type),
1528 )?;
1529 jp2::check_after_codestream(&file, raw_channels)?;
1530 let mut metadata = jp2::metadata(&file, &plans, siz)?;
1531 let selection = selection?;
1532 if selection.subset {
1533 metadata.channels = pick(metadata.channels, &selection.order);
1534 }
1535 let srgb = match options.color {
1536 ColorOutput::AsCoded => None,
1537 ColorOutput::Srgb => {
1538 let plan = jp2::plan_srgb(
1539 &metadata,
1540 &plans,
1541 &selection.area,
1542 options.resolution_reduction,
1543 cap,
1544 )?;
1545 // Chroma replication keys on the parity of the area's origin on
1546 // the reference grid (the full-resolution one, whatever the
1547 // reduction), so on part of the image it would not give the crop
1548 // of the whole image's conversion. An area equal to the image
1549 // (a window clipped to it, or the only tile) is the whole image.
1550 if plan.replicates_chroma() && selection.area.image_rect() != siz.image_rect() {
1551 return Err(Error::unsupported(
1552 "sRGB output from sub-sampled sYCC chroma on an area smaller than the \
1553 image, under `DecodeOptions::region`",
1554 ));
1555 }
1556 // A converted image is sRGB (or gray) and carries no profile, as
1557 // OpenJPEG reports it.
1558 plan.describe(&mut metadata);
1559 Some(plan)
1560 }
1561 };
1562 check_reduction(&parsed.header, options.resolution_reduction, None)?;
1563 Ok(Jp2Prefix {
1564 codestream: file.codestream,
1565 parsed,
1566 plans,
1567 metadata,
1568 srgb,
1569 selection,
1570 })
1571}
1572
1573/// Decode a JP2 file: read it up to its tile data, decode the codestream,
1574/// and apply the channel plans, then any sRGB step, to the samples.
1575fn decode_jp2(
1576 bytes: &[u8],
1577 options: &DecodeOptions,
1578 ledger: Option<&incremental::Ledger>,
1579) -> Result<Image> {
1580 let prefix = read_jp2_prefix(bytes, options)?;
1581 let cs = codestream::parse_tiles_with(prefix.codestream, prefix.parsed, options.strict)?;
1582 let image = decode_codestream(cs, options, &prefix.selection, ledger)?;
1583 // A subset is planned raw, so the plans would pass it through, but they
1584 // are planned for every component.
1585 let mut components = if prefix.selection.subset {
1586 image.components
1587 } else {
1588 prefix.plans.apply(image.components)?
1589 };
1590 if let Some(srgb) = &prefix.srgb {
1591 components = srgb.apply(components)?;
1592 }
1593 Ok(Image {
1594 components,
1595 jp2: Some(prefix.metadata),
1596 ..image
1597 })
1598}
1599
1600/// Decode a parsed codestream into the area and components `selection`
1601/// names.
1602fn decode_codestream(
1603 cs: codestream::Codestream<'_>,
1604 options: &DecodeOptions,
1605 selection: &window::Selection,
1606 ledger: Option<&incremental::Ledger>,
1607) -> Result<Image> {
1608 let reduction = options.resolution_reduction;
1609 let layers = options.max_quality_layers;
1610
1611 // Each tile is a whole decode of its own: its own header, its own packets,
1612 // its own wavelet pyramid in its own coordinate frame. Nothing crosses a
1613 // tile boundary — that is what tiling is for — so the tiles meet only at the
1614 // end, when each writes its rectangle of the canvas. A window keeps the
1615 // part of each tile inside it, and the tiles with no part inside it are
1616 // not decoded.
1617 let mut canvas = image::Canvas::over(&cs.header, &selection.area, reduction, &selection.order)?;
1618 let reads = selection.tiles(&cs.header.siz);
1619 // Whether the decode returns less than the image, so a tile may need
1620 // only part of its samples.
1621 let windowed = selection.area.image_rect() != cs.header.siz.image_rect();
1622 // One work bound for every tile's packet walk, and one for every tile's
1623 // code-blocks, in proportion to the tiles' data, so that many small
1624 // tiles cannot each spend a floor's worth. A POC sequence's bitmap stays
1625 // within the default bound however far the caller raises it.
1626 let bytes = tile_bytes(&cs);
1627 let poc_bitmap = tier2::decode_visits(bytes);
1628 let packet_bound = options.packet_work_limit.apply(poc_bitmap);
1629 // The walk is not cut by what earlier decodes of an incremental decoder
1630 // spent: those decodes' walks are kept, and this one goes on from them,
1631 // so that what they all spend is what one walk spends (see
1632 // [`incremental::Ledger`]).
1633 let meter = tier2::Meter::new(packet_bound);
1634 let mut block_work = match &options.code_block_work_limit {
1635 WorkLimit::Unlimited => None,
1636 limit => {
1637 let bound = limit.apply(tier1::decode_work(bytes));
1638 Some(ledger.map_or(bound, |l| l.blocks_left(bound)))
1639 }
1640 };
1641 let first_work = block_work.unwrap_or(0);
1642 // Not strict: what the codestream walk found missing, then each tile's
1643 // packets, and the smallest reduction every tile is complete at so far.
1644 let mut entries = window::keep_entries(cs.entries.clone(), &reads);
1645 let mut complete = Some(0u8);
1646 // A missing tile reads no packet, but setting its samples to 0 visits
1647 // each of its tile-components, and a header of a few kilobytes can
1648 // declare 65535 tiles of 16384 components with none of them present. So
1649 // each tile-component of a missing tile costs a visit, charged here,
1650 // before any tile is decoded.
1651 let missing: u64 = entries
1652 .iter()
1653 .filter_map(|entry| match entry {
1654 ReportEntry::MissingTiles { tiles } => Some(u64::from(tiles.end - tiles.start)),
1655 _ => None,
1656 })
1657 .sum();
1658 let cost = missing.saturating_mul(cs.header.siz.components.len() as u64);
1659 if !meter.try_spend(cost) {
1660 if let Some(ledger) = ledger {
1661 ledger.refuse();
1662 }
1663 return Err(limit_hint::missing_tiles(cost, meter.first(), poc_bitmap));
1664 }
1665 for (position, tile) in cs.tiles.iter().enumerate() {
1666 // `tiles` holds every tile when strict, so `index` is also its
1667 // position; not strict, a missing tile is left out.
1668 let index = tile.index as usize;
1669 if !reads.get(index).copied().unwrap_or(false) {
1670 continue;
1671 }
1672 // The tile's own parameters: the main header with this tile's tile-part
1673 // header resolved over it. A tile with no markers of its own borrows the
1674 // main header; any other is a copy, sized by the component count, held
1675 // for this tile alone, as a codestream can declare tens of thousands.
1676 // That copy is paid for by the geometry the packet walk then builds for
1677 // every component, whether or not the tile's data runs out; a tile
1678 // with no data at all is not resolved. So the copies stay within
1679 // `tiles × components`, which SIZ's rule that no tile-component is
1680 // empty holds to the image's samples (under a window or a tile, the
1681 // samples of the tiles read), with `strict` off as with it on.
1682 let header = cs.tile_header(position)?;
1683
1684 // A tile COD can give one tile a shallower pyramid than the rest, so
1685 // the reduction is checked per tile, not once for the image.
1686 check_reduction(&header, reduction, Some(index))?;
1687
1688 // Tier-2: parse packets into per-code-block coded segments, per
1689 // component. The walk covers every resolution and layer whatever the
1690 // reduction and layer cap: packet order is the codestream's framing,
1691 // so the dropped levels' and layers' packets must still be stepped
1692 // over to reach the kept ones.
1693 let walked = if options.strict {
1694 tier2::decode_packets_metered(&header, tile, &meter, poc_bitmap, reduction, layers)
1695 .map(|coded| (coded, None))
1696 } else if let Some(ledger) = ledger {
1697 ledger
1698 .walk(
1699 &header,
1700 tile,
1701 &meter,
1702 poc_bitmap,
1703 reduction,
1704 layers,
1705 canvas.bytes(),
1706 )
1707 .map(|(coded, reach)| (coded, Some(reach)))
1708 } else {
1709 tier2::decode_packets_partial(&header, tile, &meter, poc_bitmap, reduction, layers)
1710 .map(|(coded, reach)| (coded, Some(reach)))
1711 };
1712 let (mut coded, reach) = match walked {
1713 Ok(walked) => walked,
1714 Err(tier2::Refused::Work(work)) => {
1715 if let Some(ledger) = ledger {
1716 ledger.refuse();
1717 }
1718 // The meter holds what is left after the refusal, so this
1719 // counts this tile's charges before it as well as the
1720 // earlier tiles'.
1721 return Err(limit_hint::packet(
1722 work,
1723 index,
1724 meter.spent(),
1725 meter.first(),
1726 poc_bitmap,
1727 ));
1728 }
1729 Err(tier2::Refused::Other(error)) => return Err(error),
1730 };
1731 // The components to reconstruct: those the decode returns, and with
1732 // them the rest of the color transform's three, which each need all
1733 // of them. It is a per-tile transform: the flag lives in COD, which a
1734 // tile-part header can override. On an image of fewer than three
1735 // components the flag is ignored, as OpenJPEG ignores it
1736 // (`mct::applies`).
1737 let mct = mct::applies(
1738 header.cod.multiple_component_transform,
1739 header.components.len(),
1740 );
1741 let mut wanted: Vec<bool> = (0..header.components.len())
1742 .map(|c| canvas.keeps(c))
1743 .collect();
1744 if mct && wanted[..3].contains(&true) {
1745 wanted[..3].fill(true);
1746 }
1747
1748 // Under a window, each component reconstructed needs only the samples
1749 // whose wavelet support reaches the window: its footprint. `None`
1750 // where the window covers the whole tile-component.
1751 let footprints = coded
1752 .components
1753 .iter()
1754 .enumerate()
1755 .map(|(component, coded)| {
1756 if !windowed || !wanted[component] {
1757 return Ok(None);
1758 }
1759 footprint_of(
1760 &cs.header, &header, selection, tile, coded, component, reduction,
1761 )
1762 })
1763 .collect::<Result<Vec<_>>>()?;
1764 if let Some(reach) = reach {
1765 // The whole image, or a whole tile of it, is reported by packet;
1766 // a part of it by the code-blocks that part needs. Whether the
1767 // window covers the tile is judged at full resolution, so that
1768 // the report is the same at every reduction.
1769 let covers = |component: usize| {
1770 let rect = cs.header.siz.tile_component_rect(tile.index, component);
1771 let area = selection.area.component_rect(component);
1772 matches!((rect, area), (Some(rect), Some(area)) if area.intersect(&rect) == rect)
1773 };
1774 let part = wanted.contains(&false)
1775 || (windowed && (0..wanted.len()).any(|component| !covers(component)));
1776 let tile_complete = if part {
1777 let footprint_at = |component: usize, r: u8| {
1778 if r == reduction {
1779 return Ok(footprints[component].clone());
1780 }
1781 footprint_of(
1782 &cs.header,
1783 &header,
1784 selection,
1785 tile,
1786 &coded.components[component],
1787 component,
1788 r,
1789 )
1790 };
1791 let scope = Scope {
1792 coded: &coded,
1793 wanted: &wanted,
1794 windowed,
1795 footprint_at,
1796 };
1797 report_part(
1798 &header,
1799 tile,
1800 &reach,
1801 &scope,
1802 reduction,
1803 layers,
1804 &mut entries,
1805 )?
1806 } else {
1807 report_tile(&header, tile, &reach, reduction, layers, &mut entries)
1808 };
1809 complete = complete.zip(tile_complete).map(|(a, b)| a.max(b));
1810 }
1811 for (coded, footprint) in coded.components.iter_mut().zip(&footprints) {
1812 if let Some(footprint) = footprint {
1813 footprint.prune(coded);
1814 }
1815 }
1816
1817 // Tier-1: the block coder (EBCOT or HT) decodes each code block into
1818 // subband coeffs. The dropped resolutions' code-blocks are skipped, never
1819 // decoded, and so are those of the components not reconstructed and
1820 // those outside a footprint. Their work is counted first, so a tile
1821 // past the bound is refused before any of it is done.
1822 if let Some(left) = &mut block_work {
1823 let work = tier1::work(&header, &coded, reduction, &wanted);
1824 #[cfg(test)]
1825 tests::BLOCK_WORK.with(|spent| spent.set(spent.get() + work));
1826 let Some(rest) = left.checked_sub(work) else {
1827 if let Some(ledger) = ledger {
1828 ledger.refuse();
1829 }
1830 return Err(limit_hint::code_blocks(
1831 index,
1832 work,
1833 *left,
1834 first_work.saturating_sub(*left),
1835 tier1::decode_work(bytes),
1836 ));
1837 };
1838 *left = rest;
1839 if let Some(ledger) = ledger {
1840 ledger.spend_blocks(work);
1841 }
1842 }
1843 #[cfg(test)]
1844 tests::BLOCKS
1845 .with(|count| count.set(count.get() + tests::blocks(&coded, reduction, &wanted)));
1846 let coeffs = tier1::decode_code_blocks(&header, &coded, reduction, &wanted)?;
1847
1848 // Invert the DWT per resolution level into samples, over the whole
1849 // tile-component or over its footprint. Tier-1 has already
1850 // dequantized the 9/7 coefficients as it placed each block.
1851 let mut samples = coeffs
1852 .into_iter()
1853 .zip(&footprints)
1854 .enumerate()
1855 .map(|(component, (coeffs, footprint))| {
1856 coeffs
1857 .map(|coeffs| match footprint {
1858 Some(footprint) => dwt::inverse_window(coeffs, footprint),
1859 None => dwt::inverse(&header, component, coeffs),
1860 })
1861 .transpose()
1862 })
1863 .collect::<Result<Vec<_>>>()?;
1864
1865 // Undo the inter-component decorrelation, if any, before the DC level
1866 // shift (ISO/IEC 15444-1 G.1). Components past the third are
1867 // untouched.
1868 if mct && wanted[0] {
1869 let mut triple = samples[..3]
1870 .iter_mut()
1871 .map(Option::take)
1872 .collect::<Option<Vec<_>>>()
1873 .ok_or_else(|| {
1874 Error::inconsistent(
1875 "the color transform's three components were not all reconstructed",
1876 )
1877 })?;
1878 // The wavelet picks the transform (G.1): 5/3 reconstructs integers
1879 // and inverts with the reversible RCT, 9/7 reconstructs floats and
1880 // inverts with the irreversible ICT. All three color components
1881 // share the wavelet (checked at parse), so component 0's decides.
1882 match header.components[0].coding.transform {
1883 codestream::markers::Transform::Reversible53 => mct::inverse_rct(&mut triple)?,
1884 codestream::markers::Transform::Irreversible97 => mct::inverse_ict(&mut triple)?,
1885 }
1886 for (slot, plane) in samples.iter_mut().zip(triple) {
1887 *slot = Some(plane);
1888 }
1889 }
1890
1891 for (component, samples) in samples.into_iter().enumerate() {
1892 let Some(samples) = samples else {
1893 continue;
1894 };
1895 let rect = cs
1896 .header
1897 .siz
1898 .tile_component_rect(tile.index, component)
1899 .ok_or_else(|| {
1900 Error::inconsistent(format!(
1901 "no tile {} or no component {component} in `SIZ`",
1902 tile.index
1903 ))
1904 })?;
1905 let rect = match footprints.get(component) {
1906 Some(Some(footprint)) => footprint.rect(),
1907 _ => rect.reduced(reduction),
1908 };
1909 canvas.place(component, rect, samples)?;
1910 }
1911 }
1912
1913 let mut image = image::assemble_over(
1914 &selection.area,
1915 canvas.into_planes(),
1916 &selection.order,
1917 reduction,
1918 )?;
1919 if !options.strict {
1920 for entry in &entries {
1921 if let ReportEntry::MissingTiles { tiles } = entry {
1922 complete = None;
1923 for tile in tiles.clone() {
1924 image::zero_tile(
1925 &mut image,
1926 &cs.header.siz,
1927 &selection.area,
1928 &selection.order,
1929 tile,
1930 reduction,
1931 );
1932 }
1933 }
1934 }
1935 image.report = DecodeReport::new(entries, complete, reduction);
1936 }
1937 Ok(image)
1938}
1939
1940/// The footprint of `selection`'s area on `component` of `tile`, whose
1941/// coded data is `coded`, at `reduction` (see [`dwt::Footprint::of`]).
1942/// `main` is the main header, `header` the tile's.
1943fn footprint_of(
1944 main: &codestream::MainHeader,
1945 header: &codestream::MainHeader,
1946 selection: &window::Selection,
1947 tile: &codestream::Tile<'_>,
1948 coded: &tier2::ComponentCoded<'_>,
1949 component: usize,
1950 reduction: u8,
1951) -> Result<Option<dwt::Footprint>> {
1952 let rect = main.siz.tile_component_rect(tile.index, component);
1953 let area = selection.area.component_rect(component);
1954 let transform = header.components.get(component).map(|c| c.coding.transform);
1955 let (Some(rect), Some(area), Some(transform)) = (rect, area, transform) else {
1956 return Err(Error::inconsistent(format!(
1957 "no tile {} or no component {component} in `SIZ`",
1958 tile.index
1959 )));
1960 };
1961 dwt::Footprint::of(
1962 coded,
1963 reduction,
1964 rect.reduced(reduction),
1965 area.reduced(reduction),
1966 transform,
1967 )
1968}
1969
1970/// The part of a tile a decode returns, for [`report_part`].
1971struct Scope<'s, 'a, F> {
1972 /// The tile's coded data.
1973 coded: &'s tier2::CodedData<'a>,
1974 /// The components reconstructed.
1975 wanted: &'s [bool],
1976 /// Whether the decode returns less than the image.
1977 windowed: bool,
1978 /// The footprint of the window on a component at a reduction: `None`
1979 /// when the window needs all of its code-blocks. Asked only when
1980 /// `windowed`.
1981 footprint_at: F,
1982}
1983
1984/// [`report_tile`] for a decode that returns part of `tile`: only the
1985/// components `scope` reconstructs count, and of them only the code-blocks
1986/// the window needs. A missing packet whose code-blocks the samples do not
1987/// need is not missing from them.
1988///
1989/// The smallest complete reduction is the smallest `r` at which, and at
1990/// every larger one the tile allows, no needed code-block lacks a packet.
1991/// The window needs other code-blocks at each reduction, so each is
1992/// checked, over the code-blocks with a packet missing and the components
1993/// that hold them: at most one pass over them per resolution. A tile whose
1994/// data ended has paid the packet work bound for each of its components'
1995/// resolutions, which bounds that.
1996fn report_part<F>(
1997 header: &codestream::MainHeader,
1998 tile: &codestream::Tile<'_>,
1999 reach: &tier2::Reach,
2000 scope: &Scope<'_, '_, F>,
2001 reduction: u8,
2002 cap: Option<u16>,
2003 entries: &mut Vec<ReportEntry>,
2004) -> Result<Option<u8>>
2005where
2006 F: Fn(usize, u8) -> Result<Option<dwt::Footprint>>,
2007{
2008 let layers = u32::from(cap.map_or(header.cod.layers, |cap| cap.min(header.cod.layers)));
2009 let components = &scope.coded.components;
2010 let kept: Vec<usize> = (0..components.len())
2011 .filter(|&c| scope.wanted.get(c).copied().unwrap_or(false))
2012 .collect();
2013 // The code-blocks of the components reconstructed with a packet missing
2014 // from a layer the decode keeps.
2015 let mut missing = Vec::new();
2016 for &c in &kept {
2017 for (res, resolution) in components[c].resolutions.iter().enumerate() {
2018 for band in &resolution.subbands {
2019 for block in &band.blocks {
2020 if let Some(from) = block.missing_from.filter(|&l| l < layers) {
2021 missing.push((c, res, band.kind, block, from));
2022 }
2023 }
2024 }
2025 }
2026 }
2027 let mut lacking = vec![false; components.len()];
2028 for &(c, ..) in &missing {
2029 lacking[c] = true;
2030 }
2031 let resolutions = |c: usize| components[c].resolutions.len();
2032 // The most a reduction can drop of every component reconstructed.
2033 let most = kept
2034 .iter()
2035 .map(|&c| resolutions(c).saturating_sub(1))
2036 .min()
2037 .unwrap_or(0);
2038 // The first layer missing from a code-block the samples need at
2039 // reduction `r`.
2040 let first_missing = |r: u8| -> Result<Option<u32>> {
2041 // Only the components with a code-block missing need a footprint.
2042 let mut footprints = vec![None; components.len()];
2043 if scope.windowed {
2044 for &c in &kept {
2045 if lacking[c] {
2046 footprints[c] = (scope.footprint_at)(c, r)?;
2047 }
2048 }
2049 }
2050 let mut first: Option<u32> = None;
2051 for &(c, res, kind, block, from) in &missing {
2052 let needed = res < resolutions(c).saturating_sub(usize::from(r))
2053 && footprints[c]
2054 .as_ref()
2055 .is_none_or(|footprint: &dwt::Footprint| footprint.needs(res, kind, block));
2056 if needed {
2057 first = Some(first.map_or(from, |f| f.min(from)));
2058 }
2059 }
2060 Ok(first)
2061 };
2062 let (whole, tile_complete) = if missing.is_empty() {
2063 (layers, Some(0))
2064 } else {
2065 let mut tile_complete = None;
2066 for r in (0..=most).rev() {
2067 let Ok(r) = u8::try_from(r) else { continue };
2068 if first_missing(r)?.is_some() {
2069 break;
2070 }
2071 tile_complete = Some(r);
2072 }
2073 (first_missing(reduction)?.unwrap_or(layers), tile_complete)
2074 };
2075 let leftover = reach.leftover.is_some() || reach.leftover_packed.is_some();
2076 let tile_complete = tile_complete.filter(|_| !leftover);
2077 push_tile_entries(tile, reach, whole, layers, tile_complete, entries);
2078 Ok(tile_complete)
2079}
2080
2081/// Add what a non-strict walk of `tile` found to `entries`, and give the
2082/// smallest reduction at which the tile has every packet. Under a layer cap
2083/// of `cap`, only the packets of the layers it keeps count: one past it that
2084/// was not read is not missing.
2085fn report_tile(
2086 header: &codestream::MainHeader,
2087 tile: &codestream::Tile<'_>,
2088 reach: &tier2::Reach,
2089 reduction: u8,
2090 cap: Option<u16>,
2091 entries: &mut Vec<ReportEntry>,
2092) -> Option<u8> {
2093 let layers = u32::from(cap.map_or(header.cod.layers, |cap| cap.min(header.cod.layers)));
2094 let missing = |comp: usize, res: usize| reach.missing_from[comp][res].filter(|&l| l < layers);
2095 let resolutions: Vec<usize> = reach.missing_from.iter().map(Vec::len).collect();
2096 // The smallest reduction at which every resolution kept is whole.
2097 let most = resolutions.iter().min().map_or(0, |&n| n.saturating_sub(1));
2098 let leftover = reach.leftover.is_some() || reach.leftover_packed.is_some();
2099 let tile_complete = (0..=most)
2100 .find(|&r| {
2101 resolutions
2102 .iter()
2103 .enumerate()
2104 .all(|(comp, &n)| (0..n.saturating_sub(r)).all(|res| missing(comp, res).is_none()))
2105 })
2106 .and_then(|r| u8::try_from(r).ok())
2107 .filter(|_| !leftover);
2108 // The leading layers whole at the resolutions this decode keeps.
2109 let mut whole = layers;
2110 for (comp, &n) in resolutions.iter().enumerate() {
2111 for res in 0..n.saturating_sub(usize::from(reduction)) {
2112 if let Some(from) = missing(comp, res) {
2113 whole = whole.min(from);
2114 }
2115 }
2116 }
2117 push_tile_entries(tile, reach, whole, layers, tile_complete, entries);
2118 tile_complete
2119}
2120
2121/// Add to `entries` the packets missing from `tile`, when only the leading
2122/// `whole` of its `layers` are whole, and the bytes its walk left over.
2123fn push_tile_entries(
2124 tile: &codestream::Tile<'_>,
2125 reach: &tier2::Reach,
2126 whole: u32,
2127 layers: u32,
2128 tile_complete: Option<u8>,
2129 entries: &mut Vec<ReportEntry>,
2130) {
2131 if whole < layers {
2132 entries.push(ReportEntry::MissingPackets {
2133 tile: tile.index,
2134 complete_layers: whole as u16,
2135 complete_reduction: tile_complete,
2136 });
2137 }
2138 if let Some((at, bytes)) = reach.leftover {
2139 entries.push(ReportEntry::LeftoverBytes {
2140 tile: tile.index,
2141 tile_part: tile.part_at(at),
2142 bytes: bytes as u64,
2143 in_packed_headers: false,
2144 });
2145 }
2146 if let Some(bytes) = reach.leftover_packed {
2147 entries.push(ReportEntry::LeftoverBytes {
2148 tile: tile.index,
2149 tile_part: tile.part_at(tile.data.len()),
2150 bytes: bytes as u64,
2151 in_packed_headers: true,
2152 });
2153 }
2154}
2155
2156/// The bytes of tile data the codestream's packets are read from: every
2157/// tile's packet data and packed packet headers.
2158pub(crate) fn tile_bytes(cs: &codestream::Codestream<'_>) -> u64 {
2159 cs.tiles
2160 .iter()
2161 .map(|tile| (tile.data.len() + tile.packed_headers.len()) as u64)
2162 .fold(0, u64::saturating_add)
2163}
2164
2165// The synthetic-bytes builders the unit tests share with `tests/` and `fuzz/`.
2166// Std only, so one `#[path]` include here serves every unit test.
2167#[cfg(test)]
2168#[path = "../tests/support/synth.rs"]
2169mod synth;
2170
2171#[cfg(test)]
2172mod tests {
2173 use super::*;
2174
2175 thread_local! {
2176 /// The sample-passes the decodes on this thread have counted against
2177 /// the code-block work bound.
2178 pub(crate) static BLOCK_WORK: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
2179 /// The code-blocks with coding passes the decodes on this thread have
2180 /// handed to the block decoder.
2181 pub(crate) static BLOCKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
2182 }
2183
2184 /// The code-blocks with coding passes in the resolutions `reduction`
2185 /// keeps of the components `wanted` marks: those Tier-1 decodes.
2186 pub(crate) fn blocks(coded: &tier2::CodedData<'_>, reduction: u8, wanted: &[bool]) -> u64 {
2187 let mut count = 0;
2188 for (component, coded) in coded.components.iter().enumerate() {
2189 if !wanted[component] {
2190 continue;
2191 }
2192 let kept = coded
2193 .resolutions
2194 .len()
2195 .saturating_sub(usize::from(reduction));
2196 for resolution in coded.resolutions.iter().take(kept.max(1)) {
2197 for subband in &resolution.subbands {
2198 count += subband.blocks.iter().filter(|b| b.num_passes > 0).count() as u64;
2199 }
2200 }
2201 }
2202 count
2203 }
2204
2205 /// The sample-passes Tier-1 runs on `bytes` (one tile) under a layer
2206 /// cap of `layers`, and the packet visits the walk spends.
2207 fn capped_work(bytes: &[u8], layers: Option<u16>) -> (u64, u64) {
2208 let parsed = codestream::parse_header(bytes).unwrap();
2209 let cs = codestream::parse_tiles(bytes, parsed).unwrap();
2210 let header = cs.tile_header(0).unwrap();
2211 let meter = tier2::Meter::new(u64::MAX);
2212 let coded =
2213 tier2::decode_packets_metered(&header, &cs.tiles[0], &meter, u64::MAX, 0, layers)
2214 .unwrap();
2215 let wanted = vec![true; coded.components.len()];
2216 (tier1::work(&header, &coded, 0, &wanted), meter.spent())
2217 }
2218
2219 /// Each layer the cap drops is Tier-1 work not done, and the packet walk
2220 /// spends the same visits whatever the cap, since it still reads every
2221 /// packet.
2222 #[test]
2223 fn a_layer_cap_cuts_block_work_and_not_packet_work() {
2224 let bytes = std::fs::read(concat!(
2225 env!("CARGO_MANIFEST_DIR"),
2226 "/tests/fixtures/layers/lrcp.j2k"
2227 ))
2228 .unwrap();
2229 let (full, visits) = capped_work(&bytes, None);
2230 let mut previous = 0;
2231 for n in 1..=4 {
2232 let (work, spent) = capped_work(&bytes, Some(n));
2233 assert!(work > previous, "-l {n}: {work} after {previous}");
2234 assert_eq!(spent, visits, "-l {n}");
2235 previous = work;
2236 }
2237 assert_eq!(previous, full);
2238 assert_eq!(capped_work(&bytes, Some(u16::MAX)), (full, visits));
2239 }
2240
2241 /// The reduction check names the component and the resolutions it would
2242 /// discard, and the tile only when it runs per tile.
2243 #[test]
2244 fn check_reduction_message_names_the_tile_only_when_given() {
2245 let bytes = std::fs::read(concat!(
2246 env!("CARGO_MANIFEST_DIR"),
2247 "/tests/fixtures/roi_maxshift_lossless.j2k"
2248 ))
2249 .unwrap();
2250 let mut header = codestream::parse_header(&bytes).unwrap().header;
2251 // One component is shallower than the rest, as a COC or tile COD makes it.
2252 let last = header.components.len() - 1;
2253 header.components[last].coding.decomposition_levels = 1;
2254 assert!(check_reduction(&header, 1, None).is_ok());
2255 let message = |tile| match check_reduction(&header, 2, tile) {
2256 Err(Error::InvalidOptions(m)) => m.message().to_owned(),
2257 other => panic!("{other:?}"),
2258 };
2259 let tail = format!("resolution reduction 2 discards all 2 resolutions of component {last}");
2260 assert_eq!(message(None), tail);
2261 assert_eq!(message(Some(7)), format!("{tail} in tile 7"));
2262 }
2263
2264 /// The sample-passes the block decoder counts on a decode of `name` (in
2265 /// `tests/fixtures/window/`) under `options`.
2266 fn block_work(name: &str, options: &DecodeOptions) -> u64 {
2267 let bytes = std::fs::read(format!(
2268 "{}/tests/fixtures/window/{name}.j2k",
2269 env!("CARGO_MANIFEST_DIR")
2270 ))
2271 .unwrap();
2272 work_of(&bytes, options)
2273 }
2274
2275 /// The sample-passes the block decoder counts on a decode of `bytes`
2276 /// under `options`.
2277 fn work_of(bytes: &[u8], options: &DecodeOptions) -> u64 {
2278 BLOCK_WORK.with(|spent| spent.set(0));
2279 BLOCKS.with(|count| count.set(0));
2280 decode_with(bytes, options).unwrap();
2281 BLOCK_WORK.with(std::cell::Cell::get)
2282 }
2283
2284 /// A window inside one tile decodes only the code-blocks whose wavelet
2285 /// support reaches it, not every code-block of the tile.
2286 #[test]
2287 fn a_window_inside_a_tile_decodes_fewer_code_blocks_than_the_tile() {
2288 // `tests/fixtures/bench/` is left out of the published package, so
2289 // the test is skipped where the directory is not there; a file
2290 // missing from a directory that is there fails it.
2291 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/bench");
2292 if !dir.is_dir() {
2293 eprintln!(
2294 "{} is not present (packaged crate?); skipping",
2295 dir.display()
2296 );
2297 return;
2298 }
2299 let path = dir.join("tiled_2048_gray.j2k");
2300 let bytes = std::fs::read(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
2301 let all = DecodeOptions::default();
2302 // Tile 27 is 768..1024 on both axes: 256 x 256 in 64 x 64 code-blocks,
2303 // over four decomposition levels.
2304 let tile = work_of(&bytes, &all.clone().with_region(Region::Tile(27)));
2305 assert!(tile > 0);
2306 let blocks = || BLOCKS.with(std::cell::Cell::get);
2307 // The tile's code-blocks with coding passes: the LL band's, one in
2308 // each band of the three coarser levels, and six of the twelve of
2309 // the finest level's 128 x 128 bands.
2310 assert_eq!(blocks(), 16);
2311 // Windows inside one code-block of each finest band: at the tile's
2312 // top-left and bottom-right corners, and one sample in the
2313 // bottom-right one. Each needs that code-block of each finest band
2314 // and every coarser one; the bottom-right blocks of two finest bands
2315 // have no coding pass.
2316 for (window, count) in [
2317 (Window::new(768, 768, 800, 800), 13),
2318 (Window::new(992, 992, 1024, 1024), 11),
2319 (Window::new(900, 900, 901, 901), 11),
2320 ] {
2321 let part = work_of(&bytes, &all.clone().with_region(Region::Window(window)));
2322 assert!(part < tile, "{window:?}: {part} of {tile}");
2323 assert_eq!(blocks(), count, "{window:?}");
2324 }
2325 // A window across the middle of the tile, whose wavelet support
2326 // reaches all four code-blocks of each finest band.
2327 let middle = Window::new(880, 880, 912, 912);
2328 assert_eq!(
2329 work_of(&bytes, &all.clone().with_region(Region::Window(middle))),
2330 tile
2331 );
2332 assert_eq!(blocks(), 16);
2333 // The window that is the whole tile decodes all of it.
2334 let whole = Window::new(768, 768, 1024, 1024);
2335 assert_eq!(
2336 work_of(&bytes, &all.clone().with_region(Region::Window(whole))),
2337 tile
2338 );
2339 assert_eq!(blocks(), 16);
2340 }
2341
2342 /// A window decodes only the tiles it reaches, and a component subset
2343 /// only its components' code-blocks, but every one of the color
2344 /// transform's three when it asks for one of them.
2345 #[test]
2346 fn a_window_or_a_subset_decodes_fewer_code_blocks() {
2347 let all = DecodeOptions::default();
2348 for name in ["tiled_53", "tiled_53_nomct"] {
2349 let whole = block_work(name, &all);
2350 // Tile 4, the middle one, is a ninth of the image.
2351 let tile = block_work(name, &all.clone().with_region(Region::Tile(4)));
2352 assert!(tile * 6 < whole, "{name}: {tile} of {whole}");
2353 assert_eq!(
2354 block_work(
2355 name,
2356 &all.clone()
2357 .with_region(Region::Window(Window::new(27, 22, 51, 42)))
2358 ),
2359 tile,
2360 "{name}"
2361 );
2362 // Tiles 0, 1, 3 and 4.
2363 let four = block_work(
2364 name,
2365 &all.clone()
2366 .with_region(Region::Window(Window::new(20, 10, 41, 31))),
2367 );
2368 assert!(four > tile && four * 2 < whole, "{name}: {four} of {whole}");
2369 }
2370 let one = all.clone().with_components(Some(vec![1]));
2371 let whole = block_work("tiled_53_nomct", &all);
2372 let single = block_work("tiled_53_nomct", &one);
2373 assert!(single * 2 < whole, "{single} of {whole}");
2374 assert_eq!(block_work("tiled_53", &one), block_work("tiled_53", &all));
2375 }
2376}