Expand description
A pure-Rust JPEG 2000 decoder. It has no C dependency, so cross-compiling it needs no C toolchain.
The decoder reads a raw codestream (ISO/IEC 15444-1 Annex A) or a
JP2 file (Annex I) into integer samples: one grid per component,
signed up to 32 bits, unsigned up to 31 (an i32 container), each with its
own bit depth, sign, and sub-sampling. Both wavelet paths decode, the
reversible 5/3 bit-exactly and the irreversible 9/7 within the standard’s
compliance bounds, as do tiling and tile-parts, precincts, quality layers,
all five progression orders and POC changes between them, packed packet
headers (PPM/PPT), every Part 1 code-block coding style, region of interest
(maxshift), non-zero canvas offsets, resolution-reduced decoding, and the
reversible (RCT) and irreversible (ICT) color transforms.
A JP2 file’s codestream decodes the same way, and the file’s header comes
back on Image::jp2. A palettized JP2 file decodes to the palette’s
channels, and a file with channel definitions puts its color channels in
color order. read_header and read_header_with read the same header
without decoding any tile data. Samples come out as coded by default;
ColorOutput::Srgb converts sYCC and restricted ICC profiles to sRGB.
The feature scope
maps what is decoded and what is not.
§Pipeline
bytes ─▶ [jp2 boxes] ─▶ codestream ─▶ tier-2 ─▶ tier-1 ─▶ dequant
(Annex I) (markers) (packets) (MQ+EBCOT) (quant)
─▶ inverse DWT ─▶ inverse MCT ─▶ [palette, cdef, sRGB] ─▶ Image
(5/3 | 9/7) (RCT | ICT) (JP2 only)decode runs these stages in order.
§Example
The core of the public surface is decode: codestream or JP2 bytes in,
an Image out, with one Component per output channel. Malformed
input never panics; it comes back as a typed Error.
use rust_j2k::{decode, Error};
// In real use these are the bytes of a `.j2k` codestream or `.jp2` file, or the GRIB2 §7
// data section of a `grid_jpeg` message. Invalid input is rejected cleanly:
match decode(b"not a codestream") {
Ok(image) => {
let first = image.component(0).expect("at least one component");
println!(
"image area {}x{}, first component {}x{}",
image.width, image.height, first.width, first.height,
);
}
Err(Error::Unsupported(what)) => println!("outside the decoded subset: {what}"),
Err(e) => println!("decode failed: {e}"),
}A JP2 file’s header says how to read its samples. To get sRGB instead of the samples as coded, ask for it in the options:
use rust_j2k::{ColorOutput, ColorSpace, DecodeOptions, decode_with};
let bytes = std::fs::read("photo.jp2")?;
let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
let image = decode_with(&bytes, &options)?;
if let Some(jp2) = &image.jp2 {
// After a conversion the color space says sRGB, or grayscale for a
// monochrome profile; a file left as coded keeps the space it
// declares. `channels` labels each component (color 1, 2, 3, opacity).
if jp2.color == ColorSpace::Srgb {
println!("sRGB, channels {:?}", jp2.channels);
}
}§Damaged input
Decoding is strict by default. Truncated or inconsistent data is an
error, and no partial image comes back with it. A raw codestream cut
short fails as Error::Codestream, a JP2 file cut short as Codestream or
Error::FileFormat, depending on where the cut falls. A codestream
whose last tile-part states its length is refused without its closing
EOC marker. A last tile-part of length 0 (Psot = 0, “to the end”)
takes the data up to the final two bytes without checking that they are
EOC, as OpenJPEG does, so a missing EOC there costs the tile its last
two bytes and usually fails the tile instead; in a JP2 file such a
tile-part can also end where its jp2c box ends. Input that is not
JPEG 2000 at all, empty input and plain text included, is Codestream
too.
Damage can show up as any variant, not only those two. A flipped bit in
a header field can read as an absurd image size (Error::Limit) or an
unknown marker or a feature the decoder does not read
(Error::Unsupported). Do not retry a file with
WorkLimit::Unlimited on that evidence alone.
JPEG 2000 carries no checksum, so damage inside the entropy-coded data is not always detected: a flipped byte in a code-block can decode without an error and give a wrong image. If that matters, check the file against a hash you keep. The correctness notes list what is refused and where this decoder is stricter than OpenJPEG.
use rust_j2k::{Error, decode};
let bytes = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/jpeg2000_regular_latlon.j2k"
));
assert!(decode(bytes).is_ok());
// Cut short: an error, not a partial image.
let cut = &bytes[..bytes.len() / 2];
assert!(matches!(decode(cut), Err(Error::Codestream(_))));
// Without its closing `EOC` marker (FF D9): refused.
assert!(decode(&bytes[..bytes.len() - 2]).is_err());
// Not JPEG 2000 at all.
assert!(matches!(decode(b"hello"), Err(Error::Codestream(_))));With DecodeOptions::strict off, a codestream cut short, or one with
bytes left after a tile’s last packet, decodes to the image the data
holds, and Image::report says what is missing (a DecodeReport).
This is what opj_decompress -allow-partial does. A codestream that
streams in can be decoded as it arrives: the report’s
complete_reduction is the finest
level the data already gives in full. Everything else damaged is refused
as when strict.
§Limits
A valid file can still be refused with Error::Limit. The decoder caps
what a file may declare and how much work it may ask for. Three limits
can be changed, each set with a WorkLimit:
DecodeOptions::sample_limit for the image’s size,
DecodeOptions::packet_work_limit for reading the packet headers and
DecodeOptions::code_block_work_limit for decoding the code-blocks.
The other guards have no option; the list is on Error::Limit. The
message says which guard the file hit. For one of the three it also
names a WorkLimit::Raised factor (see WorkLimit for how far to
trust it).
For a file from a source you trust, lift all three. WorkLimit has an
example that retries after an Error::Limit.
§Conformance
All 23 codestreams of the ISO/IEC 15444-4 conformance suite decode within
their class-1 error bounds, and its nine JP2 files within their compliance
class. That gate runs in tests/ against committed oracle snapshots, with
no external tools. Correctness is defined by cross-checking OpenJPEG, not
by self-consistency. An input using a
feature outside the decoded set (HTJ2K, a Part 2 extension) is rejected
with Error::Unsupported, never half-decoded. GRIB2 §5.40 (grid_jpeg)
payloads, the crate’s original target, are raw codestreams and decode
directly. The feature map is in docs/scope.md.
Structs§
- Channel
Definition - What one output channel is: its type and the color it belongs to.
- Channel
Definition Entry - One entry of a file’s channel definition box (
cdef), as written: the channel it describes and that channel’s definition. - Channel
Mapping - One channel of a file’s component mapping (
cmapbox): where an output channel’s samples come from. - Color
Specification - One Colour Specification box (
colr, I.5.3.3), as stored. - Component
- One decoded component: its own sample grid, its declared depth and sign, and the sub-sampling that maps it onto the image’s reference grid.
- Component
Info - One output channel’s sample format and size, as on the
Componentthatdecodewould return. - Decode
Options - Options for
decode_with.decodeisdecode_withatDecodeOptions::default. - Decode
Report - What a decode left out, and how far the data reached.
- File
Type - The File Type box (
ftyp, I.5.2), as stored. A file is read whenjp2is its brand or in its compatibility list. - Header
- An image’s header: what
decodewould return, without the samples. - Image
- A decoded image: the image area on the reference grid, plus its components.
- Image
Header - The Image Header box’s (
ihdr, I.5.3.1) flagsC,UnkCandIPR, as stored. None of them changes the decode. The codestream’s SIZ decides the image size, the component count and the depths, soihdr’sHEIGHT,WIDTH,NCandBPC, and thebpccbox, are not reported. - IprBox
- An intellectual property box (
jp2i). The standard leaves the format of its contents open, so they are not parsed. - Jp2Metadata
- What the JP2 wrapper said about the decoded samples.
- Palette
- A JP2 file’s palette, from its
pclrbox: a table ofNEentries (1 to 1024), each a row of one value per column (1 to 255 columns). - Palette
Column - One palette column’s sample format, from its
Bibyte. - Ratio
- A resolution as the file stores it:
numerator / denominator × 10^exponentgrid points per meter. Kept as integers, so the value is exact;Ratio::grid_points_per_metergives it as a float. - Reader
Requirements - A Reader Requirements box (
rreq, ISO/IEC 15444-2 M.11.1): the features a reader must support to use the file, each with a mask saying which of the file’s requirement expressions it belongs to. - Res
- One resolution: grid points per meter in each direction.
- Resolution
- The resolutions a JP2 file’s
resbox gives, in grid points per meter. - Standard
Feature - One standard feature of a Reader Requirements box:
SFand itsSM. - UuidBox
- A
uuidbox: a 16-byte identifier and the data it labels. - Uuid
Info - A UUID info box (
uinf): the UUIDs its UUID list box (ulst) names and its data entry URL box (url), which says where more about them can be found. - Vendor
Feature - One vendor feature of a Reader Requirements box:
VFand itsVM. - XmlBox
- An
xmlbox: XML text the file carries, which is not parsed.
Enums§
- Association
- The color a channel is associated with, from a channel definition
(
Asoc). - Channel
Type - A channel’s type, from a channel definition (
Typ). - Color
Output - What color space a JP2 file’s color channels come out in: the
DecodeOptions::coloroption. - Color
Space - The color space a JP2 file declares for its color channels.
- Error
- A decode failure, tagged by the class of fault.
- Mapping
Kind - How a mapped channel is made from its component (
MTYP). - Report
Entry - One thing a decode with
strictoff left out or skipped, onDecodeReport::entries. - Work
Limit - How far a decode may go against one of its bounds: the
DecodeOptions::packet_work_limitandDecodeOptions::code_block_work_limitwork bounds, and theDecodeOptions::sample_limiton the image’s size.
Functions§
- decode
- Decode a JPEG 2000 codestream (Annex A) or JP2 file (Annex I)
into an
Image: the reference-grid image area plus oneComponentper output channel, each on its own sample grid. For a raw codestream that is one per SIZ component, in SIZ order. A JP2 file can change the channels: its palette and channel definitions (below), and, throughdecode_with, the sRGB output option. - decode_
with - Decode a JPEG 2000 codestream or JP2 file like
decode, governed byoptions. - read_
header - Read a JPEG 2000 codestream’s or JP2 file’s
Headerwithout decoding any tile data: the image area, each output channel’s sample format, and, for a JP2 file, the sameJp2Metadatathatdecodewould put onImage::jp2. - read_
header_ with - Read a JPEG 2000 codestream’s or JP2 file’s
Headerwithout decoding any tile data, for the sameoptionsasdecode_with: the header describes theImagethatdecode_with(bytes, options)would return.
Type Aliases§
- Result
- Crate result alias.