use crate::bool_decoder::{BoolDecoder, BoolDecoderError};
use crate::coded_header::{DEFAULT_MV_CONTEXT, MV_PROB_COUNT, MvProbUpdates};
use crate::encoder::BoolEncoder;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct Mv {
pub row: i16,
pub col: i16,
}
pub type MvContext = [u8; MV_PROB_COUNT];
pub type MvContexts = [MvContext; 2];
const MVP_IS_SHORT: usize = 0;
const MVP_SIGN: usize = 1;
const MVP_SHORT: usize = 2;
const MVP_BITS: usize = MVP_SHORT + 7;
pub const SMALL_MVTREE: [i8; 14] = [
2, 8, 4, 6, -0, -1, -2, -3, 10, 12, -4, -5, -6, -7, ];
pub fn resolve_mv_contexts(base: &MvContexts, updates: &MvProbUpdates) -> MvContexts {
let mut out = *base;
for component in 0..2 {
for position in 0..MV_PROB_COUNT {
if let Some(prob) = updates[component][position] {
out[component][position] = prob;
}
}
}
out
}
pub fn default_mv_contexts() -> MvContexts {
DEFAULT_MV_CONTEXT
}
fn read_small_mv(dec: &mut BoolDecoder<'_>, p: &MvContext) -> Result<i32, BoolDecoderError> {
let mut i: usize = 0;
loop {
let prob = p[MVP_SHORT + (i >> 1)];
let bit = dec.read_bool(prob)? as usize;
let next = SMALL_MVTREE[i + bit];
if next <= 0 {
return Ok((-next) as i32);
}
i = next as usize;
}
}
pub fn read_mv_component(
dec: &mut BoolDecoder<'_>,
p: &MvContext,
) -> Result<i32, BoolDecoderError> {
let mut a: i32 = 0;
if dec.read_bool(p[MVP_IS_SHORT])? {
for i in 0..3 {
a += (dec.read_bool(p[MVP_BITS + i])? as i32) << i;
}
let mut i = 9;
loop {
a += (dec.read_bool(p[MVP_BITS + i])? as i32) << i;
i -= 1;
if i <= 3 {
break;
}
}
if (a & 0xfff0) == 0 || dec.read_bool(p[MVP_BITS + 3])? {
a += 8;
}
} else {
a = read_small_mv(dec, p)?;
}
if a != 0 && dec.read_bool(p[MVP_SIGN])? {
Ok(-a)
} else {
Ok(a)
}
}
pub fn read_mv(dec: &mut BoolDecoder<'_>, contexts: &MvContexts) -> Result<Mv, BoolDecoderError> {
let row = read_mv_component(dec, &contexts[0])? as i16;
let col = read_mv_component(dec, &contexts[1])? as i16;
Ok(Mv { row, col })
}
fn write_small_mv(enc: &mut BoolEncoder, p: &MvContext, leaf: i32) {
debug_assert!((0..=7).contains(&leaf));
let mut i: usize = 0;
for k in (0..3).rev() {
let bit = (leaf >> k) & 1 != 0;
let prob = p[MVP_SHORT + (i >> 1)];
enc.write_bool(prob, bit);
let next = SMALL_MVTREE[i + bit as usize];
if next <= 0 {
debug_assert_eq!(
next,
-(leaf as i8),
"§17.1 small_mvtree descent must land on leaf {leaf}"
);
break;
}
i = next as usize;
}
}
pub fn write_mv_component(enc: &mut BoolEncoder, p: &MvContext, value: i32) {
debug_assert!(
(-1023..=1023).contains(&value),
"§17.1 MV component out of range: {value}"
);
let a = value.unsigned_abs() as i32;
if a > 7 {
enc.write_bool(p[MVP_IS_SHORT], true);
for i in 0..3 {
enc.write_bool(p[MVP_BITS + i], (a >> i) & 1 != 0);
}
let mut i = 9;
loop {
enc.write_bool(p[MVP_BITS + i], (a >> i) & 1 != 0);
i -= 1;
if i <= 3 {
break;
}
}
if (a & 0xfff0) != 0 {
enc.write_bool(p[MVP_BITS + 3], (a >> 3) & 1 != 0);
}
} else {
enc.write_bool(p[MVP_IS_SHORT], false);
write_small_mv(enc, p, a);
}
if a != 0 {
enc.write_bool(p[MVP_SIGN], value < 0);
}
}
pub fn write_mv(enc: &mut BoolEncoder, contexts: &MvContexts, mv: Mv) {
write_mv_component(enc, &contexts[0], mv.row as i32);
write_mv_component(enc, &contexts[1], mv.col as i32);
}
pub fn mv_component_bits(p: &MvContext, value: i32) -> f64 {
debug_assert!((-1023..=1023).contains(&value));
use crate::encoder::bool_bits;
fn small_mv_bits(p: &MvContext, leaf: i32) -> f64 {
let mut bits = 0.0;
let mut i: usize = 0;
for k in (0..3).rev() {
let bit = (leaf >> k) & 1 != 0;
bits += bool_bits(p[MVP_SHORT + (i >> 1)], bit);
let next = SMALL_MVTREE[i + bit as usize];
if next <= 0 {
debug_assert_eq!(
next,
-(leaf as i8),
"§17.1 small_mvtree descent must land on leaf {leaf}"
);
break;
}
i = next as usize;
}
bits
}
let a = value.unsigned_abs() as i32;
let mut bits = 0.0;
if a > 7 {
bits += bool_bits(p[MVP_IS_SHORT], true);
for i in 0..3 {
bits += bool_bits(p[MVP_BITS + i], (a >> i) & 1 != 0);
}
let mut i = 9;
loop {
bits += bool_bits(p[MVP_BITS + i], (a >> i) & 1 != 0);
i -= 1;
if i <= 3 {
break;
}
}
if (a & 0xfff0) != 0 {
bits += bool_bits(p[MVP_BITS + 3], (a >> 3) & 1 != 0);
}
} else {
bits += bool_bits(p[MVP_IS_SHORT], false);
bits += small_mv_bits(p, a);
}
if a != 0 {
bits += bool_bits(p[MVP_SIGN], value < 0);
}
bits
}
pub fn mv_bits(contexts: &MvContexts, mv: Mv) -> f64 {
mv_component_bits(&contexts[0], mv.row as i32) + mv_component_bits(&contexts[1], mv.col as i32)
}
#[cfg(test)]
mod tests {
use super::*;
struct BoolEncoder {
out: Vec<u8>,
range: u32,
bottom: u32,
bit_count: i32,
}
impl BoolEncoder {
fn new() -> Self {
BoolEncoder {
out: Vec::new(),
range: 255,
bottom: 0,
bit_count: 24,
}
}
fn write_bool(&mut self, prob: u8, val: bool) {
let split = 1 + (((self.range - 1) * prob as u32) >> 8);
if val {
self.bottom = self.bottom.wrapping_add(split);
self.range -= split;
} else {
self.range = split;
}
while self.range < 128 {
self.range <<= 1;
if (self.bottom >> 31) & 1 == 1 {
let mut i = self.out.len();
while i > 0 {
i -= 1;
if self.out[i] == 255 {
self.out[i] = 0;
} else {
self.out[i] = self.out[i].wrapping_add(1);
break;
}
}
}
self.bottom <<= 1;
self.bit_count -= 1;
if self.bit_count == 0 {
let byte = (self.bottom >> 24) as u8;
self.out.push(byte);
self.bottom &= (1 << 24) - 1;
self.bit_count = 8;
}
}
}
fn finish(mut self) -> Vec<u8> {
let c = self.bit_count;
let v = self.bottom;
if v & (1u32 << (32 - c)) != 0 {
let mut i = self.out.len();
while i > 0 {
i -= 1;
if self.out[i] == 255 {
self.out[i] = 0;
} else {
self.out[i] = self.out[i].wrapping_add(1);
break;
}
}
}
let mut v = v;
v <<= c & 7;
let mut c_shift = c >> 3;
while c_shift > 0 {
v <<= 8;
c_shift -= 1;
}
for _ in 0..4 {
self.out.push((v >> 24) as u8);
v <<= 8;
}
while self.out.len() < 2 {
self.out.push(0);
}
self.out
}
fn write_mv_component(&mut self, p: &MvContext, value: i32) {
let a = value.unsigned_abs() as i32;
if a > 7 {
self.write_bool(p[MVP_IS_SHORT], true);
for i in 0..3 {
self.write_bool(p[MVP_BITS + i], (a >> i) & 1 != 0);
}
let mut i = 9;
loop {
self.write_bool(p[MVP_BITS + i], (a >> i) & 1 != 0);
i -= 1;
if i <= 3 {
break;
}
}
if (a & 0xfff0) != 0 {
self.write_bool(p[MVP_BITS + 3], (a >> 3) & 1 != 0);
}
} else {
self.write_bool(p[MVP_IS_SHORT], false);
self.write_small_mv(p, a);
}
if a != 0 {
self.write_bool(p[MVP_SIGN], value < 0);
}
}
fn write_small_mv(&mut self, p: &MvContext, leaf: i32) {
fn find_path(tree: &[i8], i: usize, target: i8, path: &mut Vec<bool>) -> bool {
for bit in 0..2 {
let next = tree[i + bit];
path.push(bit == 1);
if next <= 0 {
if next == -target {
return true;
}
} else if find_path(tree, next as usize, target, path) {
return true;
}
path.pop();
}
false
}
let mut path = Vec::new();
assert!(
find_path(&SMALL_MVTREE, 0, leaf as i8, &mut path),
"no SMALL_MVTREE path for leaf {leaf}"
);
let mut i = 0usize;
for &bit in &path {
let prob = p[MVP_SHORT + (i >> 1)];
self.write_bool(prob, bit);
let next = SMALL_MVTREE[i + bit as usize];
if next <= 0 {
break;
}
i = next as usize;
}
}
}
fn roundtrip_component(ctx: &MvContext, value: i32) -> i32 {
let mut enc = BoolEncoder::new();
enc.write_mv_component(ctx, value);
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("init");
read_mv_component(&mut dec, ctx).expect("decode")
}
#[test]
fn small_mvtree_shape_matches_spec() {
assert_eq!(
SMALL_MVTREE,
[2, 8, 4, 6, 0, -1, -2, -3, 10, 12, -4, -5, -6, -7]
);
}
#[test]
fn mvp_index_offsets_match_spec() {
assert_eq!(MVP_IS_SHORT, 0);
assert_eq!(MVP_SIGN, 1);
assert_eq!(MVP_SHORT, 2);
assert_eq!(MVP_BITS, 9);
assert_eq!(MVP_BITS + 10, MV_PROB_COUNT);
}
#[test]
fn short_values_round_trip() {
let ctx = DEFAULT_MV_CONTEXT[0];
for v in -7..=7 {
assert_eq!(roundtrip_component(&ctx, v), v, "short value {v}");
}
}
#[test]
fn zero_has_no_sign_bit() {
for ctx in &DEFAULT_MV_CONTEXT {
assert_eq!(roundtrip_component(ctx, 0), 0);
}
}
#[test]
fn long_values_round_trip() {
let ctx = DEFAULT_MV_CONTEXT[1];
for &v in &[8, 9, 14, 15, 16, 17, 31, 100, 511, 512, 1023] {
assert_eq!(roundtrip_component(&ctx, v), v, "long +{v}");
assert_eq!(roundtrip_component(&ctx, -v), -v, "long -{v}");
}
}
#[test]
fn implicit_bit3_boundary() {
let ctx = DEFAULT_MV_CONTEXT[0];
for &v in &[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 24, 25] {
assert_eq!(roundtrip_component(&ctx, v), v, "boundary {v}");
}
}
#[test]
fn full_extremes_round_trip() {
let ctx = DEFAULT_MV_CONTEXT[0];
assert_eq!(roundtrip_component(&ctx, 1023), 1023);
assert_eq!(roundtrip_component(&ctx, -1023), -1023);
}
#[test]
fn read_mv_uses_row_then_column_contexts() {
let contexts = default_mv_contexts();
let mut enc = BoolEncoder::new();
enc.write_mv_component(&contexts[0], 5);
enc.write_mv_component(&contexts[1], -300);
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("init");
let mv = read_mv(&mut dec, &contexts).expect("read_mv");
assert_eq!(mv, Mv { row: 5, col: -300 });
}
#[test]
fn read_mv_distinct_contexts_are_load_bearing() {
let mut contexts = default_mv_contexts();
contexts[0][MVP_IS_SHORT] = 30;
contexts[1][MVP_IS_SHORT] = 220;
let mut enc = BoolEncoder::new();
enc.write_mv_component(&contexts[0], 200);
enc.write_mv_component(&contexts[1], 9);
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("init");
let good = read_mv(&mut dec, &contexts).expect("read_mv");
assert_eq!(good, Mv { row: 200, col: 9 });
let swapped = [contexts[1], contexts[0]];
let mut dec2 = BoolDecoder::init(&bytes).expect("init");
let bad = read_mv(&mut dec2, &swapped);
if let Ok(v) = bad {
assert_ne!(v, Mv { row: 200, col: 9 });
}
}
#[test]
fn default_mv_contexts_equals_spec_defaults() {
assert_eq!(default_mv_contexts(), DEFAULT_MV_CONTEXT);
assert_eq!(default_mv_contexts()[0][0], 162); assert_eq!(default_mv_contexts()[1][0], 164); }
#[test]
fn resolve_no_updates_is_identity() {
let base = default_mv_contexts();
let updates: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
assert_eq!(resolve_mv_contexts(&base, &updates), base);
}
#[test]
fn resolve_overlays_some_positions() {
let base = default_mv_contexts();
let mut updates: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
updates[0][MVP_IS_SHORT] = Some(200);
updates[1][MVP_SIGN] = Some(50);
let resolved = resolve_mv_contexts(&base, &updates);
assert_eq!(resolved[0][MVP_IS_SHORT], 200);
assert_eq!(resolved[1][MVP_SIGN], 50);
assert_eq!(resolved[0][MVP_SIGN], base[0][MVP_SIGN]);
assert_eq!(resolved[1][MVP_IS_SHORT], base[1][MVP_IS_SHORT]);
}
#[test]
fn resolve_persists_across_chained_frames() {
let mut first_updates: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
first_updates[0][MVP_SHORT] = Some(99);
first_updates[0][MVP_SHORT + 1] = Some(33);
let frame1 = resolve_mv_contexts(&default_mv_contexts(), &first_updates);
let mut second_updates: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
second_updates[0][MVP_SHORT + 1] = Some(77); let frame2 = resolve_mv_contexts(&frame1, &second_updates);
assert_eq!(frame2[0][MVP_SHORT], 99); assert_eq!(frame2[0][MVP_SHORT + 1], 77); }
#[test]
fn round_trip_under_resolved_context() {
let mut updates: MvProbUpdates = [[None; MV_PROB_COUNT]; 2];
updates[0][MVP_IS_SHORT] = Some(40);
updates[0][MVP_SHORT + 2] = Some(180);
updates[0][MVP_BITS] = Some(20);
let ctx = resolve_mv_contexts(&default_mv_contexts(), &updates)[0];
for &v in &[0, 3, 7, 8, 15, 16, 200, -200, 1023, -1023] {
assert_eq!(roundtrip_component(&ctx, v), v, "resolved-ctx {v}");
}
}
#[test]
fn mv_default_is_zero_vector() {
assert_eq!(Mv::default(), Mv { row: 0, col: 0 });
}
fn roundtrip_component_public(ctx: &MvContext, value: i32) -> i32 {
let mut enc = crate::encoder::BoolEncoder::new();
super::write_mv_component(&mut enc, ctx, value);
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("init");
read_mv_component(&mut dec, ctx).expect("decode")
}
#[test]
fn public_write_mv_component_round_trips_short_and_long() {
let ctx = DEFAULT_MV_CONTEXT[0];
for v in -7..=7 {
assert_eq!(roundtrip_component_public(&ctx, v), v, "short v={v}");
}
for &v in &[8, 9, 15, 16, 17, 24, 100, 511, 512, 1023] {
assert_eq!(roundtrip_component_public(&ctx, v), v, "long +{v}");
assert_eq!(roundtrip_component_public(&ctx, -v), -v, "long -{v}");
}
}
#[test]
fn public_write_mv_round_trips_through_read_mv() {
let contexts = default_mv_contexts();
let mut enc = crate::encoder::BoolEncoder::new();
super::write_mv(&mut enc, &contexts, Mv { row: -12, col: 47 });
let bytes = enc.finish();
let mut dec = BoolDecoder::init(&bytes).expect("init");
let mv = read_mv(&mut dec, &contexts).expect("read_mv");
assert_eq!(mv, Mv { row: -12, col: 47 });
}
#[test]
fn mv_component_bits_zero_is_just_is_short_bit() {
let ctx = DEFAULT_MV_CONTEXT[0];
let bits = super::mv_component_bits(&ctx, 0);
assert!(
bits > 0.0,
"non-zero bool cost expected for V=0, got {bits}"
);
assert!(bits < 8.0, "V=0 emits a handful of bools, got {bits}");
}
fn mv_component_bits_reference(p: &MvContext, value: i32) -> f64 {
fn bool_bits(prob: u8, value: bool) -> f64 {
let p0 = (prob.max(1) as f64) / 256.0;
let p = if value { 1.0 - p0 } else { p0 };
-p.max(1.0 / 256.0).log2()
}
fn find_path(tree: &[i8], i: usize, target: i8, path: &mut Vec<bool>) -> bool {
for bit in 0..2 {
let next = tree[i + bit];
path.push(bit == 1);
if next <= 0 {
if next == -target {
return true;
}
} else if find_path(tree, next as usize, target, path) {
return true;
}
path.pop();
}
false
}
let a = value.unsigned_abs() as i32;
let mut bits = 0.0;
if a > 7 {
bits += bool_bits(p[MVP_IS_SHORT], true);
for i in 0..3 {
bits += bool_bits(p[MVP_BITS + i], (a >> i) & 1 != 0);
}
let mut i = 9;
loop {
bits += bool_bits(p[MVP_BITS + i], (a >> i) & 1 != 0);
i -= 1;
if i <= 3 {
break;
}
}
if (a & 0xfff0) != 0 {
bits += bool_bits(p[MVP_BITS + 3], (a >> 3) & 1 != 0);
}
} else {
bits += bool_bits(p[MVP_IS_SHORT], false);
let mut path = Vec::new();
assert!(find_path(&SMALL_MVTREE, 0, a as i8, &mut path));
let mut tree_bits = 0.0;
let mut i: usize = 0;
for &bit in &path {
tree_bits += bool_bits(p[MVP_SHORT + (i >> 1)], bit);
let next = SMALL_MVTREE[i + bit as usize];
if next <= 0 {
break;
}
i = next as usize;
}
bits += tree_bits;
}
if a != 0 {
bits += bool_bits(p[MVP_SIGN], value < 0);
}
bits
}
#[test]
fn mv_component_bits_matches_reference_over_full_range() {
let mut synthetic = [0u8; MV_PROB_COUNT];
for (i, slot) in synthetic.iter_mut().enumerate() {
*slot = [0u8, 1, 7, 128, 200, 254, 255][i % 7];
}
for ctx in [DEFAULT_MV_CONTEXT[0], DEFAULT_MV_CONTEXT[1], synthetic] {
for value in -1023..=1023 {
let got = super::mv_component_bits(&ctx, value);
let want = mv_component_bits_reference(&ctx, value);
assert!(
got == want,
"mv_component_bits({value}) = {got}, reference = {want}"
);
}
}
}
#[test]
fn mv_component_bits_grow_with_magnitude() {
let ctx = DEFAULT_MV_CONTEXT[0];
let b0 = super::mv_component_bits(&ctx, 0);
let b4 = super::mv_component_bits(&ctx, 4);
let b32 = super::mv_component_bits(&ctx, 32);
let b256 = super::mv_component_bits(&ctx, 256);
assert!(
b0 < b4 && b4 < b32 && b32 < b256,
"expected monotone growth, got {b0} < {b4} < {b32} < {b256}"
);
}
#[test]
fn mv_bits_is_sum_of_component_bits() {
let ctx = default_mv_contexts();
let mv = Mv { row: 7, col: -200 };
let total = super::mv_bits(&ctx, mv);
let parts = super::mv_component_bits(&ctx[0], mv.row as i32)
+ super::mv_component_bits(&ctx[1], mv.col as i32);
assert!((total - parts).abs() < 1e-12);
}
}