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,
}
#[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>,
vcausal: 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],
vcausal: false,
}
}
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 excludes_south(&self, y: u32) -> bool {
self.vcausal && y % 4 == 3
}
fn neighbour_sums(&self, x: u32, y: u32) -> (u8, u8, u8) {
let south = !self.excludes_south(y);
let (x, y) = (x as i64, y as i64);
let sig_south = |dx: i64| (south && self.sig_at(x + dx, y + 1)) as u8;
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 + sig_south(0);
let d = self.sig_at(x - 1, y - 1) as u8
+ self.sig_at(x + 1, y - 1) as u8
+ sig_south(-1)
+ sig_south(1);
(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 south_contrib = if self.excludes_south(y) {
0
} else {
self.contrib_at(x as i64, y as i64 + 1)
};
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) + south_contrib).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,
}
}
pub(crate) 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 sig_prop_pass_raw(
raw: &mut RawDecoder<'_>,
state: &mut BlockState,
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;
}
if state.zc_context(x, y, orient) == CTX_ZC {
continue; }
if raw.decode() == 1 {
state.set_significant_magnitude(x, y, bpno);
state.set_significant(x, y);
state.set_negative(x, y, raw.decode() == 1);
}
state.set_visited(x, y, true);
}
}
}
fn mag_ref_pass_raw(raw: &mut RawDecoder<'_>, state: &mut BlockState, 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 bit = raw.decode();
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,
style: u8,
) -> Result<()> {
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();
if style & crate::codestream::markers::code_block_style::SEGSYM != 0 {
read_segmentation_symbol(mq, cx)?;
}
Ok(())
}
fn read_segmentation_symbol(mq: &mut MqDecoder<'_>, cx: &mut [Context]) -> Result<()> {
let mut symbol = 0u8;
for _ in 0..4 {
symbol = (symbol << 1) | mq.decode(&mut cx[CTX_UNI as usize]);
}
if symbol != 0b1010 {
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::Unsupported(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 cblk_numbps = top as i32 - i32::from(roi_shift);
'segments: for (bytes, passes) in segments {
let raw = bypass && pass_type != PassType::Cleanup && (bpno as i32) <= cblk_numbps - 4;
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) => {
cleanup_pass(mq, state, &mut cx, orient, bpno, style)?
}
(PassCoder::Raw(rd), PassType::SigProp) => {
sig_prop_pass_raw(rd, state, orient, 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.is_negative(x, y) { -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.neighbour_sums(1, 3);
assert_eq!((h, v, d), (0, 1, 2), "default neighbourhood");
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 neighbours flip the sign");
assert_eq!(state.mr_context(1, 3), CTX_MR + 1);
state.vcausal = true;
assert_eq!(
state.neighbour_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 neighbour, neutral sign");
assert_eq!(state.mr_context(1, 3), CTX_MR, "no significant neighbour");
for x in 0..3 {
state.set_significant(x, 3);
}
let (_, v_interior, _) = state.neighbour_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}");
}
#[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::Unsupported(_)), "{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_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);
}
}