#[non_exhaustive]pub struct DecodeOptions {
pub resolution_reduction: u8,
pub max_quality_layers: Option<u16>,
pub region: Region,
pub components: Option<Vec<u16>>,
pub raw_channels: bool,
pub color: ColorOutput,
pub packet_work_limit: WorkLimit,
pub code_block_work_limit: WorkLimit,
pub sample_limit: WorkLimit,
pub strict: bool,
}Expand description
Options for decode_with. decode is decode_with at
DecodeOptions::default.
Start from DecodeOptions::default and set what differs with its
with_* method, or the field directly. The struct is #[non_exhaustive],
so a new option is not a breaking change.
Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.resolution_reduction: u8How many of the finest resolution levels to discard. Each level about
halves the output in both axes, so 1 decodes a half-size image, 2
a quarter-size, and so on: the wavelet pyramid’s own lower
resolutions, not a resample. The exact size depends on the image
origin; Image and ComponentInfo::width give the formula. Every
component must keep at least one resolution: a reduction that consumes
some component’s whole pyramid is rejected as
Error::InvalidOptions. Header::max_reduction gives the largest
the main header allows.
max_quality_layers: Option<u16>How many of the leading quality layers to decode: Some(n) decodes
layers 0..n of each tile, None (the default) every layer. A
codestream builds its image up in layers, each adding coding passes
to the code-blocks, so a cap gives a lower-fidelity image at full
size from fewer passes, and the block decoder does less work. It is
OpenJPEG’s opj_decompress -l n.
A cap at or above a tile’s layer count decodes that tile whole, as
OpenJPEG does. Some(0) is Error::InvalidOptions. It combines
with resolution_reduction.
The packets of the later layers are still read, since they frame the
packets after them, so a fault in one is still an error, and they
count against packet_work_limit as
without a cap. Only their coding passes are left out. With
strict off, a packet of a layer past the cap that
the data does not reach is not reported missing.
Header::quality_layers is the layer
count the main header declares.
use rust_j2k::{DecodeOptions, decode, decode_with};
// For a 32x24 file in three quality layers, the last one lossless.
let bytes = std::fs::read("image.j2k")?;
let whole = decode(&bytes).expect("decodes");
let first = decode_with(&bytes, &DecodeOptions::default().with_max_quality_layers(Some(1)))
.expect("decodes");
// The same size, from fewer coding passes.
assert_eq!((first.width, first.height), (whole.width, whole.height));
assert_ne!(first.components[0].samples, whole.components[0].samples);
// A cap at or past the layer count is the whole decode.
let all = decode_with(&bytes, &DecodeOptions::default().with_max_quality_layers(Some(3)))
.expect("decodes");
assert_eq!(all.components[0].samples, whole.components[0].samples);region: RegionThe area to decode: Region::Whole (the default) the whole image,
Region::Window a rectangle of the reference grid, and
Region::Tile one tile. One field holds all three, so a window and a
tile cannot be asked for together. A window is OpenJPEG’s
opj_set_decode_area (opj_decompress -d x0,y0,x1,y1); a tile is its
opj_get_decoded_tile (opj_decompress -t index).
§Window
A Region::Window returns the part of the image inside it. It is in
reference-grid coordinates, as SIZ declares them, whatever the
resolution_reduction.
Header::image_area gives the image area in those coordinates,
and TileGrid::tile each tile’s rectangle.
The part of it outside the image area is left out, as OpenJPEG clips
it. The returned Image covers what is left, x0..x1 by y0..y1:
its width is x1 - x0 at full resolution and
ceil(x1 / 2^r) - ceil(x0 / 2^r) at a reduction of r, and each
component’s is the same of ceil(x0 / dx) and ceil(x1 / dx) for its
sub-sampling dx (ComponentInfo::width gives the formula for the
whole image). The samples are those of a whole decode at the same
position. ColorOutput::Srgb from sYCC with sub-sampled chroma is
Error::Unsupported when the window, cut to the image area, does not
cover all of it, as the chroma replication depends on where the
decoded area starts.
Only the tiles the window reaches are decoded, so a small window of a
large tiled image costs a few tiles. The packets of the other tiles
are not read, so damage in them is not found, as in OpenJPEG. With
strict off, a codestream cut short after the tiles
the window reaches still gives the window’s samples.
opj_decompress -allow-partial -d 2.5.0 refuses such a file, while
-t decodes each tile, the cut one included, as this decoder does. In
the
tiles it reaches, only the code-blocks whose wavelet support reaches
the window are decoded, so damage in the others is not found either.
Nor is a code-block it skips checked against the bit-plane limit, so
a window can decode where the whole image is refused as
Error::Limit.
An empty window, one with no part inside the image area, and one that
holds no sample of a returned component at the reduction are
Error::InvalidOptions.
use rust_j2k::{DecodeOptions, Region, Window, decode, decode_with};
// For a 32x24 file with its image area at the grid's origin.
let bytes = std::fs::read("image.j2k")?;
let whole = decode(&bytes).expect("decodes");
let options = DecodeOptions::default().with_region(Region::Window(Window::new(8, 4, 20, 30)));
let part = decode_with(&bytes, &options).expect("decodes");
// The window is cut to the image: rows 4 to 23.
assert_eq!((part.width, part.height), (12, 20));
assert_eq!(part.components[0].sample(0, 0), whole.components[0].sample(8, 4));§Tile
Region::Tile returns tile index’s area of the image. Tiles are
numbered in raster order from 0, as the codestream’s Isot numbers
them. The result is the decode of a Region::Window set to the
tile’s rectangle on the reference grid: its size, its samples and its
failures, the refusal of sRGB output from sub-sampled sYCC included
(unless the image is one tile). Header::tiles gives the tile grid
and TileGrid::count the number of tiles; an index at or past the
count is Error::InvalidOptions.
components: Option<Vec<u16>>Decode only these components, in this order: Some(list) returns one
Component per entry of list, each the component of that SIZ
index, and None (the default) every component. It is OpenJPEG’s
opj_set_decoded_components (opj_decompress -c), which takes them
in the given order too.
Each returned component has the samples of a whole decode. The other
components’ packets are still read, as they frame the packets after
them, but their code-blocks are not decoded. Under the codestream’s
color transform (RCT or ICT), components 0, 1 and 2 are decoded
together whenever one of them is asked for, since each of them needs
all three. OpenJPEG skips the color transform instead when the
components are chosen, so its -c returns other samples for those
three.
On a JP2 file the list names codestream components, which come out
as coded: the palette and channel definitions are not applied, as
with raw_channels, and as OpenJPEG has it.
Jp2Metadata::channels describes the components returned.
An empty list, an index named twice, an index past SIZ’s component
count, and a list with ColorOutput::Srgb are
Error::InvalidOptions. The last holds even on a gray codestream,
where sRGB output would pass the samples through, as it does for
raw_channels.
use rust_j2k::{DecodeOptions, decode, decode_with};
// For a file of three components under the irreversible color transform.
let bytes = std::fs::read("image.j2k")?;
let whole = decode(&bytes).expect("decodes");
let options = DecodeOptions::default().with_components(Some(vec![2, 0]));
let some = decode_with(&bytes, &options).expect("decodes");
assert_eq!(some.components.len(), 2);
assert_eq!(some.components[0], whole.components[2]);
assert_eq!(some.components[1], whole.components[0]);raw_channels: boolReturn a JP2 file’s codestream components as coded, without applying
the file’s palette (pclr + cmap) or channel definitions (cdef):
the file decodes exactly as its codestream does on its own, in SIZ
order, and Jp2Metadata::palette_applied is false. It means no
color conversion either, so it cannot be combined with
ColorOutput::Srgb (Error::InvalidOptions). Each index
plane is reported on Jp2Metadata::channels as
ChannelType::Unspecified with Association::None, since it is
not a color until it goes through the palette; every other channel
is labeled as a file without a cdef is (see
Jp2Metadata::channels), whatever the cdef box says. The
boxes’ layout is still checked, so a malformed pclr, cmap or
cdef is still Error::FileFormat; the palette mapping and column
depths, and the channel definitions’ entries, are not.
The metadata carries what the decode left out, so a caller can rebuild the default decode, in order, from the raw one:
- Expand the index planes. For each entry of
Jp2Metadata::channel_mapping, in order, take the raw channelcomponent; aMappingKind::Directentry is used as it is, and aMappingKind::Paletteentry looks each sample up as an index into that column ofJp2Metadata::palette(an index past the table reads its last entry, a negative one its first). Each channel takes its bit depth and sign from its palette column: columncolumnfor a palette entry, and columnifor a direct entry at positioni, as OpenJPEG has it. Without a palette the raw channels are used as they are. - Put the channels in color order with
Jp2Metadata::channel_definitions, by the rule documented there (each swap looks up where the entry’s channel has moved to, not its original position). Without acdefthe order from step 1 stands.
The result is the channels of the default decode. No effect on a raw
codestream. Default false.
color: ColorOutputWhat color space the color channels come out in. Default
ColorOutput::AsCoded.
packet_work_limit: WorkLimitHow much work reading the packet headers may take, against the bound
described on decode. Default WorkLimit::Default.
This also bounds the walk of a Psot = 0 tile that read_header_with
describes, so read_header_with takes the same option.
That walk, in a JP2 file whose last tile-part has Psot = 0, decides
where the tile ends: at the end of the jp2c box if the packets end
exactly there, otherwise at the end of the file. A walk that stops at
the default bound reads to the end of the file, so the box’s trailing
bytes count as left after the last packet. Raising the limit can let
the walk finish. The same file can then decode in full where the
default gives Error::Codestream (or, with
strict off, a report with a
ReportEntry::LeftoverBytes), and no Error::Limit ever
suggested the change.
code_block_work_limit: WorkLimitHow much work decoding the code-blocks may take, against the bound
described on decode. Default WorkLimit::Default.
sample_limit: WorkLimitHow many samples the decoded image may hold, against the limit
described on decode: 2^29 samples (2 GiB as i32) by default,
summed over the output channels at
resolution_reduction. Default
WorkLimit::Default.
Under a window or a tile (region), the count
is the samples of the tiles the decode reads, in every component, as
each of those tiles is reconstructed whole; a palette’s expanded
channels and sRGB output count only the returned area. A small window
of a large tiled image therefore fits the default, but a window of
one large tile counts the whole tile. A
components subset does not lower the count, as
the packets of every component of a tile read are still walked.
Raised(n) allows n times 2^29 samples. Unlimited lifts the
limit: the decode allocates what the header declares, 4 bytes per
sample for the output, and about 1.35 to 3.2 times that in all at its
peak (see the sample limit), so a small hostile file can ask
for many gigabytes. If
the allocation fails the process aborts, as Rust’s allocation
failures do. Only an image too large for this target to
address (isize::MAX bytes of samples) is still refused, with
Error::Limit. Use it only for files from a source you trust.
read_header_with checks the same limit, so it refuses what the
decode would.
strict: boolRefuse missing data with an Error (true, the default), or decode
what is there and say what is missing on Image::report (false).
It is the same switch as OpenJPEG’s strict mode
(opj_decoder_set_strict_mode, opj_decompress -allow-partial) and
GDAL’s STRICT option.
false relaxes these two things and no others; any other relaxation
is a separate option:
- The input may end anywhere after the first
SOTmarker, which ends the main header: inside a tile-part, its header or its packets, with or without theEOCmarker. Input that ends before the firstSOTisError::Incomplete, as when strict. Tiles with no tile-part are filled with 0, and packets that were never read (cut off, or left out by thePOCvolumes) add nothing to their code-blocks. A tile-part count (TNsot) that disagrees with the tile-parts found is taken as advisory. - Bytes left after a tile’s last packet are skipped rather than refused, and the tile is reported as possibly wrong.
Everything else is refused as a strict decode refuses it: a damaged
packet header, coded data that fails to decode, a marker fault, tile-parts
out of order or with a gap, and every Error::Limit. The work bounds
and the sample limit hold as they do when strict, counted on the data
that is there. A missing tile is not walked, but each of its
tile-components is charged against the packet work bound (under a
window or tile, those of the missing tiles it reads), as are the
packets after the end of the data, so a short input cannot ask for
unbounded work.
Strict or not, only the data a decode reads is checked. With a
region of a window or a tile, the tiles outside it
are not read, with a window the code-blocks of the tiles it reaches
that the window does not need are not decoded, and with
components the code-blocks of the components
left out are not decoded, so damage there goes unseen, as with
opj_decompress -t and -d. Nor is a code-block a decode skips
checked against the bit-plane limit, so it can succeed where the
whole decode is refused as Error::Limit.
For a codestream as it streams in: a prefix that holds every packet of
the resolutions a reduction keeps decodes at that reduction to the same
samples as the whole codestream, and the report’s
complete_reduction says which
reduction that is. IncrementalDecoder decodes such prefixes for
you: each refine goes on from where the last one stopped reading
packets. The packets it reads again are listed in
docs/incremental-decoding.md.
use rust_j2k::{DecodeOptions, Error, decode_with, read_header};
let bytes = std::fs::read("image.j2k")?;
let prefix = &bytes[..bytes.len() - 20];
// Strict, the default: a cut codestream is an error.
assert!(matches!(
decode_with(prefix, &DecodeOptions::default()),
Err(Error::Codestream(_))
));
// Not strict: the image, and what it lacks.
let options = DecodeOptions::default().with_strict(false);
let image = decode_with(prefix, &options).expect("decodes");
assert!(!image.report.is_complete());
// The coarsest level a decode may ask for, and the finest the data holds.
let max = read_header(prefix).expect("the main header is there").max_reduction;
if let Some(r) = image.report.complete_reduction.filter(|&r| r <= max) {
let coarse = decode_with(prefix, &options.with_resolution_reduction(r)).expect("decodes");
assert!(coarse.report.is_complete());
}Implementations§
Source§impl DecodeOptions
impl DecodeOptions
Sourcepub fn with_resolution_reduction(self, levels: u8) -> Self
pub fn with_resolution_reduction(self, levels: u8) -> Self
These options with
resolution_reduction set to levels.
use rust_j2k::DecodeOptions;
let options = DecodeOptions::default().with_resolution_reduction(1);
assert_eq!(options.resolution_reduction, 1);Sourcepub fn with_max_quality_layers(self, layers: Option<u16>) -> Self
pub fn with_max_quality_layers(self, layers: Option<u16>) -> Self
These options with
max_quality_layers set to layers.
Header::quality_layers is how many
layers the main header declares.
use rust_j2k::DecodeOptions;
let options = DecodeOptions::default().with_max_quality_layers(Some(2));
assert_eq!(options.max_quality_layers, Some(2));Sourcepub fn with_region(self, region: Region) -> Self
pub fn with_region(self, region: Region) -> Self
These options with region set to region.
use rust_j2k::{DecodeOptions, Region, Window};
let options = DecodeOptions::default().with_region(Region::Tile(3));
assert_eq!(options.region, Region::Tile(3));
let window = Region::Window(Window::new(0, 0, 64, 64));
assert_eq!(DecodeOptions::default().with_region(window.clone()).region, window);Sourcepub fn with_components(self, components: Option<Vec<u16>>) -> Self
pub fn with_components(self, components: Option<Vec<u16>>) -> Self
These options with components set to
components.
use rust_j2k::DecodeOptions;
let options = DecodeOptions::default().with_components(Some(vec![0]));
assert_eq!(options.components, Some(vec![0]));Sourcepub fn with_raw_channels(self, raw: bool) -> Self
pub fn with_raw_channels(self, raw: bool) -> Self
These options with raw_channels set to raw.
use rust_j2k::DecodeOptions;
let options = DecodeOptions::default().with_raw_channels(true);
assert!(options.raw_channels);Sourcepub fn with_color(self, color: ColorOutput) -> Self
pub fn with_color(self, color: ColorOutput) -> Self
These options with color set to color.
use rust_j2k::{ColorOutput, DecodeOptions};
let options = DecodeOptions::default().with_color(ColorOutput::Srgb);
assert_eq!(options.color, ColorOutput::Srgb);Sourcepub fn with_packet_work_limit(self, limit: WorkLimit) -> Self
pub fn with_packet_work_limit(self, limit: WorkLimit) -> Self
These options with packet_work_limit
set to limit.
use rust_j2k::{DecodeOptions, WorkLimit};
let options = DecodeOptions::default().with_packet_work_limit(WorkLimit::Raised(4));
assert_eq!(options.packet_work_limit, WorkLimit::Raised(4));Sourcepub fn with_code_block_work_limit(self, limit: WorkLimit) -> Self
pub fn with_code_block_work_limit(self, limit: WorkLimit) -> Self
These options with
code_block_work_limit set to limit.
use rust_j2k::{DecodeOptions, WorkLimit};
let options = DecodeOptions::default().with_code_block_work_limit(WorkLimit::Unlimited);
assert_eq!(options.code_block_work_limit, WorkLimit::Unlimited);Sourcepub fn with_sample_limit(self, limit: WorkLimit) -> Self
pub fn with_sample_limit(self, limit: WorkLimit) -> Self
These options with sample_limit set to
limit.
use rust_j2k::{DecodeOptions, WorkLimit};
// Up to 3 x 2^29 samples, enough for a 20000 x 20000 RGB image.
let options = DecodeOptions::default().with_sample_limit(WorkLimit::Raised(3));
assert_eq!(options.sample_limit, WorkLimit::Raised(3));Sourcepub fn with_retry(&self, limit: &LimitDetail) -> Option<Self>
pub fn with_retry(&self, limit: &LimitDetail) -> Option<Self>
These options with the limit that refused a decode set to the one
it gave to retry with, or None if no option raises it or the
refusal gave none (LimitDetail::retry_with).
use rust_j2k::{DecodeOptions, Error, WorkLimit, decode};
// A file that asks for far more work than its size allows.
let bytes = std::fs::read("image.j2k")?;
let Err(Error::Limit(limit)) = decode(&bytes) else { panic!() };
let options = DecodeOptions::default().with_retry(&limit).unwrap();
assert_eq!(options.code_block_work_limit, WorkLimit::Raised(2));Sourcepub fn with_strict(self, strict: bool) -> Self
pub fn with_strict(self, strict: bool) -> Self
These options with strict set to strict.
use rust_j2k::DecodeOptions;
assert!(DecodeOptions::default().strict);
let options = DecodeOptions::default().with_strict(false);
assert!(!options.strict);