use crate::tier1::mq::{Context, MqDecoder};
#[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,
}
#[derive(Debug)]
pub struct BlockState {
pub width: u32,
pub height: u32,
pub coeffs: Vec<i32>,
significant: Vec<bool>,
visited: Vec<bool>,
negative: Vec<bool>,
refined: Vec<bool>,
}
impl BlockState {
pub fn new(width: u32, height: u32) -> Self {
let n = (width * height) as usize;
BlockState {
width,
height,
coeffs: vec![0; n],
significant: vec![false; n],
visited: vec![false; n],
negative: vec![false; n],
refined: vec![false; n],
}
}
fn idx(&self, x: u32, y: u32) -> usize {
(y * self.width + x) as usize
}
fn in_bounds(&self, x: i64, y: i64) -> bool {
x >= 0 && y >= 0 && x < self.width as i64 && y < self.height as i64
}
fn sig_at(&self, x: i64, y: i64) -> bool {
self.in_bounds(x, y) && self.significant[self.idx(x as u32, y as u32)]
}
fn contrib_at(&self, x: i64, y: i64) -> i32 {
if !self.sig_at(x, y) {
0
} else if self.negative[self.idx(x as u32, y as u32)] {
-1
} else {
1
}
}
pub fn is_significant(&self, x: u32, y: u32) -> bool {
self.significant[self.idx(x, y)]
}
pub fn set_significant(&mut self, x: u32, y: u32) {
let i = self.idx(x, y);
self.significant[i] = true;
}
pub fn is_visited(&self, x: u32, y: u32) -> bool {
self.visited[self.idx(x, y)]
}
pub fn set_visited(&mut self, x: u32, y: u32, value: bool) {
let i = self.idx(x, y);
self.visited[i] = value;
}
fn set_significant_magnitude(&mut self, x: u32, y: u32, bpno: u32) {
let one = 1i32 << bpno;
let i = self.idx(x, y);
self.coeffs[i] = one | (one >> 1);
}
fn refine_magnitude(&mut self, x: u32, y: u32, bpno: u32, bit: u8) {
let poshalf = (1i32 << bpno) >> 1;
let i = self.idx(x, y);
self.coeffs[i] += if bit == 1 { poshalf } else { -poshalf };
}
fn clear_visited(&mut self) {
self.visited.iter_mut().for_each(|v| *v = false);
}
pub fn is_negative(&self, x: u32, y: u32) -> bool {
self.negative[self.idx(x, y)]
}
pub fn set_negative(&mut self, x: u32, y: u32, value: bool) {
let i = self.idx(x, y);
self.negative[i] = value;
}
pub fn is_refined(&self, x: u32, y: u32) -> bool {
self.refined[self.idx(x, y)]
}
pub fn set_refined(&mut self, x: u32, y: u32) {
let i = self.idx(x, y);
self.refined[i] = true;
}
fn neighbour_sums(&self, x: u32, y: u32) -> (u8, u8, u8) {
let (x, y) = (x as i64, y as i64);
let h = self.sig_at(x - 1, y) as u8 + self.sig_at(x + 1, y) as u8;
let v = self.sig_at(x, y - 1) as u8 + self.sig_at(x, y + 1) as u8;
let d = self.sig_at(x - 1, y - 1) as u8
+ self.sig_at(x + 1, y - 1) as u8
+ self.sig_at(x - 1, y + 1) as u8
+ self.sig_at(x + 1, y + 1) as u8;
(h, v, d)
}
pub fn zc_context(&self, x: u32, y: u32, orient: Orientation) -> u8 {
let (h, v, d) = self.neighbour_sums(x, y);
let label = match orient {
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),
};
CTX_ZC + label
}
pub fn sc_context(&self, x: u32, y: u32) -> (u8, u8) {
let (x, y) = (x as i64, y as i64);
let h = (self.contrib_at(x - 1, y) + self.contrib_at(x + 1, y)).clamp(-1, 1);
let v = (self.contrib_at(x, y - 1) + self.contrib_at(x, y + 1)).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),
(-1, -1) => (4, 1),
_ => unreachable!("clamped contributions are in -1..=1"),
};
(CTX_SC + label, xor)
}
pub fn mr_context(&self, x: u32, y: u32) -> u8 {
if self.is_refined(x, y) {
CTX_MR + 2
} else {
let (h, v, d) = self.neighbour_sums(x, y);
let label = if h + v + d > 0 { 1 } else { 0 };
CTX_MR + label
}
}
}
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,
}
}
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,
}
}
fn init_contexts() -> [Context; NUM_CONTEXTS] {
let mut cx = [Context::default(); NUM_CONTEXTS];
cx[CTX_ZC as usize].index = 4;
cx[CTX_RUN as usize].index = 3;
cx[CTX_UNI as usize].index = 46;
cx
}
fn decode_sign(mq: &mut MqDecoder<'_>, state: &mut BlockState, cx: &mut [Context], x: u32, y: u32) {
let (ctx, xor) = state.sc_context(x, y);
let bit = mq.decode(&mut cx[ctx as usize]);
state.set_negative(x, y, bit ^ xor == 1);
}
fn stripes(width: u32, height: u32) -> impl Iterator<Item = (u32, u32)> {
(0..height)
.step_by(4)
.flat_map(move |y0| (0..width).map(move |x| (x, y0)))
}
fn sig_prop_pass(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context],
orient: Orientation,
bpno: u32,
) {
let (w, h) = (state.width, state.height);
for (x, y0) in stripes(w, h) {
for y in y0..(y0 + 4).min(h) {
if state.is_significant(x, y) {
continue;
}
let ctx = state.zc_context(x, y, orient);
if ctx == CTX_ZC {
continue; }
if mq.decode(&mut cx[ctx as usize]) == 1 {
state.set_significant_magnitude(x, y, bpno);
state.set_significant(x, y);
decode_sign(mq, state, cx, x, y);
}
state.set_visited(x, y, true);
}
}
}
fn mag_ref_pass(mq: &mut MqDecoder<'_>, state: &mut BlockState, cx: &mut [Context], bpno: u32) {
let (w, h) = (state.width, state.height);
for (x, y0) in stripes(w, h) {
for y in y0..(y0 + 4).min(h) {
if !state.is_significant(x, y) || state.is_visited(x, y) {
continue;
}
let ctx = state.mr_context(x, y);
let bit = mq.decode(&mut cx[ctx as usize]);
state.refine_magnitude(x, y, bpno, bit);
state.set_refined(x, y);
}
}
}
fn cleanup_pass(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
cx: &mut [Context],
orient: Orientation,
bpno: u32,
) {
let (w, h) = (state.width, state.height);
for (x, y0) in stripes(w, h) {
let rows = (y0 + 4).min(h) - y0;
let mut first = 0;
if rows == 4 {
let aggregate = (0..4).all(|dy| {
let y = y0 + dy;
!state.is_significant(x, y)
&& !state.is_visited(x, y)
&& state.zc_context(x, y, orient) == CTX_ZC
});
if aggregate {
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 = (hi << 1) | lo; let y = y0 + run as u32;
state.set_significant_magnitude(x, y, bpno);
state.set_significant(x, y);
decode_sign(mq, state, cx, x, y);
first = run as u32 + 1;
}
}
for dy in first..rows {
let y = y0 + dy;
if state.is_significant(x, y) || state.is_visited(x, y) {
continue;
}
let ctx = state.zc_context(x, y, orient);
if mq.decode(&mut cx[ctx as usize]) == 1 {
state.set_significant_magnitude(x, y, bpno);
state.set_significant(x, y);
decode_sign(mq, state, cx, x, y);
}
}
}
state.clear_visited();
}
pub fn decode_block(
mq: &mut MqDecoder<'_>,
state: &mut BlockState,
orient: Orientation,
numbps: u32,
num_passes: u32,
zero_bit_planes: u32,
style: u8,
) {
let _ = style;
if num_passes == 0 {
return;
}
let top = numbps.saturating_sub(zero_bit_planes);
if top < 1 {
return; }
debug_assert!(top <= MAX_BIT_PLANES, "bit-plane count {top} overflows i32");
let mut cx = init_contexts();
let mut bpno = top;
let mut left = num_passes;
cleanup_pass(mq, state, &mut cx, orient, bpno);
left -= 1;
while left > 0 && bpno > 1 {
bpno -= 1;
sig_prop_pass(mq, state, &mut cx, orient, bpno);
left -= 1;
if left == 0 {
break;
}
mag_ref_pass(mq, state, &mut cx, bpno);
left -= 1;
if left == 0 {
break;
}
cleanup_pass(mq, state, &mut cx, orient, bpno);
left -= 1;
}
for y in 0..state.height {
for x in 0..state.width {
let i = state.idx(x, y);
let mag = state.coeffs[i] / 2;
state.coeffs[i] = if state.is_negative(x, y) { -mag } else { mag };
}
}
}
#[cfg(test)]
mod tests {
use super::golden_vectors::GOLDEN_BLOCKS;
use super::*;
use crate::tier1::mq::MqDecoder;
fn decode_golden(g: &super::golden_vectors::GoldenBlock) -> Vec<i32> {
let mut mq = MqDecoder::new(g.segment);
let mut state = BlockState::new(g.width, g.height);
let numbps = g.num_passes.div_ceil(3) + g.zero_bit_planes;
decode_block(
&mut mq,
&mut state,
Orientation::Ll,
numbps,
g.num_passes,
g.zero_bit_planes,
0,
);
state.coeffs
}
#[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 zero_passes_yields_all_zero_coefficients() {
let mut mq = MqDecoder::new(GOLDEN_BLOCKS[0].segment);
let mut state = BlockState::new(4, 4);
decode_block(&mut mq, &mut state, Orientation::Ll, 8, 0, 0, 0);
assert!(state.coeffs.iter().all(|&c| c == 0));
}
#[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_neighbours() {
let b = BlockState::new(5, 5);
assert_eq!(b.mr_context(2, 2), CTX_MR);
}
#[test]
fn mr_first_refinement_with_a_significant_neighbour() {
let b = block_with(&[(2, 1)]);
assert_eq!(b.mr_context(2, 2), CTX_MR + 1);
}
#[test]
fn mr_after_first_refinement_ignores_neighbours() {
let mut b = block_with(&[(2, 1)]);
b.set_refined(2, 2);
assert_eq!(b.mr_context(2, 2), CTX_MR + 2);
}
#[test]
fn neighbours_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);
}
}