pub mod mq;
pub mod passes;
use crate::codestream::MainHeader;
use crate::codestream::markers::Transform;
use crate::tier1::passes::{
BlockParams, BlockState, MAX_BIT_PLANES, Orientation, decode_block, top_coded_plane,
};
use crate::tier2::{BandKind, CodeBlock, CodedData, ComponentCoded, Resolution, Subband};
use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq)]
pub struct Band<T> {
pub origin: (u32, u32),
pub width: usize,
pub height: usize,
pub data: Vec<T>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct DetailBands<T> {
pub hl: Band<T>,
pub lh: Band<T>,
pub hh: Band<T>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Bands<T> {
pub ll: Band<T>,
pub levels: Vec<DetailBands<T>>,
}
#[derive(Debug, Clone, PartialEq)]
pub enum SubbandCoeffs {
Reversible(Bands<i32>),
Irreversible(Bands<f32>),
}
pub fn decode_code_blocks(
header: &MainHeader,
coded: &CodedData<'_>,
reduction: u8,
) -> Result<Vec<SubbandCoeffs>> {
coded
.components
.iter()
.enumerate()
.map(|(index, component)| {
let transform = header
.components
.get(index)
.ok_or_else(|| {
Error::Inconsistent(format!("no coding parameters for component {index}"))
})?
.coding
.transform;
match transform {
Transform::Reversible53 => Ok(SubbandCoeffs::Reversible(assemble(
header,
index,
component,
reduction,
|q| q / 2,
)?)),
Transform::Irreversible97 => Ok(SubbandCoeffs::Irreversible(assemble(
header,
index,
component,
reduction,
|q| q as f32,
)?)),
}
})
.collect()
}
fn assemble<T, F>(
header: &MainHeader,
comp: usize,
coded: &ComponentCoded<'_>,
reduction: u8,
convert: F,
) -> Result<Bands<T>>
where
T: Copy + Default,
F: Fn(i32) -> T + Copy,
{
let params = BlockParams {
style: header.components[comp].coding.code_block_style,
roi_shift: header.components[comp].roi_shift,
};
let keep = coded
.resolutions
.len()
.saturating_sub(1 + usize::from(reduction));
let mut resolutions = coded.resolutions.iter();
let coarsest = resolutions
.next()
.ok_or_else(|| Error::Inconsistent("Tier-2 produced no resolutions to decode".into()))?;
let ll = decode_subband(
subband_of(coarsest, BandKind::Ll)?,
numbps(header, comp, 0)?,
params,
convert,
)?;
let mut levels = Vec::with_capacity(keep);
for (level, resolution) in resolutions.take(keep).enumerate() {
let base = 1 + level * 3;
levels.push(DetailBands {
hl: decode_subband(
subband_of(resolution, BandKind::Hl)?,
numbps(header, comp, base)?,
params,
convert,
)?,
lh: decode_subband(
subband_of(resolution, BandKind::Lh)?,
numbps(header, comp, base + 1)?,
params,
convert,
)?,
hh: decode_subband(
subband_of(resolution, BandKind::Hh)?,
numbps(header, comp, base + 2)?,
params,
convert,
)?,
});
}
Ok(Bands { ll, levels })
}
fn numbps(header: &MainHeader, comp: usize, band: usize) -> Result<u32> {
let qcd = &header
.components
.get(comp)
.ok_or_else(|| Error::Inconsistent(format!("no coding parameters for component {comp}")))?
.quant;
let (exp, _) = qcd.subband_step(band).ok_or_else(|| {
Error::Inconsistent(format!(
"component {comp} carries {} step sizes but subband {band} needs one",
qcd.steps.len()
))
})?;
Ok((u32::from(qcd.guard_bits) + u32::from(exp)).saturating_sub(1))
}
fn subband_of<'a, 'b>(res: &'a Resolution<'b>, kind: BandKind) -> Result<&'a Subband<'b>> {
res.subbands
.iter()
.find(|s| s.kind == kind)
.ok_or_else(|| Error::Inconsistent(format!("resolution is missing its {kind:?} subband")))
}
fn decode_subband<T, F>(
sb: &Subband<'_>,
numbps: u32,
params: BlockParams,
convert: F,
) -> Result<Band<T>>
where
T: Copy + Default,
F: Fn(i32) -> T,
{
let orient = match sb.kind {
BandKind::Ll => Orientation::Ll,
BandKind::Hl => Orientation::Hl,
BandKind::Lh => Orientation::Lh,
BandKind::Hh => Orientation::Hh,
};
let mut data = vec![T::default(); sb.width * sb.height];
for block in &sb.blocks {
if block.num_passes == 0 {
continue;
}
let top = top_coded_plane(numbps, block.zero_bit_planes, params.roi_shift);
if top > MAX_BIT_PLANES {
return Err(Error::Unsupported(format!(
"code-block needs {top} bit-planes, over the {MAX_BIT_PLANES}-plane limit"
)));
}
let mut state = BlockState::new(block.width as u32, block.height as u32);
let segments: Vec<(Vec<u8>, u32)> = block
.segments
.iter()
.map(|segment| (segment.bytes(), segment.passes))
.collect();
decode_block(
&segments,
&mut state,
orient,
numbps,
block.num_passes,
block.zero_bit_planes,
params,
)?;
place_block(&mut data, sb.width, block, &state, &convert);
}
Ok(Band {
origin: sb.origin,
width: sb.width,
height: sb.height,
data,
})
}
fn place_block<T, F>(
data: &mut [T],
band_width: usize,
block: &CodeBlock<'_>,
state: &BlockState,
convert: &F,
) where
F: Fn(i32) -> T,
{
for row in 0..block.height {
let dst = (block.y + row) * band_width + block.x;
let src = row * block.width;
for col in 0..block.width {
data[dst + col] = convert(state.coeffs[src + col]);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tier2::{BandKind, CodeBlock, Subband};
fn one_block_subband(num_passes: u32, zero_bit_planes: u32) -> Subband<'static> {
Subband {
kind: BandKind::Ll,
origin: (0, 0),
width: 1,
height: 1,
block_cols: 1,
block_rows: 1,
blocks: vec![CodeBlock {
x: 0,
y: 0,
width: 1,
height: 1,
num_passes,
zero_bit_planes,
segments: vec![crate::tier2::CodedSegment {
passes: 1,
chunks: vec![&[0x80][..]],
}],
}],
}
}
#[test]
fn excessive_bit_planes_rejected() {
let sb = one_block_subband(1, 0);
let err = decode_subband::<i32, _>(&sb, MAX_BIT_PLANES + 1, default_params(), |q| q)
.expect_err("must reject");
assert!(matches!(err, Error::Unsupported(_)), "got {err:?}");
}
#[test]
fn a_maxshift_that_overflows_the_bit_planes_is_rejected() {
let sb = one_block_subband(1, 0);
let params = BlockParams {
style: 0,
roi_shift: 1,
};
let err = decode_subband::<i32, _>(&sb, MAX_BIT_PLANES, params, |q| q)
.expect_err("MAX_BIT_PLANES + 1 planes");
assert!(matches!(err, Error::Unsupported(_)), "got {err:?}");
decode_subband::<i32, _>(&sb, MAX_BIT_PLANES - 1, params, |q| q).expect("in range");
}
#[test]
fn excess_zero_bit_planes_decodes_to_zeros() {
let sb = one_block_subband(1, 5);
let band = decode_subband::<i32, _>(&sb, 4, default_params(), |q| q)
.expect("saturates to zero coded planes, as the oracle does");
assert!(band.data.iter().all(|&c| c == 0));
}
#[test]
fn max_bit_planes_accepted() {
let sb = one_block_subband(1, 0);
let band = decode_subband::<i32, _>(&sb, MAX_BIT_PLANES, default_params(), |q| q)
.expect("in range");
assert_eq!(band.data.len(), 1);
}
fn default_params() -> BlockParams {
BlockParams::default()
}
}