use crate::tier1::mq::{Context, MqDecoder, RawDecoder};
use crate::{Error, Result};
#[cfg(test)]
#[path = "golden_vectors.rs"]
mod golden_vectors;
pub const CTX_ZC: u8 = 0;
pub const CTX_SC: u8 = 9;
pub const CTX_MR: u8 = 14;
pub const CTX_RUN: u8 = 17;
pub const CTX_UNI: u8 = 18;
pub const NUM_CONTEXTS: usize = 19;
pub const MAX_BIT_PLANES: u32 = 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
Ll,
Lh,
Hl,
Hh,
}
const NB_N: u16 = 1 << 0;
const NB_S: u16 = 1 << 1;
const NB_W: u16 = 1 << 2;
const NB_E: u16 = 1 << 3;
const NB_NW: u16 = 1 << 4;
const NB_NE: u16 = 1 << 5;
const NB_SW: u16 = 1 << 6;
const NB_SE: u16 = 1 << 7;
const NB_ALL: u16 = 0xFF;
const NB_SOUTH: u16 = NB_S | NB_SW | NB_SE;
const SIG: u16 = 1 << 8;
const VISITED: u16 = 1 << 9;
const NEGATIVE: u16 = 1 << 10;
const REFINED: u16 = 1 << 11;
const NEG_N: u16 = 1 << 12;
const NEG_S: u16 = 1 << 13;
const NEG_W: u16 = 1 << 14;
const NEG_E: u16 = 1 << 15;
const fn each_row(bits: u16) -> u64 {
(bits as u64) * 0x0001_0001_0001_0001
}
const fn column_neighbors(vcausal: bool) -> u64 {
if vcausal {
each_row(NB_ALL) & !((NB_SOUTH as u64) << 48)
} else {
each_row(NB_ALL)
}
}
#[derive(Debug)]
pub struct BlockState {
pub width: u32,
pub height: u32,
pub coeffs: Vec<i32>,
stripe_len: usize,
state: Vec<u16>,
vcausal: bool,
}
impl BlockState {
pub fn new(width: u32, height: u32) -> Self {
let n = (width * height) as usize;
let stripe_len = 4 * (width as usize + 2);
let padded = stripe_len * (height.div_ceil(4) as usize + 2);
BlockState {
width,
height,
coeffs: vec![0; n],
stripe_len,
state: vec![0; padded],
vcausal: false,
}
}
fn idx(&self, x: u32, y: u32) -> usize {
(y * self.width + x) as usize
}
#[inline]
fn pad(&self, x: u32, y: u32) -> usize {
(y as usize / 4 + 1) * self.stripe_len + (x as usize + 1) * 4 + y as usize % 4
}
}
#[inline(always)]
fn column_word(state: &[u16], p: usize) -> u64 {
let c = &state[p..p + 4];
u64::from(c[0]) | u64::from(c[1]) << 16 | u64::from(c[2]) << 32 | u64::from(c[3]) << 48
}
#[inline(always)]
fn north(p: usize, r: usize, stripe_len: usize) -> usize {
if r == 0 { p - stripe_len + 3 } else { p - 1 }
}
#[inline(always)]
fn south(p: usize, r: usize, stripe_len: usize) -> usize {
if r == 3 { p + stripe_len - 3 } else { p + 1 }
}
#[inline(always)]
fn mark_significant(state: &mut [u16], p: usize, r: usize, stripe_len: usize, negative: bool) {
let n = north(p, r, stripe_len);
let s = south(p, r, stripe_len);
let sign = |bit: u16| if negative { bit } else { 0 };
state[p] |= SIG | sign(NEGATIVE);
state[n - 4] |= NB_SE;
state[n] |= NB_S | sign(NEG_S);
state[n + 4] |= NB_SW;
state[p - 4] |= NB_E | sign(NEG_E);
state[p + 4] |= NB_W | sign(NEG_W);
state[s - 4] |= NB_NE;
state[s] |= NB_N | sign(NEG_N);
state[s + 4] |= NB_NW;
}
#[inline(always)]
fn visible(word: u16, hide_south: bool) -> u16 {
if hide_south { word & !NB_SOUTH } else { word }
}
#[inline(always)]
fn neighbor_mask(word: u16) -> u8 {
(word & NB_ALL) as u8
}
#[inline(always)]
fn sign_context(word: u16) -> (u8, u8) {
let key = (word & (NB_N | NB_S | NB_W | NB_E)) | ((word >> 8) & 0xF0);
let entry = SIGN_TABLE[usize::from(key as u8)];
(entry & 0x7F, entry >> 7)
}
#[inline(always)]
fn refinement_context(word: u16) -> u8 {
if word & REFINED != 0 {
CTX_MR + 2
} else {
CTX_MR + u8::from(neighbor_mask(word) != 0)
}
}
#[cfg(test)]
impl BlockState {
fn excludes_south(&self, y: u32) -> bool {
self.vcausal && y % 4 == 3
}
fn word(&self, x: u32, y: u32) -> u16 {
visible(self.state[self.pad(x, y)], self.excludes_south(y))
}
pub fn is_significant(&self, x: u32, y: u32) -> bool {
self.state[self.pad(x, y)] & SIG != 0
}
pub fn set_significant(&mut self, x: u32, y: u32) {
let p = self.pad(x, y);
mark_significant(&mut self.state, p, y as usize % 4, self.stripe_len, false);
}
pub fn is_visited(&self, x: u32, y: u32) -> bool {
self.state[self.pad(x, y)] & VISITED != 0
}
pub fn set_visited(&mut self, x: u32, y: u32, value: bool) {
let p = self.pad(x, y);
if value {
self.state[p] |= VISITED;
} else {
self.state[p] &= !VISITED;
}
}
pub fn is_negative(&self, x: u32, y: u32) -> bool {
self.state[self.pad(x, y)] & NEGATIVE != 0
}
pub fn set_negative(&mut self, x: u32, y: u32, value: bool) {
let p = self.pad(x, y);
let (sl, r) = (self.stripe_len, y as usize % 4);
let bits = [
(p, NEGATIVE),
(north(p, r, sl), NEG_S),
(south(p, r, sl), NEG_N),
(p - 4, NEG_E),
(p + 4, NEG_W),
];
for (i, bit) in bits {
if value {
self.state[i] |= bit;
} else {
self.state[i] &= !bit;
}
}
}
pub fn is_refined(&self, x: u32, y: u32) -> bool {
self.state[self.pad(x, y)] & REFINED != 0
}
pub fn set_refined(&mut self, x: u32, y: u32) {
let p = self.pad(x, y);
self.state[p] |= REFINED;
}
pub fn neighbor_sums(&self, x: u32, y: u32) -> (u8, u8, u8) {
neighbor_sums(neighbor_mask(self.word(x, y)))
}
pub fn zc_context(&self, x: u32, y: u32, orient: Orientation) -> u8 {
CTX_ZC + zc_table(orient)[usize::from(neighbor_mask(self.word(x, y)))]
}
pub fn sc_context(&self, x: u32, y: u32) -> (u8, u8) {
sign_context(self.word(x, y))
}
pub fn mr_context(&self, x: u32, y: u32) -> u8 {
refinement_context(self.word(x, y))
}
}
const fn zc_label_lh(h: u8, v: u8, d: u8) -> u8 {
match (h, v, d) {
(2, _, _) => 8,
(1, v, _) if v >= 1 => 7,
(1, 0, d) if d >= 1 => 6,
(1, 0, 0) => 5,
(0, 2, _) => 4,
(0, 1, _) => 3,
(0, 0, d) if d >= 2 => 2,
(0, 0, 1) => 1,
_ => 0,
}
}
const fn zc_label_hh(hv: u8, d: u8) -> u8 {
match (d, hv) {
(d, _) if d >= 3 => 8,
(2, hv) if hv >= 1 => 7,
(2, _) => 6,
(1, hv) if hv >= 2 => 5,
(1, 1) => 4,
(1, _) => 3,
(0, hv) if hv >= 2 => 2,
(0, 1) => 1,
_ => 0,
}
}
const fn neighbor_sums(mask: u8) -> (u8, u8, u8) {
let mask = mask as u16;
let h = (mask & NB_W != 0) as u8 + (mask & NB_E != 0) as u8;
let v = (mask & NB_N != 0) as u8 + (mask & NB_S != 0) as u8;
let d = (mask & (NB_NW | NB_NE | NB_SW | NB_SE)).count_ones() as u8;
(h, v, d)
}
const fn build_zc_table(group: Orientation) -> [u8; 256] {
let mut table = [0u8; 256];
let mut mask = 0;
while mask < 256 {
let (h, v, d) = neighbor_sums(mask as u8);
table[mask] = match group {
Orientation::Ll | Orientation::Lh => zc_label_lh(h, v, d),
Orientation::Hl => zc_label_lh(v, h, d),
Orientation::Hh => zc_label_hh(h + v, d),
};
mask += 1;
}
table
}
static ZC_LL_LH: [u8; 256] = build_zc_table(Orientation::Lh);
static ZC_HL: [u8; 256] = build_zc_table(Orientation::Hl);
static ZC_HH: [u8; 256] = build_zc_table(Orientation::Hh);
fn zc_table(orient: Orientation) -> &'static [u8; 256] {
match orient {
Orientation::Ll | Orientation::Lh => &ZC_LL_LH,
Orientation::Hl => &ZC_HL,
Orientation::Hh => &ZC_HH,
}
}
const fn build_sign_table() -> [u8; 256] {
const fn contrib(key: usize, sig: u16) -> i32 {
let neg = (sig as usize) << 4;
if key & sig as usize == 0 {
0
} else if key & neg != 0 {
-1
} else {
1
}
}
const fn clamp(v: i32) -> i32 {
if v > 1 {
1
} else if v < -1 {
-1
} else {
v
}
}
let mut table = [0u8; 256];
let mut key = 0;
while key < 256 {
let h = clamp(contrib(key, NB_W) + contrib(key, NB_E));
let v = clamp(contrib(key, NB_N) + contrib(key, NB_S));
let (label, xor) = match (h, v) {
(1, 1) => (4, 0),
(1, 0) => (3, 0),
(1, -1) => (2, 0),
(0, 1) => (1, 0),
(0, 0) => (0, 0),
(0, -1) => (1, 1),
(-1, 1) => (2, 1),
(-1, 0) => (3, 1),
_ => (4, 1),
};
table[key] = (CTX_SC + label) | (xor << 7);
key += 1;
}
table
}
static SIGN_TABLE: [u8; 256] = build_sign_table();
pub(crate) fn init_contexts() -> [Context; NUM_CONTEXTS] {
let mut cx = [Context::default(); NUM_CONTEXTS];
cx[CTX_ZC as usize] = Context::new(4, 0);
cx[CTX_RUN as usize] = Context::new(3, 0);
cx[CTX_UNI as usize] = Context::new(46, 0);
cx
}
struct Plane<'s> {
state: &'s mut [u16],
coeffs: &'s mut [i32],
width: usize,
height: usize,
stripe_len: usize,
}
impl<'s> Plane<'s> {
fn new(block: &'s mut BlockState) -> Self {
Plane {
state: &mut block.state,
coeffs: &mut block.coeffs,
width: block.width as usize,
height: block.height as usize,
stripe_len: block.stripe_len,
}
}
fn full_stripes(&self) -> usize {
self.height / 4
}
fn last_rows(&self) -> usize {
self.height % 4
}
#[inline(always)]
fn column(&self, k: usize, x: usize) -> usize {
(k + 1) * self.stripe_len + (x + 1) * 4
}
#[inline(always)]
fn become_significant(&mut self, i: usize, p: usize, r: usize, bpno: u32, negative: bool) {
let one = 1i32 << bpno;
self.coeffs[i] = one | (one >> 1);
mark_significant(self.state, p, r, self.stripe_len, negative);
}
#[inline(always)]
fn refine_magnitude(&mut self, i: usize, p: usize, bpno: u32, bit: u8) {
let poshalf = (1i32 << bpno) >> 1;
self.coeffs[i] += if bit == 1 { poshalf } else { -poshalf };
self.state[p] |= REFINED;
}
}
#[inline(always)]
fn decode_sign(mq: &mut MqDecoder<'_>, cx: &mut [Context; NUM_CONTEXTS], word: u16) -> bool {
let (ctx, xor) = sign_context(word);
mq.decode(&mut cx[usize::from(ctx)]) ^ xor == 1
}
#[inline(always)]
#[allow(clippy::too_many_arguments)]
fn zero_code(
mq: &mut MqDecoder<'_>,
cx: &mut [Context; NUM_CONTEXTS],
plane: &mut Plane<'_>,
table: &[u8; 256],
word: u16,
i: usize,
p: usize,
r: usize,
bpno: u32,
) {
let ctx = CTX_ZC + table[usize::from(neighbor_mask(word))];
if mq.decode(&mut cx[usize::from(ctx)]) == 1 {
let negative = decode_sign(mq, cx, word);
plane.become_significant(i, p, r, bpno, negative);
}
}
macro_rules! each_stripe_row {
($r:ident => $body:expr) => {{
{
let $r: usize = 0;
$body;
}
{
let $r: usize = 1;
$body;
}
{
let $r: usize = 2;
$body;
}
{
let $r: usize = 3;
$body;
}
}};
}
#[inline(always)]
#[allow(clippy::too_many_arguments)]
fn sig_prop_sample(
mq: &mut MqDecoder<'_>,
cx: &mut [Context; NUM_CONTEXTS],
plane: &mut Plane<'_>,
table: &[u8; 256],
i: usize,
p: usize,
r: usize,
hide: bool,
bpno: u32,
) {
let word = plane.state[p];
if word & SIG != 0 {
return;
}
let word = visible(word, hide);
if neighbor_mask(word) == 0 {
return; }
zero_code(mq, cx, plane, table, word, i, p, r, bpno);
plane.state[p] |= VISITED;
}
#[inline(always)]
#[allow(clippy::too_many_arguments)]
fn mag_ref_sample(
mq: &mut MqDecoder<'_>,
cx: &mut [Context; NUM_CONTEXTS],
plane: &mut Plane<'_>,
i: usize,
p: usize,
hide: bool,
bpno: u32,
) {
let word = plane.state[p];
if word & (SIG | VISITED) != SIG {
return; }
let ctx = refinement_context(visible(word, hide));
let bit = mq.decode(&mut cx[usize::from(ctx)]);
plane.refine_magnitude(i, p, bpno, bit);
}
#[inline(always)]
#[allow(clippy::too_many_arguments)]
fn cleanup_sample(
mq: &mut MqDecoder<'_>,
cx: &mut [Context; NUM_CONTEXTS],
plane: &mut Plane<'_>,
table: &[u8; 256],
i: usize,
p: usize,
r: usize,
hide: bool,
bpno: u32,
) {
let word = plane.state[p];
if word & (SIG | VISITED) != 0 {
plane.state[p] = word & !VISITED;
return;
}
zero_code(mq, cx, plane, table, visible(word, hide), i, p, r, bpno);
}
fn sig_prop_pass(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
orient: Orientation,
bpno: u32,
) {
if state.vcausal {
sig_prop_pass_impl::<true>(mq, state, cx, orient, bpno);
} else {
sig_prop_pass_impl::<false>(mq, state, cx, orient, bpno);
}
}
#[inline(never)]
fn sig_prop_pass_impl<const VC: bool>(
mq_out: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
orient: Orientation,
bpno: u32,
) {
let mut mq = mq_out.clone();
let table = zc_table(orient);
let mut plane = Plane::new(state);
let w = plane.width;
for k in 0..plane.full_stripes() {
for x in 0..w {
let p = plane.column(k, x);
if column_word(plane.state, p) & column_neighbors(VC) == 0 {
continue; }
let i = 4 * k * w + x;
each_stripe_row!(r => sig_prop_sample(
&mut mq, cx, &mut plane, table, i + r * w, p + r, r, VC && r == 3, bpno
));
}
}
let (k, rows) = (plane.full_stripes(), plane.last_rows());
for x in 0..w {
let p = plane.column(k, x);
let i = 4 * k * w + x;
for r in 0..rows {
sig_prop_sample(
&mut mq,
cx,
&mut plane,
table,
i + r * w,
p + r,
r,
false,
bpno,
);
}
}
*mq_out = mq;
}
fn mag_ref_pass(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
bpno: u32,
) {
if state.vcausal {
mag_ref_pass_impl::<true>(mq, state, cx, bpno);
} else {
mag_ref_pass_impl::<false>(mq, state, cx, bpno);
}
}
#[inline(never)]
fn mag_ref_pass_impl<const VC: bool>(
mq_out: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
bpno: u32,
) {
let mut mq = mq_out.clone();
let mut plane = Plane::new(state);
let w = plane.width;
for k in 0..plane.full_stripes() {
for x in 0..w {
let p = plane.column(k, x);
if column_word(plane.state, p) & each_row(SIG) == 0 {
continue; }
let i = 4 * k * w + x;
each_stripe_row!(r => mag_ref_sample(
&mut mq, cx, &mut plane, i + r * w, p + r, VC && r == 3, bpno
));
}
}
let (k, rows) = (plane.full_stripes(), plane.last_rows());
for x in 0..w {
let p = plane.column(k, x);
let i = 4 * k * w + x;
for r in 0..rows {
mag_ref_sample(&mut mq, cx, &mut plane, i + r * w, p + r, false, bpno);
}
}
*mq_out = mq;
}
#[inline(always)]
fn for_each_sample(
state: &mut BlockState,
mut f: impl FnMut(&mut Plane<'_>, usize, usize, usize, bool),
) {
let vcausal = state.vcausal;
let mut plane = Plane::new(state);
let w = plane.width;
let stripes = plane.height.div_ceil(4);
for k in 0..stripes {
let rows = (plane.height - 4 * k).min(4);
for x in 0..w {
let p = plane.column(k, x);
let i = 4 * k * w + x;
for r in 0..rows {
f(&mut plane, i + r * w, p + r, r, vcausal && r == 3);
}
}
}
}
fn sig_prop_pass_raw(raw: &mut RawDecoder<'_>, state: &mut BlockState, bpno: u32) {
for_each_sample(state, |plane, i, p, r, hide| {
let word = plane.state[p];
if word & SIG != 0 {
return;
}
if neighbor_mask(visible(word, hide)) == 0 {
return; }
if raw.decode() == 1 {
let negative = raw.decode() == 1;
plane.become_significant(i, p, r, bpno, negative);
}
plane.state[p] |= VISITED;
});
}
fn mag_ref_pass_raw(raw: &mut RawDecoder<'_>, state: &mut BlockState, bpno: u32) {
for_each_sample(state, |plane, i, p, _, _| {
if plane.state[p] & (SIG | VISITED) != SIG {
return;
}
let bit = raw.decode();
plane.refine_magnitude(i, p, bpno, bit);
});
}
fn cleanup_pass(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
orient: Orientation,
bpno: u32,
style: u8,
terminated: bool,
) -> Result<()> {
if state.vcausal {
cleanup_pass_impl::<true>(mq, state, cx, orient, bpno);
} else {
cleanup_pass_impl::<false>(mq, state, cx, orient, bpno);
}
if style & crate::codestream::markers::code_block_style::SEGSYM != 0 {
read_segmentation_symbol(mq, cx, terminated)?;
}
Ok(())
}
#[inline(never)]
fn cleanup_pass_impl<const VC: bool>(
mq_out: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context; NUM_CONTEXTS],
orient: Orientation,
bpno: u32,
) {
let mut mq = mq_out.clone();
let table = zc_table(orient);
let mut plane = Plane::new(state);
let w = plane.width;
let run_bits = each_row(SIG | VISITED) | column_neighbors(VC);
for k in 0..plane.full_stripes() {
for x in 0..w {
let p = plane.column(k, x);
let i = 4 * k * w + x;
let mut first = 0;
if column_word(plane.state, p) & run_bits == 0 {
if mq.decode(&mut cx[CTX_RUN as usize]) == 0 {
continue; }
let hi = mq.decode(&mut cx[CTX_UNI as usize]);
let lo = mq.decode(&mut cx[CTX_UNI as usize]);
let run = usize::from((hi << 1) | lo); let word = visible(plane.state[p + run], VC && run == 3);
let negative = decode_sign(&mut mq, cx, word);
plane.become_significant(i + run * w, p + run, run, bpno, negative);
first = run + 1;
}
each_stripe_row!(r => if r >= first {
cleanup_sample(
&mut mq, cx, &mut plane, table, i + r * w, p + r, r, VC && r == 3, bpno,
)
});
}
}
let (k, rows) = (plane.full_stripes(), plane.last_rows());
for x in 0..w {
let p = plane.column(k, x);
let i = 4 * k * w + x;
for r in 0..rows {
cleanup_sample(
&mut mq,
cx,
&mut plane,
table,
i + r * w,
p + r,
r,
false,
bpno,
);
}
}
*mq_out = mq;
}
fn read_segmentation_symbol(
mq: &mut MqDecoder<'_>,
cx: &mut [Context],
terminated: bool,
) -> Result<()> {
let mut symbol = 0u8;
for _ in 0..4 {
symbol = (symbol << 1) | mq.decode(&mut cx[CTX_UNI as usize]);
}
if symbol != 0b1010 && (terminated || !mq.ran_past_end()) {
return Err(Error::Codestream(format!(
"segmentation symbol at the end of a cleanup pass is {symbol:#06b}, expected 0b1010; \
the coded data is corrupt"
)));
}
Ok(())
}
fn undo_maxshift(mag: i32, roi_shift: u8) -> i32 {
if roi_shift == 0 {
return mag;
}
if roi_shift >= 31 {
return 0;
}
let threshold = 1i32 << roi_shift;
if mag >= threshold {
mag >> roi_shift
} else {
mag
}
}
pub fn top_coded_plane(numbps: u32, zero_bit_planes: u32, roi_shift: u8) -> u32 {
(numbps + u32::from(roi_shift)).saturating_sub(zero_bit_planes)
}
#[derive(Debug, Clone, Copy, Default)]
pub struct BlockParams {
pub style: u8,
pub roi_shift: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PassType {
SigProp,
MagRef,
Cleanup,
}
enum PassCoder<'a> {
Mq(MqDecoder<'a>),
Raw(RawDecoder<'a>),
}
pub fn decode_block(
segments: &[(Vec<u8>, u32)],
state: &mut BlockState,
orient: Orientation,
numbps: u32,
num_passes: u32,
zero_bit_planes: u32,
params: BlockParams,
) -> Result<()> {
let BlockParams { style, roi_shift } = params;
use crate::codestream::markers::code_block_style::{
LAZY, PTERM, RESET, SEGSYM, TERMALL, VCAUSAL,
};
debug_assert_eq!(
style & !(LAZY | TERMALL | PTERM | SEGSYM | VCAUSAL | RESET),
0,
"decode_cod rejects every style flag but bypass, restart, pterm, segsym, vcausal and reset",
);
state.vcausal = style & VCAUSAL != 0;
if num_passes == 0 {
return Ok(());
}
let top = top_coded_plane(numbps, zero_bit_planes, 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"
)));
}
if top < 1 {
return Ok(()); }
let mut cx = init_contexts();
let mut bpno = top;
let mut pass_type = PassType::Cleanup;
let bypass = style & LAZY != 0;
let raw_from = top as i32 - 4;
'segments: for (bytes, passes) in segments {
let raw = bypass && pass_type != PassType::Cleanup && (bpno as i32) <= raw_from;
let mut coder = if raw {
PassCoder::Raw(RawDecoder::new(bytes))
} else {
PassCoder::Mq(MqDecoder::new(bytes))
};
for _ in 0..*passes {
if bpno < 1 {
break 'segments;
}
match (&mut coder, pass_type) {
(PassCoder::Mq(mq), PassType::SigProp) => {
sig_prop_pass(mq, state, &mut cx, orient, bpno)
}
(PassCoder::Mq(mq), PassType::MagRef) => mag_ref_pass(mq, state, &mut cx, bpno),
(PassCoder::Mq(mq), PassType::Cleanup) => {
let terminated = style & TERMALL != 0
|| bpno == 1
|| (bypass && bpno as i32 - 1 <= raw_from);
cleanup_pass(mq, state, &mut cx, orient, bpno, style, terminated)?
}
(PassCoder::Raw(rd), PassType::SigProp) => sig_prop_pass_raw(rd, state, bpno),
(PassCoder::Raw(rd), PassType::MagRef) => mag_ref_pass_raw(rd, state, bpno),
(PassCoder::Raw(_), PassType::Cleanup) => {
unreachable!("a bypass cleanup pass is MQ-coded, never raw")
}
}
if style & RESET != 0 && !raw {
cx = init_contexts();
}
pass_type = match pass_type {
PassType::SigProp => PassType::MagRef,
PassType::MagRef => PassType::Cleanup,
PassType::Cleanup => {
bpno -= 1;
PassType::SigProp
}
};
}
if let PassCoder::Mq(mq) = &coder {
if style & PTERM != 0 && !mq.ends_predictably() {
return Err(Error::Codestream(format!(
"code-block style declares predictable termination, but a codeword segment \
leaves {} of its {} byte(s) unconsumed; the coded data is corrupt",
mq.unconsumed(),
bytes.len(),
)));
}
}
}
for y in 0..state.height {
for x in 0..state.width {
let i = state.idx(x, y);
let mag = undo_maxshift(state.coeffs[i], roi_shift);
state.coeffs[i] = if state.state[state.pad(x, y)] & NEGATIVE != 0 {
-mag
} else {
mag
};
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::golden_vectors::GOLDEN_BLOCKS;
use super::*;
fn decode_golden(g: &super::golden_vectors::GoldenBlock) -> Vec<i32> {
let segments = [(g.segment.to_vec(), g.num_passes)];
let mut state = BlockState::new(g.width, g.height);
let numbps = g.num_passes.div_ceil(3) + g.zero_bit_planes;
decode_block(
&segments,
&mut state,
g.orient,
numbps,
g.num_passes,
g.zero_bit_planes,
BlockParams::default(),
)
.expect("the default style decodes without a style check");
state.coeffs.iter().map(|&c| c / 2).collect()
}
#[test]
fn golden_blocks_decode_to_expected_coefficients() {
for g in GOLDEN_BLOCKS {
assert_eq!(decode_golden(g), g.coeffs, "block {}", g.name);
}
}
#[test]
fn vertically_causal_context_excludes_the_next_stripe() {
let mut state = BlockState::new(3, 8);
for x in 0..3 {
state.set_significant(x, 4);
state.set_negative(x, 4, true);
}
let (h, v, d) = state.neighbor_sums(1, 3);
assert_eq!((h, v, d), (0, 1, 2), "default neighborhood");
assert_ne!(state.zc_context(1, 3, Orientation::Ll), CTX_ZC);
let (_, xor_default) = state.sc_context(1, 3);
assert_eq!(xor_default, 1, "negative south neighbors flip the sign");
assert_eq!(state.mr_context(1, 3), CTX_MR + 1);
state.vcausal = true;
assert_eq!(
state.neighbor_sums(1, 3),
(0, 0, 0),
"south excluded at ci==3"
);
assert_eq!(state.zc_context(1, 3, Orientation::Ll), CTX_ZC);
let (sc, xor_causal) = state.sc_context(1, 3);
assert_eq!((sc, xor_causal), (CTX_SC, 0), "no neighbor, neutral sign");
assert_eq!(state.mr_context(1, 3), CTX_MR, "no significant neighbor");
for x in 0..3 {
state.set_significant(x, 3);
}
let (_, v_interior, _) = state.neighbor_sums(1, 2);
assert_eq!(v_interior, 1, "an interior row is unaffected by vcausal");
}
#[test]
fn zero_passes_yields_all_zero_coefficients() {
let mut state = BlockState::new(4, 4);
decode_block(
&[(vec![0x80], 0)],
&mut state,
Orientation::Ll,
8,
0,
0,
BlockParams::default(),
)
.expect("zero passes decode to nothing");
assert!(state.coeffs.iter().all(|&c| c == 0));
}
#[test]
fn predictable_termination_catches_a_segment_the_codeword_does_not_consume() {
use crate::codestream::markers::code_block_style::PTERM;
let padded = vec![0x80, 0, 0, 0, 0, 0, 0, 0];
let mut state = BlockState::new(4, 4);
let err = decode_block(
&[(padded.clone(), 1)],
&mut state,
Orientation::Ll,
8,
1,
0,
BlockParams {
style: PTERM,
roi_shift: 0,
},
)
.expect_err("eight bytes for one cleanup pass leaves more than two unconsumed");
assert!(matches!(err, Error::Codestream(_)), "{err:?}");
let mut state = BlockState::new(4, 4);
decode_block(
&[(padded, 1)],
&mut state,
Orientation::Ll,
8,
1,
0,
BlockParams::default(),
)
.expect("the same segment is fine without the flag");
}
#[test]
fn predictable_termination_ignores_a_segment_stopped_by_the_bit_plane_floor() {
use crate::codestream::markers::code_block_style::PTERM;
let mut state = BlockState::new(4, 4);
decode_block(
&[(vec![0x80, 0, 0, 0, 0, 0, 0, 0], 4)],
&mut state,
Orientation::Ll,
8,
4,
7,
BlockParams {
style: PTERM,
roi_shift: 0,
},
)
.expect("a segment the decoder stops early in is not checked");
}
#[test]
fn a_corrupt_segmentation_symbol_is_a_codestream_error() {
use crate::codestream::markers::code_block_style::SEGSYM;
let mut state = BlockState::new(4, 4);
let err = decode_block(
&[(vec![0x00; 8], 1)],
&mut state,
Orientation::Ll,
8,
1,
0,
BlockParams {
style: SEGSYM,
roi_shift: 0,
},
)
.expect_err("the trailing symbol is not 1010");
let Error::Codestream(message) = &err else {
panic!("{err:?}")
};
assert!(message.contains("segmentation symbol"), "{message}");
}
fn decode_fill(numbps: u32, passes: u32, style: u8) -> Result<()> {
let mut state = BlockState::new(4, 4);
decode_block(
&[(Vec::new(), passes)],
&mut state,
Orientation::Ll,
numbps,
passes,
0,
BlockParams {
style,
roi_shift: 0,
},
)
}
fn assert_segmentation_symbol_error(result: Result<()>) {
let err = result.expect_err("a terminated pass reads a correct symbol from fill");
let Error::Codestream(message) = &err else {
panic!("{err:?}")
};
assert!(message.contains("segmentation symbol"), "{message}");
}
#[test]
fn a_wrong_segmentation_symbol_read_from_fill_decodes_on_an_unterminated_pass() {
use crate::codestream::markers::code_block_style::SEGSYM;
let mut mq = MqDecoder::new(&[]);
let mut cx = init_contexts();
let mut state = BlockState::new(4, 4);
cleanup_pass(&mut mq, &mut state, &mut cx, Orientation::Ll, 8, 0, false).unwrap();
let symbol = (0..4).fold(0u8, |s, _| (s << 1) | mq.decode(&mut cx[CTX_UNI as usize]));
assert_ne!(symbol, 0b1010);
assert!(mq.ran_past_end());
decode_fill(8, 1, SEGSYM).expect("a symbol read from fill decodes");
decode_fill(5, 10, SEGSYM).expect("no pass up to plane 2 is terminated");
}
#[test]
fn a_wrong_segmentation_symbol_on_a_restart_pass_is_an_error() {
use crate::codestream::markers::code_block_style::{SEGSYM, TERMALL};
assert_segmentation_symbol_error(decode_fill(8, 1, SEGSYM | TERMALL));
}
#[test]
fn a_wrong_segmentation_symbol_on_the_last_cleanup_is_an_error() {
use crate::codestream::markers::code_block_style::SEGSYM;
assert_segmentation_symbol_error(decode_fill(1, 1, SEGSYM));
decode_fill(2, 1, SEGSYM).expect("the cleanup of plane 2 is not terminated");
}
#[test]
fn a_wrong_segmentation_symbol_on_a_bypass_terminated_cleanup_is_an_error() {
use crate::codestream::markers::code_block_style::{LAZY, SEGSYM};
assert_segmentation_symbol_error(decode_fill(5, 10, SEGSYM | LAZY));
decode_fill(5, 9, SEGSYM | LAZY).expect("the cleanup of plane 3 is not terminated");
}
#[test]
fn undo_maxshift_matches_the_reference_formula_across_the_boundary() {
fn reference(mag: i32, roishift: u8) -> i32 {
if roishift == 0 {
return mag;
}
let thresh = 1i32 << roishift;
if mag >= thresh { mag >> roishift } else { mag }
}
for roi_shift in 0..=12u8 {
let threshold = 1i32 << roi_shift;
let cases = [
0,
1,
threshold - 2,
threshold - 1,
threshold,
threshold + 1,
threshold * 2,
threshold * 1234 + 7,
i32::MAX,
];
for mag in cases.into_iter().filter(|&m| m >= 0) {
assert_eq!(
undo_maxshift(mag, roi_shift),
reference(mag, roi_shift),
"mag {mag}, roi_shift {roi_shift}"
);
}
}
}
#[test]
fn the_maxshift_threshold_separates_background_from_region() {
let roi_shift = 6;
let threshold = 1i32 << roi_shift; assert_eq!(undo_maxshift(threshold - 1, roi_shift), 63, "background");
assert_eq!(undo_maxshift(threshold, roi_shift), 1, "region");
assert_eq!(undo_maxshift(0, roi_shift), 0, "zero is neither");
assert_eq!(undo_maxshift(threshold, 0), threshold);
}
#[test]
fn zero_bit_planes_count_against_the_maxshift_raised_planes() {
assert_eq!(top_coded_plane(10, 3, 0), 7, "no ROI");
assert_eq!(top_coded_plane(10, 3, 9), 16, "ROI block, few zero planes");
assert_eq!(top_coded_plane(10, 13, 9), 6, "background block, P > Mb");
assert_eq!(top_coded_plane(10, 19, 9), 0, "all planes zero");
assert_eq!(top_coded_plane(10, 25, 9), 0, "past Kmax saturates");
}
#[test]
fn an_out_of_range_maxshift_is_rejected_rather_than_overflowing() {
for roi_shift in [31u8, 32, 64, 255] {
let mut state = BlockState::new(4, 4);
let err = decode_block(
&[(vec![0x80], 1)],
&mut state,
Orientation::Ll,
8,
1,
0,
BlockParams {
style: 0,
roi_shift,
},
)
.expect_err(&format!("maxshift {roi_shift} passes the bit-plane limit"));
assert!(matches!(err, Error::Limit(_)), "{err:?}");
}
}
#[test]
fn an_inexpressible_maxshift_on_a_decodable_block_zeroes_it() {
for roi_shift in [31u8, 64, 255] {
let mut state = BlockState::new(4, 4);
let zero_bit_planes = 8 + u32::from(roi_shift) - 5;
decode_block(
&[(vec![0x80, 0x27], 3)],
&mut state,
Orientation::Ll,
8,
3,
zero_bit_planes,
BlockParams {
style: 0,
roi_shift,
},
)
.expect("a small top decodes whatever the maxshift");
assert!(
state.coeffs.iter().all(|&c| c == 0),
"roi_shift {roi_shift}: every coefficient reads as region and shifts to nothing"
);
}
}
#[test]
fn an_empty_codeword_segment_does_not_panic() {
let mut state = BlockState::new(4, 4);
decode_block(
&[(Vec::new(), 1), (vec![0x80], 1)],
&mut state,
Orientation::Ll,
8,
2,
0,
BlockParams {
style: crate::codestream::markers::code_block_style::TERMALL,
roi_shift: 0,
},
)
.expect("an empty segment decodes as 0xFF padding");
}
#[test]
fn golden_block_recovers_signs() {
let sparse = GOLDEN_BLOCKS
.iter()
.find(|g| g.name == "sparse_8x8")
.unwrap();
let out = decode_golden(sparse);
assert!(
out.iter().any(|&c| c > 0),
"expected a positive coefficient"
);
assert!(
out.iter().any(|&c| c < 0),
"expected a negative coefficient"
);
assert_eq!(out, sparse.coeffs);
}
fn block_with(sig: &[(u32, u32)]) -> BlockState {
let mut b = BlockState::new(5, 5);
for &(x, y) in sig {
b.set_significant(x, y);
}
b
}
#[test]
fn state_round_trips() {
let mut b = BlockState::new(4, 3);
assert!(!b.is_significant(1, 2));
b.set_significant(1, 2);
assert!(b.is_significant(1, 2));
assert!(!b.is_visited(1, 2));
b.set_visited(1, 2, true);
assert!(b.is_visited(1, 2));
b.set_visited(1, 2, false);
assert!(!b.is_visited(1, 2));
b.set_negative(1, 2, true);
assert!(b.is_negative(1, 2));
assert!(!b.is_refined(1, 2));
b.set_refined(1, 2);
assert!(b.is_refined(1, 2));
}
#[test]
fn zc_ll_lh_all_labels() {
let cases: [(&[(u32, u32)], u8); 9] = [
(&[], 0), (&[(1, 1)], 1), (&[(1, 1), (3, 3)], 2), (&[(2, 1)], 3), (&[(2, 1), (2, 3)], 4), (&[(1, 2)], 5), (&[(1, 2), (1, 1)], 6), (&[(1, 2), (2, 1)], 7), (&[(1, 2), (3, 2)], 8), ];
for (sig, want) in cases {
let b = block_with(sig);
assert_eq!(
b.zc_context(2, 2, Orientation::Ll),
CTX_ZC + want,
"LL {sig:?}"
);
assert_eq!(
b.zc_context(2, 2, Orientation::Lh),
CTX_ZC + want,
"LH {sig:?}"
);
}
}
#[test]
fn zc_hl_swaps_h_and_v() {
let horiz = block_with(&[(1, 2), (3, 2)]);
assert_eq!(horiz.zc_context(2, 2, Orientation::Ll), CTX_ZC + 8);
assert_eq!(horiz.zc_context(2, 2, Orientation::Hl), CTX_ZC + 4);
let vert = block_with(&[(2, 1), (2, 3)]);
assert_eq!(vert.zc_context(2, 2, Orientation::Ll), CTX_ZC + 4);
assert_eq!(vert.zc_context(2, 2, Orientation::Hl), CTX_ZC + 8);
let mix = block_with(&[(1, 2), (2, 1)]);
assert_eq!(mix.zc_context(2, 2, Orientation::Hl), CTX_ZC + 7);
}
#[test]
fn zc_hh_all_labels() {
let cases: [(&[(u32, u32)], u8); 9] = [
(&[], 0), (&[(2, 1)], 1), (&[(2, 1), (1, 2)], 2), (&[(1, 1)], 3), (&[(1, 1), (2, 1)], 4), (&[(1, 1), (2, 1), (1, 2)], 5), (&[(1, 1), (3, 3)], 6), (&[(1, 1), (3, 3), (2, 1)], 7), (&[(1, 1), (3, 3), (3, 1)], 8), ];
for (sig, want) in cases {
let b = block_with(sig);
assert_eq!(
b.zc_context(2, 2, Orientation::Hh),
CTX_ZC + want,
"HH {sig:?}"
);
}
}
fn block_for_sign(h: i32, v: i32) -> BlockState {
let mut b = BlockState::new(5, 5);
let mut sign = |x: u32, y: u32, neg: bool| {
b.set_significant(x, y);
b.set_negative(x, y, neg);
};
match h {
1 => sign(1, 2, false),
-1 => sign(1, 2, true),
_ => {}
}
match v {
1 => sign(2, 1, false),
-1 => sign(2, 1, true),
_ => {}
}
b
}
#[test]
fn sc_all_nine_contexts_and_xorbit() {
let cases: [(i32, i32, u8, u8); 9] = [
(1, 1, 4, 0),
(1, 0, 3, 0),
(1, -1, 2, 0),
(0, 1, 1, 0),
(0, 0, 0, 0),
(0, -1, 1, 1),
(-1, 1, 2, 1),
(-1, 0, 3, 1),
(-1, -1, 4, 1),
];
for (h, v, label, xor) in cases {
let b = block_for_sign(h, v);
assert_eq!(b.sc_context(2, 2), (CTX_SC + label, xor), "H={h} V={v}");
}
}
#[test]
fn sc_contributions_clamp() {
let mut b = BlockState::new(5, 5);
for x in [1, 3] {
b.set_significant(x, 2); }
assert_eq!(b.sc_context(2, 2), (CTX_SC + 3, 0));
}
#[test]
fn mr_first_refinement_with_no_significant_neighbors() {
let b = BlockState::new(5, 5);
assert_eq!(b.mr_context(2, 2), CTX_MR);
}
#[test]
fn mr_first_refinement_with_a_significant_neighbor() {
let b = block_with(&[(2, 1)]);
assert_eq!(b.mr_context(2, 2), CTX_MR + 1);
}
#[test]
fn mr_after_first_refinement_ignores_neighbors() {
let mut b = block_with(&[(2, 1)]);
b.set_refined(2, 2);
assert_eq!(b.mr_context(2, 2), CTX_MR + 2);
}
#[test]
fn neighbors_clamp_at_corners() {
let mut b = BlockState::new(3, 3);
b.set_significant(1, 0); assert_eq!(b.zc_context(0, 0, Orientation::Ll), CTX_ZC + 5);
let mut c = BlockState::new(3, 3);
c.set_significant(1, 1); assert_eq!(c.zc_context(2, 2, Orientation::Ll), CTX_ZC + 1);
let _ = b.sc_context(0, 0);
let _ = b.mr_context(0, 0);
}
#[test]
fn edge_columns_see_no_neighbor_across_the_block_edge() {
let (w, h) = (4, 6);
let mut east = BlockState::new(w, h);
for y in 0..h {
east.set_significant(w - 1, y);
east.set_negative(w - 1, y, true);
}
for y in 0..h {
assert_eq!(east.neighbor_sums(0, y), (0, 0, 0), "(0, {y})");
assert_eq!(east.sc_context(0, y), (CTX_SC, 0), "(0, {y})");
assert_eq!(east.mr_context(0, y), CTX_MR, "(0, {y})");
let d = u8::from(y > 0) + u8::from(y + 1 < h);
assert_eq!(east.neighbor_sums(w - 2, y), (1, 0, d), "({}, {y})", w - 2);
}
let mut west = BlockState::new(w, h);
for y in 0..h {
west.set_significant(0, y);
}
for y in 0..h {
assert_eq!(west.neighbor_sums(w - 1, y), (0, 0, 0), "({}, {y})", w - 1);
let v = u8::from(y > 0) + u8::from(y + 1 < h);
assert_eq!(west.neighbor_sums(0, y), (0, v, 0), "(0, {y})");
}
}
#[test]
fn edge_rows_count_only_in_block_neighbors() {
let mut full = BlockState::new(3, 3);
for y in 0..3 {
for x in 0..3 {
full.set_significant(x, y);
}
}
for (x, y) in [(0, 0), (2, 0), (0, 2), (2, 2)] {
assert_eq!(full.neighbor_sums(x, y), (1, 1, 1), "corner ({x}, {y})");
}
assert_eq!(full.neighbor_sums(1, 0), (2, 1, 2), "top edge");
assert_eq!(full.neighbor_sums(1, 2), (2, 1, 2), "bottom edge");
assert_eq!(full.neighbor_sums(0, 1), (1, 2, 2), "left edge");
assert_eq!(full.neighbor_sums(2, 1), (1, 2, 2), "right edge");
assert_eq!(full.neighbor_sums(1, 1), (2, 2, 4), "center");
let mut column = BlockState::new(1, 8);
let mut row = BlockState::new(8, 1);
for i in 0..8 {
column.set_significant(0, i);
row.set_significant(i, 0);
}
for i in 0..8 {
let n = u8::from(i > 0) + u8::from(i < 7);
assert_eq!(column.neighbor_sums(0, i), (0, n, 0), "column {i}");
assert_eq!(row.neighbor_sums(i, 0), (n, 0, 0), "row {i}");
}
let mut bottom = BlockState::new(5, 3);
for x in 0..5 {
bottom.set_significant(x, 2);
}
for x in 0..5 {
assert_eq!(bottom.neighbor_sums(x, 0), (0, 0, 0), "({x}, 0)");
}
}
#[test]
fn vertically_causal_masks_each_south_neighbor_on_a_stripe_bottom_row() {
for bottom in [3u32, 7, 11] {
for dx in [0u32, 1, 2] {
let mut b = BlockState::new(3, 13);
b.set_significant(dx, bottom + 1);
b.set_negative(dx, bottom + 1, true);
let seen = if dx == 1 { (0, 1, 0) } else { (0, 0, 1) };
assert_eq!(b.neighbor_sums(1, bottom), seen, "default, dx {dx}");
b.vcausal = true;
let at = format!("vcausal, row {bottom}, dx {dx}");
assert_eq!(b.neighbor_sums(1, bottom), (0, 0, 0), "{at}");
for orient in [Orientation::Ll, Orientation::Hl, Orientation::Hh] {
assert_eq!(b.zc_context(1, bottom, orient), CTX_ZC, "{at}");
}
assert_eq!(b.sc_context(1, bottom), (CTX_SC, 0), "{at}");
assert_eq!(b.mr_context(1, bottom), CTX_MR, "{at}");
b.set_significant(1, bottom);
assert_eq!(b.neighbor_sums(dx, bottom + 1), seen, "{at}, north kept");
}
let mut b = BlockState::new(3, 13);
b.vcausal = true;
b.set_significant(1, bottom);
assert_eq!(
b.neighbor_sums(1, bottom - 1),
(0, 1, 0),
"row {}",
bottom - 1
);
}
}
#[test]
fn vertically_causal_cleanup_aggregates_past_a_next_stripe_neighbor() {
use crate::codestream::markers::code_block_style::VCAUSAL;
let bytes = [0x5A, 0xC3, 0x1F, 0x88, 0x24, 0xE7, 0x6B, 0x90, 0x3D, 0x71];
let run = |south_significant: bool, vcausal: bool| {
let mut state = BlockState::new(1, 5);
state.vcausal = vcausal;
if south_significant {
state.set_significant(0, 4);
} else {
state.set_visited(0, 4, true);
}
let mut mq = MqDecoder::new(&bytes);
let mut cx = init_contexts();
let style = if vcausal { VCAUSAL } else { 0 };
cleanup_pass(
&mut mq,
&mut state,
&mut cx,
Orientation::Ll,
4,
style,
false,
)
.unwrap();
let stripe: Vec<(i32, bool)> = (0..4)
.map(|y| (state.coeffs[y as usize], state.is_negative(0, y)))
.collect();
let contexts: Vec<(u8, u8)> = cx.iter().map(|c| (c.index(), c.mps())).collect();
let after: Vec<u8> = (0..32)
.map(|_| mq.decode(&mut cx[CTX_UNI as usize]))
.collect();
(stripe, contexts, after)
};
assert_eq!(
run(true, true),
run(false, true),
"under VCAUSAL the next stripe's neighbor must not break the run"
);
assert_ne!(
run(true, false),
run(false, false),
"without VCAUSAL the neighbor breaks the run"
);
}
#[test]
fn zc_tables_match_the_label_functions() {
for mask in 0..=255u8 {
let (h, v, d) = neighbor_sums(mask);
assert_eq!(u32::from(h + v + d), mask.count_ones());
let want = [
(Orientation::Ll, zc_label_lh(h, v, d)),
(Orientation::Lh, zc_label_lh(h, v, d)),
(Orientation::Hl, zc_label_lh(v, h, d)),
(Orientation::Hh, zc_label_hh(h + v, d)),
];
for (orient, label) in want {
let got = zc_table(orient)[usize::from(mask)];
assert_eq!(got, label, "{orient:?} mask {mask:#010b}");
assert_eq!(got == 0, mask == 0, "{orient:?} mask {mask:#010b}");
}
}
}
#[test]
fn padded_contexts_match_bounds_checked_neighbor_reads() {
struct Reference {
w: u32,
h: u32,
sig: Vec<bool>,
neg: Vec<bool>,
vcausal: bool,
}
impl Reference {
fn at(&self, x: i64, y: i64) -> Option<usize> {
let inside = x >= 0 && y >= 0 && x < self.w.into() && y < self.h.into();
inside.then(|| (y * i64::from(self.w) + x) as usize)
}
fn sig(&self, x: i64, y: i64) -> u8 {
u8::from(self.at(x, y).is_some_and(|i| self.sig[i]))
}
fn contrib(&self, x: i64, y: i64) -> i32 {
match self.at(x, y) {
Some(i) if self.sig[i] && self.neg[i] => -1,
Some(i) if self.sig[i] => 1,
_ => 0,
}
}
fn south(&self, y: i64) -> bool {
!(self.vcausal && y % 4 == 3)
}
fn sums(&self, x: i64, y: i64) -> (u8, u8, u8) {
let s = |dx: i64| {
if self.south(y) {
self.sig(x + dx, y + 1)
} else {
0
}
};
let h = self.sig(x - 1, y) + self.sig(x + 1, y);
let v = self.sig(x, y - 1) + s(0);
let d = self.sig(x - 1, y - 1) + self.sig(x + 1, y - 1) + s(-1) + s(1);
(h, v, d)
}
fn sign(&self, x: i64, y: i64) -> (u8, u8) {
let south = if self.south(y) {
self.contrib(x, y + 1)
} else {
0
};
let h = (self.contrib(x - 1, y) + self.contrib(x + 1, y)).clamp(-1, 1);
let v = (self.contrib(x, y - 1) + south).clamp(-1, 1);
let (label, xor) = match (h, v) {
(1, 1) => (4, 0),
(1, 0) => (3, 0),
(1, -1) => (2, 0),
(0, 1) => (1, 0),
(0, 0) => (0, 0),
(0, -1) => (1, 1),
(-1, 1) => (2, 1),
(-1, 0) => (3, 1),
_ => (4, 1),
};
(CTX_SC + label, xor)
}
}
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let mut shapes: Vec<(u32, u32)> = Vec::new();
for w in 1..=6 {
for h in 1..=9 {
shapes.push((w, h));
}
}
shapes.extend([(13, 10), (16, 16), (64, 4), (4, 64)]);
for (w, h) in shapes {
let n = (w * h) as usize;
let mut maps: Vec<Vec<bool>> =
(0..n).map(|k| (0..n).map(|i| i == k).collect()).collect();
for density in [8u64, 32, 64, 128, 224] {
maps.push((0..n).map(|_| next() % 256 < density).collect());
}
for vcausal in [false, true] {
for sig in &maps {
let neg: Vec<bool> = (0..n).map(|_| next() % 2 == 1).collect();
let mut state = BlockState::new(w, h);
state.vcausal = vcausal;
for y in 0..h {
for x in 0..w {
let i = (y * w + x) as usize;
if sig[i] {
state.set_significant(x, y);
state.set_negative(x, y, neg[i]);
}
}
}
let reference = Reference {
w,
h,
sig: sig.clone(),
neg,
vcausal,
};
for y in 0..h {
for x in 0..w {
let at = format!("{w}x{h} vcausal {vcausal} at ({x}, {y})");
let (sh, sv, sd) = reference.sums(x.into(), y.into());
assert_eq!(state.neighbor_sums(x, y), (sh, sv, sd), "{at}");
let zc = [
(Orientation::Ll, zc_label_lh(sh, sv, sd)),
(Orientation::Hl, zc_label_lh(sv, sh, sd)),
(Orientation::Hh, zc_label_hh(sh + sv, sd)),
];
for (orient, label) in zc {
let got = state.zc_context(x, y, orient);
assert_eq!(got, CTX_ZC + label, "{at} {orient:?}");
}
let sign = reference.sign(x.into(), y.into());
assert_eq!(state.sc_context(x, y), sign, "{at}");
let mr = CTX_MR + u8::from(sh + sv + sd > 0);
assert_eq!(state.mr_context(x, y), mr, "{at}");
}
}
}
}
}
}
#[test]
fn each_neighbor_direction_sets_its_own_bit() {
let directions: [(i32, i32, u16, u16); 8] = [
(0, -1, NB_N, NEG_N),
(0, 1, NB_S, NEG_S),
(-1, 0, NB_W, NEG_W),
(1, 0, NB_E, NEG_E),
(-1, -1, NB_NW, 0),
(1, -1, NB_NE, 0),
(-1, 1, NB_SW, 0),
(1, 1, NB_SE, 0),
];
for cy in [4u32, 5, 7] {
for (dx, dy, bit, neg_bit) in directions {
for negative in [false, true] {
let (x, y) = ((1 + dx) as u32, (cy as i32 + dy) as u32);
let want = bit | if negative { neg_bit } else { 0 };
let at = format!("center (1, {cy}), neighbor ({x}, {y}), negative {negative}");
let mut b = BlockState::new(3, 12);
b.set_significant(x, y);
b.set_negative(x, y, negative);
assert_eq!(b.state[b.pad(1, cy)], want, "{at}");
let mut m = BlockState::new(3, 12);
let p = m.pad(x, y);
mark_significant(&mut m.state, p, y as usize % 4, m.stripe_len, negative);
assert_eq!(m.state[m.pad(1, cy)], want, "{at}, mark_significant");
for oy in 0..12u32 {
for ox in 0..3u32 {
if ox.abs_diff(x) > 1 || oy.abs_diff(y) > 1 {
assert_eq!(m.state[m.pad(ox, oy)], 0, "{at}, ({ox}, {oy})");
}
}
}
}
}
}
}
mod reference {
use super::*;
fn sign(
mq: &mut MqDecoder<'_>,
cx: &mut [Context],
b: &BlockState,
x: u32,
y: u32,
) -> bool {
let (ctx, xor) = b.sc_context(x, y);
mq.decode(&mut cx[usize::from(ctx)]) ^ xor == 1
}
fn significant(b: &mut BlockState, x: u32, y: u32, bpno: u32, negative: bool) {
let one = 1i32 << bpno;
let i = b.idx(x, y);
b.coeffs[i] = one | (one >> 1);
b.set_significant(x, y);
b.set_negative(x, y, negative);
}
fn scan(b: &BlockState) -> Vec<(u32, u32)> {
let mut order = Vec::new();
for y0 in (0..b.height).step_by(4) {
for x in 0..b.width {
for y in y0..(y0 + 4).min(b.height) {
order.push((x, y));
}
}
}
order
}
fn zero_code(
mq: &mut MqDecoder<'_>,
cx: &mut [Context],
b: &mut BlockState,
orient: Orientation,
(x, y): (u32, u32),
bpno: u32,
) {
let ctx = b.zc_context(x, y, orient);
if mq.decode(&mut cx[usize::from(ctx)]) == 1 {
let negative = sign(mq, cx, b, x, y);
significant(b, x, y, bpno, negative);
}
}
pub fn sig_prop(
mq: &mut MqDecoder<'_>,
cx: &mut [Context],
b: &mut BlockState,
orient: Orientation,
bpno: u32,
) {
for (x, y) in scan(b) {
if b.is_significant(x, y) || b.neighbor_sums(x, y) == (0, 0, 0) {
continue;
}
zero_code(mq, cx, b, orient, (x, y), bpno);
b.set_visited(x, y, true);
}
}
pub fn mag_ref(mq: &mut MqDecoder<'_>, cx: &mut [Context], b: &mut BlockState, bpno: u32) {
for (x, y) in scan(b) {
if !b.is_significant(x, y) || b.is_visited(x, y) {
continue;
}
let bit = mq.decode(&mut cx[usize::from(b.mr_context(x, y))]);
let half = (1i32 << bpno) >> 1;
let i = b.idx(x, y);
b.coeffs[i] += if bit == 1 { half } else { -half };
b.set_refined(x, y);
}
}
pub fn cleanup(
mq: &mut MqDecoder<'_>,
cx: &mut [Context],
b: &mut BlockState,
orient: Orientation,
bpno: u32,
) {
let quiet = |b: &BlockState, x: u32, y: u32| {
!b.is_significant(x, y) && !b.is_visited(x, y) && b.neighbor_sums(x, y) == (0, 0, 0)
};
for y0 in (0..b.height).step_by(4) {
for x in 0..b.width {
let rows = (y0 + 4).min(b.height) - y0;
let mut first = 0;
if rows == 4 && (y0..y0 + 4).all(|y| quiet(b, x, y)) {
if mq.decode(&mut cx[CTX_RUN as usize]) == 0 {
continue;
}
let hi = mq.decode(&mut cx[CTX_UNI as usize]);
let lo = mq.decode(&mut cx[CTX_UNI as usize]);
let run = u32::from((hi << 1) | lo);
let negative = sign(mq, cx, b, x, y0 + run);
significant(b, x, y0 + run, bpno, negative);
first = run + 1;
}
for y in y0 + first..y0 + rows {
if !b.is_significant(x, y) && !b.is_visited(x, y) {
zero_code(mq, cx, b, orient, (x, y), bpno);
}
}
}
}
for y in 0..b.height {
for x in 0..b.width {
b.set_visited(x, y, false);
}
}
}
}
type PassOutcome = (Vec<(i32, bool, bool, bool, bool)>, Vec<Context>, Vec<u8>);
fn pass_outcome(
b: &BlockState,
cx: &[Context; NUM_CONTEXTS],
mq: &mut MqDecoder<'_>,
) -> PassOutcome {
let mut samples = Vec::new();
for y in 0..b.height {
for x in 0..b.width {
samples.push((
b.coeffs[b.idx(x, y)],
b.is_significant(x, y),
b.is_visited(x, y),
b.is_negative(x, y),
b.is_refined(x, y),
));
}
}
let mut uniform = Context::new(46, 0);
let after = (0..48).map(|_| mq.decode(&mut uniform)).collect();
(samples, cx.to_vec(), after)
}
#[test]
fn pass_loops_match_a_per_sample_reference() {
let mut seed = 0x2545_F491_4F6C_DD1Du64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let shapes = [
(1, 1),
(1, 4),
(1, 5),
(2, 7),
(3, 8),
(4, 9),
(5, 10),
(6, 11),
(7, 12),
(8, 3),
(9, 6),
(13, 13),
(16, 16),
(5, 2),
];
let orients = [
Orientation::Ll,
Orientation::Lh,
Orientation::Hl,
Orientation::Hh,
];
let densities = [0u64, 4, 16, 64, 160, 240];
let trials = 6;
let mut checked = 0;
for (w, h) in shapes {
for vcausal in [false, true] {
for density in densities {
for _ in 0..trials {
let mut start = BlockState::new(w, h);
start.vcausal = vcausal;
for y in 0..h {
for x in 0..w {
if next() % 256 < density {
start.set_significant(x, y);
start.set_negative(x, y, next() % 2 == 1);
let i = start.idx(x, y);
start.coeffs[i] = (next() % 1000) as i32 + 64;
if next() % 3 == 0 {
start.set_refined(x, y);
}
}
if next() % 256 < density / 2 {
start.set_visited(x, y, true);
}
}
}
let bytes: Vec<u8> = (0..24).map(|_| next() as u8).collect();
let mut cx = init_contexts();
for c in cx.iter_mut() {
*c = Context::new((next() % 47) as u8, (next() % 2) as u8);
}
let orient = orients[(next() % 4) as usize];
let bpno = (next() % 8) as u32 + 2;
let copy = |from: &BlockState| {
let mut b = BlockState::new(w, h);
b.state.clone_from(&from.state);
b.coeffs.clone_from(&from.coeffs);
b.vcausal = from.vcausal;
b
};
for pass in 0..3 {
let (mut real, mut want) = (copy(&start), copy(&start));
let mut mq = MqDecoder::new(&bytes);
let mut ref_mq = MqDecoder::new(&bytes);
let (mut cx_real, mut cx_want) = (cx, cx);
match pass {
0 => {
sig_prop_pass(&mut mq, &mut real, &mut cx_real, orient, bpno);
reference::sig_prop(
&mut ref_mq,
&mut cx_want,
&mut want,
orient,
bpno,
);
}
1 => {
mag_ref_pass(&mut mq, &mut real, &mut cx_real, bpno);
reference::mag_ref(&mut ref_mq, &mut cx_want, &mut want, bpno);
}
_ => {
cleanup_pass(
&mut mq,
&mut real,
&mut cx_real,
orient,
bpno,
0,
false,
)
.unwrap();
reference::cleanup(
&mut ref_mq,
&mut cx_want,
&mut want,
orient,
bpno,
);
}
}
assert_eq!(
pass_outcome(&real, &cx_real, &mut mq),
pass_outcome(&want, &cx_want, &mut ref_mq),
"{w}x{h} vcausal {vcausal} density {density} {orient:?} pass {pass}"
);
checked += 1;
}
}
}
}
}
assert_eq!(checked, shapes.len() * 2 * densities.len() * trials * 3);
}
}