pub(crate) mod ebcot;
mod ht;
use crate::codestream::MainHeader;
use crate::codestream::markers::Transform;
use crate::pipeline::{Band, Bands, DetailBands, SubbandCoeffs};
use crate::quant;
use crate::tier2::{
BandExtent, BandKind, CodeBlock, CodedData, Coder, ComponentCoded, Resolution, Subband,
};
use crate::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BlockCoder {
Ebcot { style: u8, roi_shift: u8 },
Ht {
roi_shift: u8,
causal: bool,
bound: CleanupBound,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CleanupBound {
magb: Option<u32>,
irreversible: bool,
}
impl CleanupBound {
fn bits(self, level: u32) -> Option<u32> {
let b = self.magb?;
Some(if self.irreversible && b <= 31 {
(b + level).saturating_sub(1).min(31)
} else {
b
})
}
}
pub(crate) fn decode_ht_block(
block: &CodeBlock<'_>,
numbps: u32,
roi_shift: u8,
causal: bool,
bound_bits: Option<u32>,
) -> Result<Vec<i32>> {
ht::decode(
block,
numbps,
ht::Params {
roi_shift,
causal,
bound_bits,
},
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Coders {
part1: BlockCoder,
ht: BlockCoder,
mixed: bool,
}
impl Coders {
fn of(header: &MainHeader, comp: usize) -> Self {
let params = &header.components[comp];
let style = params.coding.code_block_style;
let roi_shift = params.roi_shift;
use crate::codestream::markers::code_block_style::{HT, HT_MIXED, VCAUSAL};
Coders {
mixed: Coder::of_style(style, header.ccap15).is_none(),
part1: BlockCoder::Ebcot {
style: style & !(HT | HT_MIXED),
roi_shift,
},
ht: BlockCoder::Ht {
roi_shift,
causal: style & VCAUSAL != 0,
bound: CleanupBound {
magb: header.ccap15.map(|c| c.magnitude_bound()),
irreversible: params.coding.transform == Transform::Irreversible97,
},
},
}
}
fn of_block(self, block: &CodeBlock<'_>) -> BlockCoder {
match block.coder {
Coder::Part1 => self.part1,
Coder::Ht => self.ht,
}
}
fn decode<'s, 'a>(
self,
block: &CodeBlock<'a>,
kind: BandKind,
level: u32,
numbps: u32,
scratch: &'s mut Scratch<'a>,
) -> Result<&'s [i32]> {
let decoded = self
.of_block(block)
.decode(block, kind, level, numbps, scratch);
match decoded {
Err(Error::Codestream(message)) if self.mixed && block.coder == Coder::Ht => {
Err(Error::codestream(format!(
"{message} (a code-block of a MIXED tile-component, read as an HT \
block since its first nonzero length field starts with 0 at Lblock \
above 3, ISO/IEC 15444-15 A.4; a Part 1 block whose Lblock grew \
more than it needed reads this way too)"
)))
}
other => other,
}
}
}
#[derive(Debug, Default)]
struct Scratch<'a> {
ebcot: ebcot::Scratch<'a>,
ht: ht::Scratch,
}
impl BlockCoder {
fn decode<'s, 'a>(
self,
block: &CodeBlock<'a>,
kind: BandKind,
level: u32,
numbps: u32,
scratch: &'s mut Scratch<'a>,
) -> Result<&'s [i32]> {
match self {
BlockCoder::Ebcot { style, roi_shift } => {
ebcot::decode(block, kind, numbps, style, roi_shift, &mut scratch.ebcot)
}
BlockCoder::Ht {
roi_shift,
causal,
bound,
} => ht::decode_into(
block,
numbps,
ht::Params {
roi_shift,
causal,
bound_bits: bound.bits(level),
},
&mut scratch.ht,
),
}
}
fn cost(self, block: &CodeBlock<'_>, numbps: u32) -> u64 {
match self {
BlockCoder::Ebcot { roi_shift, .. } => ebcot::passes_run(numbps, block, roi_shift),
BlockCoder::Ht { roi_shift, .. } => ht::passes_run(block, numbps, roi_shift),
}
}
}
pub fn decode_code_blocks(
header: &MainHeader,
coded: &CodedData<'_>,
reduction: u8,
wanted: &[bool],
) -> Result<Vec<Option<SubbandCoeffs>>> {
coded
.components
.iter()
.enumerate()
.map(|(index, component)| {
if !wanted.get(index).copied().unwrap_or(false) {
return Ok(None);
}
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(Some(SubbandCoeffs::Reversible(assemble(
header,
index,
component,
reduction,
|_| Ok(|q| q / 2),
)?))),
Transform::Irreversible97 => Ok(Some(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,
wanted: &[bool],
) -> u64 {
let mut total = 0u64;
for (comp, component) in coded.components.iter().enumerate() {
if header.components.get(comp).is_none() || !wanted.get(comp).copied().unwrap_or(false) {
continue;
}
let coders = Coders::of(header, comp);
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 = coders.of_block(block).cost(block, numbps);
let samples = (block.width as u64).saturating_mul(block.height as u64);
total = total.saturating_add(passes.saturating_mul(samples));
}
}
}
}
total
}
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<'a, T, F, G>(
header: &MainHeader,
comp: usize,
coded: &ComponentCoded<'a>,
reduction: u8,
convert_for: G,
) -> Result<Bands<T>>
where
T: Copy + Default,
F: Fn(i32) -> T,
G: Fn(usize) -> Result<F>,
{
let coders = Coders::of(header, comp);
let keep = coded
.resolutions
.len()
.saturating_sub(1 + usize::from(reduction));
let levels = u32::try_from(coded.resolutions.len().saturating_sub(1)).unwrap_or(u32::MAX);
let mut resolutions = coded.resolutions.iter();
let coarsest = resolutions
.next()
.ok_or_else(|| Error::inconsistent("tier-2 produced no resolutions to decode"))?;
let mut scratch = Scratch::default();
let mut decode = |res: usize, resolution: &Resolution<'a>, kind: BandKind| {
let band = band_index(res, kind);
let level = match res {
0 => levels,
_ => (levels + 1).saturating_sub(res as u32),
};
let listed;
let sb = match subband_of(resolution, kind) {
Ok(sb) => sb,
Err(_) if resolution.subbands.is_empty() => {
listed = empty_subband(extent_of(coded, res, kind)?, kind);
&listed
}
Err(error) => return Err(error),
};
decode_subband(
sb,
level,
numbps(header, comp, band)?,
coders,
&mut scratch,
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;
if resolution.subbands.iter().all(|s| s.width * s.height == 0) {
let [hl, lh, hh] = match coded.detail_extents(res) {
Some(extents) => extents.map(Some),
None => [BandKind::Hl, BandKind::Lh, BandKind::Hh].map(|k| coded.band(res, k)),
};
levels.push(DetailBands {
hl: empty_band(header, comp, res, BandKind::Hl, hl)?,
lh: empty_band(header, comp, res, BandKind::Lh, lh)?,
hh: empty_band(header, comp, res, BandKind::Hh, hh)?,
});
continue;
}
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 extent_of(coded: &ComponentCoded<'_>, res: usize, kind: BandKind) -> Result<BandExtent> {
coded
.band(res, kind)
.ok_or_else(|| Error::inconsistent(format!("resolution is missing its {kind:?} subband")))
}
fn empty_subband(extent: BandExtent, kind: BandKind) -> Subband<'static> {
Subband {
kind,
origin: extent.origin,
width: extent.width,
height: extent.height,
block_cols: 0,
block_rows: 0,
blocks: Vec::new(),
}
}
fn empty_band<T>(
header: &MainHeader,
comp: usize,
res: usize,
kind: BandKind,
extent: Option<BandExtent>,
) -> Result<Band<T>> {
let extent = extent.ok_or_else(|| {
Error::inconsistent(format!("resolution is missing its {kind:?} subband"))
})?;
numbps(header, comp, band_index(res, kind))?;
Ok(Band {
origin: extent.origin,
width: extent.width,
height: extent.height,
data: Vec::new(),
})
}
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<'a, T, F>(
sb: &Subband<'a>,
level: u32,
numbps: u32,
coders: Coders,
scratch: &mut Scratch<'a>,
convert: F,
) -> Result<Band<T>>
where
T: Copy + Default,
F: Fn(i32) -> T,
{
let mut data = vec![T::default(); sb.width * sb.height];
for block in &sb.blocks {
if block.num_passes == 0 {
continue;
}
let coeffs = coders.decode(block, sb.kind, level, numbps, scratch)?;
place_block(&mut data, sb.width, block, coeffs, &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<'_>,
coeffs: &[i32],
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(coeffs[src + col]);
}
}
}
#[cfg(test)]
mod tests {
use super::ebcot::passes::MAX_BIT_PLANES;
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][..]],
}],
cut: false,
placeholders: 0,
coder: Coder::Part1,
missing_from: None,
}],
}
}
#[test]
fn excessive_bit_planes_rejected() {
let sb = one_block_subband(1, 0);
let err = decode_subband::<i32, _>(
&sb,
1,
MAX_BIT_PLANES + 1,
default_params(),
&mut Scratch::default(),
|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 = part1_coders(1);
let err = decode_subband::<i32, _>(
&sb,
1,
MAX_BIT_PLANES,
params,
&mut Scratch::default(),
|q| q,
)
.expect_err("MAX_BIT_PLANES + 1 planes");
assert!(matches!(err, Error::Limit(_)), "got {err:?}");
decode_subband::<i32, _>(
&sb,
1,
MAX_BIT_PLANES - 1,
params,
&mut Scratch::default(),
|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, 1, 4, default_params(), &mut Scratch::default(), |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,
1,
MAX_BIT_PLANES,
default_params(),
&mut Scratch::default(),
|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 {
rect: None,
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],
1,
numbps(&header, 0, 0).unwrap(),
default_params(),
&mut Scratch::default(),
|q| q,
)
.unwrap()
.data[0];
assert_ne!(q, 0);
let out = decode_code_blocks(&header, &coded, 0, &[true]).unwrap();
let Some(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());
}
}
}
#[test]
fn the_cleanup_bound_follows_8_7_3() {
let bound = |magb, irreversible| CleanupBound { magb, irreversible };
assert_eq!(bound(None, false).bits(3), None);
assert_eq!(bound(None, true).bits(3), None);
for level in [0, 1, 5] {
assert_eq!(bound(Some(11), false).bits(level), Some(11));
assert_eq!(bound(Some(35), true).bits(level), Some(35));
}
assert_eq!(bound(Some(11), true).bits(1), Some(11));
assert_eq!(bound(Some(11), true).bits(3), Some(13));
assert_eq!(bound(Some(11), true).bits(0), Some(10));
assert_eq!(bound(Some(30), true).bits(5), Some(31));
assert_eq!(bound(Some(31), true).bits(1), Some(31));
}
#[test]
fn a_mixed_block_goes_to_its_own_coder() {
let coders = Coders {
part1: BlockCoder::Ebcot {
style: 0,
roi_shift: 0,
},
ht: BlockCoder::Ht {
roi_shift: 0,
causal: false,
bound: CleanupBound {
magb: None,
irreversible: false,
},
},
mixed: true,
};
let mut sb = one_block_subband(1, 0);
decode_subband::<i32, _>(&sb, 1, 1, coders, &mut Scratch::default(), |q| q)
.expect("a Part 1 block");
sb.blocks[0].coder = Coder::Ht;
sb.blocks[0].segments[0].chunks = vec![&[0, 0][..]];
let err = decode_subband::<i32, _>(&sb, 1, 1, coders, &mut Scratch::default(), |q| q)
.expect_err("an HT block");
let Error::Codestream(message) = &err else {
panic!("got {err:?}")
};
assert!(
message
.message()
.contains("MIXED tile-component, read as an HT block")
&& message.message().contains("A.4")
&& message
.message()
.contains("Lblock grew more than it needed"),
"{message}"
);
let plain = Coders {
mixed: false,
..coders
};
let err = decode_subband::<i32, _>(&sb, 1, 1, plain, &mut Scratch::default(), |q| q)
.expect_err("an HT block");
let Error::Codestream(message) = &err else {
panic!("got {err:?}")
};
assert!(!message.message().contains("MIXED"), "{message}");
}
#[test]
fn coders_of_marks_a_mixed_tile_component() {
use crate::codestream::markers::Ccap15;
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;
for (style, ccap15, mixed) in [
(0xC0, None, true),
(0xC0, Some(Ccap15(0xC000)), true),
(0xC0, Some(Ccap15(0x0000)), false),
(0x40, None, false),
(0x00, None, false),
] {
header.components[0].coding.code_block_style = style;
header.ccap15 = ccap15;
assert_eq!(
Coders::of(&header, 0).mixed,
mixed,
"style {style:#04x}, {ccap15:?}"
);
}
}
fn noise(seed: u32, len: usize) -> Vec<u8> {
let mut x = seed.wrapping_mul(2_654_435_761).max(1);
(0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
((x >> 24) as u8).min(0xFE)
})
.collect()
}
fn busy_zero_planes(coder: Coder) -> u32 {
match coder {
Coder::Part1 => 0,
Coder::Ht => BUSY_PLANES - 2,
}
}
const BUSY_PLANES: u32 = 28;
fn shaped_block(
(x, y): (usize, usize),
(width, height): (usize, usize),
coder: Coder,
data: &[u8],
) -> CodeBlock<'_> {
let passes = match coder {
Coder::Part1 => 3 * BUSY_PLANES - 2,
Coder::Ht => 1,
};
CodeBlock {
x,
y,
width,
height,
num_passes: passes,
zero_bit_planes: busy_zero_planes(coder),
segments: vec![crate::tier2::CodedSegment {
passes,
chunks: vec![data],
}],
cut: false,
placeholders: 0,
coder,
missing_from: None,
}
}
fn busy_data(coders: Coders, coder: Coder, (w, h): (usize, usize)) -> Vec<u8> {
(1..=10_000)
.map(|seed| match coder {
Coder::Part1 => noise(seed, 2 * w * h + 64),
Coder::Ht => {
let mut bytes = noise(seed, 4 * w * h + 64);
let last = bytes.len() - 1;
bytes[last - 1] = (bytes[last - 1] & 0xF0) | 8;
bytes[last] = 2;
bytes
}
})
.find(|data| {
let block = shaped_block((0, 0), (w, h), coder, data);
coders
.decode(
&block,
BandKind::Hl,
1,
BUSY_PLANES,
&mut Scratch::default(),
)
.is_ok_and(|c| {
let significant = c.iter().filter(|&&c| c != 0).count();
match coder {
Coder::Part1 => 4 * significant > c.len(),
Coder::Ht => significant >= w.min(h),
}
})
})
.expect("noise that codes enough")
}
const SHAPES: [(usize, usize); 9] = [
(4, 64),
(64, 4),
(32, 32),
(32, 5),
(5, 32),
(64, 64),
(3, 7),
(64, 8),
(64, 6),
];
const HT_SHAPES: [(usize, usize); 9] = [
(16, 2),
(2, 16),
(8, 8),
(8, 3),
(3, 8),
(16, 16),
(3, 7),
(16, 4),
(16, 3),
];
fn check_shapes_in_turn(coders: Coders, coder: Coder, shapes: &[(usize, usize)], what: &str) {
let data: Vec<Vec<u8>> = shapes
.iter()
.map(|&shape| busy_data(coders, coder, shape))
.collect();
let mut shared = Scratch::default();
let kinds = [BandKind::Hl, BandKind::Hh, BandKind::Lh];
for ((&shape, data), &kind) in shapes.iter().zip(&data).zip(kinds.iter().cycle()) {
let block = shaped_block((0, 0), shape, coder, data);
let alone = coders
.decode(&block, kind, 1, BUSY_PLANES, &mut Scratch::default())
.unwrap()
.to_vec();
let reused = coders
.decode(&block, kind, 1, BUSY_PLANES, &mut shared)
.unwrap();
assert_eq!(reused, &alone[..], "the {shape:?} block, {what}");
}
}
#[test]
fn reused_buffers_decode_each_part1_block_as_alone() {
use crate::codestream::markers::code_block_style::{RESET, VCAUSAL};
for style in [0, VCAUSAL, RESET] {
let coder = BlockCoder::Ebcot {
style,
roi_shift: 0,
};
let coders = Coders {
part1: coder,
ht: coder,
mixed: false,
};
check_shapes_in_turn(
coders,
Coder::Part1,
&SHAPES,
&format!("style {style:#04x}"),
);
}
}
#[test]
fn reused_buffers_decode_each_ht_block_as_alone() {
let coder = BlockCoder::Ht {
roi_shift: 0,
causal: false,
bound: CleanupBound {
magb: None,
irreversible: false,
},
};
let coders = Coders {
part1: coder,
ht: coder,
mixed: false,
};
check_shapes_in_turn(coders, Coder::Ht, &HT_SHAPES, "HT");
}
fn refined_block<'a>(
shape: (usize, usize),
cleanup: &'a [u8],
refinement: &'a [u8],
) -> CodeBlock<'a> {
let mut block = shaped_block((0, 0), shape, Coder::Ht, cleanup);
block.num_passes = 3;
block.segments.push(crate::tier2::CodedSegment {
passes: 2,
chunks: vec![refinement],
});
block
}
#[test]
fn reused_buffers_decode_each_refined_ht_block_as_alone() {
let coder = BlockCoder::Ht {
roi_shift: 0,
causal: false,
bound: CleanupBound {
magb: None,
irreversible: false,
},
};
let coders = Coders {
part1: coder,
ht: coder,
mixed: false,
};
fn decode<'a>(
coders: Coders,
block: &CodeBlock<'a>,
scratch: &mut Scratch<'a>,
) -> Result<Vec<i32>> {
coders
.decode(block, BandKind::Hl, 1, BUSY_PLANES, scratch)
.map(<[i32]>::to_vec)
}
let data: Vec<(Vec<u8>, Vec<u8>)> = HT_SHAPES
.iter()
.map(|&shape| {
let cleanup = busy_data(coders, Coder::Ht, shape);
let base = decode(
coders,
&shaped_block((0, 0), shape, Coder::Ht, &cleanup),
&mut Scratch::default(),
)
.unwrap();
let refinement = (1..=10_000)
.map(|seed| noise(seed, shape.0 * shape.1 + 16))
.find(|refinement| {
let block = refined_block(shape, &cleanup, refinement);
decode(coders, &block, &mut Scratch::default()).is_ok_and(|c| {
let pairs = || base.iter().zip(&c);
let sigprop = pairs().filter(|&(&b, &r)| b == 0 && r != 0).count();
let magref = pairs().any(|(&b, &r)| b != 0 && b != r);
sigprop >= 2 && magref
})
})
.expect("refinement noise that changes the block");
(cleanup, refinement)
})
.collect();
let mut shared = Scratch::default();
for (&shape, (cleanup, refinement)) in HT_SHAPES.iter().zip(&data) {
let block = refined_block(shape, cleanup, refinement);
let alone = decode(coders, &block, &mut Scratch::default()).unwrap();
let reused = decode(coders, &block, &mut shared).unwrap();
assert_eq!(reused, alone, "the refined {shape:?} block");
}
}
#[test]
fn reused_buffers_decode_a_band_of_edge_blocks_as_its_blocks_alone() {
let coders = default_params();
let layout = [
((0, 0), (32, 32)),
((32, 0), (4, 32)),
((0, 32), (32, 5)),
((32, 32), (4, 5)),
];
let data: Vec<Vec<u8>> = layout
.iter()
.map(|&(_, shape)| busy_data(coders, Coder::Part1, shape))
.collect();
let sb = Subband {
kind: BandKind::Hl,
origin: (0, 0),
width: 36,
height: 37,
block_cols: 2,
block_rows: 2,
blocks: layout
.iter()
.zip(&data)
.map(|(&(at, shape), data)| shaped_block(at, shape, Coder::Part1, data))
.collect(),
};
let band =
decode_subband::<i32, _>(&sb, 1, BUSY_PLANES, coders, &mut Scratch::default(), |q| q)
.unwrap();
let mut expected = vec![0; 36 * 37];
for block in &sb.blocks {
let alone = coders
.decode(block, sb.kind, 1, BUSY_PLANES, &mut Scratch::default())
.unwrap()
.to_vec();
place_block(&mut expected, 36, block, &alone, &|q| q);
}
assert_eq!(band.data, expected);
}
fn default_params() -> Coders {
part1_coders(0)
}
fn part1_coders(roi_shift: u8) -> Coders {
let coder = BlockCoder::Ebcot {
style: 0,
roi_shift,
};
Coders {
part1: coder,
ht: coder,
mixed: false,
}
}
}
#[cfg(test)]
mod work_bound_tests;