pub mod markers;
use std::borrow::Cow;
use crate::{Error, Result};
use markers::{
Cod, Coding, ComponentParams, PocVolume, Progression, Qcd, QuantStyle, Siz, SizComponent,
TlmEntry, Transform, marker,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MainHeader {
pub siz: Siz,
pub cod: Cod,
pub qcd: Qcd,
pub components: Vec<ComponentParams>,
pub tlm: Vec<TlmEntry>,
pub poc: Vec<PocVolume>,
pub crg: Vec<(u16, u16)>,
}
impl MainHeader {
pub fn new(siz: Siz, cod: Cod, qcd: Qcd) -> Self {
let components = vec![
ComponentParams {
coding: cod.coding(),
quant: qcd.clone(),
roi_shift: 0,
};
siz.components.len()
];
MainHeader {
siz,
cod,
qcd,
components,
tlm: Vec::new(),
poc: Vec::new(),
crg: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Tile<'a> {
pub index: u32,
pub header: TileHeader,
pub data: Cow<'a, [u8]>,
pub packed_headers: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Codestream<'a> {
pub header: MainHeader,
pub tiles: Vec<Tile<'a>>,
}
impl Codestream<'_> {
pub fn tile_header(&self, index: usize) -> Result<MainHeader> {
let tile = self
.tiles
.get(index)
.ok_or_else(|| Error::Inconsistent(format!("no tile {index}")))?;
resolve_tile_header(&self.header, &tile.header)
}
}
const JP2_SIGNATURE: [u8; 12] = [
0x00, 0x00, 0x00, 0x0C, b'j', b'P', b' ', b' ', 0x0D, 0x0A, 0x87, 0x0A,
];
pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
if bytes.starts_with(&JP2_SIGNATURE) {
return Err(Error::Unsupported(
"JP2 file format wrapper; pass the contained codestream (the `jp2c` box contents)"
.into(),
));
}
let (header, sot_offset, ppm) = parse_main_header(bytes)?;
let tiles = walk_tiles(bytes, sot_offset, &header, &ppm)?;
let codestream = Codestream { header, tiles };
for index in 0..codestream.tiles.len() {
let tile = codestream.tile_header(index)?;
let pairs = tile.components.iter().zip(&codestream.header.components);
for (component, (in_tile, in_main)) in pairs.enumerate() {
if in_tile.coding.transform != in_main.coding.transform {
return Err(Error::Unsupported(format!(
"tile {index} codes component {component} with the {:?} wavelet where the \
main header uses {:?}; tiles that disagree on a component's wavelet are \
not decoded",
in_tile.coding.transform, in_main.coding.transform,
)));
}
}
}
Ok(codestream)
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct TileHeader {
cod: Option<Cod>,
qcd: Option<Qcd>,
coc: Vec<(usize, Coding)>,
qcc: Vec<(usize, Qcd)>,
rgn: Vec<(usize, u8)>,
poc: Vec<PocVolume>,
}
#[derive(Debug)]
struct TileParts<'a> {
parts: Vec<&'a [u8]>,
declared_parts: Option<u8>,
header: TileHeader,
packed_headers: Vec<u8>,
}
fn walk_tiles<'a>(
bytes: &'a [u8],
sot_offset: usize,
main: &MainHeader,
ppm: &[Vec<u8>],
) -> Result<Vec<Tile<'a>>> {
let tile_count = main.siz.num_tiles() as usize;
let mut ppm_seq = 0usize;
let mut tiles: Vec<TileParts<'a>> = (0..tile_count)
.map(|_| TileParts {
parts: Vec::new(),
declared_parts: None,
header: TileHeader::default(),
packed_headers: Vec::new(),
})
.collect();
let mut part_offset = sot_offset;
loop {
let mut cur = Cursor::at(bytes, part_offset);
if cur.u16()? != marker::SOT {
return Err(Error::Codestream(
"tile-part does not start with SOT".into(),
));
}
let sot = decode_sot(segment(&mut cur)?)?;
let index = usize::from(sot.tile_index);
let tile = tiles.get_mut(index).ok_or_else(|| {
Error::Codestream(format!(
"tile-part names tile {index}, but the grid holds {tile_count} tiles"
))
})?;
if usize::from(sot.tile_part_index) != tile.parts.len() {
return Err(Error::Codestream(format!(
"tile {index} tile-part index is {}, but {} of its tile-parts have been read",
sot.tile_part_index,
tile.parts.len(),
)));
}
if sot.num_tile_parts != 0 {
if sot.tile_part_index >= sot.num_tile_parts {
return Err(Error::Codestream(format!(
"tile {index} tile-part {} of a declared {} tile-parts",
sot.tile_part_index, sot.num_tile_parts,
)));
}
match tile.declared_parts {
Some(declared) if declared != sot.num_tile_parts => {
return Err(Error::Codestream(format!(
"tile {index} declares {} tile-parts in one SOT and {declared} in another",
sot.num_tile_parts,
)));
}
_ => tile.declared_parts = Some(sot.num_tile_parts),
}
}
let first_part = sot.tile_part_index == 0;
let (tile_header, packed) = read_tile_part_header(&mut cur, &main.siz, first_part)?;
if first_part {
tile.header = tile_header;
} else {
check_poc_budget(tile.header.poc.len() + tile_header.poc.len())?;
tile.header.poc.extend(tile_header.poc);
}
if ppm.is_empty() {
tile.packed_headers.extend(packed);
} else {
if !packed.is_empty() {
return Err(Error::Unsupported(
"a codestream carrying both PPM and PPT packed headers is not decoded".into(),
));
}
let chunk = ppm.get(ppm_seq).ok_or_else(|| {
Error::Codestream(
"PPM carries fewer packet-header chunks than the codestream has tile-parts"
.into(),
)
})?;
ppm_seq += 1;
tile.packed_headers.extend_from_slice(chunk);
}
let data_start = cur.pos;
let data_end = if sot.psot == 0 {
bytes
.len()
.checked_sub(2)
.filter(|&end| end >= data_start && read_u16(bytes, end) == Some(marker::EOC))
.ok_or_else(|| {
Error::Codestream("Psot=0 tile-part is not terminated by EOC".into())
})?
} else {
let end = part_offset
.checked_add(sot.psot as usize)
.filter(|&end| end <= bytes.len())
.ok_or_else(|| Error::Codestream("Psot overruns the codestream".into()))?;
if end < data_start {
return Err(Error::Codestream(
"Psot is shorter than the tile-part header".into(),
));
}
end
};
tiles[index].parts.push(&bytes[data_start..data_end]);
match read_u16(bytes, data_end) {
Some(marker::EOC) => break,
Some(marker::SOT) => part_offset = data_end,
Some(other) => {
return Err(Error::Codestream(format!(
"expected SOT or EOC after a tile-part, found {other:#06X}"
)));
}
None => return Err(Error::Codestream("missing EOC after the tile-part".into())),
}
}
if ppm_seq != ppm.len() {
return Err(Error::Codestream(format!(
"PPM carries {} packet-header chunk(s) but the codestream has {ppm_seq} tile-part(s)",
ppm.len(),
)));
}
tiles
.into_iter()
.enumerate()
.map(|(index, tile)| {
if tile.parts.is_empty() {
return Err(Error::Codestream(format!(
"the codestream carries no tile-part for tile {index}"
)));
}
if let Some(declared) = tile.declared_parts {
if usize::from(declared) != tile.parts.len() {
return Err(Error::Codestream(format!(
"tile {index} declares {declared} tile-parts but carries {}",
tile.parts.len()
)));
}
}
let data = match <[&[u8]; 1]>::try_from(tile.parts.as_slice()) {
Ok([only]) => Cow::Borrowed(only),
Err(_) => Cow::Owned(tile.parts.concat()),
};
Ok(Tile {
index: index as u32,
header: tile.header,
data,
packed_headers: tile.packed_headers,
})
})
.collect()
}
fn read_tile_part_header(
cur: &mut Cursor<'_>,
siz: &Siz,
first_part: bool,
) -> Result<(TileHeader, Vec<u8>)> {
let mut tile = TileHeader::default();
let mut ppt: Vec<(u8, Vec<u8>)> = Vec::new();
let overrides_here = |code: u16| -> Result<()> {
if first_part {
Ok(())
} else {
Err(Error::Codestream(format!(
"marker {code:#06X} appears in a tile-part header other than the first; \
the coding-parameter overrides belong to the first tile-part of a tile"
)))
}
};
loop {
let m = cur.u16()?;
match m {
marker::SOD => break,
marker::COM => {
segment(cur)?;
}
marker::COD => {
overrides_here(m)?;
if tile.cod.replace(decode_cod(segment(cur)?)?).is_some() {
return Err(Error::Codestream(
"duplicate COD marker in the tile-part header".into(),
));
}
}
marker::QCD => {
overrides_here(m)?;
if tile
.qcd
.replace(decode_quant(segment(cur)?, "QCD")?)
.is_some()
{
return Err(Error::Codestream(
"duplicate QCD marker in the tile-part header".into(),
));
}
}
marker::COC => {
overrides_here(m)?;
let (index, coding) = decode_coc(segment(cur)?, siz)?;
if tile.coc.iter().any(|&(i, _)| i == index) {
return Err(Error::Codestream(format!(
"duplicate COC marker for component {index} in the tile-part header"
)));
}
tile.coc.push((index, coding));
}
marker::QCC => {
overrides_here(m)?;
let (index, quant) = decode_qcc(segment(cur)?, siz)?;
if tile.qcc.iter().any(|&(i, _)| i == index) {
return Err(Error::Codestream(format!(
"duplicate QCC marker for component {index} in the tile-part header"
)));
}
tile.qcc.push((index, quant));
}
marker::RGN => {
overrides_here(m)?;
let (index, shift) = decode_rgn(segment(cur)?, siz)?;
if tile.rgn.iter().any(|&(i, _)| i == index) {
return Err(Error::Codestream(format!(
"duplicate RGN marker for component {index} in the tile-part header"
)));
}
tile.rgn.push((index, shift));
}
marker::PLT => {
decode_plt(segment(cur)?)?;
}
marker::POC => {
decode_poc(segment(cur)?, siz, &mut tile.poc)?;
}
marker::PPT => {
let mut body = segment(cur)?;
let zppt = body.u8()?;
if ppt.iter().any(|&(z, _)| z == zppt) {
return Err(Error::Codestream(format!(
"duplicate PPT index Zppt {zppt} in one tile-part header"
)));
}
let ippt = body.take(body.remaining())?;
ppt.push((zppt, ippt.to_vec()));
}
marker::TLM | marker::PLM | marker::SOP | marker::EPH => {
return Err(Error::Codestream(format!(
"marker {m:#06X} is not permitted in a tile-part header"
)));
}
other => {
return Err(Error::Codestream(format!(
"unexpected marker {other:#06X} in tile-part header"
)));
}
}
}
ppt.sort_by_key(|&(z, _)| z);
let packed = ppt.into_iter().flat_map(|(_, bytes)| bytes).collect();
Ok((tile, packed))
}
fn resolve_tile_header(main: &MainHeader, tile: &TileHeader) -> Result<MainHeader> {
let mut header = main.clone();
if let Some(cod) = &tile.cod {
header.cod = cod.clone();
let coding = header.cod.coding();
for params in &mut header.components {
params.coding = coding.clone();
}
}
if let Some(qcd) = &tile.qcd {
header.qcd = qcd.clone();
for params in &mut header.components {
params.quant = qcd.clone();
}
}
for (index, coding) in &tile.coc {
header.components[*index].coding = coding.clone();
}
for (index, quant) in &tile.qcc {
header.components[*index].quant = quant.clone();
}
for (index, shift) in &tile.rgn {
header.components[*index].roi_shift = *shift;
}
check_poc_budget(header.poc.len() + tile.poc.len())?;
header.poc.extend(tile.poc.iter().copied());
validate_resolved(&header)?;
Ok(header)
}
struct Sot {
tile_index: u16,
psot: u32,
tile_part_index: u8,
num_tile_parts: u8,
}
fn decode_sot(mut b: Cursor<'_>) -> Result<Sot> {
let tile_index = b.u16()?;
let psot = b.u32()?;
let tile_part_index = b.u8()?;
let num_tile_parts = b.u8()?;
b.expect_consumed("SOT")?;
Ok(Sot {
tile_index,
psot,
tile_part_index,
num_tile_parts,
})
}
fn read_u16(bytes: &[u8], pos: usize) -> Option<u16> {
let hi = *bytes.get(pos)?;
let lo = *bytes.get(pos + 1)?;
Some(u16::from_be_bytes([hi, lo]))
}
struct Segment<'a> {
code: u16,
body: &'a [u8],
}
const MAX_MAIN_HEADER_SEGMENTS: usize = 1 << 16;
fn walk_main_header(bytes: &[u8]) -> Result<(Vec<Segment<'_>>, usize)> {
let mut cur = Cursor::new(bytes);
if cur.u16()? != marker::SOC {
return Err(Error::Codestream(
"does not start with the SOC marker".into(),
));
}
let mut segments = Vec::new();
let sot_offset = loop {
let code = cur.u16()?;
match code {
marker::SOT => break cur.pos - 2,
marker::SOC | marker::SOD | marker::EOC => {
return Err(Error::Codestream(format!(
"unexpected marker {code:#06X} before any tile-part"
)));
}
_ if !marker::is_marker(code) => {
return Err(Error::Codestream(format!(
"expected a marker in the main header, found {code:#06X}"
)));
}
_ => {
if segments.len() == MAX_MAIN_HEADER_SEGMENTS {
return Err(Error::Codestream(format!(
"main header has more than {MAX_MAIN_HEADER_SEGMENTS} marker segments"
)));
}
let body = if marker::has_segment(code) {
segment(&mut cur)?.buf
} else {
&[][..]
};
segments.push(Segment { code, body });
}
}
};
Ok((segments, sot_offset))
}
fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize, Vec<Vec<u8>>)> {
let (segments, sot_offset) = walk_main_header(bytes)?;
let Some(first) = segments.first() else {
return Err(Error::Codestream(
"main header has no marker segments".into(),
));
};
if first.code != marker::SIZ {
return Err(Error::Codestream(
"SIZ must be the first marker after SOC".into(),
));
}
let siz = decode_siz(Cursor::new(first.body))?;
validate_geometry(&siz)?;
check_sample_budget(&siz)?;
let mut cod = None;
let mut qcd = None;
let mut coc: Vec<Option<Coding>> = vec![None; siz.components.len()];
let mut qcc: Vec<Option<Qcd>> = vec![None; siz.components.len()];
let mut rgn: Vec<Option<u8>> = vec![None; siz.components.len()];
let mut tlm: Vec<TlmEntry> = Vec::new();
let mut poc: Vec<PocVolume> = Vec::new();
let mut crg: Option<Vec<(u16, u16)>> = None;
let mut ppm: Vec<(u8, Vec<u8>)> = Vec::new();
for seg in &segments[1..] {
let body = || Cursor::new(seg.body);
match seg.code {
marker::SIZ => {
return Err(Error::Codestream("duplicate SIZ marker".into()));
}
marker::COD => {
if cod.is_some() {
return Err(Error::Codestream("duplicate COD marker".into()));
}
cod = Some(decode_cod(body())?);
}
marker::QCD => {
if qcd.is_some() {
return Err(Error::Codestream("duplicate QCD marker".into()));
}
qcd = Some(decode_quant(body(), "QCD")?);
}
marker::COC => {
let (index, coding) = decode_coc(body(), &siz)?;
if coc[index].replace(coding).is_some() {
return Err(Error::Codestream(format!(
"duplicate COC marker for component {index}"
)));
}
}
marker::QCC => {
let (index, quant) = decode_qcc(body(), &siz)?;
if qcc[index].replace(quant).is_some() {
return Err(Error::Codestream(format!(
"duplicate QCC marker for component {index}"
)));
}
}
marker::RGN => {
let (index, shift) = decode_rgn(body(), &siz)?;
if rgn[index].replace(shift).is_some() {
return Err(Error::Codestream(format!(
"duplicate RGN marker for component {index}"
)));
}
}
marker::COM => {}
marker::TLM => decode_tlm(body(), &siz, &mut tlm)?,
marker::PLM => decode_plm(body())?,
marker::POC => decode_poc(body(), &siz, &mut poc)?,
marker::CRG => {
if crg.replace(decode_crg(body(), &siz)?).is_some() {
return Err(Error::Codestream("duplicate CRG marker".into()));
}
}
marker::PLT => {
return Err(Error::Codestream(
"PLT is a tile-part-header marker; it is not permitted in the main header"
.into(),
));
}
marker::PPM => {
let mut b = body();
let zppm = b.u8()?;
let ippm = b.take(b.remaining())?;
ppm.push((zppm, ippm.to_vec()));
}
marker::CAP | marker::PPT | marker::SOP | marker::EPH => {
return Err(Error::Unsupported(format!(
"marker {} is outside the decoded subset",
marker::describe(seg.code)
)));
}
code if marker::PART2.contains(&code) => {
return Err(Error::Unsupported(format!(
"{} is a JPEG 2000 Part 2 marker, outside the Part 1 subset",
marker::describe(seg.code)
)));
}
code if marker::RESERVED_NO_SEGMENT.contains(&code) => {}
other => {
return Err(Error::Unsupported(format!(
"unrecognized marker {other:#06X} in the main header"
)));
}
}
}
let cod = cod.ok_or_else(|| Error::Codestream("missing required COD marker".into()))?;
let qcd = qcd.ok_or_else(|| Error::Codestream("missing required QCD marker".into()))?;
let mut header = MainHeader::new(siz, cod, qcd);
header.tlm = tlm;
header.poc = poc;
header.crg = crg.unwrap_or_default();
for (params, ((coding, quant), shift)) in header
.components
.iter_mut()
.zip(coc.into_iter().zip(qcc).zip(rgn))
{
if let Some(coding) = coding {
params.coding = coding;
}
if let Some(quant) = quant {
params.quant = quant;
}
if let Some(shift) = shift {
params.roi_shift = shift;
}
}
validate_resolved(&header)?;
let ppm_chunks = decode_ppm_chunks(ppm)?;
Ok((header, sot_offset, ppm_chunks))
}
fn validate_resolved(header: &MainHeader) -> Result<()> {
for (index, params) in header.components.iter().enumerate() {
let needed = 3 * usize::from(params.coding.decomposition_levels) + 1;
if params.quant.style != QuantStyle::ScalarDerived && params.quant.steps.len() < needed {
return Err(Error::Marker(format!(
"component {index} carries {} quantization step entries but its {} \
decomposition levels need {needed}",
params.quant.steps.len(),
params.coding.decomposition_levels
)));
}
if params.coding.transform == Transform::Irreversible97
&& params.quant.style == QuantStyle::None
{
return Err(Error::Marker(format!(
"component {index} pairs the 9/7 wavelet with the no-quantization style"
)));
}
}
if header.cod.multiple_component_transform {
crate::mct::check_geometry(&header.siz.components)?;
let transform = header.components[0].coding.transform;
for (index, params) in header.components.iter().take(3).enumerate() {
if params.coding.transform != transform {
return Err(Error::Unsupported(format!(
"COD signals the colour transform but component {index} uses a different \
wavelet than component 0; the transform is undefined over a mix"
)));
}
}
}
Ok(())
}
const MAX_IMAGE_SAMPLES: u64 = 1 << 26;
fn check_sample_budget(siz: &Siz) -> Result<()> {
let mut total: u64 = 0;
for index in 0..siz.components.len() {
let (width, height) = siz
.component_extent(index)
.ok_or_else(|| Error::Inconsistent(format!("SIZ declares no component {index}")))?;
total += u64::from(width) * u64::from(height);
if total > MAX_IMAGE_SAMPLES {
return Err(Error::Unsupported(format!(
"components total over {MAX_IMAGE_SAMPLES} samples, above the decode guard"
)));
}
}
Ok(())
}
fn validate_geometry(siz: &Siz) -> Result<()> {
if siz.x_size == 0 || siz.y_size == 0 {
return Err(Error::Marker("SIZ declares a zero-size image".into()));
}
if siz.x_offset >= siz.x_size || siz.y_offset >= siz.y_size {
return Err(Error::Marker(format!(
"image offset ({}, {}) is not inside the image {}×{}",
siz.x_offset, siz.y_offset, siz.x_size, siz.y_size
)));
}
if siz.tile_width == 0 || siz.tile_height == 0 {
return Err(Error::Marker("SIZ declares a zero-size tile".into()));
}
if siz.tile_x_offset > siz.x_offset || siz.tile_y_offset > siz.y_offset {
return Err(Error::Marker(format!(
"tile offset ({}, {}) is past the image offset ({}, {})",
siz.tile_x_offset, siz.tile_y_offset, siz.x_offset, siz.y_offset
)));
}
if u64::from(siz.tile_x_offset) + u64::from(siz.tile_width) <= u64::from(siz.x_offset)
|| u64::from(siz.tile_y_offset) + u64::from(siz.tile_height) <= u64::from(siz.y_offset)
{
return Err(Error::Marker(format!(
"tile ({}×{} at offset ({}, {})) does not reach the image offset ({}, {})",
siz.tile_width,
siz.tile_height,
siz.tile_x_offset,
siz.tile_y_offset,
siz.x_offset,
siz.y_offset,
)));
}
let (width, height) = siz.image_extent_at(0);
if u64::from(width) * u64::from(height) > MAX_IMAGE_SAMPLES {
return Err(Error::Unsupported(format!(
"image area {width}×{height} exceeds the decode guard of {MAX_IMAGE_SAMPLES} samples",
)));
}
const MAX_TILES: u32 = 65535;
let tiles = siz.num_tiles();
if tiles > MAX_TILES {
return Err(Error::Marker(format!(
"tile grid is {}×{} = {tiles} tiles, past the {MAX_TILES}-tile limit on Isot",
siz.tile_grid().0,
siz.tile_grid().1,
)));
}
Ok(())
}
fn decode_siz(mut b: Cursor<'_>) -> Result<Siz> {
let _rsiz = b.u16()?; let x_size = b.u32()?;
let y_size = b.u32()?;
let x_offset = b.u32()?;
let y_offset = b.u32()?;
let tile_width = b.u32()?;
let tile_height = b.u32()?;
let tile_x_offset = b.u32()?;
let tile_y_offset = b.u32()?;
let csiz = b.u16()?;
if csiz == 0 {
return Err(Error::Marker("SIZ declares zero components".into()));
}
if csiz > markers::MAX_COMPONENTS {
return Err(Error::Marker(format!(
"SIZ declares {csiz} components, above the limit of {}",
markers::MAX_COMPONENTS
)));
}
if b.remaining() != 3 * csiz as usize {
return Err(Error::Codestream(format!(
"SIZ has {} bytes for {csiz} component records, expected {}",
b.remaining(),
3 * csiz as usize,
)));
}
let mut components = Vec::with_capacity(csiz as usize);
for index in 0..csiz {
let ssiz = b.u8()?;
let x_sampling = b.u8()?;
let y_sampling = b.u8()?;
let bit_depth = (ssiz & 0x7F) + 1;
if bit_depth > 38 {
return Err(Error::Marker(format!(
"component {index} declares bit depth {bit_depth}, above the limit of 38"
)));
}
if x_sampling == 0 || y_sampling == 0 {
return Err(Error::Marker(format!(
"component {index} declares a zero sub-sampling factor ({x_sampling}, {y_sampling})"
)));
}
components.push(SizComponent {
bit_depth,
signed: ssiz & 0x80 != 0,
x_sampling,
y_sampling,
});
}
b.expect_consumed("SIZ")?;
let siz = Siz {
x_size,
y_size,
x_offset,
y_offset,
tile_width,
tile_height,
tile_x_offset,
tile_y_offset,
components,
};
Ok(siz)
}
fn decode_cod(mut b: Cursor<'_>) -> Result<Cod> {
let scod = b.u8()?;
if scod & 0xF8 != 0 {
return Err(Error::Marker(format!(
"COD sets reserved Scod bits {:#04X}",
scod & 0xF8
)));
}
let explicit_precincts = scod & 0x01 != 0;
let use_sop = scod & 0x02 != 0;
let use_eph = scod & 0x04 != 0;
let progression = match b.u8()? {
0 => Progression::Lrcp,
1 => Progression::Rlcp,
2 => Progression::Rpcl,
3 => Progression::Pcrl,
4 => Progression::Cprl,
other => {
return Err(Error::Marker(format!("reserved progression order {other}")));
}
};
let layers = b.u16()?;
if layers == 0 {
return Err(Error::Marker("COD declares zero quality layers".into()));
}
let mct = b.u8()?;
let multiple_component_transform = match mct {
0 => false,
1 => true,
other => {
return Err(Error::Unsupported(format!(
"multiple-component transform type {other}; only the Part 1 colour transform is decoded"
)));
}
};
let coding = decode_coding(&mut b, "COD", explicit_precincts)?;
let Coding {
decomposition_levels,
code_block_width,
code_block_height,
code_block_style,
transform,
precinct_sizes,
} = coding;
b.expect_consumed("COD")?;
Ok(Cod {
progression,
layers,
decomposition_levels,
code_block_width,
code_block_height,
code_block_style,
use_sop,
use_eph,
multiple_component_transform,
transform,
precinct_sizes,
})
}
const MAX_POC_VOLUMES: usize = 32;
fn check_poc_budget(volumes: usize) -> Result<()> {
if volumes > MAX_POC_VOLUMES {
return Err(Error::Unsupported(format!(
"{volumes} progression volumes exceeds the decode guard of {MAX_POC_VOLUMES}"
)));
}
Ok(())
}
fn decode_poc(mut b: Cursor<'_>, siz: &Siz, into: &mut Vec<PocVolume>) -> Result<()> {
let comp_room = if siz.components.len() < 257 { 1 } else { 2 };
let volume_size = 5 + 2 * comp_room;
let body_len = b.remaining();
if body_len == 0 || !body_len.is_multiple_of(volume_size) {
return Err(Error::Marker(format!(
"POC body is {body_len} bytes, not a whole number of {volume_size}-byte volumes"
)));
}
check_poc_budget(into.len() + body_len / volume_size)?;
let read_comp = |b: &mut Cursor<'_>| -> Result<u16> {
if comp_room == 1 {
Ok(u16::from(b.u8()?))
} else {
b.u16()
}
};
for _ in 0..body_len / volume_size {
let res_start = b.u8()?;
let comp_start = read_comp(&mut b)?;
let layer_end = b.u16()?;
let res_end = b.u8()?;
let comp_end = read_comp(&mut b)?;
let progression = Progression::from_u8(b.u8()?)
.ok_or_else(|| Error::Marker("POC volume sets a reserved progression order".into()))?;
if res_end <= res_start || comp_end <= comp_start || layer_end == 0 {
return Err(Error::Marker(format!(
"POC volume has an empty range: resolutions [{res_start}, {res_end}), \
components [{comp_start}, {comp_end}), layers [0, {layer_end})"
)));
}
into.push(PocVolume {
res_start,
res_end,
comp_start,
comp_end,
layer_end,
progression,
});
}
Ok(())
}
fn decode_coding(b: &mut Cursor<'_>, origin: &str, explicit_precincts: bool) -> Result<Coding> {
let decomposition_levels = b.u8()?;
if decomposition_levels > 32 {
return Err(Error::Marker(format!(
"{origin} sets reserved decomposition level count {decomposition_levels} (max 32)"
)));
}
let code_block_width = b.u8()?;
let code_block_height = b.u8()?;
let code_block_style = b.u8()?;
use markers::code_block_style::{LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL};
let undecoded = code_block_style & !(LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET);
if undecoded != 0 {
return Err(Error::Unsupported(format!(
"{origin} code-block style ({}) is outside the decoded subset",
markers::code_block_style::describe(undecoded),
)));
}
let transform = match b.u8()? {
0 => Transform::Irreversible97,
1 => Transform::Reversible53,
other => {
return Err(Error::Marker(format!(
"{origin} sets reserved wavelet transform {other}"
)));
}
};
let precinct_sizes = if explicit_precincts {
let mut sizes = Vec::with_capacity(usize::from(decomposition_levels) + 1);
for resolution in 0..=usize::from(decomposition_levels) {
let byte = b.u8()?;
let (ppx, ppy) = (byte & 0x0F, byte >> 4);
if resolution > 0 && (ppx == 0 || ppy == 0) {
return Err(Error::Marker(format!(
"{origin} sets precinct 2^{ppx}×2^{ppy} at resolution {resolution}; \
a zero exponent is permitted only at resolution 0"
)));
}
sizes.push((ppx, ppy));
}
sizes
} else {
Vec::new()
};
Ok(Coding {
decomposition_levels,
code_block_width,
code_block_height,
code_block_style,
transform,
precinct_sizes,
})
}
fn component_index(b: &mut Cursor<'_>, siz: &Siz, origin: &str) -> Result<usize> {
let count = siz.components.len();
let index = if count < 257 {
usize::from(b.u8()?)
} else {
usize::from(b.u16()?)
};
if index >= count {
return Err(Error::Marker(format!(
"{origin} targets component {index}, but SIZ declares {count}"
)));
}
Ok(index)
}
fn decode_coc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Coding)> {
let index = component_index(&mut b, siz, "COC")?;
let scoc = b.u8()?;
let explicit_precincts = scoc & 0x01 != 0;
if scoc & 0xFE != 0 {
return Err(Error::Marker(format!(
"COC sets reserved Scoc bits {:#04X}",
scoc & 0xFE
)));
}
let coding = decode_coding(&mut b, "COC", explicit_precincts)?;
b.expect_consumed("COC")?;
Ok((index, coding))
}
fn decode_qcc(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, Qcd)> {
let index = component_index(&mut b, siz, "QCC")?;
let quant = decode_quant(b, "QCC")?;
Ok((index, quant))
}
fn decode_rgn(mut b: Cursor<'_>, siz: &Siz) -> Result<(usize, u8)> {
let index = component_index(&mut b, siz, "RGN")?;
let srgn = b.u8()?;
if srgn != 0 {
return Err(Error::Unsupported(format!(
"region-of-interest style {srgn}; only the implicit maxshift (Srgn = 0) is decoded"
)));
}
let shift = b.u8()?;
b.expect_consumed("RGN")?;
Ok((index, shift))
}
fn decode_tlm(mut b: Cursor<'_>, siz: &Siz, entries: &mut Vec<TlmEntry>) -> Result<()> {
b.u8()?; let stlm = b.u8()?;
if stlm & 0x8F != 0 {
return Err(Error::Marker(format!(
"TLM sets reserved Stlm bits {:#04X}",
stlm & 0x8F
)));
}
let st = (stlm >> 4) & 0x3;
if st == 3 {
return Err(Error::Marker(
"TLM tile-index width ST = 3 is not defined".into(),
));
}
let sp = (stlm >> 6) & 0x1;
let entry_size = usize::from(st) + 2 * (usize::from(sp) + 1);
if !b.remaining().is_multiple_of(entry_size) {
return Err(Error::Codestream(format!(
"TLM carries {} entry bytes, not a multiple of its {entry_size}-byte entries",
b.remaining()
)));
}
while b.remaining() > 0 {
let tile_index = match st {
0 => entries.len() as u32,
1 => u32::from(b.u8()?),
_ => u32::from(b.u16()?),
};
if tile_index >= siz.num_tiles() {
return Err(Error::Marker(format!(
"TLM names tile {tile_index}, but the grid holds {} tiles",
siz.num_tiles()
)));
}
let length = match sp {
0 => u32::from(b.u16()?),
_ => b.u32()?,
};
entries.push(TlmEntry { tile_index, length });
}
Ok(())
}
fn decode_crg(mut b: Cursor<'_>, siz: &Siz) -> Result<Vec<(u16, u16)>> {
let count = siz.components.len();
if b.remaining() != count * 4 {
return Err(Error::Marker(format!(
"CRG carries {} bytes, not the {} its {count} components need",
b.remaining(),
count * 4
)));
}
let mut offsets = Vec::with_capacity(count);
for _ in 0..count {
let x = b.u16()?;
let y = b.u16()?;
offsets.push((x, y));
}
Ok(offsets)
}
fn decode_plm(mut b: Cursor<'_>) -> Result<()> {
b.u8()?; Ok(())
}
fn decode_plt(mut b: Cursor<'_>) -> Result<()> {
b.u8()?; let chains = b.take(b.remaining())?;
if chains.last().is_some_and(|&last| last & 0x80 != 0) {
return Err(Error::Codestream(
"PLT ends in the middle of a packet-length entry".into(),
));
}
Ok(())
}
fn decode_ppm_chunks(mut markers: Vec<(u8, Vec<u8>)>) -> Result<Vec<Vec<u8>>> {
if markers.is_empty() {
return Ok(Vec::new());
}
markers.sort_by_key(|&(z, _)| z);
if markers.windows(2).any(|w| w[0].0 == w[1].0) {
return Err(Error::Codestream(
"duplicate PPM index Zppm in the main header".into(),
));
}
let joined: Vec<u8> = markers.into_iter().flat_map(|(_, bytes)| bytes).collect();
let mut cur = Cursor::new(&joined);
let mut chunks = Vec::new();
while cur.remaining() > 0 {
let nppm = cur.u32()? as usize;
chunks.push(cur.take(nppm)?.to_vec());
}
Ok(chunks)
}
fn decode_quant(mut b: Cursor<'_>, origin: &str) -> Result<Qcd> {
let sqcd = b.u8()?;
let guard_bits = sqcd >> 5;
let style = match sqcd & 0x1F {
0 => QuantStyle::None,
1 => QuantStyle::ScalarDerived,
2 => QuantStyle::ScalarExpounded,
other => {
return Err(Error::Marker(format!(
"{origin} sets reserved quantization style {other}"
)));
}
};
const MAX_STEP_ENTRIES: usize = 3 * 32 + 1;
let mut steps = Vec::new();
match style {
QuantStyle::None => {
if b.remaining() == 0 {
return Err(Error::Codestream(format!(
"{origin} carries no step entries"
)));
}
while b.remaining() > 0 {
let v = b.u8()?;
if steps.len() < MAX_STEP_ENTRIES {
steps.push((v >> 3, 0));
}
}
}
QuantStyle::ScalarDerived | QuantStyle::ScalarExpounded => {
if b.remaining() == 0 || !b.remaining().is_multiple_of(2) {
return Err(Error::Codestream(format!(
"{origin} step table is truncated"
)));
}
if style == QuantStyle::ScalarDerived && b.remaining() != 2 {
return Err(Error::Codestream(format!(
"derived {origin} must carry exactly one step entry"
)));
}
while b.remaining() > 0 {
let v = b.u16()?;
if steps.len() < MAX_STEP_ENTRIES {
steps.push((((v >> 11) & 0x1F) as u8, v & 0x07FF));
}
}
}
}
Ok(Qcd {
style,
guard_bits,
steps,
})
}
fn segment<'a>(cur: &mut Cursor<'a>) -> Result<Cursor<'a>> {
let len = cur.u16()? as usize;
if len < 2 {
return Err(Error::Codestream("marker segment length below 2".into()));
}
let body = cur.take(len - 2)?;
Ok(Cursor::new(body))
}
struct Cursor<'a> {
buf: &'a [u8],
pos: usize,
}
impl<'a> Cursor<'a> {
fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0 }
}
fn at(buf: &'a [u8], pos: usize) -> Self {
Self { buf, pos }
}
fn remaining(&self) -> usize {
self.buf.len() - self.pos
}
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
if self.remaining() < n {
return Err(Error::Codestream("truncated marker segment".into()));
}
let slice = &self.buf[self.pos..self.pos + n];
self.pos += n;
Ok(slice)
}
fn u8(&mut self) -> Result<u8> {
Ok(self.take(1)?[0])
}
fn u16(&mut self) -> Result<u16> {
let b = self.take(2)?;
Ok(u16::from_be_bytes([b[0], b[1]]))
}
fn u32(&mut self) -> Result<u32> {
let b = self.take(4)?;
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
fn expect_consumed(&self, marker: &str) -> Result<()> {
if self.remaining() != 0 {
return Err(Error::Codestream(format!(
"{marker} segment has {} unexpected trailing byte(s)",
self.remaining()
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests;