pub mod bio;
mod geometry;
mod progression;
pub(crate) mod resume;
pub mod spans;
pub mod tagtree;
use crate::codestream::markers::Rect;
use crate::codestream::markers::marker;
use crate::codestream::{MainHeader, Tile};
use crate::{Error, Result};
use bio::BitReader;
use spans::UnreadSpans;
use std::borrow::Cow;
use std::cell::Cell;
use std::ops::Range;
use tagtree::{Saved, TagTree};
pub(crate) use geometry::{
BandGeom, MAX_CODE_BLOCKS, MAX_PRECINCTS, PrecinctGeom, ResolutionGeom, resolution_geoms,
};
pub(crate) use progression::{PacketWalk, for_each_packet};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BandKind {
Ll,
Hl,
Lh,
Hh,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Coder {
Part1,
Ht,
}
impl Coder {
pub(crate) fn of_style(
style: u8,
ccap15: Option<crate::codestream::markers::Ccap15>,
) -> Option<Coder> {
use crate::codestream::markers::code_block_style::{HT, HT_MIXED};
if style & HT == 0 {
Some(Coder::Part1)
} else if style & HT_MIXED == 0 || ccap15.is_some_and(|c| c.ht_only()) {
Some(Coder::Ht)
} else {
None
}
}
}
#[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>>,
pub cut: bool,
pub placeholders: u32,
pub coder: Coder,
pub missing_from: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodedSegment<'a> {
pub passes: u32,
pub chunks: Vec<&'a [u8]>,
}
impl<'a> CodedSegment<'a> {
pub fn bytes(&self) -> Cow<'a, [u8]> {
match self.chunks[..] {
[] => Cow::Borrowed(&[]),
[chunk] => Cow::Borrowed(chunk),
_ => Cow::Owned(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>>,
pub rect: Option<Rect>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BandExtent {
pub origin: (u32, u32),
pub width: usize,
pub height: usize,
}
impl BandExtent {
fn of_bounds(x0: i64, x1: i64, y0: i64, y1: i64) -> Self {
BandExtent {
origin: (x0.max(0) as u32, y0.max(0) as u32),
width: (x1 - x0).max(0) as usize,
height: (y1 - y0).max(0) as usize,
}
}
}
impl ComponentCoded<'_> {
pub fn band(&self, r: usize, kind: BandKind) -> Option<BandExtent> {
let resolution = self.resolutions.get(r)?;
if let Some(sb) = resolution.subbands.iter().find(|s| s.kind == kind) {
return Some(BandExtent {
origin: sb.origin,
width: sb.width,
height: sb.height,
});
}
if !resolution.subbands.is_empty() {
return None;
}
let nl = u32::try_from(self.resolutions.len() - 1).ok()?;
geometry::band_rects(self.rect?, nl, u32::try_from(r).ok()?)
.find(|b| b.0 == kind)
.map(|(_, x0, x1, y0, y1)| BandExtent::of_bounds(x0, x1, y0, y1))
}
pub fn detail_extents(&self, r: usize) -> Option<[BandExtent; 3]> {
if r == 0 || !self.resolutions.get(r)?.subbands.is_empty() {
return None;
}
let nl = u32::try_from(self.resolutions.len() - 1).ok()?;
let mut bands = geometry::band_rects(self.rect?, nl, u32::try_from(r).ok()?)
.map(|(_, x0, x1, y0, y1)| BandExtent::of_bounds(x0, x1, y0, y1));
Some([bands.next()?, bands.next()?, bands.next()?])
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CodedData<'a> {
pub components: Vec<ComponentCoded<'a>>,
}
pub(crate) fn decode_packets_metered<'a>(
header: &MainHeader,
tile: &'a Tile<'a>,
meter: &Meter,
poc_bitmap: u64,
reduction: u8,
layers: Option<u16>,
) -> std::result::Result<CodedData<'a>, Refused> {
meter.clear_refusal();
let mut budget = Budget {
reduction,
layers,
..Budget::decode(meter.left(), poc_bitmap)
};
decode_packets_within(header, tile, &mut budget, meter).map_err(|error| refused(meter, error))
}
#[cfg(test)]
pub fn decode_packets<'a>(
header: &MainHeader,
tile: &'a Tile<'a>,
visits: &mut u64,
poc_bitmap: u64,
reduction: u8,
) -> std::result::Result<CodedData<'a>, Refused> {
let meter = Meter::new(*visits);
let coded = decode_packets_metered(header, tile, &meter, poc_bitmap, reduction, None);
*visits = meter.left();
coded
}
fn refused(meter: &Meter, error: Error) -> Refused {
match (meter.refusal(), error) {
(Some(work), Error::Limit(_)) => Refused::Work(work),
(_, error) => Refused::Other(error),
}
}
pub(crate) const DECODE_VISITS_MIN: u64 = 1 << 24;
pub(crate) const DECODE_VISITS_PER_BYTE: u64 = 32;
pub(crate) fn decode_visits(bytes: u64) -> u64 {
DECODE_VISITS_MIN.max(bytes.saturating_mul(DECODE_VISITS_PER_BYTE))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Budget {
pub(crate) precincts: usize,
pub(crate) blocks: usize,
pub(crate) poc_bitmap: u64,
pub(crate) poc_counts: bool,
pub(crate) poc_coverage: bool,
pub(crate) reduction: u8,
pub(crate) layers: Option<u16>,
}
impl Budget {
pub(crate) const fn decode(visits: u64, poc_bitmap: u64) -> Budget {
Budget {
precincts: MAX_PRECINCTS,
blocks: MAX_CODE_BLOCKS,
poc_bitmap: if visits < poc_bitmap {
visits
} else {
poc_bitmap
},
poc_counts: true,
poc_coverage: true,
reduction: 0,
layers: None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct Reach {
pub(crate) missing_from: Vec<Vec<Option<u32>>>,
pub(crate) leftover: Option<(usize, usize)>,
pub(crate) leftover_packed: Option<usize>,
}
impl Reach {
fn miss(&mut self, comp: usize, res: usize, layer: u32) {
if let Some(from) = self.missing_from.get_mut(comp).and_then(|c| c.get_mut(res)) {
*from = Some(from.map_or(layer, |f| f.min(layer)));
}
}
}
pub fn decode_packets_partial<'a>(
header: &MainHeader,
tile: &'a Tile<'a>,
meter: &Meter,
poc_bitmap: u64,
reduction: u8,
layers: Option<u16>,
) -> std::result::Result<(CodedData<'a>, Reach), Refused> {
meter.clear_refusal();
let mut budget = Budget {
reduction,
layers,
..Budget::decode(meter.left(), poc_bitmap)
};
let mut reach = Reach::default();
walk_packets(header, tile, &mut budget, meter, Some(&mut reach))
.map(|coded| (coded, reach))
.map_err(|error| refused(meter, error))
}
pub(crate) fn decode_packets_within<'a>(
header: &MainHeader,
tile: &'a Tile<'a>,
budget: &mut Budget,
meter: &Meter,
) -> Result<CodedData<'a>> {
walk_packets(header, tile, budget, meter, None)
}
fn walk_packets<'a>(
header: &MainHeader,
tile: &'a Tile<'a>,
budget: &mut Budget,
meter: &Meter,
mut reach: Option<&mut Reach>,
) -> Result<CodedData<'a>> {
let data: &'a [u8] = &tile.data;
let geoms = tile_geometry(header, tile.index, budget, |dropped| {
meter.spend(
dropped,
WorkRefusal::DroppedBlocks {
blocks: dropped as u64,
},
)
})?;
let mut states = band_states(header, &geoms);
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,
tile: tile.index,
};
if let Some(reach) = reach.as_deref_mut() {
reach.missing_from = geoms.iter().map(|c| vec![None; c.len()]).collect();
progression::poc_gaps(header, &walk, |comp, res, layer| {
reach.miss(comp, res, u32::from(layer));
mark_gap(&mut states[comp][res], u32::from(layer));
Ok(())
})?;
} else if budget.poc_coverage {
progression::check_poc_coverage(header, &walk, tile.index)?;
}
let strict = reach.is_none();
let end_visits = geoms
.iter()
.map(Vec::len)
.sum::<usize>()
.saturating_mul(END_VISITS);
let mut log = Vec::new();
let mut scratch = Scratch::default();
let mut ended = false;
let mut packet_index = 0u32;
for_each_packet(
header,
&walk,
meter,
budget.poc_bitmap,
budget.poc_counts,
|layer, resolution, component, precinct| {
if let Some(reach) = reach.as_deref_mut() {
if ended {
meter.spend(1, WorkRefusal::PacketWalk)?;
reach.miss(component, resolution, layer);
mark_unread(&mut states[component][resolution], precinct, layer);
return Ok(());
}
}
let geom = &geoms[component][resolution];
let packet = parse_packet(
&mut streams,
meter,
layer,
packet_index,
delimiters,
header.components[component].coding.code_block_style,
&geom.bands,
precinct,
&mut states[component][resolution],
&mut scratch,
budget.layers.is_none_or(|cap| layer < u32::from(cap)),
if strict { None } else { Some(&mut log) },
None,
)?;
if packet != Packet::Read {
ended = true;
mark_unread(&mut states[component][resolution], precinct, layer);
meter.spend(end_visits, WorkRefusal::PacketWalk)?;
if let Some(reach) = reach.as_deref_mut() {
reach.miss(component, resolution, layer);
}
}
packet_index += 1;
Ok(())
},
)?;
let mut components = Vec::with_capacity(states.len());
for (comp, (component_states, component_geoms)) in states.iter().zip(&geoms).enumerate() {
let rect = header
.siz
.tile_component_rect(tile.index, comp)
.ok_or_else(|| Error::inconsistent(format!("no component {comp} in `SIZ`")))?;
let mut resolutions = Vec::with_capacity(component_states.len());
for (band_states, level) in component_states.iter().zip(component_geoms) {
let subbands = if level.bands.is_empty() {
Vec::new()
} else {
build_subbands(&level.bands, band_states, data)
};
resolutions.push(Resolution { subbands });
}
components.push(ComponentCoded {
resolutions,
rect: Some(rect),
});
}
if let Some(reach) = reach {
if !ended {
if streams.body_pos < data.len() {
reach.leftover = Some((streams.body_pos, data.len() - streams.body_pos));
}
if packed && streams.header_pos < streams.header.len() {
reach.leftover_packed = Some(streams.header.len() - streams.header_pos);
}
}
return Ok(CodedData { components });
}
if streams.body_pos != data.len() {
return Err(Error::codestream(format!(
"tile {} has {} byte(s) left after the last packet",
tile.index,
data.len() - streams.body_pos
)));
}
if packed && streams.header_pos != streams.header.len() {
return Err(Error::codestream(format!(
"tile {} has {} byte(s) of packed packet headers left after the last packet",
tile.index,
streams.header.len() - streams.header_pos
)));
}
Ok(CodedData { components })
}
fn tile_geometry(
header: &MainHeader,
tile: u32,
budget: &mut Budget,
mut dropped: impl FnMut(usize) -> Result<()>,
) -> Result<Vec<Vec<ResolutionGeom>>> {
let component_count = header.siz.components.len();
let mut geoms = Vec::with_capacity(component_count);
for c in 0..component_count {
let resolutions =
resolution_geoms(header, tile, c, &mut budget.precincts, &mut budget.blocks)?;
let kept = resolutions
.len()
.saturating_sub(usize::from(budget.reduction));
dropped(
resolutions[kept..]
.iter()
.flat_map(|resolution| &resolution.bands)
.map(BandGeom::block_count)
.sum(),
)?;
geoms.push(resolutions);
}
Ok(geoms)
}
fn band_states(header: &MainHeader, geoms: &[Vec<ResolutionGeom>]) -> Vec<Vec<Vec<BandState>>> {
geoms
.iter()
.zip(&header.components)
.map(|(component, params)| {
let coder = Coder::of_style(params.coding.code_block_style, header.ccap15);
component
.iter()
.map(|level| {
level
.bands
.iter()
.map(|band| BandState::new(band, coder))
.collect()
})
.collect()
})
.collect()
}
const ZBP_LIMIT: u32 = 293;
const LBLOCK_MAX: u32 = 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SegmentKind {
Mq,
Raw,
HtCleanup { placeholders: Option<u32> },
HtRefinement,
}
fn next_segment(coder: Coder, style: u8, last: Option<&SegmentState>) -> (SegmentKind, u32) {
use crate::codestream::markers::code_block_style::{LAZY, TERMALL};
let last = last.map(|s| s.kind);
if coder == Coder::Ht {
match last {
Some(SegmentKind::HtCleanup { .. }) => (SegmentKind::HtRefinement, 2),
_ => (
SegmentKind::HtCleanup {
placeholders: Some(0),
},
1,
),
}
} else if style & TERMALL != 0 {
(SegmentKind::Mq, 1)
} else if style & LAZY != 0 {
match last {
None => (SegmentKind::Mq, 10),
Some(SegmentKind::Mq) => (SegmentKind::Raw, 2),
Some(_) => (SegmentKind::Mq, 1),
}
} else {
(SegmentKind::Mq, 109)
}
}
fn length_bits(lblock: u32, passes: u32) -> u32 {
lblock + passes.ilog2()
}
const HT_CLEANUP_MAX: u64 = 65534;
const HT_REFINEMENT_MAX: u64 = 2046;
fn add_length(segment: &mut SegmentState, bytes: u32) -> Result<()> {
segment.length += u64::from(bytes);
let (what, max) = match segment.kind {
SegmentKind::HtCleanup { .. } => ("cleanup", HT_CLEANUP_MAX),
SegmentKind::HtRefinement => ("refinement", HT_REFINEMENT_MAX),
SegmentKind::Mq | SegmentKind::Raw => return Ok(()),
};
if segment.length > max {
return Err(Error::codestream(format!(
"HT {what} segment is {} bytes, over the limit of {max}",
segment.length
)));
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FirstCleanup {
Placeholders,
Cleanup {
placeholders: u32,
passes: u32,
length: u32,
},
}
fn ht_first_cleanup(
lblock: u32,
prior: u32,
new: u32,
bio: &mut BitReader,
) -> Result<FirstCleanup> {
let placeholders = 3 * ((prior + new - 1) / 3);
let mut read = 0;
if placeholders >= prior {
let passes = placeholders + 1 - prior;
let bits = length_bits(lblock, passes);
match bio.read(bits) {
0 => read = bits,
1 => {
return Err(Error::codestream(
"HT code-block's first cleanup segment is 1 byte long; it must be at least 2",
));
}
length => {
return Ok(FirstCleanup::Cleanup {
placeholders,
passes,
length,
});
}
}
}
if bio.read(length_bits(lblock, new) - read) != 0 {
return Err(Error::codestream(
"HT code-block placeholder passes carry bytes",
));
}
Ok(FirstCleanup::Placeholders)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MixedFirst {
Empty,
Ht(FirstCleanup),
Part1 { length: u32 },
}
fn mixed_first_length(
lblock: u32,
prior: u32,
new: u32,
bio: &mut BitReader,
) -> Result<MixedFirst> {
let width = length_bits(lblock, new);
let placeholders = 3 * ((prior + new - 1) / 3);
let cleanup = (placeholders >= prior)
.then(|| (length_bits(lblock, placeholders + 1 - prior), placeholders));
let part1 = |top: u32, read: u32, bio: &mut BitReader| match (top << (width - read))
| bio.read(width - read)
{
0 => MixedFirst::Empty,
length => MixedFirst::Part1 { length },
};
if lblock <= 3 {
return Ok(part1(0, 0, bio));
}
if bio.read_bit() == 1 {
return Ok(part1(1, 1, bio));
}
let Some((bits, placeholders)) = cleanup else {
return Ok(part1(0, 1, bio));
};
match bio.read(bits - 1) {
top @ (0 | 1) => Ok(part1(top, bits, bio)),
top if u64::from(top) > HT_CLEANUP_MAX => Ok(part1(top, bits, bio)),
length => Ok(MixedFirst::Ht(FirstCleanup::Cleanup {
placeholders,
passes: placeholders + 1 - prior,
length,
})),
}
}
fn become_part1(block: &mut BlockState) {
block.coder = Some(Coder::Part1);
match block.segments.first_mut() {
Some(segment) => {
segment.kind = SegmentKind::Mq;
segment.max_passes = u32::MAX;
block.num_passes += segment.kept;
}
None => block
.segments
.push(SegmentState::new(SegmentKind::Mq, u32::MAX)),
}
}
#[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,
tile: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum WorkRefusal {
PacketWalk,
PocReach { reached: u64 },
DroppedBlocks { blocks: u64 },
}
impl WorkRefusal {
pub(crate) fn why(&self) -> String {
match self {
WorkRefusal::PacketWalk => "reading the packet headers goes past the packet work \
bound (see `DecodeOptions::packet_work_limit`)"
.into(),
WorkRefusal::PocReach { reached } => format!(
"the `POC` volumes reach {reached} packets, a step each, more than \
the steps left of the packet work bound (see \
`DecodeOptions::packet_work_limit`)"
),
WorkRefusal::DroppedBlocks { blocks } => format!(
"the resolutions the reduction drops hold {blocks} code-blocks in \
one component, a step each, more than the steps left of the \
packet work bound (see `DecodeOptions::packet_work_limit`)"
),
}
}
}
#[derive(Debug)]
pub(crate) enum Refused {
Work(WorkRefusal),
Other(Error),
}
impl From<Refused> for Error {
fn from(refused: Refused) -> Error {
match refused {
Refused::Work(work) => Error::limit_unhinted(crate::LimitKind::PacketWork, work.why()),
Refused::Other(error) => error,
}
}
}
pub(crate) struct Meter {
first: u64,
left: Cell<u64>,
refusal: Cell<Option<WorkRefusal>>,
}
impl Meter {
pub(crate) fn new(first: u64) -> Self {
Meter {
first,
left: Cell::new(first),
refusal: Cell::new(None),
}
}
pub(crate) fn first(&self) -> u64 {
self.first
}
pub(crate) fn left(&self) -> u64 {
self.left.get()
}
pub(crate) fn spent(&self) -> u64 {
self.first.saturating_sub(self.left.get())
}
fn refusal(&self) -> Option<WorkRefusal> {
self.refusal.get()
}
fn clear_refusal(&self) {
self.refusal.set(None);
}
pub(crate) fn try_spend(&self, n: u64) -> bool {
match self.left.get().checked_sub(n) {
Some(rest) => {
self.left.set(rest);
true
}
None => false,
}
}
pub(crate) fn spend(&self, n: usize, why: WorkRefusal) -> Result<()> {
if self.try_spend(n as u64) {
Ok(())
} else {
Err(self.refuse(why))
}
}
pub(crate) fn refuse(&self, why: WorkRefusal) -> Error {
self.refusal.set(Some(why));
Error::limit_unhinted(crate::LimitKind::PacketWork, why.why())
}
}
const END_VISITS: usize = 32;
fn packed_overrun() -> Error {
Error::codestream("a packet header runs past the end of its `PPM` or `PPT` packed headers")
}
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"));
}
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 {
coder: Option<Coder>,
included: bool,
lblock: u32,
zero_bit_planes: u32,
num_passes: u32,
segments: Vec<SegmentState>,
}
struct SegmentState {
kind: SegmentKind,
passes: u32,
kept: u32,
max_passes: u32,
length: u64,
chunks: Vec<Range<usize>>,
}
impl SegmentState {
fn new(kind: SegmentKind, max_passes: u32) -> Self {
SegmentState {
kind,
passes: 0,
kept: 0,
max_passes,
length: 0,
chunks: Vec::new(),
}
}
fn kept_placeholders(&self) -> u32 {
match self.kind {
SegmentKind::HtCleanup {
placeholders: Some(p),
} => self.kept.min(p),
SegmentKind::HtCleanup { placeholders: None } => self.kept,
_ => 0,
}
}
fn coded_kept(&self) -> u32 {
self.kept - self.kept_placeholders()
}
}
impl BlockState {
fn new(coder: Option<Coder>) -> Self {
BlockState {
coder,
included: false,
lblock: 3,
zero_bit_planes: 0,
num_passes: 0,
segments: Vec::new(),
}
}
fn skipped_planes(&self) -> u32 {
match self.segments.first() {
Some(
s @ SegmentState {
kind:
SegmentKind::HtCleanup {
placeholders: Some(p),
},
..
},
) if s.coded_kept() > 0 => p / 3,
_ => 0,
}
}
}
struct BandState {
precincts: Vec<PrecinctState>,
blocks: Vec<BlockState>,
}
struct PrecinctState {
inclusion: TagTree,
zero_bits: TagTree,
gap: Option<u32>,
ended: Option<u32>,
}
impl PrecinctState {
fn unread(&self) -> Option<u32> {
match (self.gap, self.ended) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
}
impl BandState {
fn heap_bytes(&self) -> usize {
use std::mem::size_of;
let precincts = self.precincts.capacity() * size_of::<PrecinctState>()
+ self
.precincts
.iter()
.map(|p| p.inclusion.heap_bytes() + p.zero_bits.heap_bytes())
.sum::<usize>();
let blocks = self.blocks.capacity() * size_of::<BlockState>()
+ self
.blocks
.iter()
.map(|b| {
b.segments.capacity() * size_of::<SegmentState>()
+ b.segments
.iter()
.map(|s| s.chunks.capacity() * size_of::<Range<usize>>())
.sum::<usize>()
})
.sum::<usize>();
precincts + blocks
}
fn drop_trees(&mut self) {
for precinct in &mut self.precincts {
precinct.inclusion = TagTree::new(1, 1);
precinct.zero_bits = TagTree::new(1, 1);
precinct.ended = None;
}
self.precincts.shrink_to_fit();
}
fn new(band: &BandGeom, coder: Option<Coder>) -> 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),
gap: None,
ended: None,
})
.collect(),
blocks: (0..band.block_count())
.map(|_| BlockState::new(coder))
.collect(),
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Journal {
trees: Vec<[Vec<Saved>; 2]>,
}
impl Journal {
fn heap_bytes(&self) -> usize {
use std::mem::size_of;
self.trees.capacity() * size_of::<[Vec<Saved>; 2]>()
+ self
.trees
.iter()
.flatten()
.map(|notes| notes.capacity() * size_of::<Saved>())
.sum::<usize>()
}
fn clear(&mut self) {
for [inclusion, zero_bits] in &mut self.trees {
inclusion.clear();
zero_bits.clear();
}
}
fn band(&mut self, band: usize) -> &mut [Vec<Saved>; 2] {
if self.trees.len() <= band {
self.trees.resize_with(band + 1, Default::default);
}
&mut self.trees[band]
}
fn restore(&self, states: &mut [BandState], precinct: usize) {
for (state, [inclusion, zero_bits]) in states.iter_mut().zip(&self.trees) {
if let Some(trees) = state.precincts.get_mut(precinct) {
trees.zero_bits.restore(zero_bits);
trees.inclusion.restore(inclusion);
}
}
}
}
struct Contribution {
band: usize,
block: usize,
segment: usize,
seg_len: usize,
}
#[derive(Default)]
struct Scratch {
contributions: Vec<Contribution>,
unread: UnreadSpans,
}
impl Scratch {
fn heap_bytes(&self) -> usize {
self.contributions.capacity() * std::mem::size_of::<Contribution>()
+ self.unread.heap_bytes()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Packet {
Read,
Ended,
}
struct Undo {
band: usize,
block: usize,
coder: Option<Coder>,
included: bool,
lblock: u32,
zero_bit_planes: u32,
num_passes: u32,
segments: usize,
last: Option<LastSegment>,
}
struct LastSegment {
kind: SegmentKind,
passes: u32,
kept: u32,
max_passes: u32,
length: u64,
chunks: usize,
}
impl LastSegment {
fn of(segment: &SegmentState) -> Self {
LastSegment {
kind: segment.kind,
passes: segment.passes,
kept: segment.kept,
max_passes: segment.max_passes,
length: segment.length,
chunks: segment.chunks.len(),
}
}
}
fn undo(log: &[Undo], states: &mut [BandState]) {
for entry in log.iter().rev() {
let block = &mut states[entry.band].blocks[entry.block];
block.coder = entry.coder;
block.included = entry.included;
block.lblock = entry.lblock;
block.zero_bit_planes = entry.zero_bit_planes;
block.num_passes = entry.num_passes;
block.segments.truncate(entry.segments);
if let (Some(last), Some(was)) = (block.segments.last_mut(), &entry.last) {
last.kind = was.kind;
last.passes = was.passes;
last.kept = was.kept;
last.max_passes = was.max_passes;
last.length = was.length;
last.chunks.truncate(was.chunks);
}
}
}
#[allow(clippy::too_many_arguments)]
fn parse_packet(
streams: &mut PacketStreams<'_>,
meter: &Meter,
layer: u32,
packet_index: u32,
delimiters: Delimiters,
style: u8,
bands: &[BandGeom],
precinct: usize,
states: &mut [BandState],
scratch: &mut Scratch,
keep: bool,
mut log: Option<&mut Vec<Undo>>,
mut journal: Option<&mut Journal>,
) -> Result<Packet> {
meter.spend(1, WorkRefusal::PacketWalk)?;
let partial = log.is_some();
if partial
&& delimiters.sop
&& peek_marker(streams.data, streams.body_pos) == Some(marker::SOP)
&& streams.body_pos + 6 > streams.data.len()
{
return Ok(Packet::Ended);
}
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() {
if partial {
return Ok(Packet::Ended);
}
return Err(Error::codestream(format!(
"the data of tile {} ends before the last packet",
streams.tile
)));
}
let mut bio = BitReader::new(&streams.header[streams.header_pos..]);
if let Some(log) = log.as_deref_mut() {
log.clear();
}
let present = bio.read_bit() == 1;
let contributions = &mut scratch.contributions;
contributions.clear();
let mut fault = None;
if present {
for (band_index, (band, state)) in bands.iter().zip(states.iter_mut()).enumerate() {
let parsed = parse_band_header(
meter,
band_index,
&band.precincts[precinct],
&mut state.precincts[precinct],
&mut state.blocks,
layer,
style,
keep,
&mut bio,
contributions,
&mut scratch.unread,
log.as_deref_mut(),
journal.as_deref_mut().map(|j| j.band(band_index)),
);
if let Err(error) = parsed {
fault = Some(error);
break;
}
}
}
if streams.packed && bio.overran() {
return Err(packed_overrun());
}
if let Some(error) = fault {
return match log.as_deref() {
Some(log) if bio.overran() => {
undo(log, states);
Ok(Packet::Ended)
}
_ => Err(error),
};
}
let header_overran = bio.overran() && !streams.packed;
bio.align();
if streams.packed && bio.overran() {
return Err(packed_overrun());
}
streams.header_pos += bio.bytes_consumed();
if let Some(log) = log.as_deref() {
let eph_cut = delimiters.eph && streams.header_pos + 2 > streams.header.len();
if header_overran || eph_cut {
undo(log, states);
return Ok(Packet::Ended);
}
}
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",
));
}
streams.header_pos += 2;
}
if !streams.packed {
streams.body_pos = streams.header_pos;
}
for contribution in contributions.iter() {
let end = match streams
.body_pos
.checked_add(contribution.seg_len)
.filter(|&e| e <= streams.data.len())
{
Some(end) => end,
None => {
if let Some(log) = log.as_deref() {
let from = log
.iter()
.position(|u| (u.band, u.block) == (contribution.band, contribution.block))
.unwrap_or(0);
undo(&log[from..], states);
return Ok(Packet::Ended);
}
return Err(Error::codestream(format!(
"a packet body segment overruns the data of tile {}",
streams.tile
)));
}
};
if keep {
states[contribution.band].blocks[contribution.block].segments[contribution.segment]
.chunks
.push(streams.body_pos..end);
}
streams.body_pos = end;
}
if !streams.packed {
streams.header_pos = streams.body_pos;
}
Ok(Packet::Read)
}
#[allow(clippy::too_many_arguments)]
fn parse_band_header(
meter: &Meter,
band_index: usize,
precinct: &PrecinctGeom,
trees: &mut PrecinctState,
blocks: &mut [BlockState],
layer: u32,
style: u8,
keep: bool,
bio: &mut BitReader,
contributions: &mut Vec<Contribution>,
unread: &mut UnreadSpans,
mut log: Option<&mut Vec<Undo>>,
mut saved: Option<&mut [Vec<Saved>; 2]>,
) -> Result<()> {
let cols = precinct.cols as u32;
let threshold = layer + 1;
unread.clear();
let mut entry = 0;
while entry < precinct.cols * precinct.rows {
let bx = entry as u32 % cols;
let by = entry as u32 / cols;
let block_index = precinct.block(bx as usize, by as usize);
entry += 1;
let was_included = blocks[block_index].included;
let span = if was_included {
None
} else {
unread.find(&trees.inclusion, bx, by, threshold)
};
if let Some(span) = span {
meter.spend(1, WorkRefusal::PacketWalk)?;
entry = span.next_entry(by, cols);
continue;
}
let contributes = if was_included {
bio.read_bit() == 1
} else {
let saved = saved.as_deref_mut().map(|[inclusion, _]| inclusion);
match trees.inclusion.read_saving(bx, by, threshold, bio, saved) {
Some(_) => {
blocks[block_index].included = true;
true
}
None => false,
}
};
if !contributes {
continue;
}
if let Some(log) = log.as_deref_mut() {
let block = &blocks[block_index];
log.push(Undo {
band: band_index,
block: block_index,
coder: block.coder,
included: was_included,
lblock: block.lblock,
zero_bit_planes: block.zero_bit_planes,
num_passes: block.num_passes,
segments: block.segments.len(),
last: block.segments.last().map(LastSegment::of),
});
}
if !was_included {
let saved = saved.as_deref_mut().map(|[_, zero_bits]| zero_bits);
blocks[block_index].zero_bit_planes = trees
.zero_bits
.read_saving(bx, by, ZBP_LIMIT, bio, saved)
.ok_or_else(|| {
Error::codestream(format!(
"code-block zero-bitplane count is over {}, the most a valid stream \
can signal",
ZBP_LIMIT - 1
))
})?;
}
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(format!(
"code-block `Lblock` grows past the limit of {LBLOCK_MAX}"
)));
}
}
let mut remaining = num_passes;
let mut placeholders = 0;
let open = SegmentKind::HtCleanup { placeholders: None };
let first_open = block.segments.first().is_none_or(|s| s.kind == open);
let prior = block.segments.first().map_or(0, |s| s.passes);
let mut part1_length = None;
let first = match block.coder {
Some(Coder::Ht) if first_open => {
Some(ht_first_cleanup(block.lblock, prior, num_passes, bio)?)
}
Some(_) => None,
None => match mixed_first_length(block.lblock, prior, num_passes, bio)? {
MixedFirst::Empty => Some(FirstCleanup::Placeholders),
MixedFirst::Ht(first) => {
block.coder = Some(Coder::Ht);
Some(first)
}
MixedFirst::Part1 { length } => {
become_part1(block);
part1_length = Some(length);
None
}
},
};
if let Some(first) = first {
if block.segments.is_empty() {
block.segments.push(SegmentState::new(open, u32::MAX));
}
let segment = &mut block.segments[0];
let passes = match first {
FirstCleanup::Placeholders => {
placeholders = num_passes;
num_passes
}
FirstCleanup::Cleanup {
placeholders: before,
passes,
length,
} => {
placeholders = before - prior;
segment.kind = SegmentKind::HtCleanup {
placeholders: Some(before),
};
segment.max_passes = before + 1;
add_length(segment, length)?;
contributions.push(Contribution {
band: band_index,
block: block_index,
segment: 0,
seg_len: length as usize,
});
passes
}
};
segment.passes += passes;
if keep {
segment.kept += passes;
}
remaining -= passes;
}
if keep {
block.num_passes += num_passes - placeholders;
}
while remaining > 0 {
if block
.segments
.last()
.is_none_or(|s| s.passes >= s.max_passes)
{
let coder = block.coder.unwrap_or(Coder::Ht);
let (kind, max_passes) = next_segment(coder, style, block.segments.last());
block.segments.push(SegmentState::new(kind, max_passes));
}
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 seg_len = match part1_length.take() {
Some(length) => length,
None => bio.read(length_bits(block.lblock, new_passes)),
};
add_length(segment, seg_len)?;
let seg_len = seg_len as usize;
let segment = &mut block.segments[segment_index];
segment.passes += new_passes;
if keep {
segment.kept += new_passes;
}
if seg_len > 0 {
contributions.push(Contribution {
band: band_index,
block: block_index,
segment: segment_index,
seg_len,
});
}
remaining -= new_passes;
}
}
Ok(())
}
fn mark_unread(bands: &mut [BandState], precinct: usize, layer: u32) {
for band in bands {
if let Some(state) = band.precincts.get_mut(precinct) {
state.ended = Some(state.ended.map_or(layer, |from| from.min(layer)));
}
}
}
fn mark_gap(bands: &mut [BandState], layer: u32) {
for band in bands {
for state in &mut band.precincts {
state.gap = Some(state.gap.map_or(layer, |from| from.min(layer)));
}
}
}
fn build_subbands<'a>(
bands: &[BandGeom],
states: &[BandState],
data: &'a [u8],
) -> Vec<Subband<'a>> {
bands
.iter()
.zip(states)
.map(|(band, state)| {
debug_assert_eq!(
state.blocks.len(),
band.block_count(),
"one block state per code-block of the band"
);
let mut unread = Vec::new();
for (geom, precinct) in band.precincts.iter().zip(&state.precincts) {
if let Some(from) = precinct.unread() {
unread.resize(state.blocks.len(), None);
for by in 0..geom.rows {
for bx in 0..geom.cols {
if let Some(flag) = unread.get_mut(geom.block(bx, by)) {
*flag = Some(from);
}
}
}
}
}
let mut blocks = Vec::with_capacity(state.blocks.len());
blocks.extend(band.block_rects().zip(&state.blocks).enumerate().map(
|(index, ((x, y, width, height), block))| {
let missing_from = unread.get(index).copied().flatten();
let unread = missing_from.is_some();
let mut cut = false;
let coder = block.coder.unwrap_or(Coder::Ht);
let zero_bit_planes = block.zero_bit_planes + block.skipped_planes();
let placeholders = block
.segments
.first()
.map_or(0, SegmentState::kept_placeholders);
let segments = block
.segments
.iter()
.take_while(|s| s.coded_kept() > 0)
.map(|s| {
cut = s.kept < s.passes || (unread && s.passes < s.max_passes);
CodedSegment {
passes: s.coded_kept(),
chunks: s.chunks.iter().map(|r| &data[r.clone()]).collect(),
}
})
.collect();
CodeBlock {
x,
y,
width,
height,
num_passes: block.num_passes,
zero_bit_planes,
segments,
cut,
placeholders,
coder,
missing_from,
}
},
));
Subband {
kind: band.kind,
origin: band.origin,
width: band.width,
height: band.height,
block_cols: band.block_cols,
block_rows: band.block_rows,
blocks,
}
})
.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 partial_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod work_bound_tests;