pub mod bio;
pub mod tagtree;
use std::collections::HashSet;
use crate::codestream::markers::{Progression, Rect, Siz, marker};
use crate::codestream::{MainHeader, Tile};
use crate::{Error, Result};
use bio::BitReader;
use tagtree::TagTree;
const MAX_PRECINCTS: usize = 1 << 18;
#[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 segments: Vec<CodedSegment<'a>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodedSegment<'a> {
pub passes: u32,
pub chunks: Vec<&'a [u8]>,
}
impl CodedSegment<'_> {
pub fn bytes(&self) -> Vec<u8> {
self.chunks.concat()
}
}
#[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 ComponentCoded<'a> {
pub resolutions: Vec<Resolution<'a>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodedData<'a> {
pub components: Vec<ComponentCoded<'a>>,
}
pub fn decode_packets<'a>(header: &MainHeader, tile: &'a Tile<'a>) -> Result<CodedData<'a>> {
let data: &'a [u8] = &tile.data;
let mut precinct_budget = MAX_PRECINCTS;
let component_count = header.siz.components.len();
let geoms = (0..component_count)
.map(|c| resolution_geoms(header, tile.index, c, &mut precinct_budget))
.collect::<Result<Vec<_>>>()?;
const MAX_CODE_BLOCKS: usize = 1 << 19;
let total_blocks: usize = geoms
.iter()
.flatten()
.flat_map(|level| &level.bands)
.map(|band| band.blocks.len())
.sum();
if total_blocks > MAX_CODE_BLOCKS {
return Err(Error::Unsupported(format!(
"{total_blocks} code-blocks exceeds the decode guard of {MAX_CODE_BLOCKS}"
)));
}
let mut states: Vec<Vec<Vec<BandState<'a>>>> = geoms
.iter()
.map(|component| {
component
.iter()
.map(|level| level.bands.iter().map(BandState::new).collect())
.collect()
})
.collect();
let walk = PacketWalk {
siz: &header.siz,
tile: header
.siz
.tile_rect(tile.index)
.ok_or_else(|| Error::Inconsistent(format!("no tile {} in SIZ", tile.index)))?,
geoms: &geoms,
};
let delimiters = Delimiters {
sop: header.cod.use_sop,
eph: header.cod.use_eph,
};
let packed = !tile.packed_headers.is_empty();
let mut streams = PacketStreams {
header: if packed { &tile.packed_headers } else { data },
header_pos: 0,
data,
body_pos: 0,
packed,
};
let mut packet_index = 0u32;
for_each_packet(header, &walk, |layer, resolution, component, precinct| {
let geom = &geoms[component][resolution];
parse_packet(
&mut streams,
layer,
packet_index,
delimiters,
header.components[component].coding.code_block_style,
&geom.bands,
precinct,
&mut states[component][resolution],
)?;
packet_index += 1;
Ok(())
})?;
let components: Vec<ComponentCoded<'a>> = states
.into_iter()
.zip(&geoms)
.map(|(component_states, component_geoms)| {
Ok(ComponentCoded {
resolutions: component_states
.into_iter()
.zip(component_geoms)
.map(|(band_states, level)| {
Ok(Resolution {
subbands: build_subbands(&level.bands, band_states)?,
})
})
.collect::<Result<Vec<_>>>()?,
})
})
.collect::<Result<Vec<_>>>()?;
if streams.body_pos != data.len() {
return Err(Error::Codestream(format!(
"tile-part has {} body byte(s) left after the last packet",
data.len() - streams.body_pos
)));
}
if packed && streams.header_pos != streams.header.len() {
return Err(Error::Codestream(format!(
"PPT packed headers have {} byte(s) left after the last packet",
streams.header.len() - streams.header_pos
)));
}
Ok(CodedData { components })
}
struct BandGeom {
kind: BandKind,
origin: (u32, u32),
width: usize,
height: usize,
block_cols: usize,
block_rows: usize,
blocks: Vec<(usize, usize, usize, usize)>,
precincts: Vec<PrecinctGeom>,
}
struct PrecinctGeom {
cols: usize,
rows: usize,
blocks: Vec<usize>,
}
struct ResolutionGeom {
ppx: u32,
ppy: u32,
precincts_wide: usize,
precincts_high: usize,
bands: Vec<BandGeom>,
}
impl ResolutionGeom {
fn precinct_count(&self) -> usize {
self.precincts_wide * self.precincts_high
}
}
struct PacketWalk<'a> {
siz: &'a Siz,
tile: Rect,
geoms: &'a [Vec<ResolutionGeom>],
}
impl PacketWalk<'_> {
fn sampling(&self, comp: usize) -> (u64, u64) {
let c = &self.siz.components[comp];
(u64::from(c.x_sampling), u64::from(c.y_sampling))
}
fn level(&self, comp: usize, res: usize) -> u32 {
(self.geoms[comp].len() - 1 - res) as u32
}
fn precinct_at(&self, comp: usize, res: usize, x: u64, y: u64) -> Option<usize> {
let geom = &self.geoms[comp][res];
if geom.precinct_count() == 0 {
return None;
}
let level = self.level(comp, res);
let (dx, dy) = self.sampling(comp);
let (sx, sy) = (dx << level, dy << level);
let (tx0, ty0) = (u64::from(self.tile.x0), u64::from(self.tile.y0));
let (tx1, ty1) = (u64::from(self.tile.x1), u64::from(self.tile.y1));
let (trx0, trx1) = (tx0.div_ceil(sx), tx1.div_ceil(sx));
let (try0, try1) = (ty0.div_ceil(sy), ty1.div_ceil(sy));
if trx0 == trx1 || try0 == try1 {
return None;
}
let (rpx, rpy) = (geom.ppx + level, geom.ppy + level);
let (px, py) = (dx << rpx, dy << rpy);
let corner = |v: u64, t0: u64, tr0: u64, span: u64, exp: u32| {
v.is_multiple_of(span) || (v == t0 && !(tr0 << level).is_multiple_of(1u64 << exp))
};
if !corner(y, ty0, try0, py, rpy) || !corner(x, tx0, trx0, px, rpx) {
return None;
}
let i = (x.div_ceil(sx) >> geom.ppx) - (trx0 >> geom.ppx);
let j = (y.div_ceil(sy) >> geom.ppy) - (try0 >> geom.ppy);
debug_assert!(
i < geom.precincts_wide as u64 && j < geom.precincts_high as u64,
"precinct index ({i}, {j}) out of the {}×{} grid",
geom.precincts_wide,
geom.precincts_high,
);
Some(j as usize * geom.precincts_wide + i as usize)
}
fn step(&self, pairs: impl Iterator<Item = (usize, usize)>) -> Option<(u64, u64)> {
let (mut step_x, mut step_y): (Option<u64>, Option<u64>) = (None, None);
for (comp, res) in pairs {
let geom = &self.geoms[comp][res];
let level = self.level(comp, res);
let (dx, dy) = self.sampling(comp);
if let Some(v) = shl32(dx, geom.ppx + level) {
step_x = Some(step_x.map_or(v, |cur: u64| cur.min(v)));
}
if let Some(v) = shl32(dy, geom.ppy + level) {
step_y = Some(step_y.map_or(v, |cur: u64| cur.min(v)));
}
}
Some((step_x?, step_y?))
}
}
fn shl32(value: u64, shift: u32) -> Option<u64> {
let scaled = value.checked_shl(shift)?;
(scaled <= u64::from(u32::MAX)).then_some(scaled)
}
struct Volume {
progression: Progression,
layers: u32,
resolutions: std::ops::Range<usize>,
components: std::ops::Range<usize>,
}
fn for_each_packet<F>(header: &MainHeader, walk: &PacketWalk<'_>, mut f: F) -> Result<()>
where
F: FnMut(u32, usize, usize, usize) -> Result<()>,
{
let components = walk.geoms.len();
let max_res = walk.geoms.iter().map(Vec::len).max().unwrap_or(0);
let layers = u32::from(header.cod.layers);
let volumes: Vec<Volume> = if header.poc.is_empty() {
vec![Volume {
progression: header.cod.progression,
layers,
resolutions: 0..max_res,
components: 0..components,
}]
} else {
header
.poc
.iter()
.map(|v| Volume {
progression: v.progression,
layers: u32::from(v.layer_end).min(layers),
resolutions: usize::from(v.res_start)..usize::from(v.res_end).min(max_res),
components: usize::from(v.comp_start)..usize::from(v.comp_end).min(components),
})
.collect()
};
if volumes.len() == 1 {
return run_order(&volumes[0], walk, &mut f);
}
let mut seen: HashSet<(u32, usize, usize, usize)> = HashSet::new();
for volume in &volumes {
run_order(volume, walk, &mut |layer, res, comp, precinct| {
if seen.insert((layer, res, comp, precinct)) {
f(layer, res, comp, precinct)
} else {
Ok(())
}
})?;
}
Ok(())
}
fn run_order<F>(volume: &Volume, walk: &PacketWalk<'_>, emit: &mut F) -> Result<()>
where
F: FnMut(u32, usize, usize, usize) -> Result<()>,
{
let layers = volume.layers;
let res_range = volume.resolutions.clone();
let comp_range = volume.components.clone();
let has = |comp: usize, res: usize| res < walk.geoms[comp].len();
let precincts = |comp: usize, res: usize| walk.geoms[comp][res].precinct_count();
let (tx0, ty0) = (u64::from(walk.tile.x0), u64::from(walk.tile.y0));
let (tx1, ty1) = (u64::from(walk.tile.x1), u64::from(walk.tile.y1));
let all_pairs =
|| (0..walk.geoms.len()).flat_map(|c| (0..walk.geoms[c].len()).map(move |r| (c, r)));
match volume.progression {
Progression::Lrcp => {
for layer in 0..layers {
for res in res_range.clone() {
for comp in comp_range.clone() {
if !has(comp, res) {
continue;
}
for precinct in 0..precincts(comp, res) {
emit(layer, res, comp, precinct)?;
}
}
}
}
}
Progression::Rlcp => {
for res in res_range.clone() {
for layer in 0..layers {
for comp in comp_range.clone() {
if !has(comp, res) {
continue;
}
for precinct in 0..precincts(comp, res) {
emit(layer, res, comp, precinct)?;
}
}
}
}
}
Progression::Rpcl => {
let Some((step_x, step_y)) = walk.step(all_pairs()) else {
return Ok(());
};
for res in res_range.clone() {
let mut y = ty0;
while y < ty1 {
let mut x = tx0;
while x < tx1 {
for comp in comp_range.clone() {
if !has(comp, res) {
continue;
}
if let Some(precinct) = walk.precinct_at(comp, res, x, y) {
for layer in 0..layers {
emit(layer, res, comp, precinct)?;
}
}
}
x += step_x - (x % step_x);
}
y += step_y - (y % step_y);
}
}
}
Progression::Pcrl => {
let Some((step_x, step_y)) = walk.step(all_pairs()) else {
return Ok(());
};
let mut y = ty0;
while y < ty1 {
let mut x = tx0;
while x < tx1 {
for comp in comp_range.clone() {
for res in res_range.clone() {
if !has(comp, res) {
continue;
}
if let Some(precinct) = walk.precinct_at(comp, res, x, y) {
for layer in 0..layers {
emit(layer, res, comp, precinct)?;
}
}
}
}
x += step_x - (x % step_x);
}
y += step_y - (y % step_y);
}
}
Progression::Cprl => {
for comp in comp_range.clone() {
let pairs = (0..walk.geoms[comp].len()).map(|r| (comp, r));
let Some((step_x, step_y)) = walk.step(pairs) else {
continue;
};
let mut y = ty0;
while y < ty1 {
let mut x = tx0;
while x < tx1 {
for res in res_range.clone() {
if !has(comp, res) {
continue;
}
if let Some(precinct) = walk.precinct_at(comp, res, x, y) {
for layer in 0..layers {
emit(layer, res, comp, precinct)?;
}
}
}
x += step_x - (x % step_x);
}
y += step_y - (y % step_y);
}
}
}
}
Ok(())
}
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,
tile: u32,
comp: usize,
precinct_budget: &mut usize,
) -> Result<Vec<ResolutionGeom>> {
let siz = &header.siz;
let cod = &header
.components
.get(comp)
.ok_or_else(|| Error::Inconsistent(format!("no coding parameters for component {comp}")))?
.coding;
let nl = cod.decomposition_levels as i64;
if nl > 32 {
return Err(Error::Unsupported(format!(
"{nl} decomposition levels exceeds the 32-level maximum"
)));
}
let rect = siz.tile_component_rect(tile, comp).ok_or_else(|| {
Error::Inconsistent(format!("no tile {tile} or no component {comp} in SIZ"))
})?;
if rect.is_empty() {
return Err(Error::Codestream(format!(
"tile {tile} has an empty area on component {comp}"
)));
}
let (tcx0, tcx1) = (i64::from(rect.x0), i64::from(rect.x1));
let (tcy0, tcy1) = (i64::from(rect.y0), i64::from(rect.y1));
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 level = nl - r;
let pow = 1i64 << level;
let (trx0, trx1) = (ceil_div(tcx0, pow), ceil_div(tcx1, pow));
let (try0, try1) = (ceil_div(tcy0, pow), ceil_div(tcy1, pow));
let (ppx, ppy) = cod.precinct(r as usize);
debug_assert!(r == 0 || (ppx >= 1 && ppy >= 1));
let (precincts_wide, tl_prc_x) = prc_span(trx0, trx1, ppx);
let (precincts_high, tl_prc_y) = prc_span(try0, try1, ppy);
let here = precincts_wide.checked_mul(precincts_high);
match here.filter(|&n| n <= *precinct_budget) {
Some(n) => *precinct_budget -= n,
None => {
return Err(Error::Unsupported(format!(
"tile precinct count exceeds the decode guard of {MAX_PRECINCTS}"
)));
}
}
let cbg = if r == 0 {
Cbg {
x0: tl_prc_x,
y0: tl_prc_y,
x_exp: ppx,
y_exp: ppy,
wide: precincts_wide,
high: precincts_high,
}
} else {
Cbg {
x0: ceil_div(tl_prc_x, 2),
y0: ceil_div(tl_prc_y, 2),
x_exp: ppx - 1,
y_exp: ppy - 1,
wide: precincts_wide,
high: precincts_high,
}
};
let (xcb, ycb) = (xcb.min(cbg.x_exp), ycb.min(cbg.y_exp));
let bands = if r == 0 {
vec![band_geom(
BandKind::Ll,
trx0,
trx1,
try0,
try1,
xcb,
ycb,
&cbg,
)]
} else {
let nb = level + 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,
ycb,
&cbg,
)
})
.collect()
};
levels.push(ResolutionGeom {
ppx,
ppy,
precincts_wide,
precincts_high,
bands,
});
}
Ok(levels)
}
struct Cbg {
x0: i64,
y0: i64,
x_exp: u32,
y_exp: u32,
wide: usize,
high: usize,
}
fn prc_span(lo: i64, hi: i64, exp: u32) -> (usize, i64) {
if hi <= lo {
return (0, 0);
}
let span = 1i64 << exp;
let start = lo.div_euclid(span) * span;
let end = ceil_div(hi, span) * span;
(((end - start) >> exp) as usize, start)
}
#[allow(clippy::too_many_arguments)]
fn band_geom(
kind: BandKind,
bx0: i64,
bx1: i64,
by0: i64,
by1: i64,
xcb: u32,
ycb: u32,
cbg: &Cbg,
) -> 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,
));
}
}
let group_w = 1i64 << cbg.x_exp;
let group_h = 1i64 << cbg.y_exp;
let mut precincts = Vec::with_capacity(cbg.wide * cbg.high);
for j in 0..cbg.high {
let gy0 = cbg.y0 + j as i64 * group_h;
let (py0, py1) = (gy0.max(by0), (gy0 + group_h).min(by1));
for i in 0..cbg.wide {
let gx0 = cbg.x0 + i as i64 * group_w;
let (px0, px1) = (gx0.max(bx0), (gx0 + group_w).min(bx1));
let (cols, col0) = grid_span(px0, px1, cbw);
let (rows, row0) = grid_span(py0, py1, cbh);
let mut owned = Vec::with_capacity(cols * rows);
for row in 0..rows {
let band_row = (row0 + row as i64 - first_row) as usize;
for col in 0..cols {
let band_col = (col0 + col as i64 - first_col) as usize;
owned.push(band_row * block_cols + band_col);
}
}
precincts.push(PrecinctGeom {
cols,
rows,
blocks: owned,
});
}
}
debug_assert_eq!(
precincts.iter().map(|p| p.blocks.len()).sum::<usize>(),
block_cols * block_rows,
"the precincts must partition the band's code-block grid"
);
BandGeom {
kind,
origin: (bx0.max(0) as u32, by0.max(0) as u32),
width,
height,
block_cols,
block_rows,
blocks,
precincts,
}
}
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 = 293;
const LBLOCK_MAX: u32 = 24;
fn segment_max_passes(style: u8, segments: &[SegmentState<'_>]) -> u32 {
use crate::codestream::markers::code_block_style::{LAZY, TERMALL};
if style & TERMALL != 0 {
1
} else if style & LAZY != 0 {
match segments.last() {
None => 10,
Some(prev) => {
if prev.max_passes == 1 || prev.max_passes == 10 {
2
} else {
1
}
}
}
} else {
109
}
}
#[derive(Debug, Clone, Copy)]
struct Delimiters {
sop: bool,
eph: bool,
}
struct PacketStreams<'a> {
header: &'a [u8],
header_pos: usize,
data: &'a [u8],
body_pos: usize,
packed: bool,
}
fn peek_marker(data: &[u8], pos: usize) -> Option<u16> {
let hi = *data.get(pos)?;
let lo = *data.get(pos + 1)?;
Some(u16::from_be_bytes([hi, lo]))
}
fn read_sop(data: &[u8], pos: usize, packet_index: u32) -> Result<usize> {
let end = pos + 6;
if end > data.len() {
return Err(Error::Codestream("truncated SOP marker segment".into()));
}
let lsop = u16::from_be_bytes([data[pos + 2], data[pos + 3]]);
if lsop != 4 {
return Err(Error::Codestream(format!(
"SOP declares Lsop {lsop}, expected 4"
)));
}
let nsop = u16::from_be_bytes([data[pos + 4], data[pos + 5]]);
let expected = (packet_index % 65536) as u16;
if nsop != expected {
return Err(Error::Codestream(format!(
"SOP sequence number {nsop} for packet {packet_index}, expected {expected}"
)));
}
Ok(end)
}
struct BlockState<'a> {
included: bool,
lblock: u32,
zero_bit_planes: u32,
num_passes: u32,
segments: Vec<SegmentState<'a>>,
}
struct SegmentState<'a> {
passes: u32,
max_passes: u32,
chunks: Vec<&'a [u8]>,
}
impl BlockState<'_> {
fn new() -> Self {
BlockState {
included: false,
lblock: 3,
zero_bit_planes: 0,
num_passes: 0,
segments: Vec::new(),
}
}
}
struct BandState<'a> {
precincts: Vec<PrecinctState>,
blocks: Vec<BlockState<'a>>,
}
struct PrecinctState {
inclusion: TagTree,
zero_bits: TagTree,
}
impl BandState<'_> {
fn new(band: &BandGeom) -> Self {
BandState {
precincts: band
.precincts
.iter()
.map(|precinct| PrecinctState {
inclusion: TagTree::new(precinct.cols as u32, precinct.rows as u32),
zero_bits: TagTree::new(precinct.cols as u32, precinct.rows as u32),
})
.collect(),
blocks: band.blocks.iter().map(|_| BlockState::new()).collect(),
}
}
}
struct Contribution {
band: usize,
block: usize,
segment: usize,
seg_len: usize,
}
#[allow(clippy::too_many_arguments)]
fn parse_packet<'a>(
streams: &mut PacketStreams<'a>,
layer: u32,
packet_index: u32,
delimiters: Delimiters,
style: u8,
bands: &[BandGeom],
precinct: usize,
states: &mut [BandState<'a>],
) -> Result<()> {
if delimiters.sop && peek_marker(streams.data, streams.body_pos) == Some(marker::SOP) {
streams.body_pos = read_sop(streams.data, streams.body_pos, packet_index)?;
}
if !streams.packed {
streams.header_pos = streams.body_pos;
}
if streams.header_pos >= streams.header.len() {
return Err(Error::Codestream(
"tile-part ends before the last packet".into(),
));
}
let mut bio = BitReader::new(&streams.header[streams.header_pos..]);
let present = bio.read_bit() == 1;
let mut contributions: Vec<Contribution> = Vec::new();
if present {
for (band_index, (band, state)) in bands.iter().zip(states.iter_mut()).enumerate() {
parse_band_header(
band_index,
&band.precincts[precinct],
&mut state.precincts[precinct],
&mut state.blocks,
layer,
style,
&mut bio,
&mut contributions,
)?;
}
}
bio.align();
streams.header_pos += bio.bytes_consumed();
if delimiters.eph {
if peek_marker(streams.header, streams.header_pos) != Some(marker::EPH) {
return Err(Error::Codestream(
"COD signals EPH but the packet header is not followed by one".into(),
));
}
streams.header_pos += 2;
}
if !streams.packed {
streams.body_pos = streams.header_pos;
}
for contribution in &contributions {
let end = streams
.body_pos
.checked_add(contribution.seg_len)
.filter(|&e| e <= streams.data.len())
.ok_or_else(|| {
Error::Codestream("packet body segment overruns the tile-part".into())
})?;
states[contribution.band].blocks[contribution.block].segments[contribution.segment]
.chunks
.push(&streams.data[streams.body_pos..end]);
streams.body_pos = end;
}
if !streams.packed {
streams.header_pos = streams.body_pos;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn parse_band_header(
band_index: usize,
precinct: &PrecinctGeom,
trees: &mut PrecinctState,
blocks: &mut [BlockState<'_>],
layer: u32,
style: u8,
bio: &mut BitReader,
contributions: &mut Vec<Contribution>,
) -> Result<()> {
let cols = precinct.cols as u32;
for (entry, &block_index) in precinct.blocks.iter().enumerate() {
let bx = entry as u32 % cols;
let by = entry as u32 / cols;
let was_included = blocks[block_index].included;
let contributes = if was_included {
bio.read_bit() == 1
} else {
match trees.inclusion.read(bx, by, layer + 1, bio) {
Some(_) => {
blocks[block_index].included = true;
true
}
None => false,
}
};
if !contributes {
continue;
}
if !was_included {
blocks[block_index].zero_bit_planes = trees
.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 block = &mut blocks[block_index];
while bio.read_bit() == 1 {
block.lblock += 1;
if block.lblock > LBLOCK_MAX {
return Err(Error::Codestream("Lblock indicator runs too long".into()));
}
}
block.num_passes += num_passes;
let mut remaining = num_passes;
loop {
if block
.segments
.last()
.is_none_or(|s| s.passes >= s.max_passes)
{
let max_passes = segment_max_passes(style, &block.segments);
block.segments.push(SegmentState {
passes: 0,
max_passes,
chunks: Vec::new(),
});
}
let segment_index = block.segments.len() - 1;
let segment = &mut block.segments[segment_index];
let new_passes = remaining.min(segment.max_passes - segment.passes);
let length_bits = block.lblock + new_passes.ilog2();
let seg_len = bio.read(length_bits) as usize;
let segment = &mut block.segments[segment_index];
segment.passes += new_passes;
if seg_len > 0 {
contributions.push(Contribution {
band: band_index,
block: block_index,
segment: segment_index,
seg_len,
});
}
remaining -= new_passes;
if remaining == 0 {
break;
}
}
}
Ok(())
}
fn build_subbands<'a>(bands: &[BandGeom], states: Vec<BandState<'a>>) -> Result<Vec<Subband<'a>>> {
for state in &states {
for block in &state.blocks {
if block.num_passes > 0 && block.segments.iter().all(|s| s.chunks.is_empty()) {
return Err(Error::Codestream(
"included code-block has coding passes but no coded bytes".into(),
));
}
}
}
Ok(bands
.iter()
.zip(states)
.map(|(band, state)| Subband {
kind: band.kind,
origin: band.origin,
width: band.width,
height: band.height,
block_cols: band.block_cols,
block_rows: band.block_rows,
blocks: band
.blocks
.iter()
.zip(state.blocks)
.map(|(&(x, y, width, height), block)| CodeBlock {
x,
y,
width,
height,
num_passes: block.num_passes,
zero_bit_planes: block.zero_bit_planes,
segments: block
.segments
.into_iter()
.map(|s| CodedSegment {
passes: s.passes,
chunks: s.chunks,
})
.collect(),
})
.collect(),
})
.collect())
}
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;