Skip to main content

Crate rust_j2k

Crate rust_j2k 

Source
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, and HTJ2K codestreams and JPH files (ISO/IEC 15444-15) the same way: 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. HTJ2K code-blocks decode with all three of their coding passes, and a tile-component may mix HT and Part 1 code-blocks. An HTJ2K file takes the same call and options as any other. A decode can stop after some quality layers, or return a window, one tile or some of the components (DecodeOptions).

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)  (EBCOT|HT) (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

This section and the API docs use the standard’s names for the parts of a codestream: markers such as SIZ, COD, SOT and EOC, tiles and tile-parts, packets, code-blocks and the reference grid. What a JPEG 2000 file holds explains them.

Decoding is strict by default. Truncated or inconsistent data is an error, and no partial image comes back with it. Input cut before the codestream’s main header is whole, that is, before its first SOT marker, is Error::Incomplete, so a caller whose input streams in can tell it to wait for more bytes. That covers every cut from the empty input on, including a JP2 file’s boxes before the codestream. A cut later fails as Error::Codestream, or as Error::FileFormat when it falls in a JP2 box after the codestream. 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, plain text included, is Codestream too.

Damage can show up as any variant, not only the ones named here. 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 = std::fs::read("image.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. Until the main header has arrived, the decode, like read_header, is Error::Incomplete. Everything else damaged is refused as when strict.

For a file that arrives in pieces, use IncrementalDecoder rather than decoding each prefix again: feed appends bytes, refine decodes them from time to time and returns the image they hold, with its report, and finish decodes the whole input once it ends. Each refine goes on from where the last one stopped reading packets.

§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 error’s LimitDetail says which guard the file hit, as a LimitKind. For one of the three it also gives the WorkLimit to retry with (see WorkLimit for how far to trust it).

For a file from a source you trust, lift all three. WorkLimit and LimitDetail have examples that retry 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. So do its 41 HTJ2K codestreams and 20 JPH files. 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 (an HTJ2K code-block that needs more than one HT coding pass set, 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§

ChannelDefinition
What one output channel is: its type and the color it belongs to.
ChannelDefinitionEntry
One entry of a file’s channel definition box (cdef), as written: the channel it describes and that channel’s definition.
ChannelMapping
One channel of a file’s component mapping (cmap box): where an output channel’s samples come from.
ColorSpecification
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.
ComponentInfo
One output channel’s sample format and size, as on the Component that decode would return.
DecodeOptions
Options for decode_with. decode is decode_with at DecodeOptions::default.
DecodeReport
What a decode left out, and how far the data reached.
ErrorDetail
What an Error other than Error::Limit carries: a diagnostic for a log.
FileType
The File Type box (ftyp, I.5.2), as stored. A file is read when jp2 or jph is its brand or in its compatibility list.
Header
An image’s header: what decode would return, without the samples.
Image
A decoded image: the image area on the reference grid, plus its components.
ImageHeader
The Image Header box’s (ihdr, I.5.3.1) flags C, UnkC and IPR, as stored. None of them changes the decode. The codestream’s SIZ decides the image size, the component count and the depths, so ihdr’s HEIGHT, WIDTH, NC and BPC, and the bpcc box, are not reported.
IncrementalDecoder
A decoder for a file that arrives a piece at a time, from a network or a slow disk.
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.
LimitDetail
What an Error::Limit carries: which limit refused the input, the WorkLimit to retry with when an option raises that limit, and a diagnostic for a log.
Palette
A JP2 file’s palette, from its pclr box: a table of NE entries (1 to 1024), each a row of one value per column (1 to 255 columns).
PaletteColumn
One palette column’s sample format, from its Bi byte.
Ratio
A resolution as the file stores it: numerator / denominator × 10^exponent grid points per meter. Kept as integers, so the value is exact; Ratio::grid_points_per_meter gives it as a float.
ReaderRequirements
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 res box gives, in grid points per meter.
StandardFeature
One standard feature of a Reader Requirements box: SF and its SM.
TileGrid
How an image is cut into tiles: the grid that the SIZ marker declares on the reference grid, the coordinate space of the whole codestream.
UuidBox
A uuid box: a 16-byte identifier and the data it labels.
UuidInfo
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.
VendorFeature
One vendor feature of a Reader Requirements box: VF and its VM.
Window
A rectangle on the image’s reference grid, x0..x1 by y0..y1, for Region::Window. The bounds are half-open: x1 and y1 are one past the last column and row.
XmlBox
An xml box: XML text the file carries, which is not parsed.

Enums§

Association
The color a channel is associated with, from a channel definition (Asoc).
ChannelType
A channel’s type, from a channel definition (Typ).
ColorOutput
What color space a JP2 file’s color channels come out in: the DecodeOptions::color option.
ColorSpace
The color space a JP2 file declares for its color channels.
Error
A decode failure, tagged by the class of fault.
LimitKind
Which limit an Error::Limit names.
MappingKind
How a mapped channel is made from its component (MTYP).
Region
The area of the image a decode returns, for DecodeOptions::region.
ReportEntry
One thing a decode with strict off left out or skipped, on DecodeReport::entries.
WorkLimit
How far a decode may go against one of its bounds: the DecodeOptions::packet_work_limit and DecodeOptions::code_block_work_limit work bounds, and the DecodeOptions::sample_limit on 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 one Component per output channel, each on its own sample grid. For a raw codestream that is one per component of the SIZ marker, in SIZ order. What a JPEG 2000 file holds explains the codestream’s parts. A JP2 file can change the channels: its palette and channel definitions (below), and, through decode_with, the sRGB output option.
decode_with
Decode a JPEG 2000 codestream or JP2 file like decode, governed by options.
read_header
Read a JPEG 2000 codestream’s or JP2 file’s Header without decoding any tile data: the image area, each output channel’s sample format, and, for a JP2 file, the same Jp2Metadata that decode would put on Image::jp2.
read_header_with
Read a JPEG 2000 codestream’s or JP2 file’s Header without decoding any tile data, for the same options as decode_with: the header describes the Image that decode_with(bytes, options) would return.

Type Aliases§

Result
Crate result alias.