pub mod mq;
pub mod passes;
use crate::codestream::MainHeader;
use crate::codestream::markers::Transform;
use crate::tier1::mq::MqDecoder;
use crate::tier1::passes::{BlockState, MAX_BIT_PLANES, Orientation, decode_block};
use crate::tier2::{BandKind, CodeBlock, CodedData, 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<'_>) -> Result<SubbandCoeffs> {
match header.cod.transform {
Transform::Reversible53 => Ok(SubbandCoeffs::Reversible(assemble(header, coded, |q| q)?)),
Transform::Irreversible97 => {
Ok(SubbandCoeffs::Irreversible(assemble(header, coded, |q| {
q as f32
})?))
}
}
}
fn assemble<T, F>(header: &MainHeader, coded: &CodedData<'_>, convert: F) -> Result<Bands<T>>
where
T: Copy + Default,
F: Fn(i32) -> T + Copy,
{
let style = header.cod.code_block_style;
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, 0)?,
style,
convert,
)?;
let mut levels = Vec::with_capacity(coded.resolutions.len().saturating_sub(1));
for (level, resolution) in resolutions.enumerate() {
let base = 1 + level * 3;
levels.push(DetailBands {
hl: decode_subband(
subband_of(resolution, BandKind::Hl)?,
numbps(header, base)?,
style,
convert,
)?,
lh: decode_subband(
subband_of(resolution, BandKind::Lh)?,
numbps(header, base + 1)?,
style,
convert,
)?,
hh: decode_subband(
subband_of(resolution, BandKind::Hh)?,
numbps(header, base + 2)?,
style,
convert,
)?,
});
}
Ok(Bands { ll, levels })
}
fn numbps(header: &MainHeader, band: usize) -> Result<u32> {
let qcd = &header.qcd;
let (exp, _) = qcd.subband_step(band).ok_or_else(|| {
Error::Inconsistent(format!(
"QCD 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, style: u8, 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 = numbps.saturating_sub(block.zero_bit_planes);
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 mut mq = MqDecoder::new(block.segment);
decode_block(
&mut mq,
&mut state,
orient,
numbps,
block.num_passes,
block.zero_bit_planes,
style,
);
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,
segment: &[0x80],
}],
}
}
#[test]
fn excessive_bit_planes_rejected() {
let sb = one_block_subband(1, 0);
let err =
decode_subband::<i32, _>(&sb, MAX_BIT_PLANES + 1, 0, |q| q).expect_err("must reject");
assert!(matches!(err, Error::Unsupported(_)), "got {err:?}");
}
#[test]
fn max_bit_planes_accepted() {
let sb = one_block_subband(1, 0);
let band = decode_subband::<i32, _>(&sb, MAX_BIT_PLANES, 0, |q| q).expect("in range");
assert_eq!(band.data.len(), 1);
}
}