pub mod mq;
pub mod passes;
use crate::codestream::MainHeader;
use crate::codestream::markers::Transform;
use crate::pipeline::{Band, Bands, DetailBands, SubbandCoeffs};
use crate::quant;
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};
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,
|_| Ok(|q| q / 2),
)?)),
Transform::Irreversible97 => Ok(SubbandCoeffs::Irreversible(assemble(
header,
index,
component,
reduction,
|band| {
let half_step = quant::half_step(header, index, band)?;
Ok(move |q| q as f32 * half_step)
},
)?)),
}
})
.collect()
}
pub(crate) const DECODE_WORK_MIN: u64 = 1 << 26;
pub(crate) const DECODE_WORK_PER_BYTE: u64 = 1 << 15;
pub(crate) fn decode_work(bytes: u64) -> u64 {
DECODE_WORK_MIN.max(bytes.saturating_mul(DECODE_WORK_PER_BYTE))
}
pub(crate) fn work(header: &MainHeader, coded: &CodedData<'_>, reduction: u8) -> u64 {
let mut total = 0u64;
for (comp, component) in coded.components.iter().enumerate() {
let Some(params) = header.components.get(comp) else {
continue;
};
let kept = component
.resolutions
.len()
.saturating_sub(usize::from(reduction))
.max(1);
for (res, resolution) in component.resolutions.iter().take(kept).enumerate() {
for subband in &resolution.subbands {
let band = band_index(res, subband.kind);
let Ok(numbps) = numbps(header, comp, band) else {
continue;
};
for block in &subband.blocks {
let passes = passes_run(numbps, block, params.roi_shift);
let samples = (block.width as u64).saturating_mul(block.height as u64);
total = total.saturating_add(passes.saturating_mul(samples));
}
}
}
}
total
}
fn passes_run(numbps: u32, block: &CodeBlock<'_>, roi_shift: u8) -> u64 {
if block.num_passes == 0 {
return 0;
}
let top = top_coded_plane(numbps, block.zero_bit_planes, roi_shift);
if !(1..=MAX_BIT_PLANES).contains(&top) {
return 0;
}
u64::from(block.num_passes.min(3 * top - 2))
}
fn band_index(res: usize, kind: BandKind) -> usize {
match (res, kind) {
(0, _) => 0,
(_, BandKind::Hl) => 3 * res - 2,
(_, BandKind::Lh) => 3 * res - 1,
(_, _) => 3 * res,
}
}
fn assemble<T, F, G>(
header: &MainHeader,
comp: usize,
coded: &ComponentCoded<'_>,
reduction: u8,
convert_for: G,
) -> Result<Bands<T>>
where
T: Copy + Default,
F: Fn(i32) -> T,
G: Fn(usize) -> Result<F>,
{
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 decode = |res: usize, resolution: &Resolution<'_>, kind: BandKind| {
let band = band_index(res, kind);
decode_subband(
subband_of(resolution, kind)?,
numbps(header, comp, band)?,
params,
convert_for(band)?,
)
};
let ll = decode(0, coarsest, BandKind::Ll)?;
let mut levels = Vec::with_capacity(keep);
for (level, resolution) in resolutions.take(keep).enumerate() {
let res = level + 1;
levels.push(DetailBands {
hl: decode(res, resolution, BandKind::Hl)?,
lh: decode(res, resolution, BandKind::Lh)?,
hh: decode(res, resolution, BandKind::Hh)?,
});
}
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::Limit(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> {
kind_block_subband(BandKind::Ll, num_passes, zero_bit_planes)
}
fn kind_block_subband(
kind: BandKind,
num_passes: u32,
zero_bit_planes: u32,
) -> Subband<'static> {
Subband {
kind,
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::Limit(_)), "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::Limit(_)), "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 coded_subband(kind: BandKind) -> Subband<'static> {
let mut sb = kind_block_subband(kind, 1, 0);
sb.blocks[0].segments[0].chunks = vec![&[0x00, 0x00, 0x00][..]];
sb
}
#[test]
fn band_index_follows_qcd_order() {
for kind in [BandKind::Ll, BandKind::Hl, BandKind::Lh, BandKind::Hh] {
assert_eq!(band_index(0, kind), 0);
}
assert_eq!(band_index(1, BandKind::Hl), 1);
assert_eq!(band_index(1, BandKind::Lh), 2);
assert_eq!(band_index(1, BandKind::Hh), 3);
assert_eq!(band_index(2, BandKind::Hl), 4);
assert_eq!(band_index(2, BandKind::Lh), 5);
assert_eq!(band_index(2, BandKind::Hh), 6);
}
#[test]
fn each_irreversible_band_is_scaled_by_its_own_step() {
let bytes = std::fs::read(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/irreversible_lossy.j2k"
))
.unwrap();
let mut header = crate::codestream::parse_header(&bytes).unwrap().header;
assert_eq!(
header.components[0].coding.transform,
Transform::Irreversible97
);
header.components[0].quant.style = crate::codestream::markers::QuantStyle::ScalarExpounded;
header.components[0].quant.guard_bits = 2;
header.components[0].quant.steps = vec![(8, 0), (8, 100), (8, 700), (8, 1500)];
let coded = CodedData {
components: vec![ComponentCoded {
resolutions: vec![
Resolution {
subbands: vec![coded_subband(BandKind::Ll)],
},
Resolution {
subbands: vec![
coded_subband(BandKind::Hl),
coded_subband(BandKind::Lh),
coded_subband(BandKind::Hh),
],
},
],
}],
};
let q = decode_subband::<i32, _>(
&coded.components[0].resolutions[0].subbands[0],
numbps(&header, 0, 0).unwrap(),
default_params(),
|q| q,
)
.unwrap()
.data[0];
assert_ne!(q, 0);
let out = decode_code_blocks(&header, &coded, 0).unwrap();
let SubbandCoeffs::Irreversible(bands) = &out[0] else {
panic!("expected the irreversible arm");
};
let got = [
bands.ll.data[0],
bands.levels[0].hl.data[0],
bands.levels[0].lh.data[0],
bands.levels[0].hh.data[0],
];
for (band, value) in got.into_iter().enumerate() {
let step = quant::half_step(&header, 0, band).unwrap();
assert_eq!(value.to_bits(), (q as f32 * step).to_bits(), "band {band}");
}
for i in 0..4 {
for j in (i + 1)..4 {
assert_ne!(got[i].to_bits(), got[j].to_bits());
}
}
}
fn default_params() -> BlockParams {
BlockParams::default()
}
}
#[cfg(test)]
mod work_bound_tests;