pub mod bio;
pub mod tagtree;
use crate::codestream::{Codestream, MainHeader};
use crate::{Error, Result};
use bio::BitReader;
use tagtree::TagTree;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BandKind {
Ll,
Hl,
Lh,
Hh,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodeBlock<'a> {
pub x: usize,
pub y: usize,
pub width: usize,
pub height: usize,
pub num_passes: u32,
pub zero_bit_planes: u32,
pub segment: &'a [u8],
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Subband<'a> {
pub kind: BandKind,
pub origin: (u32, u32),
pub width: usize,
pub height: usize,
pub block_cols: usize,
pub block_rows: usize,
pub blocks: Vec<CodeBlock<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Resolution<'a> {
pub subbands: Vec<Subband<'a>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodedData<'a> {
pub resolutions: Vec<Resolution<'a>>,
}
pub fn decode_packets<'a>(cs: &Codestream<'a>) -> Result<CodedData<'a>> {
let tile = cs
.tile_parts
.first()
.ok_or_else(|| Error::Codestream("codestream carries no tile-part".into()))?;
let data = tile.data;
let geoms = resolution_geoms(&cs.header)?;
let mut cursor = 0usize;
let mut resolutions = Vec::with_capacity(geoms.len());
for bands in &geoms {
let (subbands, next) = parse_packet(data, cursor, bands)?;
cursor = next;
resolutions.push(Resolution { subbands });
}
if cursor != data.len() {
return Err(Error::Codestream(format!(
"tile-part has {} byte(s) left after the last packet",
data.len() - cursor
)));
}
Ok(CodedData { resolutions })
}
struct BandGeom {
kind: BandKind,
origin: (u32, u32),
width: usize,
height: usize,
block_cols: usize,
block_rows: usize,
blocks: Vec<(usize, usize, usize, usize)>,
}
fn ceil_div(a: i64, b: i64) -> i64 {
debug_assert!(b > 0, "ceil_div needs a positive divisor");
let q = a.div_euclid(b);
if a.rem_euclid(b) != 0 { q + 1 } else { q }
}
fn resolution_geoms(header: &MainHeader) -> Result<Vec<Vec<BandGeom>>> {
let siz = &header.siz;
let cod = &header.cod;
let nl = cod.decomposition_levels as i64;
if nl > 32 {
return Err(Error::Unsupported(format!(
"{nl} decomposition levels exceeds the 32-level maximum"
)));
}
let comp = siz
.components
.first()
.ok_or_else(|| Error::Codestream("SIZ declares no components".into()))?;
let xr = (comp.x_sampling.max(1)) as i64;
let yr = (comp.y_sampling.max(1)) as i64;
let tx0 = (siz.tile_x_offset as i64).max(siz.x_offset as i64);
let ty0 = (siz.tile_y_offset as i64).max(siz.y_offset as i64);
let tx1 = (siz.tile_x_offset as i64 + siz.tile_width as i64).min(siz.x_size as i64);
let ty1 = (siz.tile_y_offset as i64 + siz.tile_height as i64).min(siz.y_size as i64);
if tx1 <= tx0 || ty1 <= ty0 {
return Err(Error::Codestream("tile has empty area".into()));
}
let (tcx0, tcx1) = (ceil_div(tx0, xr), ceil_div(tx1, xr));
let (tcy0, tcy1) = (ceil_div(ty0, yr), ceil_div(ty1, yr));
let xcb = cod.code_block_width as u32 + 2;
let ycb = cod.code_block_height as u32 + 2;
if xcb > 10 || ycb > 10 || xcb + ycb > 12 {
return Err(Error::Marker(format!(
"code-block size 2^{xcb}×2^{ycb} exceeds the 2^10 / xcb+ycb≤12 limit"
)));
}
let mut levels = Vec::with_capacity((nl + 1) as usize);
for r in 0..=nl {
let bands = if r == 0 {
let pow = 1i64 << nl;
vec![band_geom(
BandKind::Ll,
ceil_div(tcx0, pow),
ceil_div(tcx1, pow),
ceil_div(tcy0, pow),
ceil_div(tcy1, pow),
xcb.min(15),
ycb.min(15),
)]
} else {
let nb = nl - r + 1;
let pow = 1i64 << nb;
let half = 1i64 << (nb - 1);
[
(BandKind::Hl, 1, 0),
(BandKind::Lh, 0, 1),
(BandKind::Hh, 1, 1),
]
.into_iter()
.map(|(kind, xob, yob)| {
band_geom(
kind,
ceil_div(tcx0 - xob * half, pow),
ceil_div(tcx1 - xob * half, pow),
ceil_div(tcy0 - yob * half, pow),
ceil_div(tcy1 - yob * half, pow),
xcb.min(14),
ycb.min(14),
)
})
.collect()
};
levels.push(bands);
}
Ok(levels)
}
fn band_geom(
kind: BandKind,
bx0: i64,
bx1: i64,
by0: i64,
by1: i64,
xcb: u32,
ycb: u32,
) -> BandGeom {
let width = (bx1 - bx0).max(0) as usize;
let height = (by1 - by0).max(0) as usize;
let cbw = 1i64 << xcb;
let cbh = 1i64 << ycb;
let (block_cols, first_col) = grid_span(bx0, bx1, cbw);
let (block_rows, first_row) = grid_span(by0, by1, cbh);
let mut blocks = Vec::with_capacity(block_cols * block_rows);
for j in 0..block_rows {
let gy0 = (first_row + j as i64) * cbh;
let cy0 = gy0.max(by0);
let cy1 = (gy0 + cbh).min(by1);
for i in 0..block_cols {
let gx0 = (first_col + i as i64) * cbw;
let cx0 = gx0.max(bx0);
let cx1 = (gx0 + cbw).min(bx1);
blocks.push((
(cx0 - bx0) as usize,
(cy0 - by0) as usize,
(cx1 - cx0) as usize,
(cy1 - cy0) as usize,
));
}
}
BandGeom {
kind,
origin: (bx0.max(0) as u32, by0.max(0) as u32),
width,
height,
block_cols,
block_rows,
blocks,
}
}
fn grid_span(lo: i64, hi: i64, cell: i64) -> (usize, i64) {
if hi <= lo {
return (0, 0);
}
let first = lo.div_euclid(cell);
let last = ceil_div(hi, cell);
((last - first) as usize, first)
}
const ZBP_LIMIT: u32 = 64;
const LBLOCK_MAX: u32 = 24;
struct BlockMeta {
num_passes: u32,
zero_bit_planes: u32,
seg_len: usize,
}
fn parse_packet<'a>(
data: &'a [u8],
start: usize,
bands: &[BandGeom],
) -> Result<(Vec<Subband<'a>>, usize)> {
let mut bio = BitReader::new(&data[start..]);
let present = bio.read_bit() == 1;
let mut metas: Vec<Vec<BlockMeta>> = Vec::with_capacity(bands.len());
for band in bands {
if !present {
metas.push(band.blocks.iter().map(|_| BlockMeta::absent()).collect());
continue;
}
metas.push(parse_band_header(band, &mut bio)?);
}
bio.align();
let mut body = start + bio.bytes_consumed();
let mut subbands = Vec::with_capacity(bands.len());
for (band, band_meta) in bands.iter().zip(&metas) {
let mut blocks = Vec::with_capacity(band.blocks.len());
for (&(x, y, width, height), meta) in band.blocks.iter().zip(band_meta) {
if meta.num_passes > 0 && meta.seg_len == 0 {
return Err(Error::Codestream(
"included code-block has coding passes but zero length".into(),
));
}
let segment = if meta.seg_len == 0 {
&[][..]
} else {
let end = body
.checked_add(meta.seg_len)
.filter(|&e| e <= data.len())
.ok_or_else(|| {
Error::Codestream("packet body segment overruns the tile-part".into())
})?;
let slice = &data[body..end];
body = end;
slice
};
blocks.push(CodeBlock {
x,
y,
width,
height,
num_passes: meta.num_passes,
zero_bit_planes: meta.zero_bit_planes,
segment,
});
}
subbands.push(Subband {
kind: band.kind,
origin: band.origin,
width: band.width,
height: band.height,
block_cols: band.block_cols,
block_rows: band.block_rows,
blocks,
});
}
Ok((subbands, body))
}
impl BlockMeta {
fn absent() -> Self {
BlockMeta {
num_passes: 0,
zero_bit_planes: 0,
seg_len: 0,
}
}
}
fn parse_band_header(band: &BandGeom, bio: &mut BitReader) -> Result<Vec<BlockMeta>> {
let cols = band.block_cols as u32;
let rows = band.block_rows as u32;
let mut inclusion = TagTree::new(cols, rows);
let mut zero_bits = TagTree::new(cols, rows);
let mut metas = Vec::with_capacity(band.blocks.len());
for idx in 0..band.blocks.len() {
let bx = idx as u32 % cols;
let by = idx as u32 / cols;
if inclusion.read(bx, by, 1, bio).is_none() {
metas.push(BlockMeta::absent());
continue;
}
let zero_bit_planes = zero_bits
.read(bx, by, ZBP_LIMIT, bio)
.ok_or_else(|| Error::Codestream("zero-bitplane count exceeds the limit".into()))?;
let num_passes = read_num_passes(bio);
let mut lblock = 3u32;
while bio.read_bit() == 1 {
lblock += 1;
if lblock > LBLOCK_MAX {
return Err(Error::Codestream("Lblock indicator runs too long".into()));
}
}
let length_bits = lblock + num_passes.ilog2();
let seg_len = bio.read(length_bits) as usize;
metas.push(BlockMeta {
num_passes,
zero_bit_planes,
seg_len,
});
}
Ok(metas)
}
fn read_num_passes(bio: &mut BitReader) -> u32 {
if bio.read_bit() == 0 {
return 1;
}
if bio.read_bit() == 0 {
return 2;
}
let n = bio.read(2);
if n != 3 {
return 3 + n;
}
let n = bio.read(5);
if n != 31 {
return 6 + n;
}
37 + bio.read(7)
}
#[cfg(test)]
mod tests;