diff --git a/Cargo.lock b/Cargo.lock index c535ff8f..1c075aa2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,6 +485,13 @@ dependencies = [ "ec-ogg", ] +[[package]] +name = "ec-vp8" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "ec-vp9-syntax" version = "0.1.0" diff --git a/crates/ec-vp8/Cargo.toml b/crates/ec-vp8/Cargo.toml new file mode 100644 index 00000000..a8b294dc --- /dev/null +++ b/crates/ec-vp8/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-vp8" +description = "Native VP8 decoder (RFC 6386) — key-frame and inter-frame decoding of the full format, replacing the runtime-dlopen'd libvpx seat." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-vp8/examples/dbg_first.rs b/crates/ec-vp8/examples/dbg_first.rs new file mode 100644 index 00000000..36e27020 --- /dev/null +++ b/crates/ec-vp8/examples/dbg_first.rs @@ -0,0 +1,18 @@ +// Decode frame 0 of an IVF with decision tracing (EC_VP8_TRACE=1). +use ec_vp8::decode::Decoder; + +fn main() { + let path = std::env::args().nth(1).expect("ivf path"); + let bytes = std::fs::read(path).unwrap(); + let sz = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize; + let frame = &bytes[44..44 + sz]; + let mut dec = Decoder::new(); + match dec.decode(frame) { + Ok(Some(pic)) => println!( + "OUT {}x{} y[0..8]={:?}", + pic.width, pic.height, &pic.y[..8] + ), + Ok(None) => println!("OUT hidden"), + Err(e) => println!("OUT ERR {e}"), + } +} diff --git a/crates/ec-vp8/examples/dump_frame.rs b/crates/ec-vp8/examples/dump_frame.rs new file mode 100644 index 00000000..31bca7de --- /dev/null +++ b/crates/ec-vp8/examples/dump_frame.rs @@ -0,0 +1,58 @@ +//! Dump decoded frame N of an IVF as raw yuv420p (ffmpeg-comparable: +//! `ffmpeg -i in.ivf -f rawvideo -pix_fmt yuv420p -` streams the same +//! layout, frame after frame). Usage: `dump_frame +//! `. Decoding stops at the first frame the crate cannot yet +//! decode (e.g. inter frames before M3), reporting it on stderr. + +use ec_vp8::decode::Decoder; + +fn main() { + let args: Vec = std::env::args().collect(); + assert_eq!(args.len(), 4, "usage: dump_frame "); + let want: usize = args[2].parse().expect("frame index"); + let bytes = std::fs::read(&args[1]).unwrap(); + + // IVF: 32-byte file header, then (4-byte LE size, 8-byte pts, data). + let mut frames = Vec::new(); + let mut pos = 32; + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; + frames.push(&bytes[pos + 12..pos + 12 + sz]); + pos += 12 + sz; + } + + let mut dec = Decoder::new(); + for (i, f) in frames.iter().enumerate() { + match dec.decode(f) { + Ok(Some(pic)) if i == want => { + let mut out = Vec::with_capacity( + pic.y.len() + pic.u.len() + pic.v.len(), + ); + for row in 0..usize::from(pic.height) { + let s = row * pic.stride; + out.extend_from_slice(&pic.y[s..s + usize::from(pic.width)]); + } + let (cw, ch) = ( + usize::from(pic.width + 1) / 2, + usize::from(pic.height + 1) / 2, + ); + for plane in [&pic.u, &pic.v] { + for row in 0..ch { + let s = row * pic.uv_stride; + out.extend_from_slice(&plane[s..s + cw]); + } + } + std::fs::write(&args[3], out).unwrap(); + return; + } + Ok(Some(_)) => {} + Ok(None) => {} + Err(e) => { + eprintln!("frame {i}: {e}"); + std::process::exit(1); + } + } + } + eprintln!("no frame {want} decoded"); + std::process::exit(1); +} diff --git a/crates/ec-vp8/src/bool.rs b/crates/ec-vp8/src/bool.rs new file mode 100644 index 00000000..fb864df2 --- /dev/null +++ b/crates/ec-vp8/src/bool.rs @@ -0,0 +1,444 @@ +//! The boolean arithmetic decoder (RFC 6386 §7). +//! +//! VP8 codes almost the entire frame as a sequence of bools, each written +//! at an 8-bit zero-probability `p` (meaning `p/256`). The decoder mirrors +//! the encoder's interval state with two numbers — `range` (128..=255) and +//! `value` (the encoded number x minus the interval's left endpoint) — and +//! renormalises one bit at a time, shifting a fresh input byte into +//! `value` for every 8 bits consumed. +//! +//! Every function here is the direct inverse of the RFC's reference +//! `bool_encoder`; the tests drive them against a test-only re-implementation +//! of that encoder and assert bit-exact round-trips. + +use ec_core::Result; + +/// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3). +pub struct BoolDecoder<'a> { + data: &'a [u8], + /// Index of the next byte to shift into `value`. + pos: usize, + /// 128..=255; identical to the encoder's range. + range: u32, + /// Encoded number minus the current interval's left endpoint; the top + /// bits hold what has been read, bytes shift in at the bottom. + value: u32, + /// Bits shifted out of `value` since the last byte was shifted in. + bit_count: u32, + /// Bytes consumed past the end of the partition (read as 0, per the + /// spec's zero-extension of x). A healthy partition stays at 0. + overreads: u32, +} + +impl<'a> BoolDecoder<'a> { + /// Start decoding the partition `data` (RFC `init_bool_decoder`): the + /// first two bytes are read into `value`, big-endian. A partition + /// shorter than two bytes (legal for unused token partitions of + /// multi-partition frames) is zero-extended like the reference + /// decoder does, and the shortfall shows up in [`Self::overreads`]. + pub fn new(data: &'a [u8]) -> Result { + if data.is_empty() { + return Ok(Self { + data, + pos: 0, + range: 255, + value: 0, + bit_count: 0, + overreads: 0, + }); + } + let mut value = u32::from(data[0]) << 8; + if data.len() > 1 { + value |= u32::from(data[1]); + } + Ok(Self { + data, + pos: data.len().min(2), + range: 255, + value, + bit_count: 0, + overreads: 0, + }) + } + + /// Bytes consumed past the end of the partition, read as zero. Any + /// non-zero value on a complete, valid partition is a desync symptom. + pub fn overreads(&self) -> u32 { + self.overreads + } + + /// Offset of the next unread input byte, for desync diagnostics. + pub fn byte_offset(&self) -> usize { + self.pos + } + + fn next_byte(&mut self) -> u32 { + match self.data.get(self.pos) { + Some(&b) => { + self.pos += 1; + u32::from(b) + } + None => { + self.overreads += 1; + 0 + } + } + } + + /// Decode one bool whose zero-probability is `prob`/256 + /// (RFC `read_bool`). Under EC_VP8_TRACE, prints the decoder state + /// after the read — `B `, byte-exact + /// the same line scripts/vp8ref_model.py prints — so the two + /// decoders can be diffed read-for-read. + pub fn read_bool(&mut self, prob: u8) -> bool { + let trace = std::env::var_os("EC_VP8_TRACE").is_some(); + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + let bigsplit = split << 8; + let bit = if self.value >= bigsplit { + self.range -= split; + self.value -= bigsplit; + true + } else { + self.range = split; + false + }; + while self.range < 128 { + self.value <<= 1; + self.range <<= 1; + self.bit_count += 1; + if self.bit_count == 8 { + self.bit_count = 0; + self.value |= self.next_byte(); + } + } + if trace { + eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit)); + } + bit + } + + /// Unsigned `n`-bit literal, bits high- to low-order, each at + /// probability 128 (RFC `read_literal`). + pub fn read_literal(&mut self, n: u32) -> u32 { + let mut v = 0; + for _ in 0..n { + v = (v << 1) + u32::from(self.read_bool(128)); + } + v + } + + /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude + /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0. + pub fn read_signed_literal(&mut self, n: u32) -> i32 { + if n == 0 { + return 0; + } + let mut v: i32 = if self.read_bool(128) { -1 } else { 0 }; + for _ in 0..n - 1 { + v = (v << 1) + i32::from(self.read_bool(128)); + } + v + } + /// Presence-gated signed integer in the frame-header shape (RFC §9.3, + /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an + /// `n`-bit magnitude followed by a sign flag (1 = negative). This is + /// every segment/quantizer/loop-filter delta in the frame header. + pub fn read_maybe_signed(&mut self, n: u32) -> i32 { + if !self.read_bool(128) { + return 0; + } + let v = self.read_literal(n) as i32; + if self.read_bool(128) { -v } else { v } + } + + /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1 + /// : 1` (RFC §8, MV probability updates use exactly this shape). + pub fn read_prob7(&mut self) -> u8 { + let x = self.read_literal(7); + if x == 0 { 1 } else { (x << 1) as u8 } + } + + /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the + /// left/right branch entries (positive = interior node index, negative + /// `-leaf`), `probs[i]` is the probability of interior node `i` (the + /// tree position halved). + pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 { + let mut i: i32 = 0; + loop { + let b = self.read_bool(probs[(i >> 1) as usize]); + i = i32::from(tree[(i + i32::from(b as i8)) as usize]); + if i <= 0 { + return (-i) as u8; + } + } + } + + /// Decode a tree-coded value, skipping the root's `dct_eob` branch — + /// used for every token after a `DCT_0`, since EOB cannot follow a + /// zero token (RFC §13.2). `tree` must be the full coefficient tree; + /// decoding starts at interior node 1. + pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 { + // The coefficient tree's layout puts the EOB leaf at the root's + // left branch; descending the right branch first is exactly + // "start at the root with a read 1". + let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch + while { + let b = self.read_bool(probs[(i >> 1) as usize]); + i = i32::from(tree[(i + i32::from(b as i8)) as usize]); + i > 0 + } {} + (-i) as u8 + } +} + +/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests +/// drive [`BoolDecoder`] against known bitstreams instead of trusting the +/// decoder to decode its own idea of the format. +#[cfg(test)] +pub(crate) struct BoolEncoder { + out: Vec, + range: u32, + bottom: u32, + bit_count: i32, +} + +#[cfg(test)] +impl BoolEncoder { + pub(crate) fn new() -> Self { + Self { + out: Vec::new(), + range: 255, + bottom: 0, + bit_count: 24, + } + } + + pub(crate) fn write_bool(&mut self, val: bool, prob: u8) { + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + if val { + self.bottom += split; + self.range -= split; + } else { + self.range = split; + } + while self.range < 128 { + self.range <<= 1; + if self.bottom & (1 << 31) != 0 { + Self::add_one_to_output(&mut self.out); + } + self.bottom <<= 1; + self.bit_count -= 1; + if self.bit_count == 0 { + self.out.push((self.bottom >> 24) as u8); + self.bottom &= (1 << 24) - 1; + self.bit_count = 8; + } + } + } + + pub(crate) fn write_literal(&mut self, v: u32, n: u32) { + for i in (0..n).rev() { + self.write_bool((v >> i) & 1 != 0, 128); + } + } + + fn add_one_to_output(out: &mut [u8]) { + for b in out.iter_mut().rev() { + if *b == 255 { + *b = 0; + } else { + *b += 1; + return; + } + } + // Carry out of the beginning cannot happen: x < 1 always (RFC). + unreachable!("bool encoder carry propagated past the first byte"); + } + + /// RFC `flush_bool_encoder`. + pub(crate) fn flush(mut self) -> Vec { + let c = self.bit_count; + let mut v = self.bottom; + if v & (1 << (32 - c)) != 0 { + Self::add_one_to_output(&mut self.out); + } + v <<= c & 7; + let mut c = c >> 3; + while c > 0 { + v <<= 8; + c -= 1; + } + for _ in 0..4 { + self.out.push((v >> 24) as u8); + v <<= 8; + } + self.out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip_bools(pattern: &[(&[bool], u8)]) { + let mut e = BoolEncoder::new(); + for (vals, p) in pattern { + for &v in *vals { + e.write_bool(v, *p); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (vals, p) in pattern { + for &v in *vals { + assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p); + } + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_bools_at_every_extreme() { + // p = 1 (all zeros essentially free) through p = 255, with 1s at + // the most improbable settings to force carry propagation. + roundtrip_bools(&[ + (&[false; 64], 1), + (&[true], 1), + (&[false, true, false, true], 128), + (&[true; 3], 255), + (&[false; 32], 255), + (&[true; 16], 1), + ]); + } + + #[test] + fn roundtrips_long_random_streams() { + // Deterministic LCG so failures reproduce. + let mut state: u64 = 0x9E3779B97F4A7C15; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let probs = [1u8, 2, 32, 128, 200, 254, 255]; + let mut e = BoolEncoder::new(); + let mut expected = Vec::new(); + for &p in &probs { + for _ in 0..200 { + let v = next() & 1 == 1; + e.write_bool(v, p); + expected.push((v, p)); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (v, p) in expected { + assert_eq!(d.read_bool(p), v); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_literals() { + let mut e = BoolEncoder::new(); + for n in 1..=19u32 { + let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 }; + e.write_literal(ones, n); + e.write_literal(0, n); + e.write_literal(0x15 & ones, n); // 0b10101 truncated + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for n in 1..=19u32 { + let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 }; + assert_eq!(d.read_literal(n), ones); + assert_eq!(d.read_literal(n), 0); + assert_eq!(d.read_literal(n), 0x15 & ones); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_signed_literals() { + let mut e = BoolEncoder::new(); + // sign flag then 4 magnitude bits: the two's-complement value in + // -16..=15 (RFC read_signed_literal shifts the sign-extended -1). + for mag in 0..=15u32 { + e.write_bool(true, 128); + e.write_literal(mag, 4); + e.write_bool(false, 128); + e.write_literal(mag, 4); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for mag in 0..=15i32 { + assert_eq!(d.read_signed_literal(5), mag - 16); + assert_eq!(d.read_signed_literal(5), mag); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_prob7() { + let mut e = BoolEncoder::new(); + for x in 0..=127u32 { + e.write_literal(x, 7); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for x in 0..=127u32 { + assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 }); + } + } + + #[test] + fn roundtrips_tree_values() { + // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2: + // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}. + let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3]; + let probs = [145u8, 156, 163, 128]; + // (bit path, leaf value) pairs of the kf ymode tree (§11.2): + // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110", + // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics. + let leaves: [(&[bool], u8); 5] = [ + (&[false], 4), + (&[true, false, false], 0), + (&[true, false, true], 1), + (&[true, true, false], 2), + (&[true, true, true], 3), + ]; + for (path, val) in leaves { + let mut e = BoolEncoder::new(); + for (i, &b) in path.iter().enumerate() { + e.write_bool(b, probs[i]); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}"); + } + } + + #[test] + fn short_partitions_zero_extend() { + // Empty/1-byte partitions are legal for unused token partitions; + // the init shortfall counts as overreads. + let mut d = BoolDecoder::new(&[]).unwrap(); + assert_eq!(d.read_bool(128), false); + let mut d = BoolDecoder::new(&[0]).unwrap(); + assert_eq!(d.read_bool(128), false); + } + + #[test] + fn overreads_are_counted_not_panicked() { + // Two bytes of init, then nothing: any read shifts in zeros. + let data = [0u8, 0]; + let mut d = BoolDecoder::new(&data).unwrap(); + for _ in 0..100 { + d.read_bool(128); + } + assert!(d.overreads() > 0); + } +} diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs new file mode 100644 index 00000000..9aeaaf7d --- /dev/null +++ b/crates/ec-vp8/src/decode.rs @@ -0,0 +1,1329 @@ +//! Frame decoding: per-row mode parsing, token decoding, intra +//! prediction and reconstruction (RFC 6386 §5, §11, §12, §13, §14). +//! +//! The decoder mirrors the reference decoder's row pipeline: per +//! macroblock row, all first-partition mode records are parsed, then +//! each macroblock's tokens are decoded from its row-assigned token +//! partition (row `r` uses partition `r % partitions`, exactly like +//! libvpx/dixie) and immediately reconstructed. The loop filter runs as +//! a post-pass in raster MB order — for a non-threaded decode this is +//! edge-for-edge identical to the reference's row-delayed filtering, +//! because an MB's filter inputs only ever come from MBs already +//! filtered earlier in that order. + +use crate::bool::BoolDecoder; +use crate::frame::{FrameType, KeyFrameDims, mb_geometry}; +use crate::header::FrameHeader; +use crate::mc; +use crate::intra; +use crate::loopfilter::{self, MbFilterInfo}; +use crate::modes; +use crate::tables::KF_BMODE_PROB; +use crate::tokens::{self, Dq, MbCoeffs, TokenContexts}; +use crate::transform; +use crate::transform::Dequant; +use crate::{Error, PersistedState, Result}; +/// Copy a visible MB-aligned image out of the 1-pixel-bordered working +/// plane into the top-left visible corner of a bordered reference +/// buffer. +fn copy_plane( + dst: &mut [u8], + dst_stride: usize, + src: &[u8], + src_stride: usize, + w: usize, + h: usize, +) { + for r in 0..h { + let s = (1 + r) * src_stride + 1; + let d = (MC_BORDER + r) * dst_stride + MC_BORDER; + dst[d..d + w].copy_from_slice(&src[s..s + w]); + } +} + +/// Reconstructed-image plane: a padded buffer with a 1-pixel left/top +/// border (127 on top including the corner, 129 on the left — RFC 6386 +/// §12) so intra prediction reads neighbours without special cases. +struct Plane { + data: Vec, + /// Row pitch: `1 + mb_cols * mb_size`. + stride: usize, +} + +impl Plane { + fn new(mb_cols: usize, mb_rows: usize, mb_size: usize) -> Self { + let stride = 1 + mb_cols * mb_size; + let rows = 1 + mb_rows * mb_size; + let mut data = vec![0u8; stride * rows]; + for cell in data[..stride].iter_mut() { + *cell = 127; + } + for row in 1..rows { + data[row * stride] = 129; + } + Plane { data, stride } + } + + fn resize(&mut self, mb_cols: usize, mb_rows: usize, mb_size: usize) { + *self = Plane::new(mb_cols, mb_rows, mb_size); + } + + /// Offset of pixel (x, y); the border occupies x = -1 / y = -1. + fn at(&self, x: usize, y: usize) -> usize { + (1 + y) * self.stride + 1 + x + } + + /// Offset of the pixel row ABOVE pixel row `y` (the border row for + /// y = 0), at pixel column `x`. + fn at_above(&self, x: usize, y: usize) -> usize { + y * self.stride + 1 + x + } + + /// Offset of the pixel column LEFT of pixel column `x` (the border + /// column for x = 0), at pixel row `y`. + fn at_left(&self, x: usize, y: usize) -> usize { + (1 + y) * self.stride + x + } + + /// Offset of the above-left pixel (border corner for x = y = 0). + fn at_above_left(&self, x: usize, y: usize) -> usize { + y * self.stride + x + } +} + +/// One macroblock's parsed prediction record. +#[derive(Clone, Default)] +struct MbInfo { + /// [`modes::YMode`] as its coded integer. + y_mode: u8, + uv_mode: u8, + b_modes: [u8; 16], + segment_id: u8, + skip: bool, + /// 0 = intra, 1 = last, 2 = golden, 3 = altref (§16.2). Key-frame + /// MBs and the border are intra. + ref_frame: u8, + /// Inter mv_ref leaf (§16.2): 0 = zero, 1 = nearest, 2 = near, + /// 3 = new, 4 = split. 0 when intra. + mv_ref: u8, + /// Whole-MB motion vector in eighth-pels; the bottom-right subblock's + /// vector for SPLITMV (what future neighbours' census sees). + mv: (i16, i16), + /// Per-subblock motion vectors (SPLITMV). + bmi: [(i16, i16); 16], + /// `need_to_clamp_mvs` (§16.2): the luma MC clamps this MV into the + /// extended-frame range. + mv_clamp: bool, + /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's + /// eob_mask); decides the loop filter's interior edges (§15.1). + has_nz: bool, +} + +/// One reference-frame slot: bordered planes, 32-pixel edge-replicated +/// borders around the MB-aligned image (dixie `extend_frame`). +#[derive(Clone)] +struct RefFrame { + y: Vec, + u: Vec, + v: Vec, + stride: usize, + uv_stride: usize, +} + +/// MC border width in pixels (libvpx `VP8BORDERINPIXELS`). +const MC_BORDER: usize = 32; + +impl MbInfo { + fn has_y2(&self) -> bool { + self.y_mode != modes::YMode::BPred.as_u8() + } +} + +/// The VP8 decoder. Feed complete frames (one full VP8 frame payload, +/// exactly what a container demuxer hands over for the `VP80`/`vp08` +/// codec). +pub struct Decoder { + state: PersistedState, + dims: KeyFrameDims, + mb_cols: usize, + mb_rows: usize, + y: Plane, + u: Plane, + v: Plane, + /// `(mb_rows + 1) * (mb_cols + 1)` records; row/column index 0 is the + /// DC_PRED border (dixie's `mb_info` border trick). + mb_info: Vec, + token_ctxs: TokenContexts, + /// Reference frame slots: [unused, last, golden, altref] (§16.2 + /// indices). Empty until the first key frame. + refs: [Option; 4], + /// Persisted per-MB segment ids, `mb_rows * mb_cols` (§9.3: when a + /// frame does not re-code the map, ids carry over). + segment_map: Vec, + frame_decoded: bool, + /// Per-frame MC filter selection (libvpx `vp8_setup_version`, + /// alloccommon.c:131-167: version 0 and the reserved 4-7 use the + /// six-tap filters, versions 1-3 the bilinear ones) and full-pel + /// flag (version 3: `fullpixel_mask = ~7`). The decoder never reads + /// `no_lpf` — dead there too. + mc_bilinear: bool, + mc_fullpel: bool, +} + +/// A decoded, displayable frame: cropped contiguous planes. +#[derive(Clone)] +pub struct Picture { + /// Luma plane, `stride`-spaced rows of `width` pixels. + pub y: Vec, + /// U (Cb) plane, half resolution. + pub u: Vec, + /// V (Cr) plane, half resolution. + pub v: Vec, + /// Frame width in pixels. + pub width: u16, + /// Frame height in pixels. + pub height: u16, + /// Luma row pitch of the returned planes. + pub stride: usize, + /// Chroma row pitch of the returned planes. + pub uv_stride: usize, +} + +impl Decoder { + /// Create an empty decoder; the first key frame sets the size. + pub fn new() -> Self { + Self { + state: PersistedState::default(), + dims: KeyFrameDims { + width: 0, + height: 0, + h_scale: 0, + v_scale: 0, + }, + mb_cols: 0, + mb_rows: 0, + y: Plane { + data: Vec::new(), + stride: 0, + }, + u: Plane { + data: Vec::new(), + stride: 0, + }, + v: Plane { + data: Vec::new(), + stride: 0, + }, + mb_info: Vec::new(), + token_ctxs: TokenContexts::new(0), + refs: [None, None, None, None], + segment_map: Vec::new(), + frame_decoded: false, + mc_bilinear: false, + mc_fullpel: false, + } + } + + /// Size of the frames this decoder produces, once known. + pub fn dimensions(&self) -> Option<(u16, u16)> { + self.frame_decoded + .then_some((self.dims.width, self.dims.height)) + } + + /// Decode one frame; returns the picture when it is for display + /// (`show_frame`). Hidden frames still update the decode state. + pub fn decode(&mut self, frame: &[u8]) -> Result> { + // Entropy revert (§9.7, libvpx decodeframe.c:1156/1245): when + // `refresh_entropy` is 0 the frame's probability updates are + // transient — libvpx copies `fc` into `lfc` at this point in + // the header and restores it after the frame. On a KEY frame + // `fc` has already been reset to defaults by then (init_frame + // runs before header parsing), so a key frame with + // refresh_entropy == 0 reverts to DEFAULTS, not to whatever the + // previous stream carried. Segmentation and loop-filter deltas + // live outside `fc` and never revert. + let key = frame.first().is_some_and(|b| b & 1 == 0); + let defaults = PersistedState::default(); + let (coeff_probs, mv_probs, ymode_probs, uv_mode_probs) = if key { + ( + defaults.coeff_probs, + defaults.mv_probs, + defaults.ymode_probs, + defaults.uv_mode_probs, + ) + } else { + ( + self.state.coeff_probs, + self.state.mv_probs, + self.state.ymode_probs, + self.state.uv_mode_probs, + ) + }; + let (header, hdr_dec) = FrameHeader::parse(frame, &mut self.state)?; + // vp8_setup_version (decodeframe.c:935): the tag's version bits + // pick the MC interpolation filter and full-pel mode for this + // frame (see the field docs on Decoder). + self.mc_bilinear = matches!(header.tag.version, 1..=3); + self.mc_fullpel = header.tag.version == 3; + let refresh_entropy = header.refresh.refresh_entropy; + let pic = match header.tag.frame_type { + FrameType::Key => self.decode_keyframe(frame, header, hdr_dec), + FrameType::Inter => self.decode_interframe(frame, header, hdr_dec), + }?; + if !refresh_entropy { + self.state.coeff_probs = coeff_probs; + self.state.mv_probs = mv_probs; + self.state.ymode_probs = ymode_probs; + self.state.uv_mode_probs = uv_mode_probs; + } + Ok(pic) + } + + fn ensure_buffers(&mut self, kf: KeyFrameDims) { + let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); + if self.mb_cols != mb_cols || self.mb_rows != mb_rows { + self.y.resize(mb_cols, mb_rows, 16); + self.u.resize(mb_cols, mb_rows, 8); + self.v.resize(mb_cols, mb_rows, 8); + self.mb_info = vec![MbInfo::default(); (mb_cols + 1) * (mb_rows + 1)]; + self.token_ctxs = TokenContexts::new(mb_cols); + } + self.mb_cols = mb_cols; + self.mb_rows = mb_rows; + self.dims = kf; + // Reset the mode border (row 0 / column 0) so the top-left mode + // contexts read DC_PRED like a fresh decode. + for col in 0..=mb_cols { + self.mb_info[col] = MbInfo::default(); + } + for row in 0..=mb_rows { + self.mb_info[row * (mb_cols + 1)] = MbInfo::default(); + } + } + + /// Mode-record index for MB (row, col); row/col 0 is the border. + fn mbi(&self, row: usize, col: usize) -> &MbInfo { + &self.mb_info[row * (self.mb_cols + 1) + col] + } + + fn mbi_mut(&mut self, row: usize, col: usize) -> &mut MbInfo { + let w = self.mb_cols + 1; + &mut self.mb_info[row * w + col] + } + + fn decode_keyframe( + &mut self, + frame: &[u8], + header: FrameHeader, + mut hdr_dec: BoolDecoder<'_>, + ) -> Result> { + let kf = header.dims.expect("key frame header carries dimensions"); + self.ensure_buffers(kf); + + // Token partition bool decoders (§9.5). + let mut partitions = Vec::with_capacity(header.partition_sizes.len()); + let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); + for &sz in &header.partition_sizes { + let end = off + sz as usize; + let slice = frame + .get(off..end) + .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; + partitions.push(BoolDecoder::new(slice)?); + off = end; + } + + // Dequant factors per segment (dixie dequant_init, §10/§14.1). + let seg = &header.segmentation; + let mut dqf = [Dequant { + y1_dc: 0, + y1_ac: 0, + y2_dc: 0, + y2_ac: 0, + uv_dc: 0, + uv_ac: 0, + }; 4]; + for (i, dq) in dqf.iter_mut().enumerate() { + let q = if seg.enabled { + if seg.abs_delta { + seg.quant_idx[i] + } else { + i32::from(header.quant.yac_qi) + seg.quant_idx[i] + } + } else { + i32::from(header.quant.yac_qi) + }; + *dq = transform::dequant( + q, + header.quant.ydc_delta, + header.quant.y2dc_delta, + header.quant.y2ac_delta, + header.quant.uvdc_delta, + header.quant.uvac_delta, + ); + } + + self.token_ctxs.reset_above_row(); + + for row in 1..=self.mb_rows { + self.token_ctxs.reset_left(); + // Phase 1: parse every mode record of the row (partition 0). + for col in 1..=self.mb_cols { + let mut mb = MbInfo::default(); + if header.segmentation.enabled && header.segmentation.update_map { + mb.segment_id = + hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); + } + if header.coeff_skip_enabled { + mb.skip = hdr_dec.read_bool(header.prob_skip_false); + } + self.decode_kf_modes(&mut hdr_dec, row, col, &mut mb); + *self.mbi_mut(row, col) = mb; + } + + // Phases 2+3 per MB: tokens then reconstruction. Token row + // `r` (0-based) reads partition `r % n` like the reference. + let part = (row - 1) % partitions.len(); + for col in 1..=self.mb_cols { + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("M {} {}", row - 1, col - 1); + } + let mb = self.mbi(row, col).clone(); + let has_y2 = mb.has_y2(); + let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); + let dq = &dqf[seg_i]; + let mb_dq = Dq { + y1_dc: dq.y1_dc, + y1_ac: dq.y1_ac, + uv_dc: dq.uv_dc, + uv_ac: dq.uv_ac, + y2_dc: dq.y2_dc, + y2_ac: dq.y2_ac, + }; + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2); + } + let probs = self.state.coeff_probs; + let coeffs = if mb.skip { + tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) + } else { + tokens::decode_mb_tokens( + &mut partitions[part], + &probs, + &mb_dq, + has_y2, + &mut self.token_ctxs, + col - 1, + ) + }; + self.mb_info[row * (self.mb_cols + 1) + col].has_nz = coeffs.has_nonzero(); + self.reconstruct_intra_mb(row - 1, col - 1, &mb, &coeffs); + } + } + + // Loop filter post-pass (see module docs for the ordering + // equivalence argument). + self.run_loopfilter(&header, true); + + // A key frame refreshes every reference slot and clears the + // persisted segment map (§9.3, §9.7). + self.segment_map = vec![0; self.mb_cols * self.mb_rows]; + let rf = self.make_ref(); + self.refs[1] = Some(rf.clone()); + self.refs[2] = Some(rf.clone()); + self.refs[3] = Some(rf); + + self.frame_decoded = true; + Ok(header.tag.show_frame.then(|| self.crop())) + } + + /// Loop-filter post-pass over the whole frame (dixie order-equivalent + /// driver; `inner_edges` follows libvpx's `skip_lf`: skipped MBs + /// filter only their boundary edges, except 4x4-coded modes). + fn run_loopfilter(&mut self, header: &FrameHeader, is_keyframe: bool) { + if header.filter_level == 0 { + return; + } + let infos: Vec = (0..self.mb_rows) + .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c))) + .map(|(r, c)| { + let mb = self.mbi(r + 1, c + 1); + MbFilterInfo { + level: self.mb_filter_level(header, mb), + inner_edges: mb.has_nz || !mb.has_y2(), + } + }) + .collect(); + // The planes are bordered; the filter sees the unbordered + // image (same row pitch) starting at pixel (0, 0). + let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride); + let (mcols, mrows) = (self.mb_cols, self.mb_rows); + let simple = header.filter_type == 1; + let sharpness = header.sharpness_level; + let yimg = &mut self.y.data[1 + ystride..]; + let uimg = &mut self.u.data[1 + ustride..]; + let vimg = &mut self.v.data[1 + vstride..]; + loopfilter::filter_frame_ex( + yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos, + is_keyframe, + ); + } + + /// Snapshot the reconstructed (post-LF) frame into a bordered + /// reference buffer with 32-pixel edge-replicated borders. + fn make_ref(&self) -> RefFrame { + let w = self.mb_cols * 16; + let h = self.mb_rows * 16; + let (cw, ch) = (self.mb_cols * 8, self.mb_rows * 8); + let mut rf = RefFrame { + y: vec![0; (w + 2 * MC_BORDER) * (h + 2 * MC_BORDER)], + u: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], + v: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)], + stride: w + 2 * MC_BORDER, + uv_stride: cw + 2 * MC_BORDER, + }; + copy_plane(&mut rf.y, rf.stride, &self.y.data, self.y.stride, w, h); + copy_plane(&mut rf.u, rf.uv_stride, &self.u.data, self.u.stride, cw, ch); + copy_plane(&mut rf.v, rf.uv_stride, &self.v.data, self.v.stride, cw, ch); + mc::extend_plane(&mut rf.y, rf.stride, w, h, MC_BORDER); + mc::extend_plane(&mut rf.u, rf.uv_stride, cw, ch, MC_BORDER); + mc::extend_plane(&mut rf.v, rf.uv_stride, cw, ch, MC_BORDER); + rf + } + + + /// Per-MB loop filter level (libvpx `loop_filter_frame_init`): + /// segment level (clamped), then the reference delta, then the mode + /// delta, clamped again. Mode slots: intra B_PRED → 0, other intra + /// and ZEROMV → 1 (no delta for other intra), the moving modes → 2, + /// SPLITMV → 3. + fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 { + let seg = &header.segmentation; + let mut level = i32::from(header.filter_level); + if seg.enabled { + let d = seg.lf_level[usize::from(mb.segment_id)]; + level = if seg.abs_delta { d } else { level + d }; + } + level = level.clamp(0, 63); + if header.lf_delta_enabled { + level += self.state.ref_lf_delta[usize::from(mb.ref_frame)]; + let mode_idx = if mb.ref_frame == 0 { + if mb.y_mode == modes::YMode::BPred.as_u8() { + Some(0) + } else { + None + } + } else { + match mb.mv_ref { + 0 => Some(1), // ZEROMV + 4 => Some(3), // SPLITMV + _ => Some(2), // NEAREST / NEAR / NEW + } + }; + if let Some(mode_idx) = mode_idx { + level += self.state.mode_lf_delta[mode_idx]; + } + level = level.clamp(0, 63); + } + level as u8 + } + /// Decode one inter frame (§16): all mode records off partition 0 + /// (row-major), then per-row tokens and reconstruction off the row's + /// token partition, loop filter, then the reference updates (§9.7). + fn decode_interframe( + &mut self, + frame: &[u8], + header: FrameHeader, + mut hdr_dec: BoolDecoder<'_>, + ) -> Result> { + if self.mb_cols == 0 || self.refs[1..4].iter().any(|r| r.is_none()) { + return Err(Error::corrupt("VP8 inter frame before the first key frame")); + } + + // Token partition bool decoders (§9.5) — identical tiling to + // key frames. + let mut partitions = Vec::with_capacity(header.partition_sizes.len()); + let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1); + for &sz in &header.partition_sizes { + let end = off + sz as usize; + let slice = frame + .get(off..end) + .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?; + partitions.push(BoolDecoder::new(slice)?); + off = end; + } + + // Dequant factors per segment (persisted segmentation state). + let seg = &header.segmentation; + let mut dqf = [Dequant { + y1_dc: 0, + y1_ac: 0, + y2_dc: 0, + y2_ac: 0, + uv_dc: 0, + uv_ac: 0, + }; 4]; + for (i, dq) in dqf.iter_mut().enumerate() { + let q = if seg.enabled { + if seg.abs_delta { + seg.quant_idx[i] + } else { + i32::from(header.quant.yac_qi) + seg.quant_idx[i] + } + } else { + i32::from(header.quant.yac_qi) + }; + *dq = transform::dequant( + q, + header.quant.ydc_delta, + header.quant.y2dc_delta, + header.quant.y2ac_delta, + header.quant.uvdc_delta, + header.quant.uvac_delta, + ); + } + let ymode_probs = self.state.ymode_probs; + let uv_mode_probs = self.state.uv_mode_probs; + let sign_bias = [ + false, + header.refresh.sign_bias_golden, + header.refresh.sign_bias_altref, + ]; + + // §13.3: non-existent neighbours are empty — the above context + // is cleared at every frame start, like the key-frame path. + self.token_ctxs.reset_above_row(); + + // Phase 1: every mode record of the frame, row-major (§16). + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("STAGE modes"); + } + for row in 1..=self.mb_rows { + for col in 1..=self.mb_cols { + let mut mb = MbInfo::default(); + if header.segmentation.enabled { + if header.segmentation.update_map { + mb.segment_id = + hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs); + self.segment_map[(row - 1) * self.mb_cols + (col - 1)] = mb.segment_id; + } else { + mb.segment_id = self.segment_map[(row - 1) * self.mb_cols + (col - 1)]; + } + } + if header.coeff_skip_enabled { + mb.skip = hdr_dec.read_bool(header.prob_skip_false); + } + self.parse_inter_modes( + &mut hdr_dec, + row, + col, + &mut mb, + &header, + &ymode_probs, + &uv_mode_probs, + &sign_bias, + ); + *self.mbi_mut(row, col) = mb; + } + } + + // Phases 2+3 per row: tokens, then reconstruction (MC or intra). + for row in 1..=self.mb_rows { + self.token_ctxs.reset_left(); + let part = (row - 1) % partitions.len(); + for col in 1..=self.mb_cols { + let mb = self.mbi(row, col).clone(); + let has_y2 = mb.has_y2(); + let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); + let dq = &dqf[seg_i]; + let mb_dq = Dq { + y1_dc: dq.y1_dc, + y1_ac: dq.y1_ac, + uv_dc: dq.uv_dc, + uv_ac: dq.uv_ac, + y2_dc: dq.y2_dc, + y2_ac: dq.y2_ac, + }; + let probs = self.state.coeff_probs; + let coeffs = if mb.skip { + tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) + } else { + tokens::decode_mb_tokens( + &mut partitions[part], + &probs, + &mb_dq, + has_y2, + &mut self.token_ctxs, + col - 1, + ) + }; + { + // "Special case: force the loop filter to skip when + // eobtotal is zero" (libvpx decodeframe.c): a decoded + // MB without non-zero coefficients filters like a + // skipped one. + let slot = &mut self.mb_info[row * (self.mb_cols + 1) + col]; + slot.has_nz = coeffs.has_nonzero(); + slot.skip = mb.skip || !coeffs.has_nonzero(); + } + self.reconstruct_inter_mb(row - 1, col - 1, &mb, &coeffs); + } + } + + self.run_loopfilter(&header, false); + + // Reference buffer updates, libvpx `swap_frame_buffers` order: + // the copies run first (copy_gf = 2 must see a possibly + // just-updated altref), then the refreshes, then last. + let new = self.make_ref(); + match header.refresh.copy_arf { + 1 => self.refs[3] = self.refs[1].clone(), + 2 => self.refs[3] = self.refs[2].clone(), + _ => {} + } + match header.refresh.copy_gf { + 1 => self.refs[2] = self.refs[1].clone(), + 2 => self.refs[2] = self.refs[3].clone(), + _ => {} + } + if header.refresh.refresh_gf { + self.refs[2] = Some(new.clone()); + } + if header.refresh.refresh_arf { + self.refs[3] = Some(new.clone()); + } + if header.refresh.refresh_last { + self.refs[1] = Some(new); + } + + self.frame_decoded = true; + Ok(header.tag.show_frame.then(|| self.crop())) + } + + /// Inter-frame mode record (§16, libvpx `read_mb_modes_mv`): intra + /// at the persisted mode probabilities, or an inter mode with its + /// motion vectors off the neighborhood census. + #[allow(clippy::too_many_arguments)] + fn parse_inter_modes( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + header: &FrameHeader, + ymode_probs: &[u8; 4], + uv_mode_probs: &[u8; 3], + sign_bias: &[bool; 3], + ) { + if !d.read_bool(header.prob_intra) { + // Intra-coded MB inside an inter frame (§16.1). Subblock + // modes decode at one CONSTANT probability array with no + // above/left context (libvpx decodemv.c:467 reads + // `fc.bmode_prob` — the flat vp8_bmode_prob default; the + // context-dependent kf_bmode_prob table is key-frame-only). + mb.ref_frame = 0; + let ymode = modes::read_ymode(d, ymode_probs); + mb.y_mode = ymode.as_u8(); + if ymode == modes::YMode::BPred { + for j in 0..16usize { + mb.b_modes[j] = modes::read_bmode(d, &modes::INTER_BMODE_PROBS).as_u8(); + } + } + mb.uv_mode = modes::read_uvmode(d, uv_mode_probs).as_u8(); + return; + } + + mb.ref_frame = if !d.read_bool(header.prob_last) { + 1 + } else if !d.read_bool(header.prob_gf) { + 2 + } else { + 3 + }; + let to_bias = sign_bias[usize::from(mb.ref_frame) - 1]; + + let edges = modes::mb_edges(col - 1, row - 1, self.mb_cols, self.mb_rows); + let above = self.mv_neighbor(row - 1, col, sign_bias); + let left = self.mv_neighbor(row, col - 1, sign_bias); + let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias); + let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias); + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs); + } + + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_INTRA] as usize][0]) { + mb.mv_ref = 0; // ZEROMV + return; + } + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAREST] as usize][1]) { + mb.mv_ref = 1; // NEARESTMV + mb.mv = near_mvs[modes::CNT_NEAREST]; + modes::clamp_mv2(&mut mb.mv, edges); + return; + } + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAR] as usize][2]) { + mb.mv_ref = 2; // NEARMV + mb.mv = near_mvs[modes::CNT_NEAR]; + modes::clamp_mv2(&mut mb.mv, edges); + return; + } + + // NEWMV or SPLITMV: both code vectors as deltas off the best + // candidate — the nearest one when it dominates the census — + // clamped into range first (§16.2-§16.4). + let near_index = usize::from(cnt[modes::CNT_NEAREST] >= cnt[modes::CNT_INTRA]); + modes::clamp_mv2(&mut near_mvs[near_index], edges); + let best = near_mvs[near_index]; + if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_SPLITMV] as usize][3]) { + mb.mv_ref = 3; // NEWMV + let mut mv = modes::read_mv(d, &self.state.mv_probs); + mv.0 = mv.0.wrapping_add(best.0); + mv.1 = mv.1.wrapping_add(best.1); + mb.mv_clamp = modes::mv_out_of_bounds(mv, edges); + mb.mv = mv; + } else { + self.parse_split_mv(d, row, col, mb, best, edges); + } + } + + /// Census input from one neighbour slot (§16.3); border and intra + /// MBs contribute nothing, zero-vector inter MBs count like intra. + fn mv_neighbor(&self, row: usize, col: usize, sign_bias: &[bool; 3]) -> modes::MvNeighbor { + if row == 0 || col == 0 || self.mbi(row, col).ref_frame == 0 { + return modes::MvNeighbor { + intra: true, + zero: false, + mv: (0, 0), + is_split: false, + sign_bias: false, + }; + } + let mb = self.mbi(row, col); + modes::MvNeighbor { + intra: false, + zero: mb.mv == (0, 0), + mv: mb.mv, + is_split: mb.mv_ref == 4, + sign_bias: sign_bias[usize::from(mb.ref_frame) - 1], + } + } + + /// SPLITMV mode record (§16.4, libvpx `decode_split_mv`): partition + /// shape, then one vector per subset coded against its left/above + /// contexts, each filling a whole group of subblocks. + fn parse_split_mv( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + best: (i16, i16), + edges: (i32, i32, i32, i32), + ) { + let s = modes::read_mv_partition(d); + let num_p = modes::MV_PARTITION_COUNT[s]; + let mv_probs = self.state.mv_probs; + for j in 0..num_p { + let k = usize::from(modes::MBSPLIT_OFFSET[s][j]); + let leftmv = if k % 4 == 0 { + let lm = self.mbi(row, col - 1); + if lm.mv_ref == 4 { + lm.bmi[k + 3] + } else { + lm.mv + } + } else { + mb.bmi[k - 1] + }; + let abovemv = if k < 4 { + let am = self.mbi(row - 1, col); + if am.mv_ref == 4 { + am.bmi[k + 12] + } else { + am.mv + } + } else { + mb.bmi[k - 4] + }; + let ctx = modes::mv_cont(leftmv, abovemv); + let blockmv = match modes::read_sub_mv_ref(d, ctx) { + modes::SubMvRef::Left4x4 => leftmv, + modes::SubMvRef::Above4x4 => abovemv, + modes::SubMvRef::Zero4x4 => (0, 0), + modes::SubMvRef::New4x4 => { + let mut mv = modes::read_mv(d, &mv_probs); + mv.0 = mv.0.wrapping_add(best.0); + mv.1 = mv.1.wrapping_add(best.1); + mv + } + }; + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!( + "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})", + row - 1, + col - 1, + j, + k, + leftmv.0, + leftmv.1, + abovemv.0, + abovemv.1, + ctx, + blockmv.0, + blockmv.1, + best.0, + best.1 + ); + } + mb.mv_clamp |= modes::mv_out_of_bounds(blockmv, edges); + let count = modes::MBSPLIT_FILL_COUNT[s]; + for &off in &modes::MBSPLIT_FILL_OFFSET[s][j * count..(j + 1) * count] { + mb.bmi[usize::from(off)] = blockmv; + } + } + mb.mv_ref = 4; + // 4x4 residual coding without a Y2 block (like B_PRED). + mb.y_mode = modes::YMode::BPred.as_u8(); + // Neighbours' census sees the bottom-right subblock's vector. + mb.mv = mb.bmi[15]; + } + + /// Reconstruct one inter-frame MB: motion compensation from the + /// reference (or intra prediction), then the residual (§16, §14). + fn reconstruct_inter_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) { + if mb.ref_frame == 0 { + self.reconstruct_intra_mb(row, col, mb, coeffs); + return; + } + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!( + "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}", + row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip + ); + } + let reff = self.refs[usize::from(mb.ref_frame)] + .as_ref() + .expect("reference slots checked at frame start"); + let x = col * 16; + let y = row * 16; + let w = self.mb_cols * 16; + let h = self.mb_rows * 16; + // Luma: one 16x16 predict, or 16 independent 4x4 predicts for + // SPLITMV (identical output to libvpx's grouped predicts). Each + // predict lands at its own (bx, by) slot of one 16x16 patch. + let mut py = [0u8; 256]; + if mb.mv_ref == 4 { + for b in 0..16usize { + let (bx, by) = ((b % 4) * 4, (b / 4) * 4); + // reconinter.c:370-374: the four corner subblocks clamp + // their MVs under need_to_clamp_mvs; the rest don't. + let corner = matches!(b, 0 | 2 | 8 | 10); + mc::predict_luma( + &reff.y, reff.stride, MC_BORDER, w, h, x + bx, y + by, mb.bmi[b], + mb.mv_clamp && corner, + &mut py[by * 16 + bx..], 16, 4, 4, self.mc_bilinear, + ); + } + } else { + mc::predict_luma( + &reff.y, reff.stride, MC_BORDER, w, h, x, y, mb.mv, mb.mv_clamp, &mut py, 16, + 16, 16, self.mc_bilinear, + ); + } + + // Chroma: libvpx predicts each plane as ONE 8x8 block for + // whole-MB modes (vp8_build_inter16x16_predictors_mb) or four + // independent 4x4 blocks for SPLITMV (build_inter4x4_predictors_mb, + // each from its quadrant's build_4x4uvmvs vector). The whole-MB + // path re-clamps UNCONDITIONALLY (reconinter.c: rounding the + // derived chroma MV to full-pel can move it outside the tap + // window even when the luma MV was in range); the SPLITMV path + // clamps only under need_to_clamp_mvs. + let mut pu = [0u8; 256]; + let mut pv = [0u8; 256]; + if mb.mv_ref == 4 { + for q in 0..4usize { + // Quadrant q: 4x4 chroma pixels at (qx4, qy4) in the MB. + let (qx4, qy4) = ((q % 2) * 4, (q / 2) * 4); + let (cx, cy) = (x / 2 + qx4, y / 2 + qy4); + let (qx, qy) = ((q % 2) * 2, (q / 2) * 2); + let uvmv = modes::chroma_mv_split( + &[ + mb.bmi[qy * 4 + qx], + mb.bmi[qy * 4 + qx + 1], + mb.bmi[qy * 4 + qx + 4], + mb.bmi[qy * 4 + qx + 5], + ], + self.mc_fullpel, + ); + mc::predict_chroma( + &reff.u, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv, + mb.mv_clamp, &mut pu[qy4 * 16 + qx4..], 16, 4, 4, + self.mc_bilinear, + ); + mc::predict_chroma( + &reff.v, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv, + mb.mv_clamp, &mut pv[qy4 * 16 + qx4..], 16, 4, 4, + self.mc_bilinear, + ); + } + } else { + let uvmv = modes::chroma_mv_whole(mb.mv, self.mc_fullpel); + mc::predict_chroma( + &reff.u, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true, + &mut pu, 16, 8, 8, self.mc_bilinear, + ); + mc::predict_chroma( + &reff.v, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true, + &mut pv, 16, 8, 8, self.mc_bilinear, + ); + } + if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 { + eprintln!( + "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}", + &pu[0..8], + &reff.u[MC_BORDER * reff.uv_stride + MC_BORDER..MC_BORDER * reff.uv_stride + MC_BORDER + 8], + coeffs.u[0].iter().sum::() + ); + } + + // Residual: every block adds onto its MC prediction. + let y_dcs: [i16; 16] = if coeffs.has_y2 { + transform::iwht4x4(&coeffs.y2) + } else { + [0; 16] + }; + for b in 0..16usize { + let (bx, by) = ((b % 4) * 4, (b / 4) * 4); + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + let dst = self.y.at(x + bx, y + by); + idct_add_into(&mut self.y.data, &c, &py, 16, by * 16 + bx, dst, self.y.stride); + } + for (plane_data, coeffs_uv, pred, stride) in [ + (&mut self.u.data, &coeffs.u, &pu, self.u.stride), + (&mut self.v.data, &coeffs.v, &pv, self.v.stride), + ] { + for b in 0..4usize { + let (bx, by) = ((b % 2) * 4, (b / 2) * 4); + let dst = (1 + y / 2 + by) * stride + 1 + x / 2 + bx; + idct_add_into(plane_data, &coeffs_uv[b], pred, 16, by * 16 + bx, dst, stride); + } + } + } + + /// Key-frame mode record (§11): Y mode at fixed probabilities, then + /// 16 context-conditioned subblock modes for B_PRED, then chroma. + fn decode_kf_modes( + &mut self, + d: &mut BoolDecoder<'_>, + row: usize, + col: usize, + mb: &mut MbInfo, + ) { + let ymode = modes::read_kf_ymode(d); + mb.y_mode = ymode.as_u8(); + if ymode == modes::YMode::BPred { + for j in 0..16u8 { + let a = self.above_block_mode(row, col, j, mb); + let l = self.left_block_mode(row, col, j, mb); + mb.b_modes[usize::from(j)] = + modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]).as_u8(); + } + } + mb.uv_mode = modes::read_uvmode(d, &modes::KF_UV_MODE_PROBS).as_u8(); + } + + /// Above subblock mode context (dixie `above_block_mode`): subblocks + /// 0-3 take the above MB's derived mode, inner subblocks the mode + /// `j-4` of this same MB (already decoded into `mb`). + fn above_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { + if j < 4 { + let above = self.mbi(row - 1, col); + if above.y_mode == modes::YMode::BPred.as_u8() { + above.b_modes[usize::from(j) + 12] + } else { + ymode_as_bmode(above.y_mode) + } + } else { + mb.b_modes[usize::from(j) - 4] + } + } + + /// Left subblock mode context (dixie `left_block_mode`). + fn left_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 { + if j % 4 == 0 { + let left = self.mbi(row, col - 1); + if left.y_mode == modes::YMode::BPred.as_u8() { + left.b_modes[usize::from(j) + 3] + } else { + ymode_as_bmode(left.y_mode) + } + } else { + mb.b_modes[usize::from(j) - 1] + } + } + + /// Predict and reconstruct one intra key-frame MB at pixel (x, y). + /// + /// Whole-MB modes predict once from the pre-MB edges and then fold + /// the 24 residual blocks in; B_PRED interleaves: each 4x4 subblock + /// predicts from the reconstructed image (which already carries the + /// earlier subblocks' residuals, §12.3) and is written back before + /// the next subblock is predicted. + fn reconstruct_intra_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) { + let x = col * 16; + let y = row * 16; + let y_mode = mb.y_mode; + let uv_mode = mb.uv_mode; + let b_modes = mb.b_modes; + let have_above = row > 0; + let have_left = col > 0; + + // The Y2 inverse WHT feeds the 16 Y subblock DCs (§14.2). + let y_dcs: [i16; 16] = if coeffs.has_y2 { + transform::iwht4x4(&coeffs.y2) + } else { + [0; 16] + }; + if std::env::var_os("EC_VP8_DEBUG").is_some() { + eprintln!( + "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}", + y_mode, + uv_mode, + coeffs.y2, + coeffs.has_y2, + &coeffs.y[0][..4], + coeffs.eobs[24], + &y_dcs[..4] + ); + } + + if y_mode == modes::YMode::BPred.as_u8() { + for b in 0..16usize { + let bx = (b % 4) * 4; + let by = (b / 4) * 4; + // A row: 4 above pixels then 4 above-right (§12.3); the + // above-right extras are shared by right-edge subblocks + // 3, 7, 11 and 15. + let mut a8 = [0u8; 8]; + let arow = self.y.at_above(x + bx, y + by); + a8[..4].copy_from_slice(&self.y.data[arow..arow + 4]); + if bx + 4 == 16 { + a8[4..].copy_from_slice(&self.above_right(x, y)); + } else { + let ar = self.y.at_above(x + bx + 4, y + by); + a8[4..].copy_from_slice(&self.y.data[ar..ar + 4]); + } + let mut l4 = [0u8; 4]; + for (i, cell) in l4.iter_mut().enumerate() { + *cell = self.y.data[self.y.at_left(x + bx, y + by + i)]; + } + let p = self.y.data[self.y.at_above_left(x + bx, y + by)]; + let mut block = [0u8; 16]; + intra::predict4(b_modes[b], &a8, &l4, p, &mut block); + for i in 0..4 { + let d = self.y.at(x + bx, y + by + i); + self.y.data[d..d + 4].copy_from_slice(&block[i * 4..i * 4 + 4]); + } + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + if c.iter().any(|&v| v != 0) { + let dst = self.y.at(x + bx, y + by); + let stride = self.y.stride; + idct_add_into(&mut self.y.data, &c, &block, 4, 0, dst, stride); + } + } + } else { + // Gather luma edges (border cells carry the 127/129 fills). + let (above, left, above_left) = { + let ay = self.y.at_above(x, y); + let mut a = [0u8; 16]; + let mut l = [0u8; 16]; + a.copy_from_slice(&self.y.data[ay..ay + 16]); + for (i, cell) in l.iter_mut().enumerate() { + *cell = self.y.data[self.y.at_left(x, y + i)]; + } + let al = self.y.data[self.y.at_above_left(x, y)]; + (a, l, al) + }; + let mut pred = [0u8; 256]; + intra::predict16( + y_mode, have_above, have_left, &above, &left, above_left, &mut pred, + ); + for b in 0..16usize { + let bx = (b % 4) * 4; + let by = (b / 4) * 4; + let mut c = coeffs.y[b]; + if coeffs.has_y2 { + c[0] = y_dcs[b]; + } + if c.iter().all(|&v| v == 0) { + for i in 0..4 { + let d = self.y.at(x + bx, y + by + i); + let s = (by + i) * 16 + bx; + self.y.data[d..d + 4].copy_from_slice(&pred[s..s + 4]); + } + } else { + let dst = self.y.at(x + bx, y + by); + let stride = self.y.stride; + idct_add_into(&mut self.y.data, &c, &pred, 16, by * 16 + bx, dst, stride); + } + } + } + + // Chroma: 8x8 prediction then four residual blocks per plane. + let (above_u, left_u, al_u) = self.chroma_edges(col, row, 0); + let (above_v, left_v, al_v) = self.chroma_edges(col, row, 1); + let mut pred_u = [0u8; 64]; + let mut pred_v = [0u8; 64]; + intra::predict8( + uv_mode, + have_above, + have_left, + &above_u, + &left_u, + al_u, + &mut pred_u, + ); + intra::predict8( + uv_mode, + have_above, + have_left, + &above_v, + &left_v, + al_v, + &mut pred_v, + ); + let (cx, cy) = (x / 2, y / 2); + for (plane_data, coeffs_uv, pred8, stride) in [ + (&mut self.u.data, &coeffs.u, &pred_u, self.u.stride), + (&mut self.v.data, &coeffs.v, &pred_v, self.v.stride), + ] { + for b in 0..4usize { + let bx = (b % 2) * 4; + let by = (b / 2) * 4; + let c = coeffs_uv[b]; + let dst = (1 + cy + by) * stride + 1 + cx + bx; + if c.iter().all(|&v| v == 0) { + for i in 0..4 { + let s = (by + i) * 8 + bx; + let d = dst + i * stride; + plane_data[d..d + 4].copy_from_slice(&pred8[s..s + 4]); + } + } else { + idct_add_into(plane_data, &c, pred8, 8, by * 8 + bx, dst, stride); + } + } + } + } + + /// Above-right extras (§12.3): real pixels from the above row, + /// replicated last pixel on the rightmost MB, 127 on the top row. + fn above_right(&self, x: usize, y: usize) -> [u8; 4] { + if y == 0 { + [127; 4] + } else if x + 16 >= self.mb_cols * 16 { + [self.y.data[self.y.at_above(x + 15, y)]; 4] + } else { + let off = self.y.at_above(x + 16, y); + [ + self.y.data[off], + self.y.data[off + 1], + self.y.data[off + 2], + self.y.data[off + 3], + ] + } + } + + fn chroma_edges(&self, col: usize, row: usize, plane: usize) -> ([u8; 8], [u8; 8], u8) { + let p = if plane == 0 { &self.u } else { &self.v }; + let x = col * 8; + let y = row * 8; + let mut a = [0u8; 8]; + let mut l = [0u8; 8]; + let aoff = p.at_above(x, y); + a.copy_from_slice(&p.data[aoff..aoff + 8]); + for (i, cell) in l.iter_mut().enumerate() { + *cell = p.data[p.at_left(x, y + i)]; + } + let al = p.data[p.at_above_left(x, y)]; + (a, l, al) + } + + /// Crop the padded planes to the real frame size. + fn crop(&self) -> Picture { + let w = usize::from(self.dims.width); + let h = usize::from(self.dims.height); + let mut y = Vec::with_capacity(w * h); + for row in 0..h { + let off = self.y.at(0, row); + y.extend_from_slice(&self.y.data[off..off + w]); + } + let (cw, ch) = ((w + 1) / 2, (h + 1) / 2); + let mut u = Vec::with_capacity(cw * ch); + let mut v = Vec::with_capacity(cw * ch); + for row in 0..ch { + let off = self.u.at(0, row); + u.extend_from_slice(&self.u.data[off..off + cw]); + let off = self.v.at(0, row); + v.extend_from_slice(&self.v.data[off..off + cw]); + } + Picture { + y, + u, + v, + width: self.dims.width, + height: self.dims.height, + stride: w, + uv_stride: cw, + } + } +} + +impl Default for Decoder { + fn default() -> Self { + Self::new() + } +} + +/// Segment-map coding tree (RFC 6386 §10): plain two-level split of 0-3. +const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3]; + +fn ymode_as_bmode(y: u8) -> u8 { + match y { + 0 => 0, // DC_PRED -> B_DC_PRED + 1 => 2, // V_PRED -> B_VE_PRED + 2 => 3, // H_PRED -> B_HE_PRED + 3 => 1, // TM_PRED -> B_TM_PRED + _ => unreachable!("non-B_PRED luma mode {y}"), + } +} + +/// Add one 4x4 block's dequantized-coefficient residual to its +/// prediction: reads the prediction patch from `pred`, clamps, writes +/// into the strided plane (§14.4/§14.5). +fn idct_add_into( + plane: &mut [u8], + coeffs: &[i16; 16], + pred: &[u8], + pred_stride: usize, + pred_off: usize, + dst_off: usize, + dst_stride: usize, +) { + let mut p = [0u8; 16]; + for i in 0..4 { + let s = pred_off + i * pred_stride; + p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]); + } + let mut out = [0u8; 16]; + transform::idct4x4_add(coeffs, &p, &mut out); + for i in 0..4 { + let d = dst_off + i * dst_stride; + plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]); + } +} diff --git a/crates/ec-vp8/src/frame.rs b/crates/ec-vp8/src/frame.rs new file mode 100644 index 00000000..7344e491 --- /dev/null +++ b/crates/ec-vp8/src/frame.rs @@ -0,0 +1,102 @@ +//! Frame-level structures and the raw (uncompressed) frame tag +//! (RFC 6386 §9.1). + +use ec_core::{Error, Result}; + +/// Key frame or interframe — the 1-bit frame type from the frame tag. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameType { + /// Key frame (`frame_type` bit 0). + Key, + /// Interframe (`frame_type` bit 1); predicted from earlier frames. + Inter, +} + +/// The 3-byte frame tag every frame starts with (RFC 6386 §9.1 item 1-4): +/// 1 bit type, 3 bits version, 1 bit show_frame, 19 bits first-partition +/// size — all read out of one little-endian 24-bit word. +#[derive(Debug, Clone, Copy)] +pub struct FrameTag { + /// Key or inter frame. + pub frame_type: FrameType, + /// 3-bit version (reconstruction-filter / loop-filter profile; only + /// bits that matter historically — the header's own loop filter fields + /// govern decoding). + pub version: u8, + /// Whether the decoded frame is for display. + pub show_frame: bool, + /// Size in bytes of the first (header/mode) data partition. + pub first_part_size: u32, +} + +/// Bytes occupied by the 3-byte frame tag. +pub const FRAME_TAG_SZ: usize = 3; + +/// Bytes occupied by the key frame's start code + size fields (§9.1). +pub const KEYFRAME_HEADER_SZ: usize = 7; + +impl FrameTag { + /// Parse the tag from the first 3 bytes of a frame. + pub fn parse(data: &[u8]) -> Result { + if data.len() < FRAME_TAG_SZ { + return Err(Error::corrupt("VP8 frame shorter than its 3-byte tag")); + } + let tag = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16); + Ok(FrameTag { + frame_type: if tag & 1 == 0 { + FrameType::Key + } else { + FrameType::Inter + }, + version: ((tag >> 1) & 7) as u8, + show_frame: (tag >> 4) & 1 == 1, + first_part_size: tag >> 5, + }) + } +} + +/// Key-frame dimensions and scaling flags (RFC 6386 §9.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KeyFrameDims { + /// Encoded (pre-scaling) width in pixels, 14 bits. + pub width: u16, + /// Encoded height in pixels, 14 bits. + pub height: u16, + /// 2-bit horizontal scale (0 = none, 1 = 5/4, 2 = 5/3, 3 = 2). + pub h_scale: u8, + /// 2-bit vertical scale. + pub v_scale: u8, +} + +/// Parse the key-frame start code (`9d 01 2a`) and dimensions that follow +/// the frame tag. `data` starts at the frame tag. +pub fn parse_keyframe_dims(data: &[u8]) -> Result { + let dims_off = FRAME_TAG_SZ; + if data.len() < dims_off + KEYFRAME_HEADER_SZ { + return Err(Error::corrupt("VP8 key frame header truncated")); + } + let c = &data[dims_off..]; + if c[0] != 0x9d || c[1] != 0x01 || c[2] != 0x2a { + return Err(Error::corrupt(format!( + "VP8 key frame start code 9d 01 2a not found (got {:02x} {:02x} {:02x})", + c[0], c[1], c[2] + ))); + } + let w = u16::from_le_bytes([c[3], c[4]]); + let h = u16::from_le_bytes([c[5], c[6]]); + Ok(KeyFrameDims { + width: w & 0x3fff, + height: h & 0x3fff, + h_scale: (w >> 14) as u8, + v_scale: (h >> 14) as u8, + }) +} + +/// Number of 16×16 macroblock columns/rows covering `width × height` +/// pixels (the encoded frame is padded up to whole macroblocks). +pub fn mb_geometry(width: u16, height: u16) -> (usize, usize) { + ( + (usize::from(width) + 15) / 16, + (usize::from(height) + 15) / 16, + ) +} diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs new file mode 100644 index 00000000..3ad1d237 --- /dev/null +++ b/crates/ec-vp8/src/header.rs @@ -0,0 +1,475 @@ +//! Uncompressed chunk and first-partition header parsing +//! (RFC 6386 §9-§10, following the reference decoder's field order). +//! +//! Three pieces of state persist across frames until the next key frame +//! resets them: the entropy context (coefficient, MV and intra-mode +//! probabilities), the segmentation feature data and the per-macroblock +//! loop-filter deltas. They live in [`PersistedState`]; every frame's +//! [`FrameHeader::parse`] folds that frame's updates into it. + +use crate::bool::BoolDecoder; +use crate::frame::{FrameTag, FrameType, KEYFRAME_HEADER_SZ, parse_keyframe_dims}; +use crate::tables::{DEFAULT_COEFF_PROBS, DEFAULT_MV_PROBS, MV_UPDATE_PROBS}; +use ec_core::{Error, Result}; + +/// Probability-array length per MV component (dixie `MV_PROB_CNT`): +/// is_short, sign, 7 short-tree, 10 long-bits probabilities. +pub const MV_PROB_CNT: usize = 19; + +/// Everything that survives from frame to frame until a key frame. +#[derive(Debug, Clone)] +pub struct PersistedState { + /// Token-tree probabilities, `[block_type][band][ctx][node]` + /// (RFC 6386 §13.3). + /// Token-tree probabilities `[block_type][band][ctx][node]` (§13.3). + pub coeff_probs: [[[[u8; 11]; 3]; 8]; 4], + /// Per-MV-component probabilities `[component][prob]` (RFC §17.2). + /// Per-MV-component probabilities `[component][prob]` (§17.2). + pub mv_probs: [[u8; MV_PROB_CNT]; 2], + /// Interframe Y-mode tree probabilities (RFC §16.1). + /// Interframe Y-mode tree probabilities (§16.1). + pub ymode_probs: [u8; 4], + /// Interframe chroma-mode tree probabilities (RFC §16.1). + /// Interframe chroma-mode tree probabilities (§16.1). + pub uv_mode_probs: [u8; 3], + /// Segment feature state (RFC §10), zeroed at each key frame. + /// Segment feature state (§10), zeroed at each key frame. + pub segmentation: SegmentationState, + /// Per-MB loop-filter deltas (RFC §9.4), zeroed at each key frame. + /// Reference-frame-based loop-filter deltas (§9.4; intra, last, + /// golden, altref order). + pub ref_lf_delta: [i32; 4], + /// Mode-based loop-filter deltas (§9.4; B_PRED, ZEROMV, MV, + /// SPLITMV order). + pub mode_lf_delta: [i32; 4], +} + +impl Default for PersistedState { + fn default() -> Self { + Self { + coeff_probs: DEFAULT_COEFF_PROBS, + mv_probs: DEFAULT_MV_PROBS, + // Interframe tree defaults (libvpx vp8_ymode_prob / + // vp8_uv_mode_prob); key frames reset these too. + ymode_probs: [112, 86, 140, 37], + uv_mode_probs: [162, 101, 204], + segmentation: SegmentationState::default(), + ref_lf_delta: [0; 4], + mode_lf_delta: [0; 4], + } + } +} + +/// Segment feature state (RFC 6386 §10). `quant_idx`/`lf_level` hold the +/// raw transmitted values; they are absolute in absolute mode and deltas +/// in delta mode. +#[derive(Debug, Clone, Default)] +pub struct SegmentationState { + /// Segment features active for the current frame. + pub enabled: bool, + /// The per-MB segment map is re-coded this frame. + pub update_map: bool, + /// Segment feature values are re-coded this frame. + pub update_data: bool, + /// 0 = absolute values, 1 = deltas against the frame baseline. + /// 0 = absolute values, 1 = deltas against the frame baseline. + pub abs_delta: bool, + /// Per-segment quantizer value or delta (§10). + pub quant_idx: [i32; 4], + /// Per-segment loop-filter level or delta (§10). + pub lf_level: [i32; 4], + /// Segment-map decoding tree probabilities (default 255). + /// Segment-map tree probabilities (default 255; §9.3 item 5). + pub tree_probs: [u8; 3], +} + +/// Frame-level fields parsed from the uncompressed chunk and the first +/// data partition. Everything the per-macroblock decode needs. +#[derive(Debug, Clone)] +pub struct FrameHeader { + /// Parsed 3-byte frame tag. + pub tag: FrameTag, + /// Key-frame dimensions (key frames only). + pub dims: Option, + /// Key-frame-only colour-space bit (0 = YUV; 1 is reserved). + pub color_space: u8, + /// Key-frame-only clamping bit (1 = reconstructed pixels guaranteed + /// 0..255, clamping optional). + pub clamping_type: u8, + /// Segment feature snapshot this frame decodes under. + pub segmentation: SegmentationState, + /// Loop filter type/level/sharpness (§9.4). + /// 0 = normal loop filter, 1 = simple (§9.4). + pub filter_type: u8, + /// Baseline loop filter strength 0-63 (0 disables filtering). + pub filter_level: u8, + /// Loop filter sharpness 0-7 (§9.4, §15.2). + pub sharpness_level: u8, + /// Per-MB loop-filter delta adjustment enabled for this frame. + pub lf_delta_enabled: bool, + /// This frame updated the (persisted) delta values. + pub lf_delta_update: bool, + /// log2 of the token partition count (1, 2, 4 or 8 partitions). + pub log2_partitions: u8, + /// Quantization indices (§9.6): base Y-AC index plus per-plane deltas. + pub quant: QuantIndices, + /// Probability an interframe MB is intra-coded (§9.10 `prob_intra`). + pub prob_intra: u8, + /// Probability an inter MB uses the last-frame reference. + pub prob_last: u8, + /// Probability an inter MB uses the golden rather than altref ref. + pub prob_gf: u8, + /// Whether this frame updated the interframe Y-mode probabilities. + pub ymode_probs_updated: bool, + /// Whether this frame updated the chroma-mode probabilities. + pub uv_mode_probs_updated: bool, + /// Reference-frame refresh/copies/sign-biases (§9.7-§9.8). + pub refresh: RefreshHeader, + /// mb_no_skip_coeff (§9.10/§9.11): per-MB "no non-zero coefficients" + /// flag is coded at all. + pub coeff_skip_enabled: bool, + /// Probability for the per-MB skip flag (meaningful when enabled). + pub prob_skip_false: u8, + /// Offset of the first token partition from the start of `data` + /// (i.e. uncompressed chunk + first partition). + pub token_data_offset: usize, + /// Token partition sizes in bytes; last entry is the remainder. + pub partition_sizes: Vec, +} + +/// Six dequantization indices (§9.6): the always-coded Y-AC index plus +/// signed deltas for the other five factors. +#[derive(Debug, Clone, Copy, Default)] +pub struct QuantIndices { + /// Base quantizer index for Y AC (7 bits). + pub yac_qi: u8, + /// Signed delta applied to the Y-DC dequant index (§9.6). + pub ydc_delta: i32, + /// Signed delta applied to the Y2-DC dequant index (§9.6). + pub y2dc_delta: i32, + /// Signed delta applied to the Y2-AC dequant index (§9.6). + pub y2ac_delta: i32, + /// Signed delta applied to the chroma-DC dequant index (§9.6). + pub uvdc_delta: i32, + /// Signed delta applied to the chroma-AC dequant index (§9.6). + pub uvac_delta: i32, +} + +/// Reference-frame refresh state for one frame (§9.7-§9.8). Key frames +/// refresh every reference and read only `refresh_entropy`. +#[derive(Debug, Clone, Copy)] +pub struct RefreshHeader { + /// The golden buffer is refreshed with the current frame. + pub refresh_gf: bool, + /// The altref buffer is refreshed with the current frame. + pub refresh_arf: bool, + /// 0 = none, 1 = copy last, 2 = copy altref (to golden). + pub copy_gf: u8, + /// 0 = none, 1 = copy last, 2 = copy golden (to altref). + pub copy_arf: u8, + /// Sign bias applied to MVs referencing the golden frame (§9.7). + pub sign_bias_golden: bool, + /// Sign bias applied to MVs referencing the altref frame (§9.7). + pub sign_bias_altref: bool, + /// Whether this frame's entropy updates persist to the next frame. + pub refresh_entropy: bool, + /// The last-frame buffer is refreshed with the current frame. + pub refresh_last: bool, +} + +impl FrameHeader { + /// The frame's type (key or inter), from the frame tag. + pub fn frame_type(&self) -> FrameType { + self.tag.frame_type + } + + /// Parse one frame's uncompressed chunk + first partition from + /// `data`, folding entropy/segmentation/filter-delta updates into + /// `state`. Returns the header and the partition-1 slice. + /// + /// `token_data_offset` + every `partition_sizes[i]` together describe + /// the bytes after partition 1. + pub fn parse<'a>( + data: &'a [u8], + state: &mut PersistedState, + ) -> Result<(FrameHeader, BoolDecoder<'a>)> { + let tag = FrameTag::parse(data)?; + let key = tag.frame_type == FrameType::Key; + let mut off = crate::frame::FRAME_TAG_SZ; + + let mut dims = None; + if key { + let kf = parse_keyframe_dims(data)?; + dims = Some(kf); + off += KEYFRAME_HEADER_SZ; + // A key frame resets every piece of persisted entropy and + // segment/filter state (dixie `decode_frame`). + *state = PersistedState::default(); + } + + let part0_end = off + tag.first_part_size as usize; + if data.len() < part0_end { + return Err(Error::corrupt(format!( + "VP8 first partition extends past end of frame \ + (need {part0_end} bytes, have {})", + data.len() + ))); + } + let mut d = BoolDecoder::new(&data[off..part0_end])?; + + // Colour space + clamping (key frames only): two literal bits; + // the colour-space bit is reserved and must be 0 (dixie reads + // both together and refuses any non-zero pair; we keep the + // (legal) clamping bit decodable and refuse only the reserved + // colour-space one). + let (color_space, clamping_type) = if key { + let cs = d.read_literal(1) as u8; + let clamp = d.read_literal(1) as u8; + if cs != 0 { + return Err(Error::unsupported( + "VP8 reserved colour-space bit", + "bit 0 of the key-frame colour-space pair was set", + )); + } + (cs, clamp) + } else { + (0, 0) + }; + + // --- segmentation (§9.3, dixie decode_segmentation_header) --- + let mut segmentation = if key { + SegmentationState::default() + } else { + state.segmentation.clone() + }; + segmentation.enabled = d.read_bool(128); + if segmentation.enabled { + segmentation.update_map = d.read_bool(128); + segmentation.update_data = d.read_bool(128); + if segmentation.update_data { + segmentation.abs_delta = d.read_bool(128); + for i in 0..4 { + segmentation.quant_idx[i] = d.read_maybe_signed(7); + } + for i in 0..4 { + segmentation.lf_level[i] = d.read_maybe_signed(6); + } + } + if segmentation.update_map { + for i in 0..3 { + segmentation.tree_probs[i] = if d.read_bool(128) { + d.read_literal(8) as u8 + } else { + 255 + }; + } + } + } else { + segmentation.update_map = false; + segmentation.update_data = false; + } + state.segmentation = segmentation.clone(); + + // --- loop filter (§9.4, dixie decode_loopfilter_header) --- + let mut ref_lf_delta = state.ref_lf_delta; + let mut mode_lf_delta = state.mode_lf_delta; + if key { + ref_lf_delta = [0; 4]; + mode_lf_delta = [0; 4]; + } + let filter_type = d.read_literal(1) as u8; + let filter_level = d.read_literal(6) as u8; + let sharpness_level = d.read_literal(3) as u8; + let lf_delta_enabled = d.read_bool(128); + let mut lf_delta_update = false; + if lf_delta_enabled && d.read_bool(128) { + lf_delta_update = true; + for i in 0..4 { + ref_lf_delta[i] = d.read_maybe_signed(6); + } + for i in 0..4 { + mode_lf_delta[i] = d.read_maybe_signed(6); + } + } + state.ref_lf_delta = ref_lf_delta; + state.mode_lf_delta = mode_lf_delta; + + // --- token partitions (§9.5) --- + let log2_partitions = d.read_literal(2) as u8; + let partitions = 1usize << log2_partitions; + let sizes_area = 3 * (partitions - 1); + if data.len() < part0_end + sizes_area { + return Err(Error::corrupt( + "VP8 token partition size table extends past end of frame", + )); + } + let mut partition_sizes = Vec::with_capacity(partitions); + let mut size_off = part0_end; + let mut remaining = (data.len() - part0_end - sizes_area) as u32; + for i in 0..partitions { + if i < partitions - 1 { + let sz = u32::from(data[size_off]) + | (u32::from(data[size_off + 1]) << 8) + | (u32::from(data[size_off + 2]) << 16); + size_off += 3; + partition_sizes.push(sz); + remaining = remaining + .checked_sub(sz) + .ok_or_else(|| Error::corrupt("VP8 token partitions exceed frame size"))?; + } else { + partition_sizes.push(remaining); + } + } + + // --- quantization indices (§9.6) --- + let mut quant = QuantIndices { + yac_qi: d.read_literal(7) as u8, + ..QuantIndices::default() + }; + quant.ydc_delta = d.read_maybe_signed(4); + quant.y2dc_delta = d.read_maybe_signed(4); + quant.y2ac_delta = d.read_maybe_signed(4); + quant.uvdc_delta = d.read_maybe_signed(4); + quant.uvac_delta = d.read_maybe_signed(4); + + // --- reference refresh (§9.7-§9.8) --- + let refresh = if key { + RefreshHeader { + refresh_gf: true, + refresh_arf: true, + copy_gf: 0, + copy_arf: 0, + sign_bias_golden: false, + sign_bias_altref: false, + refresh_entropy: d.read_bool(128), + refresh_last: true, + } + } else { + let refresh_gf = d.read_bool(128); + let refresh_arf = d.read_bool(128); + let copy_gf = if refresh_gf { + 0 + } else { + d.read_literal(2) as u8 + }; + let copy_arf = if refresh_arf { + 0 + } else { + d.read_literal(2) as u8 + }; + RefreshHeader { + refresh_gf, + refresh_arf, + copy_gf, + copy_arf, + sign_bias_golden: d.read_bool(128), + sign_bias_altref: d.read_bool(128), + refresh_entropy: d.read_bool(128), + refresh_last: d.read_bool(128), + } + }; + + // --- entropy updates (§9.9; dixie decode_entropy_header) --- + // Coefficient probability updates are read for every frame; on + // key frames the tables were reset to defaults above. + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for l in 0..11 { + if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) { + state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8; + } + } + } + } + } + + // mb_no_skip_coeff (§9.11 / inter §9.10). + let coeff_skip_enabled = d.read_bool(128); + let prob_skip_false = if coeff_skip_enabled { + d.read_literal(8) as u8 + } else { + 128 + }; + // Interframe-only probability updates. + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("STAGE interprobs"); + } + let mut ymode_probs_updated = false; + let mut uv_mode_probs_updated = false; + let (prob_intra, prob_last, prob_gf) = if !key { + let probs = ( + d.read_literal(8) as u8, + d.read_literal(8) as u8, + d.read_literal(8) as u8, + ); + ymode_probs_updated = d.read_bool(128); + if ymode_probs_updated { + for i in 0..4 { + state.ymode_probs[i] = d.read_literal(8) as u8; + } + } + uv_mode_probs_updated = d.read_bool(128); + if uv_mode_probs_updated { + for i in 0..3 { + state.uv_mode_probs[i] = d.read_literal(8) as u8; + } + } + // MV probability updates: P(7) form, x ? x << 1 : 1 (§17.2). + for c in 0..2 { + for j in 0..MV_PROB_CNT { + if d.read_bool(MV_UPDATE_PROBS[c][j]) { + state.mv_probs[c][j] = d.read_prob7(); + } + } + } + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs); + eprintln!("MVT c0 = {:?}", state.mv_probs[0]); + eprintln!("MVT c1 = {:?}", state.mv_probs[1]); + } + probs + } else { + (112, 86, 140) // placeholders; only read on inter frames + }; + + // The reference decoder zero-fills past the end of a partition; + // tiny partitions (e.g. one-MB key frames) can legitimately + // overrun by a byte or two. Gross overruns are still desyncs. + if d.overreads() > 16 { + return Err(Error::corrupt(format!( + "VP8 first partition over-read by {} bytes (header desync)", + d.overreads() + ))); + } + + let header = FrameHeader { + tag, + dims, + color_space, + clamping_type, + segmentation, + filter_type, + filter_level, + sharpness_level, + lf_delta_enabled, + lf_delta_update, + log2_partitions, + quant, + refresh, + prob_intra, + prob_last, + prob_gf, + ymode_probs_updated, + uv_mode_probs_updated, + coeff_skip_enabled, + prob_skip_false, + token_data_offset: part0_end, + partition_sizes, + }; + let _ = off; + // The partition-0 decoder is returned mid-stream: the per-MB + // mode records continue from exactly where the header stopped. + Ok((header, d)) + } +} diff --git a/crates/ec-vp8/src/intra.rs b/crates/ec-vp8/src/intra.rs new file mode 100644 index 00000000..d2d82021 --- /dev/null +++ b/crates/ec-vp8/src/intra.rs @@ -0,0 +1,711 @@ +//! Intra-frame prediction for VP8 (RFC 6386, Section 12). +//! +//! This module implements the spatial predictors a VP8 decoder applies to +//! intra-coded macroblocks: the 16x16 luma predictors and 8x8 (per-plane) +//! chroma predictors of Section 12.2/12.3, and the ten 4x4 subblock +//! predictors of Section 12.3. All functions are dependency-free, `unsafe`-free, +//! allocate nothing, and are bit-exact against the normative integer math of +//! the RFC code listings (which are in turn identical to the libvpx oracle in +//! `vp8/common/reconintra.c`, `vp8/common/reconintra4x4.c` and +//! `vpx_dsp/intrapred.c`). +//! +//! # Edge-pixel conventions (RFC 6386 Section 12, p.50) +//! +//! Pixels outside the visible frame are pre-filled by the caller: 127 for the +//! row above the top row (including the above-left pixel `P`), 129 for the +//! column left of the leftmost column. V_PRED/H_PRED/TM_PRED consume those +//! fill values directly; DC_PRED instead decides from the availability flags +//! which genuinely-visible pixels to average (RFC Section 12.2, "Note that +//! the averages used in these exceptional cases are not the same as those +//! that would be arrived at by using the out-of-bounds A and L values"). +//! +//! # 4x4 above-right synthesis +//! +//! The 4x4 predictors use an 8-pixel above row `A[0..8]`: the 4 pixels +//! immediately above the subblock plus the 4 "above-right" pixels +//! (frame positions (-1,16)..(-1,19) relative to the macroblock; RFC +//! Section 12.3, subblocks 3/7/11/15). Producing those extra four pixels is +//! the caller's job: for a macroblock not on the top frame row they come from +//! the row above (replicating pixel (-1,15) at the rightmost macroblock of a +//! row); on the top frame row they are 127. [`predict4`] only consumes +//! `A[0..8]` as given. + +#![deny(unsafe_code)] + +/// Weighted average of three adjacent pixels centered at `y` +/// (RFC 6386 Section 12.3 `avg3`: `(x + 2y + z + 2) >> 2`; libvpx `AVG3`). +/// +/// Arguments are valid pixel values, so the result always fits in `u8` and no +/// clamp is needed (RFC Section 12.3, comment above `avg3`). +#[inline] +fn avg3(x: u8, y: u8, z: u8) -> u8 { + ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8 +} + +/// Simple average of two pixels (RFC 6386 Section 12.3 `avg2`: +/// `(x + y + 1) >> 1`; libvpx `AVG2`). +#[inline] +fn avg2(x: u8, y: u8) -> u8 { + ((u32::from(x) + u32::from(y) + 1) >> 1) as u8 +} + +/// `clamp255(v)`: clamp an integer pixel difference into the valid `u8` range +/// (RFC 6386 Section 12.2 `TMpred` / Section 12.3 `B_TM_PRED`). +#[inline] +fn clamp255(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +/// Shared DC/V/H/TM core for the 16x16 luma and 8x8 chroma blocks +/// (RFC 6386 Section 12.2 semantics; Section 12.3 states 16x16 luma is +/// "essentially identical" with 16-pixel edges). +/// +/// DC rounding follows the RFC formula `DCvalue = (sum + (1 << (shf-1))) >> shf` +/// with `shf` = log2 of the number of averaged pixels: 32/16 pixels for the +/// 16x16 both/single-edge cases, 16/8 for 8x8. +fn predict_block( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; N], + left: &[u8; N], + above_left: u8, + out: &mut [u8], +) { + match mode { + // DC_PRED: fill the block with the average of the genuinely visible + // edge pixels; availability flags alone decide which edges count + // (RFC Section 12.2). Neither edge: constant 128. + 0 => { + let sum_above: u32 = above.iter().map(|&p| u32::from(p)).sum(); + let sum_left: u32 = left.iter().map(|&p| u32::from(p)).sum(); + let tz = N.trailing_zeros(); // log2(N) + let v: u32 = match (have_above, have_left) { + (true, true) => (sum_above + sum_left + N as u32) >> (tz + 1), + (false, false) => 128, + // Above available only: average the above row. + (true, false) => (sum_above + (N as u32 >> 1)) >> tz, + // Left column available only: average the left column. + (false, true) => (sum_left + (N as u32 >> 1)) >> tz, + }; + out.fill(v as u8); + } + // V_PRED: every row is a copy of the above row A (RFC Section 12.2). + 1 => { + for row in out.chunks_exact_mut(N) { + row.copy_from_slice(above); + } + } + // H_PRED: every column is a copy of the left column L (RFC Section 12.2). + 2 => { + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { + row.fill(l); + } + } + // TM_PRED: X_ij = clamp255(L_i + A_j - P) (RFC Section 12.2 `TMpred`). + // Unlike DC_PRED this mode does use the 127/129 out-of-bounds fills. + 3 => { + for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) { + for (o, &a) in row.iter_mut().zip(above.iter()) { + *o = clamp255(i32::from(l) + i32::from(a) - i32::from(above_left)); + } + } + } + _ => panic!("predict_block: invalid intra mode {mode} (expected 0..=3)"), + } +} + +/// 16x16 luma prediction (RFC 6386 Section 12.3; predictor math per +/// Section 12.2). +/// +/// `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. `above` holds the 16 +/// reconstructed pixels of the row above the macroblock, `left` the 16 pixels +/// of the column to its left (adjacent entries separated by one frame row), +/// `above_left` is the corner pixel `P`. `have_above`/`have_left` state +/// whether those edges are genuinely in-frame. +/// +/// For DC the flags alone decide what is averaged (the out-of-bounds fills +/// are NOT used); V/H/TM consume the caller-prepared out-of-bounds fills +/// (127 above/`above_left` on the top frame row, 129 on the left frame +/// column) written into `above`/`left`/`above_left`. +/// +/// `out` receives 256 row-major prediction pixels. +pub fn predict16( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; 16], + left: &[u8; 16], + above_left: u8, + out: &mut [u8; 256], +) { + predict_block::<16>(mode, have_above, have_left, above, left, above_left, out); +} + +/// 8x8 chroma prediction for one plane (RFC 6386 Section 12.2). +/// +/// Identical semantics to [`predict16`] with 8-pixel edges; call it once for +/// U and once for V. `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. DC averages +/// 16 pixels (both edges: `(sumA + sumL + 8) >> 4`) or 8 pixels (one edge: +/// `(sum + 4) >> 3`), or fills 128. +/// +/// `out` receives 64 row-major prediction pixels. +pub fn predict8( + mode: u8, + have_above: bool, + have_left: bool, + above: &[u8; 8], + left: &[u8; 8], + above_left: u8, + out: &mut [u8; 64], +) { + predict_block::<8>(mode, have_above, have_left, above, left, above_left, out); +} + +/// 4x4 subblock prediction (RFC 6386 Section 12.3 `subblock_intra_predict`). +/// +/// `mode` is a BMode integer: `0=B_DC 1=B_TM 2=B_VE 3=B_HE 4=B_LD 5=B_RD +/// 6=B_VR 7=B_VL 8=B_HD 9=B_HU`. `above` is the 8-pixel row `A[0..8]` +/// (4 above + 4 above-right; see the [module docs](self) for the caller-side +/// synthesis rule), `left` is `L[0..4]`, `above_left` is `P = A[-1] = L[-1]`. +/// +/// Both edges are always considered present for subblocks: the caller +/// pre-fills out-of-bounds pixels (127 above including P, 129 left) before +/// the call, which is why no availability flags exist here. +/// +/// `out` receives 16 row-major prediction pixels. +/// +/// # RFC typo +/// +/// The RFC listing for `B_HD_PRED` contains the line +/// `B[2][0] = B[3][2] = svg2p(E + 1)`; `svg2p` is a typo for `avg2p` (there +/// is no `svg2p` definition; libvpx's `d153_predictor` computes `AVG2(K, J)` +/// there, confirming the correction implemented here). +pub fn predict4(mode: u8, above: &[u8; 8], left: &[u8; 4], above_left: u8, out: &mut [u8; 16]) { + // The 9 already-constructed edge pixels in RFC scan order: + // E[0..4] = L[3], L[2], L[1], L[0]; E[4] = P; E[5..9] = A[0..4]. + let e: [u8; 9] = [ + left[3], left[2], left[1], left[0], above_left, above[0], above[1], above[2], above[3], + ]; + // Row-major B[r][c] = b[r * 4 + c]. + let mut b = [0u8; 16]; + // avg3p(E + k) = avg3(E[k-1], E[k], E[k+1]); avg2p(E + k) = avg2(E[k], E[k+1]). + match mode { + // B_DC_PRED: DC value = (sum(A[0..4]) + sum(L[0..4]) + 4) >> 3. + 0 => { + let mut v: u32 = 4; + for i in 0..4 { + v += u32::from(above[i]) + u32::from(left[i]); + } + v >>= 3; + b.fill(v as u8); + } + // B_TM_PRED: just like 16x16 TM_PRED (RFC Section 12.3). + 1 => { + for r in 0..4 { + for c in 0..4 { + b[r * 4 + c] = + clamp255(i32::from(left[r]) + i32::from(above[c]) - i32::from(above_left)); + } + } + } + // B_VE_PRED: all four rows = smoothed top row avg3p(A + c), where + // A[-1] = P participates in column 0 (libvpx `vpx_ve_predictor_4x4`). + 2 => { + for c in 0..4usize { + let v = if c == 0 { + avg3(above_left, above[0], above[1]) + } else { + avg3(above[c - 1], above[c], above[c + 1]) + }; + b[c] = v; + b[4 + c] = v; + b[8 + c] = v; + b[12 + c] = v; + } + } + // B_HE_PRED: columns = smoothed left column; bottom row exceptional + // because L[4] does not exist: avg3(L[2], L[3], L[3]). + 3 => { + let rows = [ + avg3(above_left, left[0], left[1]), + avg3(left[0], left[1], left[2]), + avg3(left[1], left[2], left[3]), + avg3(left[2], left[3], left[3]), + ]; + for (r, &v) in rows.iter().enumerate() { + b[r * 4..r * 4 + 4].fill(v); + } + } + // B_LD_PRED: southwest (left and down) 45-degree diagonals off the + // above row; B[3][3] uses avg3(A[6], A[7], A[7]) because A[8] does + // not exist (libvpx `d45e_predictor_4x4`). + 4 => { + b[0] = avg3(above[0], above[1], above[2]); + b[1] = avg3(above[1], above[2], above[3]); + b[4] = b[1]; + b[2] = avg3(above[2], above[3], above[4]); + b[5] = b[2]; + b[8] = b[2]; + b[3] = avg3(above[3], above[4], above[5]); + b[6] = b[3]; + b[9] = b[3]; + b[12] = b[3]; + b[7] = avg3(above[4], above[5], above[6]); + b[10] = b[7]; + b[13] = b[7]; + b[11] = avg3(above[5], above[6], above[7]); + b[14] = b[11]; + b[15] = avg3(above[6], above[7], above[7]); + } + // B_RD_PRED: southeast 45-degree diagonals off the whole E edge + // (libvpx `d135_predictor_4x4`). + 5 => { + b[12] = avg3(e[0], e[1], e[2]); + b[13] = avg3(e[1], e[2], e[3]); + b[8] = b[13]; + b[14] = avg3(e[2], e[3], e[4]); + b[9] = b[14]; + b[4] = b[14]; + b[15] = avg3(e[3], e[4], e[5]); + b[10] = b[15]; + b[5] = b[15]; + b[0] = b[15]; + b[11] = avg3(e[4], e[5], e[6]); + b[6] = b[11]; + b[1] = b[11]; + b[7] = avg3(e[5], e[6], e[7]); + b[2] = b[7]; + b[3] = avg3(e[6], e[7], e[8]); + } + // B_VR_PRED: vertical-right diagonals mixing avg3/avg2 along E + // (libvpx `d117_predictor_4x4`). + 6 => { + b[12] = avg3(e[1], e[2], e[3]); + b[8] = avg3(e[2], e[3], e[4]); + b[13] = avg3(e[3], e[4], e[5]); + b[4] = b[13]; + b[9] = avg2(e[4], e[5]); + b[0] = b[9]; + b[14] = avg3(e[4], e[5], e[6]); + b[5] = b[14]; + b[10] = avg2(e[5], e[6]); + b[1] = b[10]; + b[15] = avg3(e[5], e[6], e[7]); + b[6] = b[15]; + b[11] = avg2(e[6], e[7]); + b[2] = b[11]; + b[7] = avg3(e[6], e[7], e[8]); + b[3] = avg2(e[7], e[8]); + } + // B_VL_PRED: vertical-left diagonals off the above row; the last two + // values do not strictly follow the pattern (RFC Section 12.3; + // libvpx `d63e_predictor_4x4`). + 7 => { + b[0] = avg2(above[0], above[1]); + b[4] = avg3(above[0], above[1], above[2]); + b[8] = avg2(above[1], above[2]); + b[1] = b[8]; + b[5] = avg3(above[1], above[2], above[3]); + b[12] = b[5]; + b[9] = avg2(above[2], above[3]); + b[2] = b[9]; + b[13] = avg3(above[2], above[3], above[4]); + b[6] = b[13]; + b[10] = avg2(above[3], above[4]); + b[3] = b[10]; + b[14] = avg3(above[3], above[4], above[5]); + b[7] = b[14]; + b[11] = avg3(above[4], above[5], above[6]); + b[15] = avg3(above[5], above[6], above[7]); + } + // B_HD_PRED: horizontal-down diagonals; the RFC's `svg2p(E + 1)` is + // the avg2p correction noted in this function's docs (libvpx + // `d153_predictor_4x4`). + 8 => { + b[12] = avg2(e[0], e[1]); + b[13] = avg3(e[0], e[1], e[2]); + b[8] = avg2(e[1], e[2]); // corrected svg2p -> avg2p line + b[14] = b[8]; + b[9] = avg3(e[1], e[2], e[3]); + b[15] = b[9]; + b[10] = avg2(e[2], e[3]); + b[4] = b[10]; + b[11] = avg3(e[2], e[3], e[4]); + b[5] = b[11]; + b[6] = avg2(e[3], e[4]); + b[0] = b[6]; + b[7] = avg3(e[3], e[4], e[5]); + b[1] = b[7]; + b[2] = avg3(e[4], e[5], e[6]); + b[3] = avg3(e[5], e[6], e[7]); + } + // B_HU_PRED: horizontal-up diagonals off the left column; the bottom + // rows cannot follow the pattern and collapse to L[3] (RFC + // Section 12.3; libvpx `d207_predictor_4x4`). + 9 => { + b[0] = avg2(left[0], left[1]); + b[1] = avg3(left[0], left[1], left[2]); + b[2] = avg2(left[1], left[2]); + b[4] = b[2]; + b[3] = avg3(left[1], left[2], left[3]); + b[5] = b[3]; + b[6] = avg2(left[2], left[3]); + b[8] = b[6]; + b[7] = avg3(left[2], left[3], left[3]); + b[9] = b[7]; + let v = left[3]; + b[10] = v; + b[11] = v; + b[12] = v; + b[13] = v; + b[14] = v; + b[15] = v; + } + _ => panic!("predict4: invalid intra 4x4 mode {mode} (expected 0..=9)"), + } + out.copy_from_slice(&b); +} + +#[cfg(test)] +mod tests { + use super::*; + + // ---------------------------------------------------------------- -- + // Reference model used to derive the expected vectors below. It is a + // verbatim Python transcription of RFC 6386 Section 12.3 + // subblock_intra_predict (with svg2p corrected to avg2p); outputs were + // generated with it and then hand-spot-checked: + // + // def avg2(x, y): return (x + y + 1) >> 1 + // def avg3(x, y, z): return (x + 2*y + z + 2) >> 2 + // def clamp255(v): return max(0, min(255, v)) + // # A = A[0..8], L = L[0..4], P = above-left + // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]] + // B_DC: v = (4 + sum(A[0:4]) + sum(L[0:4])) >> 3 + // B_TM: B[r][c] = clamp255(L[r] + A[c] - P) + // B_VE: col c: avg3(P, A0, A1) then avg3(A[c-1], A[c], A[c+1]) + // B_HE: rows avg3(P, L0, L1), avg3(L0, L1, L2), avg3(L1, L2, L3), + // avg3(L2, L3, L3) + // B_LD: B[0][0]=avg3(A0,A1,A2); B[0][1]=B[1][0]=avg3(A1,A2,A3); ... + // B[3][3]=avg3(A6,A7,A7) + // B_RD: B[3][0]=avg3(E0,E1,E2); B[3][1]=B[2][0]=avg3(E1,E2,E3); + // B[3][2]=B[2][1]=B[1][0]=avg3(E2,E3,E4); + // diag=avg3(E3,E4,E5); ...; B[0][3]=avg3(E6,E7,E8) + // B_VR: B[3][0]=avg3(E1,E2,E3); B[2][0]=avg3(E2,E3,E4); + // B[3][1]=B[1][0]=avg3(E3,E4,E5); B[2][1]=B[0][0]=avg2(E4,E5); + // B[3][2]=B[1][1]=avg3(E4,E5,E6); B[2][2]=B[0][1]=avg2(E5,E6); + // B[3][3]=B[1][2]=avg3(E5,E6,E7); B[2][3]=B[0][2]=avg2(E6,E7); + // B[1][3]=avg3(E6,E7,E8); B[0][3]=avg2(E7,E8) + // B_VL: B[0][0]=avg2(A0,A1); B[1][0]=avg3(A0,A1,A2); + // B[2][0]=B[0][1]=avg2(A1,A2); B[1][1]=B[3][0]=avg3(A1,A2,A3); + // B[2][1]=B[0][2]=avg2(A2,A3); B[3][1]=B[1][2]=avg3(A2,A3,A4); + // B[2][2]=B[0][3]=avg2(A3,A4); B[3][2]=B[1][3]=avg3(A3,A4,A5); + // B[2][3]=avg3(A4,A5,A6); B[3][3]=avg3(A5,A6,A7) + // B_HD: B[3][0]=avg2(E0,E1); B[3][1]=avg3(E0,E1,E2); + // B[2][0]=B[3][2]=avg2(E1,E2) <- svg2p typo corrected + // B[2][1]=B[3][3]=avg3(E1,E2,E3); + // B[2][2]=B[1][0]=avg2(E2,E3); + // B[2][3]=B[1][1]=avg3(E2,E3,E4); + // B[1][2]=B[0][0]=avg2(E3,E4); + // B[1][3]=B[0][1]=avg3(E3,E4,E5); + // B[0][2]=avg3(E4,E5,E6); B[0][3]=avg3(E5,E6,E7) + // B_HU: B[0][0]=avg2(L0,L1); B[0][1]=avg3(L0,L1,L2); + // B[0][2]=B[1][0]=avg2(L1,L2); B[0][3]=B[1][1]=avg3(L1,L2,L3); + // B[1][2]=B[2][0]=avg2(L2,L3); + // B[1][3]=B[2][1]=avg3(L2,L3,L3); + // B[2][2..4]=B[3][0..4]=L3 + // ---------------------------------------------------------------- -- + + /// Fixed edge pattern shared by all ten subblock tests: + /// above = [10,20,30,40,50,60,70,80], left = [15,25,35,45], P = 5. + const EDGE_A: [u8; 8] = [10, 20, 30, 40, 50, 60, 70, 80]; + const EDGE_L: [u8; 4] = [15, 25, 35, 45]; + const EDGE_P: u8 = 5; + + fn assert_pred4(mode: u8, expected: [u8; 16]) { + let mut out = [0u8; 16]; + predict4(mode, &EDGE_A, &EDGE_L, EDGE_P, &mut out); + assert_eq!(out, expected, "predict4 mode {mode}"); + } + + #[test] + fn subblock_dc_constant() { + // v = (4 + (10+20+30+40) + (15+25+35+45)) >> 3 = (4+100+120)>>3 = 28. + assert_pred4(0, [28; 16]); + } + + #[test] + fn subblock_tm_gradient() { + // B[r][c] = L[r] + A[c] - P = L[r] + A[c] - 5. + assert_pred4( + 1, + [ + 20, 30, 40, 50, // row 0: 15 + A[c] - 5 + 30, 40, 50, 60, // row 1: 25 + A[c] - 5 + 40, 50, 60, 70, // row 2 + 50, 60, 70, 80, // row 3 + ], + ); + } + + #[test] + fn subblock_ve_smoothed_row() { + // Row = avg3(A[c-1], A[c], A[c+1]) with A[-1] = P: + // avg3(5,10,20)=11, avg3(10,20,30)=20, avg3(20,30,40)=30, + // avg3(30,40,50)=40. + let row = [11, 20, 30, 40]; + let mut expected = [0u8; 16]; + for r in 0..4 { + expected[r * 4..r * 4 + 4].copy_from_slice(&row); + } + assert_pred4(2, expected); + } + + #[test] + fn subblock_he_smoothed_column() { + // Rows: avg3(5,15,25)=15, avg3(15,25,35)=25, avg3(25,35,45)=35, + // avg3(35,45,45)=43 (bottom-row exception, L[4] absent). + assert_pred4( + 3, + [ + 15, 15, 15, 15, 25, 25, 25, 25, 35, 35, 35, 35, 43, 43, 43, 43, + ], + ); + } + + #[test] + fn subblock_ld_downright_diagonal() { + // B[3][3] = avg3(70,80,80) = (70 + 160 + 80 + 2) >> 2 = 78 (A[8] + // does not exist). + assert_pred4( + 4, + [ + 20, 30, 40, 50, // avg3(10,20,30)=20, avg3(20,30,40)=30, ... + 30, 40, 50, 60, // + 40, 50, 60, 70, // + 50, 60, 70, 78, // + ], + ); + } + + #[test] + fn subblock_rd_downright_diagonal() { + // E = [45,35,25,15,5,10,20,30,40]. + // B[3][0] = avg3(45,35,25) = 35; B[3][1]=B[2][0] = avg3(35,25,15) = 25; + // B[3][2]=B[2][1]=B[1][0] = avg3(25,15,5) = 15; + // main diagonal = avg3(15,5,10) = 9; B[2][3]=B[1][2]=B[0][1] = + // avg3(5,10,20) = 11; B[1][3]=B[0][2] = avg3(10,20,30) = 20; + // B[0][3] = avg3(20,30,40) = 30. + assert_pred4( + 5, + [ + 9, 11, 20, 30, // + 15, 9, 11, 20, // + 25, 15, 9, 11, // + 35, 25, 15, 9, // + ], + ); + } + + #[test] + fn subblock_vr_mixed_diagonal() { + // E = [45,35,25,15,5,10,20,30,40]. + // B[0][0] = avg2(E4,E5) = avg2(5,10) = 8; + // B[0][1] = avg2(10,20) = 15; B[0][2] = avg2(20,30) = 25; + // B[0][3] = avg2(30,40) = 35; B[1][0] = avg3(15,5,10) = 9; + // B[1][1] = avg3(5,10,20) = 11; B[1][2] = avg3(10,20,30) = 20; + // B[1][3] = avg3(20,30,40) = 30; B[2][0] = avg3(25,15,5) = 15; + // B[2][1] = 8; B[2][2] = 15; B[2][3] = 25; + // B[3][0] = avg3(35,25,15) = 25; B[3][1] = 9; B[3][2] = 11; B[3][3] = 20. + assert_pred4( + 6, + [ + 8, 15, 25, 35, // + 9, 11, 20, 30, // + 15, 8, 15, 25, // + 25, 9, 11, 20, // + ], + ); + } + + #[test] + fn subblock_vl_downleft_diagonal() { + // avg2/avg3 pairs along the above row: + // cols: avg2(10,20)=15, avg2(20,30)=25, avg2(30,40)=35, avg2(40,50)=45; + // rows shift by avg3: 20, 30, 40, 50; last column 45/50/60/70 with + // B[2][3]=avg3(50,60,70)=60, B[3][3]=avg3(60,70,80)=70. + assert_pred4( + 7, + [ + 15, 25, 35, 45, // + 20, 30, 40, 50, // + 25, 35, 45, 60, // + 30, 40, 50, 70, // + ], + ); + } + + #[test] + fn subblock_hd_uses_avg2p_for_svg2p_typo_line() { + // E = [45,35,25,15,5,10,20,30,40]. + // The RFC's `svg2p(E + 1)` line: B[2][0] = B[3][2] = avg2p(E+1) = + // avg2(E[1], E[2]) = avg2(35,25) = 30. A mis-transcription (any + // avg3-style or E-shifted variant) would not yield 30 here. + // B[3][0] = avg2(45,35) = 40; B[3][1] = avg3(45,35,25) = 35; + // B[2][1]=B[3][3] = avg3(35,25,15) = 25; B[2][2]=B[1][0] = + // avg2(25,15) = 20; B[2][3]=B[1][1] = avg3(25,15,5) = 15; + // B[1][2]=B[0][0] = avg2(15,5) = 10; B[1][3]=B[0][1] = + // avg3(15,5,10) = 9; B[0][2] = avg3(5,10,20) = 11; + // B[0][3] = avg3(10,20,30) = 20. + assert_pred4( + 8, + [ + 10, 9, 11, 20, // + 20, 15, 10, 9, // + 30, 25, 20, 15, // + 40, 35, 30, 25, // + ], + ); + // Directly pin the corrected-typo cells. + let mut out = [0u8; 16]; + predict4(8, &EDGE_A, &EDGE_L, EDGE_P, &mut out); + assert_eq!( + (out[8], out[14]), + (30, 30), + "B[2][0] and B[3][2] = avg2(E1,E2)" + ); + } + + #[test] + fn subblock_hu_up_diagonal() { + // B[0][0] = avg2(15,25) = 20; B[0][1] = avg3(15,25,35) = 25; + // B[0][2]=B[1][0] = avg2(25,35) = 30; B[0][3]=B[1][1] = + // avg3(25,35,45) = 35; B[1][2]=B[2][0] = avg2(35,45) = 40; + // B[1][3]=B[2][1] = avg3(35,45,45) = 43; bottom rows = L[3] = 45. + assert_pred4( + 9, + [ + 20, 25, 30, 35, // + 30, 35, 40, 43, // + 40, 43, 45, 45, // + 45, 45, 45, 45, // + ], + ); + } + + #[test] + fn dc16_all_availability_cases() { + // above = [10; 16] (sum 160), left = [20; 16] (sum 320). + let above = [10u8; 16]; + let left = [20u8; 16]; + let mut out = [0u8; 256]; + + // Both edges: (160 + 320 + 16) >> 5 = 15. + predict16(0, true, true, &above, &left, 5, &mut out); + assert_eq!(out, [15; 256]); + + // Neither edge (top-left macroblock): constant 128. The array + // contents are irrelevant here; availability flags decide. + predict16(0, false, false, &above, &left, 5, &mut out); + assert_eq!(out, [128; 256]); + + // Above only (left frame column): (160 + 8) >> 4 = 10. + predict16(0, true, false, &above, &left, 5, &mut out); + assert_eq!(out, [10; 256]); + + // Left only (top frame row): (320 + 8) >> 4 = 20. + predict16(0, false, true, &above, &left, 5, &mut out); + assert_eq!(out, [20; 256]); + } + + #[test] + fn dc8_all_availability_cases() { + // above = [10; 8] (sum 80), left = [20; 8] (sum 160). + let above = [10u8; 8]; + let left = [20u8; 8]; + let mut out = [0u8; 64]; + + // Both: (80 + 160 + 8) >> 4 = 15. + predict8(0, true, true, &above, &left, 5, &mut out); + assert_eq!(out, [15; 64]); + + // Neither: 128. + predict8(0, false, false, &above, &left, 5, &mut out); + assert_eq!(out, [128; 64]); + + // Above only: (80 + 4) >> 3 = 10. + predict8(0, true, false, &above, &left, 5, &mut out); + assert_eq!(out, [10; 64]); + + // Left only: (160 + 4) >> 3 = 20. + predict8(0, false, true, &above, &left, 5, &mut out); + assert_eq!(out, [20; 64]); + } + + #[test] + fn tm16_clamps_both_directions() { + let mut out = [0u8; 256]; + + // Negative difference clamps to 0: P high (250), L and A low (0) + // gives L + A - P = -250 everywhere. + predict16(3, true, true, &[0u8; 16], &[0u8; 16], 250, &mut out); + assert_eq!(out, [0; 256]); + + // Overflow clamps to 255: P = 0, L = A = 255 gives 510 everywhere. + predict16(3, true, true, &[255u8; 16], &[255u8; 16], 0, &mut out); + assert_eq!(out, [255; 256]); + + // Exact in-range gradient: out[r][c] = 200 + c - 50 = 150 + c, + // no clamping, verifies arithmetic (not just the clamps). + let above: [u8; 16] = core::array::from_fn(|i| i as u8); + predict16(3, true, true, &above, &[200u8; 16], 50, &mut out); + for r in 0..16 { + let row: [u8; 16] = core::array::from_fn(|c| (150 + c) as u8); + assert_eq!(out[r * 16..r * 16 + 16], row, "TM16 row {r}"); + } + } + + #[test] + fn tm4_clamps_via_predict4() { + // Same clamp contract at 4x4 (RFC B_TM_PRED == clamp255(L + A - P)). + let mut out = [0u8; 16]; + predict4(1, &[0u8; 8], &[0u8; 4], 250, &mut out); + assert_eq!(out, [0; 16]); + predict4(1, &[255u8; 8], &[255u8; 4], 0, &mut out); + assert_eq!(out, [255; 16]); + } + + #[test] + fn v_and_h_copy_edges() { + // V_PRED: every 16x16 row equals the above row. + let above: [u8; 16] = core::array::from_fn(|i| (i * 7 + 3) as u8); + let mut out = [0u8; 256]; + predict16(1, true, true, &above, &[0u8; 16], 0, &mut out); + for row in out.chunks_exact(16) { + assert_eq!(row, above); + } + + // H_PRED: every 8x8 row is the constant left[r]. + let left: [u8; 8] = core::array::from_fn(|i| (i * 11 + 1) as u8); + let mut out8 = [0u8; 64]; + predict8(2, true, true, &[0u8; 8], &left, 0, &mut out8); + for (r, row) in out8.chunks_exact(8).enumerate() { + assert_eq!(row, [left[r]; 8]); + } + } + + #[test] + #[should_panic(expected = "invalid intra mode")] + fn predict16_rejects_invalid_mode() { + let mut out = [0u8; 256]; + predict16(4, true, true, &[0u8; 16], &[0u8; 16], 0, &mut out); + } + + #[test] + #[should_panic(expected = "invalid intra 4x4 mode")] + fn predict4_rejects_invalid_mode() { + let mut out = [0u8; 16]; + predict4(10, &[0u8; 8], &[0u8; 4], 0, &mut out); + } +} diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs new file mode 100644 index 00000000..051e93a7 --- /dev/null +++ b/crates/ec-vp8/src/lib.rs @@ -0,0 +1,31 @@ +//! Native VP8 (RFC 6386) decoder — the future replacement for edith's +//! runtime-dlopen'd libvpx seat. +//! +//! The crate is written from the specification ([RFC 6386]) alone; libvpx's +//! output is used only as a test oracle (sample-exactness witnesses), never +//! as code to port. Every module documents the spec section it implements. +//! +//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386 +//! +//! # Unsafe +//! +//! This crate contains no `unsafe` code. + +#![deny(unsafe_code)] +#![warn(missing_docs)] + +pub mod bool; +pub mod decode; +pub mod frame; +pub mod header; +pub mod intra; +pub mod loopfilter; +mod mc; +pub mod modes; +pub mod stream; +pub mod tables; +pub mod tokens; +pub mod transform; + +pub use ec_core::{Error, Result}; +pub use header::PersistedState; diff --git a/crates/ec-vp8/src/loopfilter.rs b/crates/ec-vp8/src/loopfilter.rs new file mode 100644 index 00000000..2039fc19 --- /dev/null +++ b/crates/ec-vp8/src/loopfilter.rs @@ -0,0 +1,1064 @@ +//! VP8 in-loop deblocking filter — RFC 6386 Section 15. +//! +//! Implements the *normal* filter (§15.3), the *simple* filter (§15.2), the +//! per-frame macroblock-edge driver in the reference decoder's exact visit +//! order, and the per-sharpness limit-table construction of §15.4. +//! +//! The arithmetic is transcribed line-for-line from the normative reference +//! sources and is bit-identical between them (verified term-by-term): +//! +//! * `dixie_loopfilter.c` shipped with RFC 6386 (§20.6) — kernels +//! (`filter_common`, `filter_mb_edge`, thresholds) and the +//! `filter_row_normal` / `filter_row_simple` drivers, +//! * libvpx `vp8/common/loopfilter_filters.c` — the same kernels as +//! branch-free C, and `vp8/common/vp8_loopfilter.c` +//! (`vp8_loop_filter_update_sharpness`, `lf_init_lut`) — the limit and +//! high-edge-variance tables. +//! +//! C signed right-shifts are arithmetic (floor); Rust `i32 >>` has the same +//! semantics, so every `>>` below reproduces the C rounding exactly. No +//! allocation, no `unsafe`. +//! +//! Frame-type note: §15.4 (and libvpx `lf_init_lut`) makes `hev_threshold` +//! depend on whether the current frame is a key frame. [`filter_frame`] +//! keeps the crate-contract signature and applies the *inter-frame* table; +//! call [`filter_frame_ex`] with the decoded `is_keyframe` flag for fully +//! type-exact decoding (the two differ only for levels ≥ 15). + +/// Per-macroblock filter inputs the decoder derives from the frame header, +/// segmentation map and per-MB prediction info. +/// +/// `level` is the *final* per-MB loop filter level (0..=63) after the +/// segment and ref/mode delta adjustments of RFC 6386 §15.4 (implemented +/// decoder-side in `decode.rs`, mirroring dixie `calculate_filter_parameters`). +/// A level of 0 disables all filtering of that macroblock (dixie: +/// `if (edge_limit) { ... }`). +/// +/// `inner_edges` controls whether the subblock (interior) edges of the MB +/// are filtered: true iff the MB has any non-zero DCT coefficient or its +/// mode is `B_PRED`/`SPLITMV` (RFC §15.1; dixie's `eob_mask` condition, +/// `filter_row_normal` ~L9308 and `filter_row_simple` ~L9433). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MbFilterInfo { + /// Effective per-MB loop filter level after segment and ref/mode delta + /// adjustments, clamped to 0..=63. + pub level: u8, + /// Filter interior (subblock) edges of this MB (any non-zero DCT + /// coefficient, or `B_PRED`/`SPLITMV` mode). + pub inner_edges: bool, +} + +/// Per-sharpness limit tables for levels 0..=63, in the order +/// `lim` / `blim` / `mblim` of libvpx `loop_filter_info_n`. +/// +/// These are the combined edge limits of RFC §15.4: +/// `mblim[l] = (l + 2) * 2 + interior_limit(l)` (macroblock edges), +/// `blim[l] = l * 2 + interior_limit(l)` (subblock edges), and +/// `lim[l] = interior_limit(l)`. Both filter variants consume these exact +/// combined values (the simple filter directly, as dixie +/// `filter_v_edge_simple` does; the normal filter splits them back into +/// center + interior tests). +#[derive(Clone, Copy, Debug)] +pub struct LoopFilterTables { + /// Interior-difference limit per level (dixie `interior_limit`). + pub lim: [u8; 64], + /// Combined subblock-edge center limit per level (dixie `b_limit`). + pub blim: [u8; 64], + /// Combined macroblock-edge center limit per level (dixie `mb_limit`). + pub mblim: [u8; 64], +} + +impl LoopFilterTables { + /// Build the three limit tables for one frame's sharpness level. + /// + /// Port of libvpx `vp8_loop_filter_update_sharpness` + /// (vp8/common/vp8_loopfilter.c), which matches the RFC §15.4 + /// pseudocode: + /// + /// ```text + /// inside = level >> (sharpness > 0) >> (sharpness > 4) + /// if sharpness > 0 and inside > 9 - sharpness: inside = 9 - sharpness + /// inside = max(inside, 1) + /// ``` + pub fn update_sharpness(sharpness: u8) -> Self { + let s = i32::from(sharpness); + let mut t = LoopFilterTables { + lim: [0; 64], + blim: [0; 64], + mblim: [0; 64], + }; + for (lvl, slot) in t.lim.iter_mut().enumerate() { + let filt_lvl = lvl as i32; + // libvpx L59-60: two conditional single-bit shifts. + let mut inside = filt_lvl; + if s > 0 { + inside >>= 1; + } + if s > 4 { + inside >>= 1; + } + // libvpx L62-66: cap only applies when sharpness > 0. + if s > 0 && inside > 9 - s { + inside = 9 - s; + } + if inside < 1 { + inside = 1; + } + *slot = inside as u8; + t.blim[lvl] = (2 * filt_lvl + inside) as u8; + t.mblim[lvl] = (2 * (filt_lvl + 2) + inside) as u8; + } + t + } +} + +/// Interior-difference limit for one level/sharpness pair (RFC §15.4). +/// +/// Same derivation as [`LoopFilterTables::update_sharpness`] for a single +/// level; provided for callers that need the value without the tables. +pub fn interior_limit(level: u8, sharpness: u8) -> i32 { + let s = i32::from(sharpness); + let mut il = i32::from(level); + if s > 0 { + // dixie: interior_limit >>= sharpness > 4 ? 2 : 1 — the two + // conditional single-bit shifts of update_sharpness folded. + il >>= if s > 4 { 2 } else { 1 }; + if il > 9 - s { + il = 9 - s; + } + } + if il < 1 { + il = 1; + } + il +} + +/// High-edge-variance threshold for one level (RFC §15.4, last block; also +/// libvpx `lf_init_lut`'s `hev_thr_lut[KEY_FRAME|INTER_FRAME]`). +/// +/// Key frames: 2 at level ≥ 40, 1 at level ≥ 15, else 0. Inter frames: 3 at +/// level ≥ 40, 2 at level ≥ 20, 1 at level ≥ 15, else 0. +pub fn hev_threshold(level: u8, is_keyframe: bool) -> i32 { + let l = i32::from(level); + if is_keyframe { + if l >= 40 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + } + } else if l >= 40 { + 3 + } else if l >= 20 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + } +} + +/// Filter one frame's worth of macroblock edges, in the reference decoder's +/// exact order (dixie `filter_row_normal` / `filter_row_simple`, applied +/// row-major over MBs; each MB visits, when enabled: left MB V-edge, then +/// subblock V-edges at +4/+8/+12, then top MB H-edge, then subblock +/// H-edges at +4/+8/+12 rows). +/// +/// `y`/`u`/`v` are unbordered plane buffers starting at pixel (0,0), +/// `stride`/`uv_stride` samples apart, sized `mb_cols*16 × mb_rows*16` +/// (and halved for chroma). Frame-boundary edges (column 0, row 0) are not +/// filtered. `mb_info` is indexed `row * mb_cols + col`; a level of 0 +/// disables all filtering of that MB. The simple variant filters only the +/// Y plane (dixie `filter_row_simple`). +/// +/// This applies the inter-frame `hev_threshold` table (see the module docs); +/// use [`filter_frame_ex`] for frame-type-exact decoding. +#[allow(clippy::too_many_arguments)] +pub fn filter_frame( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + stride: usize, + uv_stride: usize, + mb_cols: usize, + mb_rows: usize, + sharpness: u8, + simple_filter_type: bool, + mb_info: &[MbFilterInfo], +) { + filter_frame_ex( + y, + u, + v, + stride, + uv_stride, + mb_cols, + mb_rows, + sharpness, + simple_filter_type, + mb_info, + false, + ); +} + +/// [`filter_frame`] with an explicit frame type: `is_keyframe` selects the +/// §15.4 key-frame `hev_threshold` table instead of the inter-frame table +/// (dixie `calculate_filter_parameters`: +/// `if (filter_level >= 20 && !is_keyframe) hev_threshold++`). +#[allow(clippy::too_many_arguments)] +pub fn filter_frame_ex( + y: &mut [u8], + u: &mut [u8], + v: &mut [u8], + stride: usize, + uv_stride: usize, + mb_cols: usize, + mb_rows: usize, + sharpness: u8, + simple_filter_type: bool, + mb_info: &[MbFilterInfo], + is_keyframe: bool, +) { + debug_assert_eq!(mb_info.len(), mb_cols * mb_rows); + debug_assert!(y.len() >= stride * (mb_rows * 16 - 1) + mb_cols * 16); + debug_assert!(u.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); + debug_assert!(v.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8); + debug_assert!(stride >= mb_cols * 16); + debug_assert!(uv_stride >= mb_cols * 8); + + let tables = LoopFilterTables::update_sharpness(sharpness); + + for row in 0..mb_rows { + for col in 0..mb_cols { + let info = &mb_info[row * mb_cols + col]; + let level = info.level as usize; + // dixie filter_row_normal L9280 / filter_row_simple L9425: + // `if (edge_limit)` — level 0 filters nothing for this MB. + if level == 0 { + continue; + } + let hev = hev_threshold(info.level, is_keyframe); + let mblim = i32::from(tables.mblim[level]); + let blim = i32::from(tables.blim[level]); + let lim = i32::from(tables.lim[level]); + let ybase = row * 16 * stride + col * 16; + let uvbase = row * 8 * uv_stride + col * 8; + + if simple_filter_type { + // dixie filter_row_simple L9436-9460. Y plane only. + if col > 0 { + filter_v_edge_simple(y, stride, ybase, mblim); + } + if info.inner_edges { + filter_v_edge_simple(y, stride, ybase + 4, blim); + filter_v_edge_simple(y, stride, ybase + 8, blim); + filter_v_edge_simple(y, stride, ybase + 12, blim); + } + if row > 0 { + filter_h_edge_simple(y, stride, ybase, mblim); + } + if info.inner_edges { + filter_h_edge_simple(y, stride, ybase + 4 * stride, blim); + filter_h_edge_simple(y, stride, ybase + 8 * stride, blim); + filter_h_edge_simple(y, stride, ybase + 12 * stride, blim); + } + continue; + } + + // dixie filter_row_normal L9282-9378. + if col > 0 { + filter_mb_v_edge(y, stride, ybase, mblim, lim, hev, 2); + filter_mb_v_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); + filter_mb_v_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); + } + if info.inner_edges { + filter_subblock_v_edge(y, stride, ybase + 4, blim, lim, hev, 2); + filter_subblock_v_edge(y, stride, ybase + 8, blim, lim, hev, 2); + filter_subblock_v_edge(y, stride, ybase + 12, blim, lim, hev, 2); + filter_subblock_v_edge(u, uv_stride, uvbase + 4, blim, lim, hev, 1); + filter_subblock_v_edge(v, uv_stride, uvbase + 4, blim, lim, hev, 1); + } + if row > 0 { + filter_mb_h_edge(y, stride, ybase, mblim, lim, hev, 2); + filter_mb_h_edge(u, uv_stride, uvbase, mblim, lim, hev, 1); + filter_mb_h_edge(v, uv_stride, uvbase, mblim, lim, hev, 1); + } + if info.inner_edges { + filter_subblock_h_edge(y, stride, ybase + 4 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(y, stride, ybase + 8 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(y, stride, ybase + 12 * stride, blim, lim, hev, 2); + filter_subblock_h_edge(u, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); + filter_subblock_h_edge(v, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1); + } + } + } +} + +// --------------------------------------------------------------------------- +// Kernels — transcriptions of dixie_loopfilter.c (RFC 6386 §20.6). +// Pixels are handled as raw unsigned samples widened to `i32`; every clamp +// is the exact dixie saturate_int8 / saturate_uint8. +// --------------------------------------------------------------------------- + +/// dixie `saturate_int8`. +#[inline] +fn sat_i8(x: i32) -> i32 { + x.clamp(-128, 127) +} + +/// dixie `saturate_uint8` (result kept as `i32` in 0..=255). +#[inline] +fn sat_u8(x: i32) -> i32 { + x.clamp(0, 255) +} + +/// dixie `simple_threshold` (RFC §15.2/§15.3): the center test +/// `|p0-q0|*2 + |p1-q1|/2 <= limit` with `limit` already the *combined* +/// edge limit (`2*E + I`, or the tables' `blim`/`mblim`). +#[inline] +fn simple_threshold(p1: i32, p0: i32, q0: i32, q1: i32, limit: i32) -> bool { + (p0 - q0).abs() * 2 + ((p1 - q1).abs() >> 1) <= limit +} + +/// dixie `normal_threshold` (RFC §15.3 `filter_yes`): the combined center +/// test plus all six interior-difference tests against `interior`. +/// `px` is `[p3, p2, p1, p0, q0, q1, q2, q3]` across the edge. +#[inline] +fn normal_threshold(px: &[i32; 8], center_limit: i32, interior: i32) -> bool { + let [_, p2, p1, p0, q0, q1, q2, _] = *px; + simple_threshold(p1, p0, q0, q1, center_limit) + && (px[0] - p2).abs() <= interior + && (p2 - p1).abs() <= interior + && (p1 - p0).abs() <= interior + && (px[7] - q2).abs() <= interior + && (q2 - q1).abs() <= interior + && (q1 - q0).abs() <= interior +} + +/// dixie `high_edge_variance` (RFC §15.3 `hev`). +#[inline] +fn high_edge_variance(p1: i32, p0: i32, q0: i32, q1: i32, hev_threshold: i32) -> bool { + (p1 - p0).abs() > hev_threshold || (q1 - q0).abs() > hev_threshold +} + +/// dixie `filter_common` (RFC §15.3 `common_adjust`). +/// +/// `use_outer_taps` is true for the simple filter and for high-variance +/// edges. Returns `[p1, p0, q0, q1]`; the returned `p1`/`q1` equal the +/// inputs unless `!use_outer_taps` (subblock filter adjusts the inner +/// taps by half the edge adjustment). +fn filter_common(p1: i32, p0: i32, q0: i32, q1: i32, use_outer_taps: bool) -> [i32; 4] { + let mut a = 3 * (q0 - p0); + if use_outer_taps { + a += sat_i8(p1 - q1); + } + a = sat_i8(a); + // dixie clamps only the top here; a ≥ -128 makes a bottom clamp dead + // code, and the arithmetic `>> 3` reproduces the C rounding exactly. + let f1 = (if a + 4 > 127 { 127 } else { a + 4 }) >> 3; + let f2 = (if a + 3 > 127 { 127 } else { a + 3 }) >> 3; + let p0 = sat_u8(p0 + f2); + let q0 = sat_u8(q0 - f1); + let (p1, q1) = if !use_outer_taps { + let a = (f1 + 1) >> 1; + (sat_u8(p1 + a), sat_u8(q1 - a)) + } else { + (p1, q1) + }; + [p1, p0, q0, q1] +} + +/// dixie `filter_mb_edge` (RFC §15.3 `MBfilter`, non-hev branch): `w` is +/// "twice the edge difference" and the 27/18/9 coefficients approximate +/// 3/7, 2/7, 1/7 of it. Returns `[p2, p1, p0, q0, q1, q2]`. +fn filter_mb_edge(p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32) -> [i32; 6] { + let w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)); + let a = (27 * w + 63) >> 7; + let (p0, q0) = (sat_u8(p0 + a), sat_u8(q0 - a)); + let a = (18 * w + 63) >> 7; + let (p1, q1) = (sat_u8(p1 + a), sat_u8(q1 - a)); + let a = (9 * w + 63) >> 7; + let (p2, q2) = (sat_u8(p2 + a), sat_u8(q2 - a)); + [p2, p1, p0, q0, q1, q2] +} + +// --------------------------------------------------------------------------- +// Edge walkers. `anchor` is the flat index of the edge's q0 sample in the +// first row (V edges) / column (H edges); `size` is the number of 8-pixel +// segments (2 = 16-pixel Y MB edge, 1 = 8-pixel chroma / subblock edge). +// Frame-boundary guarantees (anchor ≥ 4 samples from the plane edge) are +// established by `filter_frame_ex`'s `col > 0` / `row > 0` guards. +// --------------------------------------------------------------------------- + +/// dixie `filter_mb_v_edge`: vertical MB edge, normal filter. +fn filter_mb_v_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for row in 0..8 * size { + let a = anchor + row * stride; + debug_assert!(a >= 4 && a + 3 < plane.len()); + let px = [ + i32::from(plane[a - 4]), + i32::from(plane[a - 3]), + i32::from(plane[a - 2]), + i32::from(plane[a - 1]), + i32::from(plane[a]), + i32::from(plane[a + 1]), + i32::from(plane[a + 2]), + i32::from(plane[a + 3]), + ]; + if !normal_threshold(&px, center_limit, interior) { + continue; + } + let [_, p2, p1, p0, q0, q1, q2, _] = px; + if high_edge_variance(p1, p0, q0, q1, hev) { + // dixie: filter_common with outer taps (p1/q1 unchanged). + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 2] = f[0] as u8; + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + 1] = f[3] as u8; + } else { + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); + plane[a - 3] = m[0] as u8; + plane[a - 2] = m[1] as u8; + plane[a - 1] = m[2] as u8; + plane[a] = m[3] as u8; + plane[a + 1] = m[4] as u8; + plane[a + 2] = m[5] as u8; + } + } +} + +/// dixie `filter_subblock_v_edge`: vertical subblock edge, normal filter. +fn filter_subblock_v_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for row in 0..8 * size { + let a = anchor + row * stride; + debug_assert!(a >= 4 && a + 3 < plane.len()); + let px = [ + i32::from(plane[a - 4]), + i32::from(plane[a - 3]), + i32::from(plane[a - 2]), + i32::from(plane[a - 1]), + i32::from(plane[a]), + i32::from(plane[a + 1]), + i32::from(plane[a + 2]), + i32::from(plane[a + 3]), + ]; + if normal_threshold(&px, center_limit, interior) { + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); + let f = filter_common(px[2], px[3], px[4], px[5], outer); + plane[a - 2] = f[0] as u8; + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + 1] = f[3] as u8; + } + } +} + +/// dixie `filter_mb_h_edge`: horizontal MB edge, normal filter. +fn filter_mb_h_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for i in 0..8 * size { + let a = anchor + i; + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); + let px = [ + i32::from(plane[a - 4 * stride]), + i32::from(plane[a - 3 * stride]), + i32::from(plane[a - 2 * stride]), + i32::from(plane[a - stride]), + i32::from(plane[a]), + i32::from(plane[a + stride]), + i32::from(plane[a + 2 * stride]), + i32::from(plane[a + 3 * stride]), + ]; + if !normal_threshold(&px, center_limit, interior) { + continue; + } + let [_, p2, p1, p0, q0, q1, q2, _] = px; + if high_edge_variance(p1, p0, q0, q1, hev) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 2 * stride] = f[0] as u8; + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + stride] = f[3] as u8; + } else { + let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); + plane[a - 3 * stride] = m[0] as u8; + plane[a - 2 * stride] = m[1] as u8; + plane[a - stride] = m[2] as u8; + plane[a] = m[3] as u8; + plane[a + stride] = m[4] as u8; + plane[a + 2 * stride] = m[5] as u8; + } + } +} + +/// dixie `filter_subblock_h_edge`: horizontal subblock edge, normal filter. +fn filter_subblock_h_edge( + plane: &mut [u8], + stride: usize, + anchor: usize, + center_limit: i32, + interior: i32, + hev: i32, + size: usize, +) { + for i in 0..8 * size { + let a = anchor + i; + debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); + let px = [ + i32::from(plane[a - 4 * stride]), + i32::from(plane[a - 3 * stride]), + i32::from(plane[a - 2 * stride]), + i32::from(plane[a - stride]), + i32::from(plane[a]), + i32::from(plane[a + stride]), + i32::from(plane[a + 2 * stride]), + i32::from(plane[a + 3 * stride]), + ]; + if normal_threshold(&px, center_limit, interior) { + let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); + let f = filter_common(px[2], px[3], px[4], px[5], outer); + plane[a - 2 * stride] = f[0] as u8; + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + plane[a + stride] = f[3] as u8; + } + } +} + +/// dixie `filter_v_edge_simple`: vertical edge, simple filter (2-tap; +/// consumes the combined limit directly, touches only p0/q0). +fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { + for row in 0..16 { + let a = anchor + row * stride; + debug_assert!(a >= 2 && a + 1 < plane.len()); + let p1 = i32::from(plane[a - 2]); + let p0 = i32::from(plane[a - 1]); + let q0 = i32::from(plane[a]); + let q1 = i32::from(plane[a + 1]); + if simple_threshold(p1, p0, q0, q1, limit) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - 1] = f[1] as u8; + plane[a] = f[2] as u8; + } + } +} + +/// dixie `filter_h_edge_simple`: horizontal edge, simple filter. +fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { + for i in 0..16 { + let a = anchor + i; + debug_assert!(a >= 2 * stride && a + stride < plane.len()); + let p1 = i32::from(plane[a - 2 * stride]); + let p0 = i32::from(plane[a - stride]); + let q0 = i32::from(plane[a]); + let q1 = i32::from(plane[a + stride]); + if simple_threshold(p1, p0, q0, q1, limit) { + let f = filter_common(p1, p0, q0, q1, true); + plane[a - stride] = f[1] as u8; + plane[a] = f[2] as u8; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // ----------------------------------------------------------------------- + // Python reference model — the SAME integer math used to derive every + // expected vector below (transcribed from dixie_loopfilter.c, RFC 6386 + // §20.6; control params from §15.4 / libvpx vp8_loopfilter.c). Run to + // regenerate the constants in these tests. + // + // def sat_i8(x): return -128 if x < -128 else (127 if x > 127 else x) + // def sat_u8(x): return 0 if x < 0 else (255 if x > 255 else x) + // + // def simple_threshold(p1, p0, q0, q1, limit): + // return (abs(p0 - q0) * 2 + (abs(p1 - q1) >> 1)) <= limit + // + // def normal_threshold(p3, p2, p1, p0, q0, q1, q2, q3, E, I): + // return simple_threshold(p1, p0, q0, q1, 2 * E + I) and \ + // abs(p3 - p2) <= I and abs(p2 - p1) <= I and abs(p1 - p0) <= I and \ + // abs(q3 - q2) <= I and abs(q2 - q1) <= I and abs(q1 - q0) <= I + // + // def high_edge_variance(p1, p0, q0, q1, t): + // return abs(p1 - p0) > t or abs(q1 - q0) > t + // + // def filter_common(p1, p0, q0, q1, outer): + // a = 3 * (q0 - p0) + // if outer: a += sat_i8(p1 - q1) + // a = sat_i8(a) + // f1 = (127 if a + 4 > 127 else a + 4) >> 3 + // f2 = (127 if a + 3 > 127 else a + 3) >> 3 + // p0 = sat_u8(p0 + f2); q0 = sat_u8(q0 - f1) + // if not outer: + // a = (f1 + 1) >> 1 + // p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) + // return p1, p0, q0, q1 + // + // def filter_mb_edge(p2, p1, p0, q0, q1, q2): + // w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0)) + // a = (27 * w + 63) >> 7; p0 = sat_u8(p0 + a); q0 = sat_u8(q0 - a) + // a = (18 * w + 63) >> 7; p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a) + // a = (9 * w + 63) >> 7; p2 = sat_u8(p2 + a); q2 = sat_u8(q2 - a) + // return p2, p1, p0, q0, q1, q2 + // + // def interior_limit(level, sharpness): + // il = level + // if sharpness: + // il >>= (2 if sharpness > 4 else 1) + // if il > 9 - sharpness: il = 9 - sharpness + // return il if il >= 1 else 1 + // + // def hev_threshold(level, key): + // if key: return 2 if level >= 40 else (1 if level >= 15 else 0) + // return 3 if level >= 40 else (2 if level >= 20 else (1 if level >= 15 else 0)) + // + // # update_sharpness: inside = lvl >> (s>0) >> (s>4), capped at 9-s + // # (only when s>0), min 1; lim=inside, blim=2*lvl+inside, + // # mblim=2*(lvl+2)+inside. + // # + // # Edge walkers mirror the Rust walkers: per row (V) / column (H), + // # threshold -> hev ? filter_common(outer=True) : filter_mb_edge for + // # MB edges, threshold -> filter_common(hev) for subblock edges, + // # threshold -> filter_common(True) touching p0/q0 only for simple. + // # Driver: row-major MBs, per MB [V-mb, V+4, V+8, V+12, H-mb, + // # H+4r, H+8r, H+12r] guarded by col>0 / inner / row>0 / inner + // # (dixie filter_row_normal / filter_row_simple). + // ----------------------------------------------------------------------- + + /// Decode a (possibly newline-wrapped) hex string into bytes. + fn unhex(s: &str) -> Vec { + let hexed: String = s.chars().filter(char::is_ascii_hexdigit).collect(); + (0..hexed.len() / 2) + .map(|i| u8::from_str_radix(&hexed[2 * i..2 * i + 2], 16).unwrap()) + .collect() + } + + /// The shared 2x2-MB driver scene: `y = (x*7) ^ (y*13 + 37)`, + /// `u = x*3 + y*5 + 11`, `v = x*5 + y*3 + 77` (all mod 256). + fn scene() -> (Vec, Vec, Vec) { + let (stride, uv_stride) = (32usize, 16usize); + let mut y = vec![0u8; stride * 32]; + let mut u = vec![0u8; uv_stride * 16]; + let mut v = vec![0u8; uv_stride * 16]; + for ty in 0..32usize { + for tx in 0..32usize { + y[ty * stride + tx] = (((tx * 7) ^ (ty * 13 + 37)) & 0xFF) as u8; + } + } + for ty in 0..16usize { + for tx in 0..16usize { + u[ty * uv_stride + tx] = ((tx * 3 + ty * 5 + 11) & 0xFF) as u8; + v[ty * uv_stride + tx] = ((tx * 5 + ty * 3 + 77) & 0xFF) as u8; + } + } + (y, u, v) + } + + const NORMAL_Y: &str = "\ +25222b3039060f141d1a6368717e474c55525ba0a9b6bf848d8a9398e1eef7fc32353c272e1118030a0d747f6669505b42454cb7bea1a8939a9d848ff6f9e0eb +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4b4259506f667d74730a0118172e253c3b32c9c0dfd6ede4e3faf188879e95 +595e574c457a736861661f140d023b30292e27dcd5cac3f8f1f6efe49d928b80666168737a454c575e59202b323d040f161118e3eaf5fcc7cec9d0dba2adb4bf +73747d666f5059424b4c353e2728111a03040df6ffe0e9d2dbdcc5ceb7b8a1aa80878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b5259 +8d8a839891aea7bcb5b2cbc0d9d6efe4fdfaf308011e172c25223b3049465f549a9d948f86b9b0aba2a5dcd7cec1f8f3eaede41f1609003b32352c275e514843 +a7a0a9b2bb848d969f98e1eaf3fcc5ced7d0d9222b343d060f08111a636c757eb4b3baa1a8979e858c8bf2f9e0efd6ddc4c3ca3138272e151c1b0209707f666d +c1c6cfd4dde2ebf0f9fe878c959aa3a8b1b6bf444d525b60696e777c050a1318cec9c0dbd2ede4fff6f188839a95aca7beb9b04b425d546f666178730a051c17 +dbdcd5cec7f8f1eae3e49d968f80b9b2abaca55e5748417a73746d661f100902e8efe6fdf4cbc2d9d0d7aea5bcb38a81989f966d647b724940475e552c233a31 +f5f2fbe0e9d6dfc4cdcab3b8a1ae979c85828b7079666f545d5a4348313e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db +0f08011a132c253e373049425b546d667f78718a839c95aea7a0b9b2cbc4ddd61c1b1209003f362d24235a5148477e756c6b6299908f86bdb4b3aaa1d8d7cec5 +292e273c350a031811166f647d724b40595e57aca5bab38881869f94ede2fbf0363138232a151c070e09707b626d545f464148b3baa5ac979e99808bf2fde4ef +43444d565f6069727b7c050e1718212a33343dc6cfd0d9e2ebecf5fe8788919a50575e454c737a61686f161d040b323920272ed5dcc3caf1f8ffe6ed949b8289 +5d5a5348417e776c65621b1009063f342d2a23d8d1cec7fcf5f2ebe099968f846a6d647f7649405b52552c273e3108031a1d14efe6f9f0cbc2c5dcd7aea1b8b3 +777079626b545d464f48313a232c151e070009f2fbe4edd6dfd8c1cab3bca5ae84838a9198a7aeb5bcbbc2c9d0dfe6edf4f3fa0108171e252c2b3239404f565d +91969f848db2bba0a9aed7dcc5caf3f8e1e6ef141d020b30393e272c555a43489e99908b82bdb4afa6a1d8d3cac5fcf7eee9e01b120d043f363128235a554c47 +abaca5beb788819a9394ede6fff0c9c2dbdcd52e2738310a03041d166f607972b8bfb6ada49b92898087fef5ece3dad1c8cfc63d342b221910170e057c736a61"; + + const NORMAL_U: &str = "\ +0b0e1114171a1d202326292c2f323538101316191c1f2225282b2e3134373a3d15181b1e2124272a2d303336393c3f421a1d202326292c2f3235383b3e414447 +1f2225282b2e3134373a3d404346494c24272a2d303336393c3f4245484b4e51292c2f3235383b3e4144474a4d5053562e3134373a3d404346494c4f5255585b +3336393c3f4245484b4e5154575a5d60383b3e4144474a4d505356595c5f62653d404346494c4f5255585b5e6164676a4245484b4e5154575a5d606366696c6f +474a4d505356595c5f6265686b6e71744c4f5255585b5e6164676a6d707376795154575a5d606366696c6f7275787b7e56595c5f6265686b6e7174777a7d8083"; + + const NORMAL_V: &str = "\ +4d52575c61666b70757a7f84898e939850555a5f64696e73787d82878c91969b53585d62676c71767b80858a8f94999e565b60656a6f74797e83888d92979ca1 +595e63686d72777c81868b90959a9fa45c61666b70757a7f84898e93989da2a75f64696e73787d82878c91969ba0a5aa62676c71767b80858a8f94999ea3a8ad +656a6f74797e83888d92979ca1a6abb0686d72777c81868b90959a9fa4a9aeb36b70757a7f84898e93989da2a7acb1b66e73787d82878c91969ba0a5aaafb4b9 +71767b80858a8f94999ea3a8adb2b7bc74797e83888d92979ca1a6abb0b5babf777c81868b90959a9fa4a9aeb3b8bdc27a7f84898e93989da2a7acb1b6bbc0c5"; + + const SIMPLE_Y: &str = "\ +25222b3831060f161b1a6368717e474e53525ba0a9b6bf8e838a9398e1eef7fc32353c2f26111807060d74776e6950534a454cafc6a1a897969d848ff6f9e0eb +3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4d4250596e647879730a0816172e343a3d33cbc0dfd6e4eae3edf188949e95 +595c57454c7b756762661f1507023b27252c26dad5cac3f3f9f6fce49d858b806661687a73454c585d59202a333d0410151118e3eaf5fcd0c5c9d0dba2adb4bf +73747d6f66505947464c35372e2811130a040df6ffe0e9d7d6dcc5c7beb8a1aa8083879096a39eb1adbfc6cdd4dbe2e9f0f7fe050c131a21282f363d4f4b5259 +8d8e8a959faeb3b8c4b2cbc8d1d6efecf5faf308011e172829223b3836465f549a9d94878eb9b0a9a4a5dcd7cec1f8f1ecede41f160900313c352c275e514843 +a7a0a9bab3848d989d98e1eaf3fcc5d0d5d0d9222b343d100508111a636c757eb4b5bfa8a1979e8a878bf2f0e9efd6d6cbc1cb333d272e1a171b0209707f666d +c1c4cad5dce2ebf1f8fe878d949aa3a9b0b8be4248525b61686e777c050a1318cec9c0d2dbede4fafbf1888a9395acaeb7b9b04b425d546a6b6178730a051c17 +dbdcd5c7cef8f1e9e4e49d978e80b9b1acaca55e574841717c746d661f100902e8efe6fdf4cbc2d3d6d7bbb7b7b68a87979f976c627b664a3e475e552c233a31 +f5f2fbe8e1d6dfcac7caa6a6a6ab979686828a7973667b5b575a4340393e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db +0f0801121b2c253a3b30494a53546d6e777871828b9c95aaaba0b9bac3c4ddd61c1d1200093f362c26235a5049477e746d6d6390988f86b4bdb3ada2d8d4cec5 +292c273d340a031315166f6d74724b47525c56aca6bab38b7e869c93ede5fbf03631382a23151c0c090970726b6d54584d4148b3baa5ac9c9999808bf2fde4ef +43444d575e6069737a7c050f1618212b32343dc6cfd0d9e3eaecf5fe8788919a5053573e487a7e6b696f130f07063a3c292b2fd1d5c2c6f2ffffebed91968284 +5d5e5a474d77736660621e160e0b3731242622dcd8cfcbeff7f2e6e09c9b8f896a6d647f7649405558552c2f36310809141d14efe6f9f0cdc0c5dcd7aea1b8b3 +7770796a63545d4c494831322b2c15180d0009f2fbe4eddcd9d8c1c2bbbca5ae84858f898fa7aeb6bbbbc2c8d1dfe6eef3f3fa0108171e262b2b3238414f565d +91949a8c96b2bba5a4aed7d5cccaf3f1e8e6ef141d020b2d3c3e272c555a43489e9990828bbdb4aea7a1d8d2cbc5fcf6efe9e01b120d04363f3128235a554c47 +abaca5bfb68881959894edeff6f0c9c9d4dcd52e2738310d00041d166f607972b8bfb6ada49b92878287fef5ece3dacfcacfc63d342b221712170e057c736a61"; + + /// Table sanity: lengths plus entries hand-derived from libvpx + /// `vp8_loop_filter_update_sharpness` (vp8/common/vp8_loopfilter.c + /// L49-75): inside = lvl >> (s>0) >> (s>4), capped at 9-s when s>0, + /// min 1; lim=inside, blim=2*lvl+inside, mblim=2*(lvl+2)+inside. + #[test] + fn sharpness_tables_match_libvpx() { + let t0 = LoopFilterTables::update_sharpness(0); + assert_eq!(t0.lim.len(), 64); + assert_eq!(t0.blim.len(), 64); + assert_eq!(t0.mblim.len(), 64); + // sharpness 0: lvl 0 -> (1, 1, 5), lvl 1 -> (1, 3, 7), + // lvl 15 -> (15, 45, 49), lvl 63 -> (63, 189, 193). + assert_eq!((t0.lim[0], t0.blim[0], t0.mblim[0]), (1, 1, 5)); + assert_eq!((t0.lim[1], t0.blim[1], t0.mblim[1]), (1, 3, 7)); + assert_eq!((t0.lim[15], t0.blim[15], t0.mblim[15]), (15, 45, 49)); + assert_eq!((t0.lim[63], t0.blim[63], t0.mblim[63]), (63, 189, 193)); + // sharpness 5: inside = lvl >> 2 capped at 4: + // lvl 3 -> (1, 7, 11), lvl 20 -> (4, 44, 48), lvl 63 -> (4, 130, 134). + let t5 = LoopFilterTables::update_sharpness(5); + assert_eq!((t5.lim[3], t5.blim[3], t5.mblim[3]), (1, 7, 11)); + assert_eq!((t5.lim[20], t5.blim[20], t5.mblim[20]), (4, 44, 48)); + assert_eq!((t5.lim[63], t5.blim[63], t5.mblim[63]), (4, 130, 134)); + // sharpness 7: inside capped at 2: + // lvl 4 -> (1, 9, 13), lvl 20 -> (2, 42, 46). + let t7 = LoopFilterTables::update_sharpness(7); + assert_eq!((t7.lim[4], t7.blim[4], t7.mblim[4]), (1, 9, 13)); + assert_eq!((t7.lim[20], t7.blim[20], t7.mblim[20]), (2, 42, 46)); + // The standalone helper must agree with the table for every level. + for sharpness in 0..=7u8 { + let t = LoopFilterTables::update_sharpness(sharpness); + for level in 0..=63u8 { + assert_eq!( + interior_limit(level, sharpness), + i32::from(t.lim[level as usize]) + ); + } + } + } + + /// §15.4 hev table (libvpx `lf_init_lut`): key 0/1/1/2 and inter + /// 0/1/2/3 at levels 0/15/20/40 respectively. + #[test] + fn hev_threshold_table() { + for level in [0u8, 14, 15, 19, 20, 39, 40, 63] { + let l = i32::from(level); + let want_key = if l >= 40 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + }; + let want_inter = if l >= 40 { + 3 + } else if l >= 20 { + 2 + } else if l >= 15 { + 1 + } else { + 0 + }; + assert_eq!(hev_threshold(level, true), want_key); + assert_eq!(hev_threshold(level, false), want_inter); + } + assert_eq!(hev_threshold(39, true), 1); + assert_eq!(hev_threshold(39, false), 2); + } + + /// Level 0 disables all filtering: a noisy frame is byte-identical. + #[test] + fn level_zero_disables_filtering() { + let (y0, u0, v0) = scene(); + let mut y = y0.clone(); + let mut u = u0.clone(); + let mut v = v0.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + false, + &[MbFilterInfo { + level: 0, + inner_edges: true, + }; 4], + ); + assert_eq!(y, y0); + assert_eq!(u, u0); + assert_eq!(v, v0); + } + + /// Kernel: normal filter, vertical MB edge, non-hev wide path. + /// Level 30, sharpness 0 -> interior 30, mblim = 2*32+30 = 94, hev = 2. + /// Patch: cols < 16 = 110, cols >= 16 = 130. Python model row: + /// w = sat_i8(-20 + 3*20) = 40; a27 = (1080+63)>>7 = 8, a18 = 6, + /// a9 = 3 -> [110, 113, 116, 118 | 122, 124, 127, 130] at cols 12..19. + #[test] + fn mb_v_edge_normal_filter_kernel() { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; + } + } + let mut u = vec![128u8; 16 * 8]; + let mut v = vec![128u8; 16 * 8]; + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 1, + 0, + false, + &[MbFilterInfo { + level: 30, + inner_edges: false, + }; 2], + ); + for r in 0..16 { + assert_eq!( + &y[r * 32 + 12..r * 32 + 20], + &[110, 113, 116, 118, 122, 124, 127, 130], + "row {r}" + ); + } + // Flat chroma planes are untouched (all filter deltas are 0). + assert!(u.iter().all(|&b| b == 128)); + assert!(v.iter().all(|&b| b == 128)); + } + + /// Kernel: hev edge takes the simple ±f path (p1/q1 unchanged). + /// Level 15, sharpness 0 -> interior 15, mblim = 2*17+15 = 49, hev = 1. + /// |p1-p0| = 2 > 1 triggers hev; Python model: a = 3*16 - 10 = 38, + /// f1 = 42>>3 = 5, f2 = 41>>3 = 5. + #[test] + fn hev_edge_takes_short_path() { + let mut plane = vec![0u8; 8 * 8]; + for r in 0..8 { + plane[r * 8..r * 8 + 8].copy_from_slice(&[101, 101, 102, 100, 116, 112, 112, 113]); + } + // Anchor: q0 at (row 0, col 4); 8 rows, one segment. + filter_mb_v_edge( + &mut plane, + 8, + 4, + 2 * (15 + 2) + 15, + 15, + hev_threshold(15, false), + 1, + ); + assert_eq!(&plane[0..8], &[101, 101, 102, 105, 111, 112, 112, 113]); + // Outer-tap path leaves the inner taps alone. + assert_eq!(plane[8 + 2], 102); + assert_eq!(plane[8 + 5], 112); + } + + /// Kernel: non-hev subblock edge runs the full path incl. p1/q1. + /// Level 15, sharpness 0 -> interior 15, blim = 2*15+15 = 45. + /// Python model: a = 3*10 = 30, f1 = 34>>3 = 4, f2 = 33>>3 = 4, + /// inner a = (4+1)>>1 = 2. + #[test] + fn subblock_edge_takes_full_three_tap_path() { + let mut plane = vec![0u8; 8 * 8]; + for r in 0..8 { + plane[r * 8..r * 8 + 8].copy_from_slice(&[100, 100, 100, 100, 110, 111, 111, 111]); + } + filter_subblock_v_edge( + &mut plane, + 8, + 4, + 2 * 15 + 15, + 15, + hev_threshold(15, false), + 1, + ); + assert_eq!(&plane[0..8], &[100, 100, 102, 104, 106, 109, 111, 111]); + } + + /// Simple filter: MB edge gets f = 5 (mb_limit = 94), subblock edges + /// are filtered too (no-op on flat interiors), chroma is untouched. + #[test] + fn simple_filter_leaves_chroma_untouched() { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c < 16 { 110 } else { 130 }; + } + } + let mut u = vec![0u8; 16 * 8]; + let mut v = vec![0u8; 16 * 8]; + for r in 0..8 { + for c in 0..16 { + u[r * 16 + c] = if c < 8 { 100 } else { 150 }; + v[r * 16 + c] = if c < 8 { 90 } else { 170 }; + } + } + let u_orig = u.clone(); + let v_orig = v.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 1, + 0, + true, + &[MbFilterInfo { + level: 30, + inner_edges: true, + }; 2], + ); + // a = 3*20 - 20 = 40 -> f1 = 44>>3 = 5, f2 = 43>>3 = 5. + for r in 0..16 { + assert_eq!( + &y[r * 32 + 12..r * 32 + 20], + &[110, 110, 110, 115, 125, 130, 130, 130], + "row {r}" + ); + } + assert_eq!(u, u_orig); + assert_eq!(v, v_orig); + } + + /// Full-frame driver, normal filter: 2x2 MBs, level 25, sharpness 1, + /// inner edges on. The whole frame must equal the Python model output + /// byte-for-byte. Sample (17,17) is q1 of MB(1,1)'s V edge and then q1 + /// of its H edge — the match proves the dixie visit order + /// (V-MB, subblock-V, H-MB, subblock-H) is reproduced. + #[test] + fn driver_normal_filter_frame_order() { + let (y0, u0, v0) = scene(); + let mut y = y0; + let mut u = u0; + let mut v = v0; + filter_frame_ex( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + false, + &[MbFilterInfo { + level: 25, + inner_edges: true, + }; 4], + false, + ); + assert_eq!(y, unhex(NORMAL_Y)); + assert_eq!(u, unhex(NORMAL_U)); + assert_eq!(v, unhex(NORMAL_V)); + assert_eq!(y[17 * 32 + 17], 0x75, "order-probe pixel (17,17)"); + } + + /// Full-frame driver, simple filter: same scene, Y-only output. + #[test] + fn driver_simple_filter_frame() { + let (_, u0, v0) = scene(); + let (mut y, _, _) = scene(); + let mut u = u0.clone(); + let mut v = v0.clone(); + filter_frame( + &mut y, + &mut u, + &mut v, + 32, + 16, + 2, + 2, + 1, + true, + &[MbFilterInfo { + level: 25, + inner_edges: true, + }; 4], + ); + assert_eq!(y, unhex(SIMPLE_Y)); + assert_eq!(u, u0); + assert_eq!(v, v0); + } + + /// Frame type matters at level 25 (hev 2 inter / 1 key): a near-tap + /// difference of exactly 2 takes the wide MBfilter path on inter + /// frames and the hev ±f path on key frames. Python model rows: + /// inter 6e6f71706f707071, key 6e6e706f70717171. + #[test] + fn frame_type_changes_hev_path() { + let build = || { + let mut y = vec![0u8; 32 * 16]; + for r in 0..16 { + for c in 0..32 { + y[r * 32 + c] = if c == 14 { + 112 + } else if c < 16 { + 110 + } else { + 113 + }; + } + } + y + }; + let mut uy = vec![128u8; 16 * 8]; + let mut vy = vec![128u8; 16 * 8]; + let mut ky = build(); + let mut uk = uy.clone(); + let mut vk = vy.clone(); + let info = [MbFilterInfo { + level: 25, + inner_edges: false, + }; 2]; + let mut inter = build(); + filter_frame_ex( + &mut inter, &mut uy, &mut vy, 32, 16, 2, 1, 1, false, &info, false, + ); + filter_frame_ex( + &mut ky, &mut uk, &mut vk, 32, 16, 2, 1, 1, false, &info, true, + ); + assert_eq!(&inter[12..20], &[110, 111, 113, 112, 111, 112, 112, 113]); + assert_eq!(&ky[12..20], &[110, 110, 112, 111, 112, 113, 113, 113]); + } +} diff --git a/crates/ec-vp8/src/mc.rs b/crates/ec-vp8/src/mc.rs new file mode 100644 index 00000000..01d64181 --- /dev/null +++ b/crates/ec-vp8/src/mc.rs @@ -0,0 +1,763 @@ +//! Motion-compensation inter predictors: reference border extension, 6-tap +//! luma prediction, bilinear chroma prediction, and the UMV-border motion +//! vector clamps. +//! +//! Normative source: [RFC 6386] §18.3 (sub-pixel interpolation, two +//! separable 1-D passes, each sample `clamp255((a + 64) >> 7)`). The loop +//! structure, intermediate widths and the border clamps follow the libvpx +//! reference implementation (`vp8/common/filter.c`, `vp8/common/ +//! reconinter.c`, `vp8/common/extend.c`) sample-for-sample; the per-pass +//! 0..=255 clamping of the 6-tap intermediate is mandated by the RFC's +//! `interp()` and is what the integer test vectors below pin down. +//! +//! Reference planes arrive already border-extended by [`extend_plane`] +//! (edge replication, `border` = 32 like libvpx's `VP8BORDERINPIXELS`); +//! `src` starts at the first byte of the bordered buffer (top-left border +//! corner) and visible pixel `(px, py)` therefore lives at +//! `src[(py + border) * stride + (px + border)]`. +//! +//! Motion vectors are `(row, col)` pairs in eighth-pel units (`i16`), and +//! the C arithmetic right shifts / two's-complement `& 7` phase extraction +//! are reproduced exactly (`i32 >> 3` and `& 7` on negatives). +//! +//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386 + +/// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes. +const VP8_FILTER_WEIGHT: i32 = 128; +/// `VP8_FILTER_SHIFT` (filter.c): normalize the 7-bit-precision result. +const VP8_FILTER_SHIFT: i32 = 7; + +/// `vp8_sub_pel_filters[8][6]` (filter.c), indexed by the 0..8 sub-pel phase. +const SUB_PEL_FILTERS: [[i32; 6]; 8] = [ + [0, 0, 128, 0, 0, 0], // degenerate whole-pel (RFC 6386 §18.3 "filters[0]") + [0, -6, 123, 12, -1, 0], + [2, -11, 108, 36, -8, 1], + [0, -9, 93, 50, -6, 0], + [3, -16, 77, 77, -16, 3], + [0, -6, 50, 93, -9, 0], + [1, -8, 36, 108, -11, 2], + [0, -1, 12, 123, -6, 0], +]; + +/// `vp8_bilinear_filters[8][2]` (filter.c); chroma prediction is always +/// bilinear (RFC 6386 §19.2). +const BILINEAR_FILTERS: [[i32; 2]; 8] = [ + [128, 0], + [112, 16], + [96, 32], + [80, 48], + [64, 64], + [48, 80], + [32, 96], + [16, 112], +]; + +#[inline] +fn clamp255(v: i32) -> i32 { + if v < 0 { + 0 + } else if v > 255 { + 255 + } else { + v + } +} + +/// Extends the visible `vis_w` x `vis_h` region of `plane` into the `border` +/// ring on all four sides by edge replication: every out-of-image sample +/// becomes the nearest in-image sample. +/// +/// Port of `copy_and_extend_plane` (extend.c) with `et = el = eb = er = +/// border` and `interleave_step = 1`, in place: first the left/right border +/// of every visible row is filled from the row's first/last column, then the +/// (already side-extended) top and bottom rows are copied into the top and +/// bottom borders — which gives the corners their corner pixels, matching +/// the C exactly. +pub(crate) fn extend_plane(plane: &mut [u8], stride: usize, vis_w: usize, vis_h: usize, border: usize) { + debug_assert!(vis_w >= 1 && vis_h >= 1); + debug_assert!(stride >= border * 2 + vis_w); + + let line = border + vis_w + border; + + // extend.c: "copy the left and right most columns out". + for r in 0..vis_h { + let base = (border + r) * stride + border; + let first = plane[base]; + let last = plane[base + vis_w - 1]; + plane[base - border..base].fill(first); + plane[base + vis_w..base + vis_w + border].fill(last); + } + + // extend.c: "Now copy the top and bottom lines into each line of the + // respective borders" — src rows are the already side-extended lines. + let top = border * stride; + let bottom = (border + vis_h - 1) * stride; + for i in 0..border { + plane.copy_within(top..top + line, (border - 1 - i) * stride); + plane.copy_within(bottom..bottom + line, (border + vis_h + i) * stride); + } +} + +/// Luma predictor for one `bw` x `bh` block (`bw`,`bh` in 4..=16, multiples +/// of 4) whose visible-image top-left pixel is `(x, y)`. +/// +/// Semantics of `vp8_build_inter_predictors_b` / +/// `vp8_build_inter16x16_predictors_mby` + `vp8_sixtap_predict*` (reconinter.c, +/// filter.c): full-pel start `(x + (mv.1 >> 3), y + (mv.0 >> 3))`, phases +/// `fx = mv.1 & 7`, `fy = mv.0 & 7`; a whole-pel MV is a plain copy, +/// otherwise the separable 6-tap filter runs horizontally into an `i32` +/// intermediate — clamped to 0..=255 per pass like libvpx's `int` `FData` — +/// then vertically, both passes computing `(dot + 64) >> 7` and clamping. +/// +/// When `need_clamp` is set, the MV is first passed through +/// [`clamp_mv_to_umv_border`]. +pub(crate) fn predict_luma( + src: &[u8], + stride: usize, + border: usize, + vis_w: usize, + vis_h: usize, + x: usize, + y: usize, + mv: (i16, i16), + need_clamp: bool, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, + bilinear: bool, +) { + debug_assert!(bw >= 4 && bw <= 16 && bw % 4 == 0); + debug_assert!(bh >= 4 && bh <= 16 && bh % 4 == 0); + + let mut mv = (i32::from(mv.0), i32::from(mv.1)); + if need_clamp { + clamp_mv_to_umv_border(&mut mv, x >> 4, y >> 4, vis_w, vis_h); + } + + let fx = (mv.1 & 7) as usize; + let fy = (mv.0 & 7) as usize; + let sx = border as i32 + x as i32 + (mv.1 >> 3); + let sy = border as i32 + y as i32 + (mv.0 >> 3); + // 6-tap reads reach 2 before / 3 after the start; the libvpx clamp + // arithmetic keeps those inside the 32-px border. + debug_assert!(sx >= 2 && sy >= 2, "reference read outside bordered plane"); + let (sx, sy) = (sx as usize, sy as usize); + + if bilinear { + bilinear_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh); + } else { + sixtap_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh); + } +} + +/// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*, +/// filter.c). `(sx, sy)` is the full-pel block origin in the bordered +/// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy). +fn sixtap_block( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + fx: usize, + fy: usize, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { + if fx == 0 && fy == 0 { + // reconinter.c build_inter_predictors_b / vp8_copy_mem*. + for r in 0..bh { + let s = (sy + r) * stride + sx; + dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]); + } + return; + } + + let hf = &SUB_PEL_FILTERS[fx]; + let vf = &SUB_PEL_FILTERS[fy]; + + // filter.c filter_block2d_first_pass on `src - 2*stride`: `bh + 5` + // horizontal lines (2 above the block, 3 below, for the vertical taps). + // Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the + // uniform loop reproduces the C for every phase combination. + let mut tmp = [0i32; 21 * 16]; // C: int FData[21 * 24] + for i in 0..bh + 5 { + let row = (sy + i - 2) * stride + sx - 2; + for j in 0..bw { + let p = row + j; + let acc = i32::from(src[p]) * hf[0] + + i32::from(src[p + 1]) * hf[1] + + i32::from(src[p + 2]) * hf[2] + + i32::from(src[p + 3]) * hf[3] + + i32::from(src[p + 4]) * hf[4] + + i32::from(src[p + 5]) * hf[5] + + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ + tmp[i * bw + j] = clamp255(acc >> VP8_FILTER_SHIFT); + } + } + + // filter.c filter_block2d_second_pass on `FData + 2*bw`: taps read the + // intermediate rows `r .. r + 5`. + for r in 0..bh { + for c in 0..bw { + let acc = tmp[r * bw + c] * vf[0] + + tmp[(r + 1) * bw + c] * vf[1] + + tmp[(r + 2) * bw + c] * vf[2] + + tmp[(r + 3) * bw + c] * vf[3] + + tmp[(r + 4) * bw + c] * vf[4] + + tmp[(r + 5) * bw + c] * vf[5] + + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ + dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8; + } + } +} + +/// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*, +/// filter.c). The dot products are provably in 0..=255 (taps are +/// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's +/// bilinear passes store `unsigned short` intermediates and skip the clamp. +fn bilinear_block( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + fx: usize, + fy: usize, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { + if fx == 0 && fy == 0 { + for r in 0..bh { + let s = (sy + r) * stride + sx; + dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]); + } + return; + } + + let hf = &BILINEAR_FILTERS[fx]; + let vf = &BILINEAR_FILTERS[fy]; + + // filter.c filter_block2d_bil_first_pass: `bh + 1` rows, horizontal + // taps [0] and [1]. Phase 0 is the exact identity, as above. + let mut tmp = [0u16; 17 * 16]; // C: unsigned short FData[17 * 16] + for i in 0..bh + 1 { + let row = (sy + i) * stride + sx; + for j in 0..bw { + let p = row + j; + let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1] + + (VP8_FILTER_WEIGHT / 2); /* Rounding */ + tmp[i * bw + j] = (acc >> VP8_FILTER_SHIFT) as u16; + } + } + + // filter.c filter_block2d_bil_second_pass: vertical taps [0] and + // `[width]` (the next intermediate row). + for r in 0..bh { + for c in 0..bw { + let acc = i32::from(tmp[r * bw + c]) * vf[0] + + i32::from(tmp[(r + 1) * bw + c]) * vf[1] + + (VP8_FILTER_WEIGHT / 2); /* Rounding */ + dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8; + } + } +} + +/// Chroma predictor for one `bw` x `bh` block whose visible-image top-left +/// chroma pixel is `(x, y)`. +/// +/// `mv` is the chroma MV in eighth-CHROMA-pel units (the caller derives it +/// from luma per libvpx: round-half-away-from-zero division by 2 (whole MB) +/// or sum-then-divide-by-8 (SPLITMV), `& fullpixel_mask`). +/// +/// The interpolation filter is the FRAME's MC filter, exactly like luma: +/// `vp8_setup_version` picks six-tap for version 0 (and reserved 4-7) and +/// bilinear for versions 1-3 (decodeframe.c:851-860 assigns BOTH +/// `subpixel_predict` and `subpixel_predict8x8` from that one switch, and +/// reconinter.c uses them for the chroma predicts). `bilinear` is that +/// per-frame selection. +/// +/// When `need_clamp` is set, the MV is first passed through +/// [`clamp_uvmv_to_umv_border`]. +pub(crate) fn predict_chroma( + src: &[u8], + uv_stride: usize, + border: usize, + vis_w: usize, + vis_h: usize, + x: usize, + y: usize, + mv: (i16, i16), + need_clamp: bool, + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, + bilinear: bool, +) { + debug_assert!(bw >= 2 && bw <= 16 && bw % 2 == 0); + debug_assert!(bh >= 2 && bh <= 16 && bh % 2 == 0); + + let mut mv = (i32::from(mv.0), i32::from(mv.1)); + if need_clamp { + // A right/bottom chroma quadrant starts at x == vis_w; it still + // lives in the last MB, so clamp the derived MB index. + let mb_cols = (vis_w + 15) >> 4; + let mb_rows = (vis_h + 15) >> 4; + let mbc = (x >> 3).min(mb_cols - 1); + let mbr = (y >> 3).min(mb_rows - 1); + clamp_uvmv_to_umv_border(&mut mv, mbc, mbr, vis_w, vis_h); + } + + let fx = (mv.1 & 7) as usize; + let fy = (mv.0 & 7) as usize; + let sx = border as i32 + x as i32 + (mv.1 >> 3); + let sy = border as i32 + y as i32 + (mv.0 >> 3); + // 6-tap reads reach 2 before / 3 after the origin. + debug_assert!(sx >= 2 && sy >= 2, "reference read outside bordered plane"); + let (sx, sy) = (sx as usize, sy as usize); + + if bilinear { + bilinear_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh); + } else { + sixtap_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh); + } +} + +/// The macroblock-level UMV border edges in eighth-pel units, exactly the +/// decoder's `xd->mb_to_{left,right,top,bottom}_edge` (decodeframe.c:503-532): +/// +/// ```c +/// xd->mb_to_top_edge = -((mb_row * 16) << 3); +/// xd->mb_to_bottom_edge = ((mb_rows - 1 - mb_row) * 16) << 3; +/// xd->mb_to_left_edge = -((mb_col * 16) << 3); +/// xd->mb_to_right_edge = ((mb_cols - 1 - mb_col) * 16) << 3; +/// ``` +/// +/// with `mb_rows`/`mb_cols` the full (partial MB inclusive) MB counts of the +/// visible frame. Returns `(left, right, top, bottom)`. +fn mb_edges(mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) -> (i32, i32, i32, i32) { + let mb_cols = (vis_w + 15) >> 4; + let mb_rows = (vis_h + 15) >> 4; + debug_assert!(mb_col < mb_cols && mb_row < mb_rows); + let left = -(((mb_col * 16) as i32) << 3); + let right = (((mb_cols - 1 - mb_col) * 16) as i32) << 3; + let top = -(((mb_row * 16) as i32) << 3); + let bottom = (((mb_rows - 1 - mb_row) * 16) as i32) << 3; + (left, right, top, bottom) +} + +/// Port of `clamp_mv_to_umv_border` (reconinter.c:257-278), luma MV in +/// eighth-pel units: +/// +/// ```c +/// if (mv->col < (xd->mb_to_left_edge - (19 << 3))) { +/// mv->col = xd->mb_to_left_edge - (16 << 3); +/// } else if (mv->col > xd->mb_to_right_edge + (18 << 3)) { +/// mv->col = xd->mb_to_right_edge + (16 << 3); +/// } +/// /* same for row with top/bottom edges */ +/// ``` +/// +/// 19 px slack toward left/top (16 px + 3 taps right of the central pixel), +/// 18 px toward right/bottom (16 px + 2 taps left of it); the clamp anchor +/// is 16 px inside the border. `mb_col`/`mb_row` locate the block's +/// macroblock; libvpx clamps with these MB-level edges for whole-MB MVs and, +/// when `need_to_clamp_mvs` is set, for each SPLITMV subblock MV too +/// (reconinter.c:370-375, 397-400). +fn clamp_mv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) { + let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h); + if mv.1 < left - (19 << 3) { + mv.1 = left - (16 << 3); + } else if mv.1 > right + (18 << 3) { + mv.1 = right + (16 << 3); + } + + if mv.0 < top - (19 << 3) { + mv.0 = top - (16 << 3); + } else if mv.0 > bottom + (18 << 3) { + mv.0 = bottom + (16 << 3); + } +} + +/// Port of `clamp_uvmv_to_umv_border` (reconinter.c:281-295), chroma MV in +/// eighth-CHROMA-pel units. The comparison doubles the chroma MV back into +/// luma eighth-pel units (`2 * mv->col`, the "different divisor": the +/// chroma border reach is half the luma one) and the clamp target is the +/// luma anchor halved: +/// +/// ```c +/// mv->col = (2 * mv->col < (xd->mb_to_left_edge - (19 << 3))) +/// ? (xd->mb_to_left_edge - (16 << 3)) >> 1 +/// : mv->col; +/// mv->col = (2 * mv->col > xd->mb_to_right_edge + (18 << 3)) +/// ? (xd->mb_to_right_edge + (16 << 3)) >> 1 +/// : mv->col; +/// /* same for row */ +/// ``` +/// +/// The C applies the two ternaries in sequence (right check sees the +/// left-clamped value, which cannot trip it); the sequential `if`s here are +/// that verbatim. `(left - (16 << 3))` is a multiple of 256 so `>> 1` is +/// exact. Callers must re-apply this clamp AFTER full-pel rounding of a +/// derived chroma MV: rounding to full-pel can move the MV outside the +/// border tap window even though the luma MV was already clamped +/// (reconinter.c:336-339 — the 16x16 path clamps the chroma MV +/// unconditionally for exactly this reason). +fn clamp_uvmv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) { + let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h); + + if 2 * mv.1 < left - (19 << 3) { + mv.1 = (left - (16 << 3)) >> 1; + } + if 2 * mv.1 > right + (18 << 3) { + mv.1 = (right + (16 << 3)) >> 1; + } + + if 2 * mv.0 < top - (19 << 3) { + mv.0 = (top - (16 << 3)) >> 1; + } + if 2 * mv.0 > bottom + (18 << 3) { + mv.0 = (bottom + (16 << 3)) >> 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Deterministic plane fill shared by every test (LCG, same sequence in + /// the hand-computed literals below). + fn lcg_plane(seed: u32, len: usize) -> Vec { + let mut out = vec![0u8; len]; + let mut s = seed; + for b in out.iter_mut() { + s = s.wrapping_mul(1664525).wrapping_add(1013904223); + *b = (s >> 16) as u8; + } + out + } + + const BORDER: usize = 32; + const STRIDE: usize = 104; // 40 visible + 2 * 32 border + const VIS_W: usize = 40; // 3 MB columns, last one partial + const VIS_H: usize = 36; // 3 MB rows, last one partial + const ROWS: usize = VIS_H + 2 * BORDER; + + fn plane() -> Vec { + lcg_plane(0x1234, STRIDE * ROWS) + } + + /// Reads visible-image pixel (`vx`, `vy`) out of a bordered plane. + fn vis(plane: &[u8], vx: usize, vy: usize) -> u8 { + plane[(vy + BORDER) * STRIDE + (vx + BORDER)] + } + + #[test] + fn extend_plane_replicates_edges_and_corners() { + let mut p = plane(); + // Distinct visible values, sentinel everywhere else. + for r in 0..VIS_H { + for c in 0..VIS_W { + p[(BORDER + r) * STRIDE + BORDER + c] = ((r * 7 + c * 3) % 251 + 4) as u8; + } + } + p[..BORDER * STRIDE].fill(0xEE); + p[(BORDER + VIS_H) * STRIDE..].fill(0xEE); + for r in 0..VIS_H { + let row = &mut p[(BORDER + r) * STRIDE..(BORDER + r) * STRIDE + STRIDE]; + row[..BORDER].fill(0xEE); + row[BORDER + VIS_W..].fill(0xEE); + } + + extend_plane(&mut p, STRIDE, VIS_W, VIS_H, BORDER); + + // Every sample of the bordered plane equals the nearest in-image sample. + for r in 0..ROWS { + for c in 0..STRIDE { + let vr = r.saturating_sub(BORDER).min(VIS_H - 1); + let vc = c.saturating_sub(BORDER).min(VIS_W - 1); + assert_eq!(p[r * STRIDE + c], vis(&p, vc, vr), "sample ({r},{c})"); + } + } + // Explicit corners (worst case of the rule above). + assert_eq!(p[0], vis(&p, 0, 0)); // top-left + assert_eq!(p[line_len() - 1], vis(&p, VIS_W - 1, 0)); // top-right + assert_eq!(p[(ROWS - 1) * STRIDE], vis(&p, 0, VIS_H - 1)); // bottom-left + assert_eq!( + p[ROWS * STRIDE - 1], + vis(&p, VIS_W - 1, VIS_H - 1) // bottom-right + ); + // The visible region itself is untouched. + for r in 0..VIS_H { + for c in 0..VIS_W { + assert_eq!( + p[(BORDER + r) * STRIDE + BORDER + c], + ((r * 7 + c * 3) % 251 + 4) as u8 + ); + } + } + } + + fn line_len() -> usize { + BORDER + VIS_W + BORDER + } + + #[test] + fn integer_mv_predict_is_a_plain_copy() { + let p = plane(); + let mut dst = [0u8; 16 * 16]; + + // Whole-pel luma MV (row=16, col=-8) → full-pel offset (x-1, y+2). + // mv.0 is the row component, mv.1 the column component. x=y=8 keeps + // every read inside the visible region of the unextended plane. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (16, -8), false, &mut dst, 16, 16, 16, + false); + for r in 0..16 { + for c in 0..16 { + assert_eq!(dst[r * 16 + c], vis(&p, 8 - 1 + c, 8 + 2 + r), "({r},{c})"); + } + } + + // Zero MV → identity copy. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (0, 0), false, &mut dst, 16, 16, 16, + false); + for r in 0..16 { + for c in 0..16 { + assert_eq!(dst[r * 16 + c], vis(&p, 8 + c, 8 + r), "({r},{c})"); + } + } + + // Chroma copy path, whole-pel chroma MV (row=-16, col=+8) + // → full-pel offset (x+1, y-2). + let mut dst8 = [0u8; 8 * 8]; + predict_chroma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 4, (-16, 8), false, &mut dst8, 8, 8, 8, + false); + for r in 0..8 { + for c in 0..8 { + assert_eq!(dst8[r * 8 + c], vis(&p, 4 + 1 + c, 4 - 2 + r), "({r},{c})"); + } + } + } + + #[test] + fn sixtap_pure_horizontal_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 4 * 4]; + + // mv = (0, 4): full-pel start (16, 12), fx = 4, fy = 0. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 16, 12, (0, 4), false, &mut dst, 4, 4, 4, false, + ); + + // Hand-computed from vp8_sub_pel_filters[4] = { 3, -16, 77, 77, -16, 3 } + // and vp8_sub_pel_filters[0] = { 0, 0, 128, 0, 0, 0 } (vertical is the + // exact identity over the clamped horizontal intermediate). + // out[0][0]: taps are visible pixels (12, 14..19) = [183, 106, 2, 87, 75, 198]: + // 183*3 - 106*16 + 2*77 + 87*77 - 75*16 + 198*3 + 64 = 5164 + // 5164 >> 7 = 40, already in 0..=255. + // out[1][2]: taps (13, 17..22) = [153, 188, 219, 13, 86, 194]: + // 153*3 - 188*16 + 219*77 + 13*77 - 86*16 + 194*3 + 64 = 14585 + // 14585 >> 7 = 113. + assert_eq!(dst[0], 40); + assert_eq!(dst[1 * 4 + 2], 113); + + // Full block against the tap-table reference formula. + for r in 0..4 { + for c in 0..4 { + let taps: Vec = (0..6) + .map(|k| i32::from(vis(&p, 16 + c - 2 + k as usize, 12 + r))) + .collect(); + let acc: i32 = taps + .iter() + .zip(SUB_PEL_FILTERS[4]) + .map(|(t, f)| t * f) + .sum::() + + 64; + assert_eq!( + dst[r * 4 + c], + (acc >> 7).clamp(0, 255) as u8, + "out[{r}][{c}] taps={taps:?} acc={acc}" + ); + } + } + } + + #[test] + fn sixtap_combined_phase_16x16_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 16 * 16]; + + // mv = (14, 18): full-pel start (10, 9), fx = 2, fy = 6. + predict_luma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (14, 18), false, &mut dst, 16, 16, 16, false, + ); + + // vp8_sub_pel_filters[2] = { 2, -11, 108, 36, -8, 1 }, each + // intermediate clamped to 0..=255 (e.g. tmp[3][10] taps + // [75, 190, 18, 15, 104, 40], raw dot -184, -184 >> 7 = -2, clamped 0); + // vertical pass with vp8_sub_pel_filters[6] = { 1, -8, 36, 108, -11, 2 }. + // + // out[0][0]: horizontal taps are visible pixels (7, 8..13), giving the + // post-clamp intermediate column h_tmp = [41, 186, 229, 210, 95, 185]: + // 41*1 - 186*8 + 229*36 + 210*108 - 95*11 + 185*2 + 64 = 28866 + // 28866 >> 7 = 225, already in 0..=255. + // + // out[5][9]: horizontal taps are visible pixels (11, 15..20), + // h_tmp = [205, 8, 14, 189, 108, 4]: + // 205*1 - 8*8 + 14*36 + 189*108 - 108*11 + 4*2 + 64 = 19941 + // 19941 >> 7 = 155. + assert_eq!(dst[0], 225); + assert_eq!(dst[5 * 16 + 9], 155); + + // Full block against the two-pass reference formula. + let mut tmp = [0i32; 21 * 16]; + for i in 0..21 { + for j in 0..16 { + let acc: i32 = (0..6) + .map(|k| i32::from(vis(&p, 10 - 2 + j + k, 9 - 2 + i))) + .zip(SUB_PEL_FILTERS[2]) + .map(|(t, f)| t * f) + .sum::() + + 64; + tmp[i * 16 + j] = (acc >> 7).clamp(0, 255); + } + } + for r in 0..16 { + for c in 0..16 { + let acc: i32 = (0..6) + .map(|k| tmp[(r + k) * 16 + c]) + .zip(SUB_PEL_FILTERS[6]) + .map(|(t, f)| t * f) + .sum::() + + 64; + assert_eq!( + dst[r * 16 + c], + (acc >> 7).clamp(0, 255) as u8, + "out[{r}][{c}]" + ); + } + } + } + + #[test] + fn bilinear_chroma_matches_hand_computed_values() { + let p = plane(); + let mut dst = [0u8; 8 * 8]; + + // mv = (11, 5): full-pel start (4, 7), fx = 5, fy = 3. + predict_chroma( + &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 6, (11, 5), false, &mut dst, 8, 8, 8, true, + ); + + // Horizontal taps { 48, 80 } (phase 5), vertical { 80, 48 } (phase 3), + // both passes (dot + 64) >> 7, no clamp (provably in range). + // + // out[0][0]: tmp[0][0] = (160*48 + 96*80 + 64) >> 7 = 120 from visible + // pixels (4,7),(5,7); tmp[1][0] = (107*48 + 42*80 + 64) >> 7 = 66 + // from (4,8),(5,8). + // 120*80 + 66*48 + 64 = 12832, 12832 >> 7 = 100. + // out[3][7]: tmp[3][7] = 84, tmp[4][7] = 189; + // 84*80 + 189*48 + 64 = 15856, 15856 >> 7 = 123. + assert_eq!(dst[0], 100); + assert_eq!(dst[3 * 8 + 7], 123); + + // Full block against the two-pass reference formula. + let mut tmp = [0u16; 9 * 8]; + for i in 0..9 { + for j in 0..8 { + tmp[i * 8 + j] = ((i32::from(vis(&p, 4 + j, 7 + i)) * 48 + + i32::from(vis(&p, 4 + j + 1, 7 + i)) * 80 + + 64) + >> 7) as u16; + } + } + for r in 0..8 { + for c in 0..8 { + let acc = i32::from(tmp[r * 8 + c]) * 80 + i32::from(tmp[(r + 1) * 8 + c]) * 48 + 64; + assert_eq!(dst[r * 8 + c], (acc >> 7) as u8, "out[{r}][{c}]"); + } + } + } + + #[test] + fn umv_border_clamps_match_libvpx_arithmetic() { + let p = plane(); + let mut a = [0u8; 16 * 16]; + let mut b = [0u8; 16 * 16]; + + // Single-MB frame (vis 16x16): mb_to_left_edge = mb_to_top_edge = 0, + // mb_to_right_edge = mb_to_bottom_edge = 0. + // + // Luma: mv (-1000, -1000) < 0 - 152 → both components set to -128 + // (left - (16 << 3)); prediction must equal an explicit (-128, -128). + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-1000, -1000), true, &mut a, 16, 16, 16, + false); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16, + false); + assert_eq!(a, b); + + // Strict threshold: (-152, -152) is NOT clamped (condition is strict + // `<`), (-153, -153) IS clamped to (-128, -128). + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), true, &mut a, 16, 16, 16, + false); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), false, &mut b, 16, 16, 16, + false); + assert_eq!(a, b); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-153, -153), true, &mut a, 16, 16, 16, + false); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16, + false); + assert_eq!(a, b); + + // Right/bottom: mv (4000, 4000) > 0 + 144 → set to +128. + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (4000, 4000), true, &mut a, 16, 16, 16, + false); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (128, 128), false, &mut b, 16, 16, 16, + false); + assert_eq!(a, b); + + // Chroma: 2 * (-2000) < -152 → (-128 >> 1) = -64 per component. + let mut ca = [0u8; 8 * 8]; + let mut cb = [0u8; 8 * 8]; + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (-2000, -2000), true, &mut ca, 8, 8, 8, + false); + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (-64, -64), false, &mut cb, 8, 8, 8, + false); + assert_eq!(ca, cb); + + // Chroma right/bottom: 2 * 2000 > 144 → (128 >> 1) = 64. + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (2000, 2000), true, &mut ca, 8, 8, 8, + false); + predict_chroma( + &p, STRIDE, BORDER, 8, 8, 0, 0, (64, 64), false, &mut cb, 8, 8, 8, + false); + assert_eq!(ca, cb); + + // An in-range MV with need_clamp=true must pass through untouched. + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), true, &mut a, 16, 16, 16, false, + ); + predict_luma( + &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), false, &mut b, 16, 16, 16, false, + ); + assert_eq!(a, b); + } +} diff --git a/crates/ec-vp8/src/modes.rs b/crates/ec-vp8/src/modes.rs new file mode 100644 index 00000000..48dd9d1e --- /dev/null +++ b/crates/ec-vp8/src/modes.rs @@ -0,0 +1,567 @@ +//! Macroblock prediction modes and their coding trees +//! (RFC 6386 §8.2, §11.2, §11.4, §16.1). + +use crate::bool::BoolDecoder; + +/// Intra macroblock luma modes (RFC 6386 §8.2 enum values are normative; +/// chroma modes are the first four). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum YMode { + /// Predict DC from the row above and column to the left. + DcPred = 0, + /// Predict rows from the row above. + VPred = 1, + /// Predict columns from the column to the left. + HPred = 2, + /// True-motion (second-difference) prediction. + TmPred = 3, + /// Each 4x4 Y subblock is independently predicted. + BPred = 4, +} + +impl YMode { + /// Value as coded in the trees (the RFC's enum integers). + pub fn as_u8(self) -> u8 { + self as u8 + } + + /// The subblock mode a 16x16 mode masquerades as for B_PRED context + /// purposes (RFC 6386 §11.3 item 4). + pub fn as_bmode(self) -> BMode { + match self { + YMode::DcPred => BMode::BDCPred, + YMode::VPred => BMode::BVEPred, + YMode::HPred => BMode::BHEPred, + YMode::TmPred => BMode::BTMPred, + YMode::BPred => unreachable!("B_PRED has no single subblock mode"), + } + } +} + +/// The ten 4x4 subblock prediction modes (RFC 6386 §11.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum BMode { + /// DC from above row and left column. + BDCPred = 0, + /// True-motion. + BTMPred = 1, + /// Vertical from smoothed above row. + BVEPred = 2, + /// Horizontal from smoothed left column. + BHEPred = 3, + /// Down-left diagonal. + BLDPred = 4, + /// Down-right diagonal. + BRDPred = 5, + /// Vertical-right diagonal. + BVRPred = 6, + /// Vertical-left diagonal. + BVLPred = 7, + /// Horizontal-down diagonal. + BHDPred = 8, + /// Horizontal-up diagonal. + BHUPred = 9, +} + +impl BMode { + /// Value as coded in the bmode tree (the RFC's enum integers). + pub fn as_u8(self) -> u8 { + self as u8 + } +} + +/// Key-frame Y-mode coding tree (RFC 6386 §11.2): B_PRED, then the four +/// full-block modes. Leaf values are the [`YMode`] enum integers. +pub const KF_YMODE_TREE: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3]; + +/// Key-frame Y-mode probabilities (fixed; RFC 6386 §11.2 and the +/// reference decoder's `kf_y_mode_probs`). +pub const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128]; + +/// Interframe Y-mode coding tree (RFC 6386 §8.2). +pub const YMODE_TREE: [i8; 8] = [0, 2, 4, 6, -1, -2, -3, -4]; + +/// Chroma-mode coding tree (RFC 6386 §8.2/§11.4): DC, V, H, TM. +pub const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; + +/// Key-frame chroma-mode probabilities (fixed; RFC 6386 §11.4). +pub const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183]; + +/// 4x4 subblock-mode coding tree (RFC 6386 §11.2). Leaf values are the +/// [`BMode`] enum integers; note the leaf 0 (B_DC_PRED) relies on the +/// tree reader's `i <= 0` leaf test. +pub const BMODE_TREE: [i8; 18] = [ + 0, 2, // B_DC_PRED = "0" + -1, 4, // B_TM = "10" + -2, 6, // B_VE = "110" + 8, 12, // inner + -3, 10, // B_HE = "11100" + -5, -6, // B_RD = "111010", B_VR = "111011" + -4, 14, // B_LD = "111110" + -7, 16, // B_VL = "1111110" + -8, -9, // B_HD = "11111110", B_HU = "11111111" +]; + +/// Subblock modes in interframes decode with this constant probability +/// array, no context (RFC 6386 §11.3 item 5 / §16). +pub const INTER_BMODE_PROBS: [u8; 9] = [120, 90, 79, 133, 87, 85, 80, 111, 151]; + +/// Decode a key-frame Y mode (RFC 6386 §11.2). +pub fn read_kf_ymode(d: &mut BoolDecoder<'_>) -> YMode { + YMode::from_u8(d.read_tree(&KF_YMODE_TREE, &KF_YMODE_PROBS)) +} + +/// Decode an interframe Y mode at the persisted probabilities +/// (RFC 6386 §16.1; `probs` is the frame header's updated array). +pub fn read_ymode(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> YMode { + YMode::from_u8(d.read_tree(&YMODE_TREE, probs)) +} + +/// Decode a chroma mode at the given (key-frame fixed or persisted +/// interframe) probabilities. +pub fn read_uvmode(d: &mut BoolDecoder<'_>, probs: &[u8; 3]) -> YMode { + YMode::from_u8(d.read_tree(&UV_MODE_TREE, probs)) +} + +/// Decode a 4x4 subblock mode at `probs` (RFC 6386 §11.3: in key frames +/// the probabilities come from the above/left context table). +pub fn read_bmode(d: &mut BoolDecoder<'_>, probs: &[u8]) -> BMode { + BMode::from_u8(d.read_tree(&BMODE_TREE, probs)) +} + +impl YMode { + fn from_u8(v: u8) -> YMode { + match v { + 0 => YMode::DcPred, + 1 => YMode::VPred, + 2 => YMode::HPred, + 3 => YMode::TmPred, + 4 => YMode::BPred, + _ => unreachable!("tree cannot produce mode {v}"), + } + } +} + +impl BMode { + fn from_u8(v: u8) -> BMode { + match v { + 0 => BMode::BDCPred, + 1 => BMode::BTMPred, + 2 => BMode::BVEPred, + 3 => BMode::BHEPred, + 4 => BMode::BLDPred, + 5 => BMode::BRDPred, + 6 => BMode::BVRPred, + 7 => BMode::BVLPred, + 8 => BMode::BHDPred, + 9 => BMode::BHUPred, + _ => unreachable!("tree cannot produce bmode {v}"), + } + } +} + +/// Inter-frame motion-vector reference modes (RFC 6386 §16.2), offset +/// from the intra modes by `num_ymodes` in the reference enum; here they +/// are their own small enum with the RFC's tree integers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum MvRef { + /// Zero motion vector ("10" second branch; coded 0). + Zero = 0, + /// "Nearest" vector (coded 1). + Nearest = 1, + /// "Near" vector (coded 2). + Near = 2, + /// Explicit offset from best (coded 3). + New = 3, + /// Per-subblock vectors (coded 4). + Split = 4, +} + +/// mv_ref coding tree (RFC 6386 §16.2): leaves are [`MvRef`] integers. +/// mv_ref coding tree (RFC 6386 §16.2); leaves are [`MvRef`] integers. +pub const MV_REF_TREE: [i8; 8] = [0, 2, -1, 4, -2, 6, -3, -4]; + +/// Motion-vector component: row then column, each with the 19-probability +/// table (§17.1). +/// Probability-table offsets of one MV component (RFC 6386 §17.1). +pub const MVP_IS_SHORT: usize = 0; +/// Sign probability offset (§17.1). +pub const MVP_SIGN: usize = 1; +/// Short-value tree offset (§17.1). +/// Short-value tree offset (§17.1). +pub const MVP_SHORT: usize = 2; +/// Long-value bit probabilities offset (§17.1). +/// Long-value bit probabilities offset (§17.1). +pub const MVP_BITS: usize = MVP_SHORT + 7; +/// Total probabilities per MV component (§17.1). +/// Total probabilities per MV component (§17.1). +pub const MVP_COUNT: usize = MVP_BITS + 10; + +/// Small-value coding tree for MV components (§17.1 `small_mvtree`). +/// Small-value coding tree for MV components (§17.1). +pub const SMALL_MV_TREE: [i8; 14] = [ + 2, 8, // "0" / "1" subtrees + 4, 6, // "00" / "01" + 0, -1, // 0 = "000", 1 = "001" + -2, -3, // 2, 3 + 10, 12, // "10" / "11" + -4, -5, // 4, 5 + -6, -7, // 6, 7 +]; + +/// SPLITMV partition shapes tree + fixed probs (§16.4). Leaves are the +/// RFC's `MVpartition` integers: 0 = top/bottom, 1 = left/right, +/// 2 = quarters, 3 = MV_16. +pub const MV_PARTITION_TREE: [i8; 6] = [-3, 2, -2, 4, 0, -1]; +/// SPLITMV partition tree fixed probabilities (§16.4). +pub const MV_PARTITION_PROBS: [u8; 3] = [110, 111, 150]; + +/// The four SPLITMV partitionings as subblock groups (§16.4), indexed +/// by the `MVpartition` integer: each group shares one motion vector, +/// decoded in the listed (leader) order. +pub const MV_PARTITIONS: [&[usize]; 4] = [ + // mv_top_bottom: {0..7} then {8..15}. + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + // mv_left_right: {0,1,4,5,8,9,12,13} then {2,3,6,7,10,11,14,15}. + &[0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], + // mv_quarters: {0,1,4,5} {2,3,6,7} {8,9,12,13} {10,11,14,15}. + &[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], + // MV_16: every subblock gets its own vector, raster order. + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Number of distinct vectors per partition shape (§16.4). +pub const MV_PARTITION_COUNT: [usize; 4] = [2, 2, 4, 16]; + +/// Inter subblock modes (§16.4): reuse the already-coded MV left/above, +/// zero, or an explicit offset. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum SubMvRef { + /// Copy the left neighbour's MV (coded 0). + Left4x4 = 0, + /// Copy the above neighbour's MV (coded 1). + Above4x4 = 1, + /// Zero MV (coded 2). + Zero4x4 = 2, + /// Explicit offset from best (coded 3). + New4x4 = 3, +} + +/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers. +/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers. +pub const SUB_MV_REF_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; + +/// Context-conditioned sub-MV probabilities (§16.4 `sub_mv_ref_prob`). +pub const SUB_MV_REF_PROBS: [[u8; 3]; 5] = [ + [147, 136, 18], + [106, 145, 1], + [179, 121, 1], + [223, 1, 34], + [208, 1, 1], +]; + +/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, +/// 3 = left==above, 2 = above zero, 1 = left zero, 0 = normal. +/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, +pub fn mv_cont(l: (i16, i16), a: (i16, i16)) -> usize { + let lez = l == (0, 0); + let aez = a == (0, 0); + let lea = l == a; + if lea && lez { + 4 + } else if lea { + 3 + } else if aez { + 2 + } else if lez { + 1 + } else { + 0 + } +} + +/// Weighted-census probability table for the mv_ref tree +/// (§16.3 `vp8_mode_contexts`, indexed by clamped count per slot). +pub const MODE_CONTEXTS: [[u8; 4]; 6] = [ + [7, 1, 1, 143], + [14, 18, 14, 107], + [135, 64, 57, 68], + [60, 56, 128, 65], + [159, 134, 128, 34], + [234, 188, 128, 28], +]; + +/// Decode an mv_ref at the census-derived probabilities (§16.2/§16.3). +pub fn read_mv_ref(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> MvRef { + match d.read_tree(&MV_REF_TREE, probs) { + 0 => MvRef::Zero, + 1 => MvRef::Nearest, + 2 => MvRef::Near, + 3 => MvRef::New, + 4 => MvRef::Split, + v => unreachable!("mv_ref tree produced {v}"), + } +} + +/// Decode a SPLITMV partition shape (§16.4); returns the `MVpartition` +/// integer indexing [`MV_PARTITIONS`]. +pub fn read_mv_partition(d: &mut BoolDecoder<'_>) -> usize { + usize::from(d.read_tree(&MV_PARTITION_TREE, &MV_PARTITION_PROBS)) +} + +/// Decode a sub-MV reference (§16.4) at the context's probabilities. +pub fn read_sub_mv_ref(d: &mut BoolDecoder<'_>, ctx: usize) -> SubMvRef { + match d.read_tree(&SUB_MV_REF_TREE, &SUB_MV_REF_PROBS[ctx]) { + 0 => SubMvRef::Left4x4, + 1 => SubMvRef::Above4x4, + 2 => SubMvRef::Zero4x4, + 3 => SubMvRef::New4x4, + v => unreachable!("sub_mv_ref tree produced {v}"), + } +} + +/// First subblock of each SPLITMV subset, per partition shape (libvpx +/// `vp8_mbsplit_offset`; shapes 16x8, 8x16, 8x8, 4x4). +pub const MBSPLIT_OFFSET: [[u8; 16]; 4] = [ + [0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Subblocks filled by one subset, per partition shape (libvpx +/// `mbsplit_fill_count`). +pub const MBSPLIT_FILL_COUNT: [usize; 4] = [8, 8, 4, 1]; + +/// Subblock indices each subset fills, per shape (libvpx +/// `mbsplit_fill_offset`; subset j starts at j * fill_count). +pub const MBSPLIT_FILL_OFFSET: [[u8; 16]; 4] = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], + [0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], + [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], +]; + +/// Decode one motion-vector component (§17.1, libvpx `read_mvcomponent`): +/// either a 3-bit small value off [`SMALL_MV_TREE`] or a 9-bit long form +/// whose bit 3 is sometimes implicit, then a sign flag. +pub fn read_mv_component(d: &mut BoolDecoder<'_>, probs: &[u8; MVP_COUNT]) -> i16 { + let mut x: i32 = 0; + if d.read_bool(probs[MVP_IS_SHORT]) { + // Large: bits 0..2, then 8..4 (bit 3 is implicit below). + for i in 0..3 { + x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i; + } + let mut i = 9; + loop { + x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i; + i -= 1; + if i <= 3 { + break; + } + } + if (x & 0xFFF0) == 0 || d.read_bool(probs[MVP_BITS + 3]) { + x += 8; + } + } else { + x = i32::from(d.read_tree(&SMALL_MV_TREE, &probs[MVP_SHORT..MVP_SHORT + 7])); + } + if x != 0 && d.read_bool(probs[MVP_SIGN]) { + x = -x; + } + x as i16 +} + +/// Both components of a whole-block motion vector (§17.1); the decoded +/// quarter-pel components double into the decoder's eighth-pel units. +pub fn read_mv(d: &mut BoolDecoder<'_>, probs: &[[u8; MVP_COUNT]; 2]) -> (i16, i16) { + ( + read_mv_component(d, &probs[0]).wrapping_mul(2), + read_mv_component(d, &probs[1]).wrapping_mul(2), + ) +} + +/// Flip a candidate motion vector when the reference it was coded +/// against has a different sign bias than the current reference +/// (§16.3, libvpx `mv_bias`). +pub fn mv_bias(from_bias: bool, to_bias: bool, mv: (i16, i16)) -> (i16, i16) { + if from_bias != to_bias { + (-mv.0, -mv.1) + } else { + mv + } +} + +/// One neighbour macroblock's motion-vector census input (§16.3). +pub struct MvNeighbor { + /// The MB is intra-coded (no MV contribution at all). + pub intra: bool, + /// The MB is inter-coded with a zero motion vector (counts like + /// intra in the census). + pub zero: bool, + /// The MB's motion vector (already sign-bias-adjusted if applicable + /// — pass `sign_bias` and the census applies it). + pub mv: (i16, i16), + /// The MB is SPLITMV (feeds the split census count). + pub is_split: bool, + /// The sign bias of the reference the MB's MV points into. + pub sign_bias: bool, +} + +/// Slot indices of the census result (§16.3). +pub const CNT_INTRA: usize = 0; +/// Slot index: nearest-candidate count. +pub const CNT_NEAREST: usize = 1; +/// Slot index: near-candidate count. +pub const CNT_NEAR: usize = 2; +/// Slot index: split-neighbour count. +pub const CNT_SPLITMV: usize = 3; + +/// The neighborhood motion-vector census (§16.3, libvpx +/// `find_near_mvs` inlined in `read_mb_modes_mv`): up to three distinct +/// candidate vectors with per-slot counts, scanned above, left, +/// above-left; each inter neighbour counts 2/2/1 toward either the +/// candidate slot it extends or the zero/intra count. +pub fn find_near_mvs( + above: MvNeighbor, + left: MvNeighbor, + aboveleft: MvNeighbor, + to_bias: bool, +) -> ([(i16, i16); 4], [i32; 4]) { + let mut mvs = [(0i16, 0i16); 4]; + let mut cnt = [0i32; 4]; + let mut idx = 0usize; + let mut cntx = 0usize; + + // Above: the first candidate is pushed unconditionally. + if !above.intra { + if !above.zero { + idx += 1; + mvs[idx] = mv_bias(above.sign_bias, to_bias, above.mv); + cntx += 1; + } + cnt[cntx] += 2; + } + for (mb, w) in [(&left, 2), (&aboveleft, 1)] { + if !mb.intra { + if !mb.zero { + let this = mv_bias(mb.sign_bias, to_bias, mb.mv); + if this != mvs[idx] { + idx += 1; + mvs[idx] = this; + cntx += 1; + } + cnt[cntx] += w; + } else { + cnt[CNT_INTRA] += i32::from(w); + } + } + } + + // Above-left merge (libvpx decodemv.c:366): when the above-left + // pushed a THIRD distinct candidate, its count landed in + // cnt[CNT_SPLITMV] (cntx reached slot 3), and if that candidate + // equals the nearest candidate, NEAREST absorbs it. The split count + // is then overwritten with the SPLITMV-neighbour census below. + if cnt[CNT_SPLITMV] != 0 && mvs[idx] == mvs[CNT_NEAREST] { + cnt[CNT_NEAREST] += 1; + } + cnt[CNT_SPLITMV] = i32::from(above.is_split) * 2 + + i32::from(left.is_split) * 2 + + i32::from(aboveleft.is_split); + + if cnt[CNT_NEAR] > cnt[CNT_NEAREST] { + cnt.swap(CNT_NEAR, CNT_NEAREST); + mvs.swap(CNT_NEAR, CNT_NEAREST); + } + (mvs, cnt) +} + +/// Per-MB motion-vector clamp edges in eighth-pels (libvpx +/// `mb_to_*_edge`): distance from the MB's edge to the frame edge. +pub fn mb_edges(col: usize, row: usize, mb_cols: usize, mb_rows: usize) -> (i32, i32, i32, i32) { + ( + -((i32::try_from(col).unwrap() * 16) << 3), + ((i32::try_from(mb_cols - 1 - col).unwrap() * 16) << 3), + -((i32::try_from(row).unwrap() * 16) << 3), + ((i32::try_from(mb_rows - 1 - row).unwrap() * 16) << 3), + ) +} + +/// Clamp a candidate MV into the current MB's allowed range plus a +/// 128-eighth-pel margin (§16.2, libvpx `vp8_clamp_mv2`). +pub fn clamp_mv2(mv: &mut (i16, i16), edges: (i32, i32, i32, i32)) { + let (l, r, t, b) = edges; + let c = i32::from(mv.1); + if c < l - 128 { + mv.1 = (l - 128) as i16; + } else if c > r + 128 { + mv.1 = (r + 128) as i16; + } + let ro = i32::from(mv.0); + if ro < t - 128 { + mv.0 = (t - 128) as i16; + } else if ro > b + 128 { + mv.0 = (b + 128) as i16; + } +} + +/// Whether an explicit MV exceeds the MB's bounds (libvpx +/// `vp8_check_mv_bounds`): strictly outside, no margin. +pub fn mv_out_of_bounds(mv: (i16, i16), edges: (i32, i32, i32, i32)) -> bool { + let (l, r, t, b) = edges; + i32::from(mv.1) < l || i32::from(mv.1) > r || i32::from(mv.0) < t || i32::from(mv.0) > b +} + +/// Chroma motion vector for a whole-MB mode (libvpx +/// `vp8_build_inter16x16_predictors_mb`): halve each component with +/// round-half-away-from-zero (`x += 1 | (x >> 31); x /= 2`). +pub fn chroma_mv_whole(mv: (i16, i16), fullpel: bool) -> (i16, i16) { + fn half(x: i16, fullpel: bool) -> i16 { + let x = i32::from(x); + let v = ((x + (1 | (x >> 31))) / 2) as i16; + // `& fullpixel_mask` (reconinter.c:333-334): version-3 streams + // are full-pel, so the sub-pel bits are cleared after rounding. + if fullpel { + v & !7 + } else { + v + } + } + (half(mv.0, fullpel), half(mv.1, fullpel)) +} + +/// Chroma motion vector for one 8x8 quadrant of a SPLITMB (libvpx +/// `build_4x4uvmvs`): sum the quadrant's four subblock vectors, then +/// divide by 8 with round-half-away-from-zero +/// (`t += 4 + (t >> 31) * 8; t /= 8`). +pub fn chroma_mv_split(quadrant: &[(i16, i16); 4], fullpel: bool) -> (i16, i16) { + fn eighth(parts: [i16; 4], fullpel: bool) -> i16 { + let t = i32::from(parts[0]) + + i32::from(parts[1]) + + i32::from(parts[2]) + + i32::from(parts[3]); + let t = t + 4 + (t >> 31) * 8; + let v = (t / 8) as i16; + // `& fullpixel_mask` (reconinter.c:472-481). + if fullpel { + v & !7 + } else { + v + } + } + ( + eighth( + [quadrant[0].0, quadrant[1].0, quadrant[2].0, quadrant[3].0], + fullpel, + ), + eighth( + [quadrant[0].1, quadrant[1].1, quadrant[2].1, quadrant[3].1], + fullpel, + ), + ) +} diff --git a/crates/ec-vp8/src/stream.rs b/crates/ec-vp8/src/stream.rs new file mode 100644 index 00000000..4f3b98a8 --- /dev/null +++ b/crates/ec-vp8/src/stream.rs @@ -0,0 +1,134 @@ +//! Whole-stream decoding: an IVF file in, decoded pictures out. +//! +//! VP8 frames are not self-delimiting — a bare frame is a 3-byte +//! uncompressed tag followed by partitions whose total size only the +//! container knows — so the whole-stream API takes the stream in the +//! container VP8 actually ships in: IVF (the RFC's companion container, +//! `DKIF`/`VP80`; also what vpxenc, ffmpeg and the WebM toolchain emit +//! for raw VP8 elementaries). Single frames from any other demuxer feed +//! [`crate::decode::Decoder::decode`] directly. +//! +//! The shape mirrors `ec_av1::stream`: [`decode_stream`] collects every +//! shown picture into a `Vec`, and [`decode_stream_with`] hands each +//! picture to a sink the moment it exists. + +use crate::decode::{Decoder, Picture}; +use crate::{Error, Result}; + +/// The IVF file magic, `DKIF`. +const DKIF: &[u8; 4] = b"DKIF"; +/// The fourcc for VP8 video (`VP80`; `VP8L`/`VP8x` are WebP-lossless/alpha). +const VP80: &[u8; 4] = b"VP80"; + +/// One demuxed IVF frame: presentation timestamp plus the compressed +/// VP8 payload. +struct IvfFrame<'a> { + pts: u64, + data: &'a [u8], +} + +/// Split an IVF byte stream into its frames, validating the container +/// envelope (magic, fourcc, framing arithmetic) as [`Error`]s rather +/// than panics. +fn demux(data: &[u8]) -> Result>> { + if data.len() < 32 || &data[0..4] != DKIF { + return Err(Error::corrupt("not an IVF stream (missing DKIF magic)")); + } + // Bytes 4..6 version (informational), 6..8 header length, 8..12 fourcc. + let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize; + if data.len() < hdr_len || hdr_len < 12 { + return Err(Error::corrupt("IVF header length out of range")); + } + if &data[8..12] != VP80 { + return Err(Error::unsupported( + "IVF fourcc", + "the stream is not VP80 (VP8 video)", + )); + } + // Bytes 12..16 carry the nominal width/height; VP8 streams set them + // to 0 and take the real dimensions from the key frame, so the + // decoder does not consult them. + let _ = u16::from_le_bytes([data[12], data[13]]); + let _ = u16::from_le_bytes([data[14], data[15]]); + let mut frames = Vec::new(); + let mut pos = hdr_len; + while pos + 12 <= data.len() { + let sz = + u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]]) + as usize; + let pts = u64::from_le_bytes([ + data[pos + 4], + data[pos + 5], + data[pos + 6], + data[pos + 7], + data[pos + 8], + data[pos + 9], + data[pos + 10], + data[pos + 11], + ]); + pos += 12; + if pos + sz > data.len() { + return Err(Error::corrupt(format!( + "IVF frame {} extends past end of stream (need {} bytes \ + at offset {})", + frames.len(), + sz, + pos + ))); + } + frames.push(IvfFrame { + pts, + data: &data[pos..pos + sz], + }); + pos += sz; + } + Ok(frames) +} + +/// Decode every frame in an IVF VP8 stream, in presentation order. +/// +/// The stream must start with a key frame; hidden frames (alternate +/// references, `show_frame == 0`) update the reference buffers but are +/// not part of the output, exactly as a player would not display them. +/// +/// # Errors +/// Returns an error when the container is truncated or not VP80 (as +/// [`demux`] reports it), when a frame is malformed (as +/// [`crate::decode::Decoder::decode`] reports it), or when an inter +/// frame appears before any key frame has supplied references. +pub fn decode_stream(data: &[u8]) -> Result> { + let mut pictures: Vec = Vec::new(); + decode_stream_with(data, |picture, _decode_idx, _pts| { + pictures.push(picture.clone()); + Ok(()) + })?; + Ok(pictures) +} + +/// Streaming form of [`decode_stream`]: hand every shown picture to +/// `sink` the moment it exists and drop it right after, so peak memory +/// is one output picture plus the reference frames instead of the whole +/// decoded stream. `decode_stream` itself is this function collecting +/// into a `Vec`. +/// +/// `sink` is called with the picture, the decode-order index of the +/// coded frame it came from, and the IVF presentation timestamp. A +/// hidden frame (`show_frame == 0`) updates the decoder state but +/// produces no picture, so the sink is not called for it. An `Err` the +/// sink returns aborts the decode and is returned unchanged. +/// +/// # Errors +/// As [`decode_stream`], plus whatever `sink` returns. +pub fn decode_stream_with( + data: &[u8], + mut sink: impl FnMut(&Picture, usize, u64) -> Result<()>, +) -> Result<()> { + let frames = demux(data)?; + let mut dec = Decoder::new(); + for (decode_idx, frame) in frames.iter().enumerate() { + if let Some(picture) = dec.decode(frame.data)? { + sink(&picture, decode_idx, frame.pts)?; + } + } + Ok(()) +} diff --git a/crates/ec-vp8/src/tables.rs b/crates/ec-vp8/src/tables.rs new file mode 100644 index 00000000..1a50dfea --- /dev/null +++ b/crates/ec-vp8/src/tables.rs @@ -0,0 +1,537 @@ +//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and +//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from +//! the RFC text; do not edit by hand. The extractor asserts every +//! table's element count, so a slip cannot drop or add values. +#![allow(clippy::all)] + +/// RFC 6386 `coeff_update_probs`. +pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], + [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], + [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], + [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], +]; + +/// RFC 6386 `default_coeff_probs`. +pub const DEFAULT_COEFF_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], + [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], + [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128], + ], + [ + [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], + [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], + [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128], + ], + [ + [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], + [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], + [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128], + ], + [ + [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], + [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], + [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128], + ], + [ + [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], + [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], + [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128], + ], + [ + [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], + [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], + [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], + [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], + [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128], + ], + [ + [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], + [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], + [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128], + ], + [ + [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], + [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], + [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128], + ], + [ + [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], + [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], + [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128], + ], + [ + [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], + [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], + [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128], + ], + [ + [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], + [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], + [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128], + ], + [ + [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], + [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], + [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128], + ], + [ + [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], + [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], + [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], + [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128], + ], + [ + [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], + [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], + [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128], + ], + [ + [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], + [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], + [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128], + ], + [ + [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], + [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], + [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], + [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], + [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], + [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], + [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], + [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128], + ], + [ + [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], + [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], + [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128], + ], + [ + [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], + [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], + [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128], + ], + [ + [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], + [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], + [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128], + ], + [ + [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], + [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], + [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128], + ], + [ + [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], + [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], + [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128], + ], + [ + [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], + [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], + [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], +]; + +/// RFC 6386 `kf_bmode_prob`. +pub const KF_BMODE_PROB: [[[u8; 9]; 10]; 10] = [ + [ + [231, 120, 48, 89, 115, 113, 120, 152, 112], + [152, 179, 64, 126, 170, 118, 46, 70, 95], + [175, 69, 143, 80, 85, 82, 72, 155, 103], + [56, 58, 10, 171, 218, 189, 17, 13, 152], + [144, 71, 10, 38, 171, 213, 144, 34, 26], + [114, 26, 17, 163, 44, 195, 21, 10, 173], + [121, 24, 80, 195, 26, 62, 44, 64, 85], + [170, 46, 55, 19, 136, 160, 33, 206, 71], + [63, 20, 8, 114, 114, 208, 12, 9, 226], + [81, 40, 11, 96, 182, 84, 29, 16, 36], + ], + [ + [134, 183, 89, 137, 98, 101, 106, 165, 148], + [72, 187, 100, 130, 157, 111, 32, 75, 80], + [66, 102, 167, 99, 74, 62, 40, 234, 128], + [41, 53, 9, 178, 241, 141, 26, 8, 107], + [104, 79, 12, 27, 217, 255, 87, 17, 7], + [74, 43, 26, 146, 73, 166, 49, 23, 157], + [65, 38, 105, 160, 51, 52, 31, 115, 128], + [87, 68, 71, 44, 114, 51, 15, 186, 23], + [47, 41, 14, 110, 182, 183, 21, 17, 194], + [66, 45, 25, 102, 197, 189, 23, 18, 22], + ], + [ + [88, 88, 147, 150, 42, 46, 45, 196, 205], + [43, 97, 183, 117, 85, 38, 35, 179, 61], + [39, 53, 200, 87, 26, 21, 43, 232, 171], + [56, 34, 51, 104, 114, 102, 29, 93, 77], + [107, 54, 32, 26, 51, 1, 81, 43, 31], + [39, 28, 85, 171, 58, 165, 90, 98, 64], + [34, 22, 116, 206, 23, 34, 43, 166, 73], + [68, 25, 106, 22, 64, 171, 36, 225, 114], + [34, 19, 21, 102, 132, 188, 16, 76, 124], + [62, 18, 78, 95, 85, 57, 50, 48, 51], + ], + [ + [193, 101, 35, 159, 215, 111, 89, 46, 111], + [60, 148, 31, 172, 219, 228, 21, 18, 111], + [112, 113, 77, 85, 179, 255, 38, 120, 114], + [40, 42, 1, 196, 245, 209, 10, 25, 109], + [100, 80, 8, 43, 154, 1, 51, 26, 71], + [88, 43, 29, 140, 166, 213, 37, 43, 154], + [61, 63, 30, 155, 67, 45, 68, 1, 209], + [142, 78, 78, 16, 255, 128, 34, 197, 171], + [41, 40, 5, 102, 211, 183, 4, 1, 221], + [51, 50, 17, 168, 209, 192, 23, 25, 82], + ], + [ + [125, 98, 42, 88, 104, 85, 117, 175, 82], + [95, 84, 53, 89, 128, 100, 113, 101, 45], + [75, 79, 123, 47, 51, 128, 81, 171, 1], + [57, 17, 5, 71, 102, 57, 53, 41, 49], + [115, 21, 2, 10, 102, 255, 166, 23, 6], + [38, 33, 13, 121, 57, 73, 26, 1, 85], + [41, 10, 67, 138, 77, 110, 90, 47, 114], + [101, 29, 16, 10, 85, 128, 101, 196, 26], + [57, 18, 10, 102, 102, 213, 34, 20, 43], + [117, 20, 15, 36, 163, 128, 68, 1, 26], + ], + [ + [138, 31, 36, 171, 27, 166, 38, 44, 229], + [67, 87, 58, 169, 82, 115, 26, 59, 179], + [63, 59, 90, 180, 59, 166, 93, 73, 154], + [40, 40, 21, 116, 143, 209, 34, 39, 175], + [57, 46, 22, 24, 128, 1, 54, 17, 37], + [47, 15, 16, 183, 34, 223, 49, 45, 183], + [46, 17, 33, 183, 6, 98, 15, 32, 183], + [65, 32, 73, 115, 28, 128, 23, 128, 205], + [40, 3, 9, 115, 51, 192, 18, 6, 223], + [87, 37, 9, 115, 59, 77, 64, 21, 47], + ], + [ + [104, 55, 44, 218, 9, 54, 53, 130, 226], + [64, 90, 70, 205, 40, 41, 23, 26, 57], + [54, 57, 112, 184, 5, 41, 38, 166, 213], + [30, 34, 26, 133, 152, 116, 10, 32, 134], + [75, 32, 12, 51, 192, 255, 160, 43, 51], + [39, 19, 53, 221, 26, 114, 32, 73, 255], + [31, 9, 65, 234, 2, 15, 1, 118, 73], + [88, 31, 35, 67, 102, 85, 55, 186, 85], + [56, 21, 23, 111, 59, 205, 45, 37, 192], + [55, 38, 70, 124, 73, 102, 1, 34, 98], + ], + [ + [102, 61, 71, 37, 34, 53, 31, 243, 192], + [69, 60, 71, 38, 73, 119, 28, 222, 37], + [68, 45, 128, 34, 1, 47, 11, 245, 171], + [62, 17, 19, 70, 146, 85, 55, 62, 70], + [75, 15, 9, 9, 64, 255, 184, 119, 16], + [37, 43, 37, 154, 100, 163, 85, 160, 1], + [63, 9, 92, 136, 28, 64, 32, 201, 85], + [86, 6, 28, 5, 64, 255, 25, 248, 1], + [56, 8, 17, 132, 137, 255, 55, 116, 128], + [58, 15, 20, 82, 135, 57, 26, 121, 40], + ], + [ + [164, 50, 31, 137, 154, 133, 25, 35, 218], + [51, 103, 44, 131, 131, 123, 31, 6, 158], + [86, 40, 64, 135, 148, 224, 45, 183, 128], + [22, 26, 17, 131, 240, 154, 14, 1, 209], + [83, 12, 13, 54, 192, 255, 68, 47, 28], + [45, 16, 21, 91, 64, 222, 7, 1, 197], + [56, 21, 39, 155, 60, 138, 23, 102, 213], + [85, 26, 85, 85, 128, 128, 32, 146, 171], + [18, 11, 7, 63, 144, 171, 4, 4, 246], + [35, 27, 10, 146, 174, 171, 12, 26, 128], + ], + [ + [190, 80, 35, 99, 180, 80, 126, 54, 45], + [85, 126, 47, 87, 176, 51, 41, 20, 32], + [101, 75, 128, 139, 118, 146, 116, 128, 85], + [56, 41, 15, 176, 236, 85, 37, 9, 62], + [146, 36, 19, 30, 171, 255, 97, 27, 20], + [71, 30, 17, 119, 118, 255, 17, 18, 138], + [101, 38, 60, 138, 55, 70, 43, 26, 142], + [138, 45, 61, 62, 219, 1, 81, 188, 64], + [32, 41, 20, 117, 151, 142, 20, 21, 163], + [112, 19, 12, 61, 195, 128, 48, 4, 24], + ], +]; + +/// RFC 6386 `coeff_bands`. +pub const COEFF_BANDS: [u8; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7]; + +/// RFC 6386 `dc_qlookup`. +pub const DC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +]; + +/// RFC 6386 `ac_qlookup`. +pub const AC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +]; + +/// RFC 6386 `Pcat1` (trailing 0 is the DCTextra sentinel). +pub const PCAT1: [u8; 2] = [159, 0]; + +/// RFC 6386 `Pcat2` (trailing 0 is the DCTextra sentinel). +pub const PCAT2: [u8; 3] = [165, 145, 0]; + +/// RFC 6386 `Pcat3` (trailing 0 is the DCTextra sentinel). +pub const PCAT3: [u8; 4] = [173, 148, 140, 0]; + +/// RFC 6386 `Pcat4` (trailing 0 is the DCTextra sentinel). +pub const PCAT4: [u8; 5] = [176, 155, 140, 135, 0]; + +/// RFC 6386 `Pcat5` (trailing 0 is the DCTextra sentinel). +pub const PCAT5: [u8; 6] = [180, 157, 141, 134, 130, 0]; + +/// RFC 6386 `Pcat6` (trailing 0 is the DCTextra sentinel). +pub const PCAT6: [u8; 12] = [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0]; + +/// RFC 6386 `k_default_mv_probs`. +pub const DEFAULT_MV_PROBS: [[u8; 19]; 2] = [ + [ + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + ], + [ + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, + 254, + ], +]; + +/// RFC 6386 `k_mv_entropy_update_probs`. +pub const MV_UPDATE_PROBS: [[u8; 19]; 2] = [ + [ + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, + 254, + ], + [ + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, + 254, + ], +]; diff --git a/crates/ec-vp8/src/tokens.rs b/crates/ec-vp8/src/tokens.rs new file mode 100644 index 00000000..d3904e36 --- /dev/null +++ b/crates/ec-vp8/src/tokens.rs @@ -0,0 +1,314 @@ +//! DCT coefficient (token) decoding — RFC 6386 §13. +//! +//! Per 4x4 block: tokens are tree-decoded at +//! `probs[type][band[position]][ctx]` where `ctx` (0..2) is the zero- +//! neighbour count — sum of the above/left block contexts for the first +//! coded coefficient, then derived from the magnitude of the previous +//! coefficient within the block (§13.3). Coefficients are written in +//! natural (de-zigzagged) order and dequantized on the fly (the first +//! coded position takes the DC factor, all others the AC factor — the +//! same arithmetic dixie applies inline and libvpx applies in +//! `vp8_dequantize_b`). +//! +//! After an EOB the block ends; after a `DCT_0` token the tree decode of +//! the next coefficient skips the EOB branch (§13.2). A block whose +//! coefficients fill all 16 positions cannot take an EOB (the decoder +//! stops at 16 exactly like the reference decoder, down to the sentinel +//! band entry). + +use crate::bool::BoolDecoder; +use crate::tables::{PCAT3, PCAT4, PCAT5, PCAT6}; + +/// De-zigzag: coefficient scan position -> natural order index +/// (RFC 6386 §13, dixie/libvpx `zigzag`). +const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + +/// Band per coefficient position, with the reference decoder's sentinel +/// entry at 16 (band 0 on the malformed no-EOB path — libvpx `kBands`). +const BANDS: [u8; 17] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]; + +/// Extra-bit probability tables per category (cat3..cat6, RFC 6386 +/// §13.2; the cat1/cat2 probabilities 159/165+145 are inlined in the +/// tree decode exactly as the reference does). Trailing 0 is the +/// DCTextra sentinel. +const CAT_EXTRA: [&[u8]; 4] = [&PCAT3, &PCAT4, &PCAT5, &PCAT6]; + +/// Dequantization factors for one macroblock (already scaled: Y2 AC has +/// the ×155/100 min-8 rule applied, Y2 DC ×2, UV DC capped at 132). +#[derive(Debug, Clone, Copy)] +pub(crate) struct Dq { + pub y1_dc: i16, + pub y1_ac: i16, + pub uv_dc: i16, + pub uv_ac: i16, + pub y2_dc: i16, + pub y2_ac: i16, +} + +/// The 25 blocks of one macroblock, dequantized, in natural coefficient +/// order. `eobs[b]` is the number of significant coefficients (position +/// of the last non-zero + 1); `eob_mask` mirrors dixie's: bit b set iff +/// block b ended with more than one significant coefficient, bit 31 set +/// iff ANY block had a non-zero coefficient. +pub(crate) struct MbCoeffs { + pub y: [[i16; 16]; 16], + pub u: [[i16; 16]; 4], + pub v: [[i16; 16]; 4], + pub y2: [i16; 16], + pub has_y2: bool, + pub eobs: [u8; 25], + pub eob_mask: u32, +} + +impl MbCoeffs { + pub(crate) fn empty(has_y2: bool) -> Self { + Self { + y: [[0; 16]; 16], + u: [[0; 16]; 4], + v: [[0; 16]; 4], + y2: [0; 16], + has_y2, + eobs: [0; 25], + eob_mask: 0, + } + } + + /// Whether any block carries a non-zero coefficient (the loop + /// filter's interior-edge condition, §15.1). + pub fn has_nonzero(&self) -> bool { + self.eob_mask & (1 << 31) != 0 + } +} + +/// Left/above context slot of each block (dixie `left_context_index` / +/// `above_context_index`). +const LEFT_INDEX: [usize; 25] = [ + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, +]; +const ABOVE_INDEX: [usize; 25] = [ + 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, +]; + +/// Token entropy contexts (dixie/libvpx layout): indices 0-3 are the Y +/// subblock columns, 4-5 U, 6-7 V, 8 the Y2 block. `left` is the running +/// one-MB-wide column state; `above` is the per-MB-column state for the +/// current row (9 slots per MB column). +pub(crate) struct TokenContexts { + pub above: Vec, + pub left: [u8; 9], +} + +impl TokenContexts { + /// `mb_cols` entries of 9 slots for the above state. + pub fn new(mb_cols: usize) -> Self { + Self { + above: vec![0u8; mb_cols * 9], + left: [0; 9], + } + } + + /// Reset the above state at the start of a row (§13.3: non-existent + /// neighbours are empty). + pub fn reset_above_row(&mut self) { + self.above.iter_mut().for_each(|s| *s = 0); + } + + /// Reset the left state at the start of a row (the caller MUST call + /// this once per MB row before decoding its tokens). + pub fn reset_left(&mut self) { + self.left = [0; 9]; + } + + /// Skip-MB context reset (dixie `reset_mb_context`): everything to 0 + /// except the Y2 slots, which survive iff this MB has no Y2 block. + pub fn reset_mb(&mut self, mb_col: usize, has_y2: bool) { + let a = &mut self.above[mb_col * 9..mb_col * 9 + 9]; + a[..8].fill(0); + self.left[..8].fill(0); + if has_y2 { + a[8] = 0; + self.left[8] = 0; + } + } + + fn ctx_pair(&self, mb_col: usize, block: usize) -> (u8, u8) { + let a = &self.above[mb_col * 9..mb_col * 9 + 9]; + (self.left[LEFT_INDEX[block]], a[ABOVE_INDEX[block]]) + } + + fn set_ctx(&mut self, mb_col: usize, block: usize, v: u8) { + self.left[LEFT_INDEX[block]] = v; + self.above[mb_col * 9 + ABOVE_INDEX[block]] = v; + } +} + +/// Decode one 4x4 block's tokens (libvpx `GetCoeffs` / RFC §13.2-13.3 +/// verbatim). `probs_t` is `[band][ctx][node]` for the block's plane +/// type; `n0` the first coded position (1 for Y blocks after a Y2). +/// Returns the number of significant coefficients. Coefficients are +/// written dequantized into `out` (natural order). +fn get_coeffs( + bc: &mut BoolDecoder<'_>, + probs_t: &[[[u8; 11]; 3]; 8], + ctx: usize, + n0: usize, + dc_factor: i16, + ac_factor: i16, + out: &mut [i16; 16], +) -> usize { + let trace = std::env::var_os("EC_VP8_TRACE").is_some(); + // One token decision: decode the bool, then — under EC_VP8_TRACE — + // print the consulted (n, band, ctx, prob) and the decoded bit so the + // stream can be diffed read-for-read against scripts/vp8ref_model.py. + macro_rules! g { + ($n:expr, $band:expr, $c:expr, $prob:expr) => {{ + let bit = bc.read_bool($prob); + if trace { + eprintln!( + "G n={} band={} ctx={} prob={} bit={}", + $n, $band, $c, $prob, u8::from(bit) + ); + } + bit + }}; + } + let mut n = n0; + let mut band = BANDS[n0]; + let mut c = ctx; + let mut p = &probs_t[band as usize][c]; + if !g!(n, band, c, p[0]) { + return 0; // immediate EOB + } + loop { + n += 1; + let mut v: i32; + if !g!(n, band, c, p[1]) { + // DCT_0: the next decision skips the EOB branch (§13.2) and + // libvpx forces the context to 0 after a zero token. + c = 0; + band = BANDS[n]; + p = &probs_t[band as usize][0]; + } else { + if !g!(n, band, c, p[2]) { + c = 1; + band = BANDS[n]; + p = &probs_t[band as usize][1]; + v = 1; + } else { + if !g!(n, band, c, p[3]) { + if !g!(n, band, c, p[4]) { + v = 2; + } else { + v = 3 + i32::from(g!(n, band, c, p[5])); + } + } else { + if !g!(n, band, c, p[6]) { + if !g!(n, band, c, p[7]) { + v = 5 + i32::from(g!(n, band, c, 159u8)); + } else { + v = 7 + 2 * i32::from(g!(n, band, c, 165u8)); + v += i32::from(g!(n, band, c, 145u8)); + } + } else { + let bit1 = usize::from(g!(n, band, c, p[8])); + let bit0 = usize::from(g!(n, band, c, p[9 + bit1])); + let cat = 2 * bit1 + bit0; + v = 0; + for &prob in CAT_EXTRA[cat].iter() { + if prob == 0 { + break; + } + v += v + i32::from(g!(n, band, c, prob)); + } + v += 3 + (8 << cat); + } + } + c = 2; + band = BANDS[n]; + p = &probs_t[band as usize][2]; + } + + // Sign flag, then dequantize (first coded position is DC). + // Shared by the ONE and magnitude paths, exactly like the + // reference walk (libvpx detokenize.c GetCoeffs). + let neg = g!(n, band, c, 128u8); + let mag = if neg { -v } else { v }; + out[ZIGZAG[n - 1]] = if n - 1 == 0 { + (mag * i32::from(dc_factor)) as i16 + } else { + (mag * i32::from(ac_factor)) as i16 + }; + if n < 16 && !g!(n, band, c, p[0]) { + return n; // EOB + } + } + if n == 16 { + return 16; // malformed without EOB: stop like the reference + } + } +} + +/// Decode all 25 blocks of one macroblock (dixie `decode_mb_tokens`): +/// Y2 first when present, then the 16 Y, then U, then V. A skipped MB +/// must not be run through here — call [`skip_mb_tokens`] instead. +pub(crate) fn decode_mb_tokens( + bc: &mut BoolDecoder<'_>, + probs: &[[[[u8; 11]; 3]; 8]; 4], + dq: &Dq, + has_y2: bool, + ctxs: &mut TokenContexts, + mb_col: usize, +) -> MbCoeffs { + let mut out = MbCoeffs::empty(has_y2); + let mut eob_mask = 0u32; + + // Decode one block and fold its contexts/mask in. + macro_rules! block { + ($idx:expr, $ptype:expr, $dc:expr, $ac:expr, $slot:expr) => {{ + let n0 = usize::from($ptype == 0); + let (l, a) = ctxs.ctx_pair(mb_col, $idx); + let ctx = (usize::from(l) + usize::from(a)).min(2); + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a); + } + let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot); + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("TBE {} eob={}", $idx, eob); + } + out.eobs[$idx] = eob as u8; + let t = u8::from(eob > 0); + ctxs.set_ctx(mb_col, $idx, t); + eob_mask |= (u32::from(eob > 1)) << $idx; + eob_mask |= u32::from(t != 0) << 31; + }}; + } + + if has_y2 { + block!(24, 1, dq.y2_dc, dq.y2_ac, &mut out.y2); + for b in 0..16 { + block!(b, 0, dq.y1_dc, dq.y1_ac, &mut out.y[b]); + } + } else { + for b in 0..16 { + block!(b, 3, dq.y1_dc, dq.y1_ac, &mut out.y[b]); + } + } + for b in 0..4 { + block!(16 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.u[b]); + } + for b in 0..4 { + block!(20 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.v[b]); + } + + out.eob_mask = eob_mask; + out +} + +/// The context reset a skipped MB applies (dixie `reset_mb_context`): +/// the returned [`MbCoeffs`] is all-zero and the contexts look like a +/// fully-empty MB — except the Y2 slots survive when the skipped MB has +/// no Y2 block. +pub(crate) fn skip_mb_tokens(ctxs: &mut TokenContexts, mb_col: usize, has_y2: bool) -> MbCoeffs { + ctxs.reset_mb(mb_col, has_y2); + MbCoeffs::empty(has_y2) +} diff --git a/crates/ec-vp8/src/transform.rs b/crates/ec-vp8/src/transform.rs new file mode 100644 index 00000000..520d7982 --- /dev/null +++ b/crates/ec-vp8/src/transform.rs @@ -0,0 +1,640 @@ +//! Inverse transforms (inverse DCT, inverse Walsh-Hadamard) and dequant +//! factor computation for VP8 (RFC 6386 §14). +//! +//! Every function here is a bit-exact transcription of the normative +//! reference implementation in libvpx (`vp8/common/idctllm.c` and +//! `vp8/common/quant_common.c`), which is also what RFC 6386 §§14.3–14.5 +//! print as pseudocode. Bit-level fidelity of the rounding is a hard +//! requirement: arithmetic right shifts (`>>` on `i32` in Rust, as in C) +//! round toward negative infinity, and both implementations rely on that +//! floor behavior for negative operands. +//! +//! Fidelity details reproduced verbatim from the oracle: +//! - The 16-bit fixed-point constants `cospi8sqrt2minus1 = 20091` and +//! `sinpi8sqrt2 = 35468` (§14.4). The `>> 16` multiplies carry **no** +//! rounding constant; the `+4` before the final `>> 3` appears only in +//! the second DCT pass. +//! - `short output[16]` intermediates: libvpx stores the first-pass +//! results into a `short` array, truncating `i32` arithmetic to `i16` +//! between passes. We reproduce those truncation points with `as i16` +//! (wrapping two's-complement truncation, identical to the de facto C +//! behavior) so results stay oracle-exact even for adversarial inputs. +//! - The inverse WHT rounds with `(x + 3) >> 3` (§14.3); the DC-only +//! shortcut uses the same constant on `input[0]` alone. +//! +//! All functions are pure, allocation-free, and free of `unsafe`. + +#![deny(unsafe_code)] + +/// 16-bit fixed-point `sqrt(2) * cos(pi/8) - 1` (RFC 6386 §14.4). The +/// product `x * sqrt(2) * cos(pi/8)` is computed as `x + ((x * K) >> 16)` +/// because the constant exceeds 1.0 and would otherwise lose precision. +const COSPI8SQRT2MINUS1: i32 = 20091; + +/// 16-bit fixed-point `sqrt(2) * sin(pi/8)` (RFC 6386 §14.4). +const SINPI8SQRT2: i32 = 35468; + +/// DC quantizer lookup, `dc_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. +const DC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +]; + +/// AC quantizer lookup, `ac_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1), +/// transcribed mechanically from libvpx `vp8/common/quant_common.c`. +const AC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +]; + +/// Clamps a (possibly delta-adjusted) quantizer index to the valid +/// qindex range `[0, 127]` — dixie `clamp_q` / libvpx bounds in +/// `quant_common.c` (RFC 6386 §14.1). +#[inline] +fn clamp_q(q: i32) -> i32 { + q.clamp(0, 127) +} + +/// `dc_qlookup[clamp(q + delta)]` — Y-after-second / per-plane DC factor +/// lookup with delta adjustment (RFC 6386 §14.1 `dc_q`). +#[inline] +fn dc_factor(q: i32, delta: i32) -> i16 { + DC_QLOOKUP[clamp_q(q + delta) as usize] +} + +/// `ac_qlookup[clamp(q + delta)]` — AC factor lookup with delta +/// adjustment (RFC 6386 §14.1 `ac_q`). +#[inline] +fn ac_factor(q: i32, delta: i32) -> i16 { + AC_QLOOKUP[clamp_q(q + delta) as usize] +} + +/// Inverse Walsh-Hadamard transform of the 16 dequantized Y2 DC +/// coefficients into the 16 Y-subblock DC residuals +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_c`, oracle +/// `vp8_short_inv_walsh4x4_c` in `idctllm.c`). +/// +/// `input` is the row-major 4x4 block of dequantized Y2 DCs; the returned +/// array holds the 16 Y-subblock DC values in the same row-major order +/// (the reference scatters `output[i]` to `mb_dqcoeff[i * 16]`, i.e. the +/// DC slot of the i-th Y subblock — the caller places them). Two passes +/// of the exact 4-point Hadamard butterfly, with `short` truncation of +/// the first-pass results and `(x + 3) >> 3` rounding in the second. +#[inline] +pub fn iwht4x4(input: &[i16; 16]) -> [i16; 16] { + let mut tmp = [0i16; 16]; + + // First pass: transform columns; results are stored transposed into + // rows of `tmp` (ip walks input[i], input[4+i], input[8+i], + // input[12+i]). libvpx stores into `short`: truncate to i16. + for i in 0..4 { + let a1 = input[i] as i32 + input[12 + i] as i32; + let b1 = input[4 + i] as i32 + input[8 + i] as i32; + let c1 = input[4 + i] as i32 - input[8 + i] as i32; + let d1 = input[i] as i32 - input[12 + i] as i32; + + tmp[i] = (a1 + b1) as i16; + tmp[4 + i] = (c1 + d1) as i16; + tmp[8 + i] = (a1 - b1) as i16; + tmp[12 + i] = (d1 - c1) as i16; + } + + let mut output = [0i16; 16]; + + // Second pass: transform rows in place, rounding with (x + 3) >> 3. + for r in 0..4 { + let i = 4 * r; + let a1 = tmp[i] as i32 + tmp[i + 3] as i32; + let b1 = tmp[i + 1] as i32 + tmp[i + 2] as i32; + let c1 = tmp[i + 1] as i32 - tmp[i + 2] as i32; + let d1 = tmp[i] as i32 - tmp[i + 3] as i32; + + let a2 = a1 + b1; + let b2 = c1 + d1; + let c2 = a1 - b1; + let d2 = d1 - c1; + + output[i] = ((a2 + 3) >> 3) as i16; + output[i + 1] = ((b2 + 3) >> 3) as i16; + output[i + 2] = ((c2 + 3) >> 3) as i16; + output[i + 3] = ((d2 + 3) >> 3) as i16; + } + + output +} + +/// One-nonzero-DC shortcut of the inverse WHT +/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_1_c`, oracle +/// `vp8_short_inv_walsh4x4_1_c` in `idctllm.c`). +/// +/// When only `input[0]` is non-zero, every Y-subblock DC equals +/// `(input[0] + 3) >> 3`. Bit-identical to `iwht4x4` for such inputs. +#[inline] +pub fn iwht4x4_dc(input: &[i16; 16]) -> [i16; 16] { + let a1 = ((input[0] as i32 + 3) >> 3) as i16; + [a1; 16] +} + +/// Full inverse DCT of one dequantized 4x4 coefficient block +/// (RFC 6386 §14.4; oracle `short_idct4x4llm_c` in `idctllm.c`). +/// +/// `coeffs` is a row-major 4x4 block of **already dequantized** +/// coefficients (dequantization happens before the transform, RFC 6386 +/// §14.5). Two passes of the 4-point inverse DCT with the §14.4 +/// fixed-point constants; the `>> 16` multiplies carry no rounding +/// constant and the `(x + 4) >> 3` rounding is applied only in the +/// second pass. First-pass results are truncated to `i16` exactly where +/// the oracle stores into its `short output[16]` scratch. +/// +/// Returns the row-major 4x4 residual. Not clamped, not added to the +/// prediction — see [`idct4x4_add`] for the combined form. +#[inline] +pub fn idct4x4(coeffs: &[i16; 16]) -> [i16; 16] { + let mut tmp = [0i16; 16]; + + // First pass: transform columns; results land transposed in rows of + // `tmp` (ip walks coeffs[i], coeffs[4+i], coeffs[8+i], coeffs[12+i]). + for i in 0..4 { + let a1 = coeffs[i] as i32 + coeffs[8 + i] as i32; + let b1 = coeffs[i] as i32 - coeffs[8 + i] as i32; + + let temp1 = (coeffs[4 + i] as i32 * SINPI8SQRT2) >> 16; + let temp2 = coeffs[12 + i] as i32 + ((coeffs[12 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); + let c1 = temp1 - temp2; + + let temp1 = coeffs[4 + i] as i32 + ((coeffs[4 + i] as i32 * COSPI8SQRT2MINUS1) >> 16); + let temp2 = (coeffs[12 + i] as i32 * SINPI8SQRT2) >> 16; + let d1 = temp1 + temp2; + + // libvpx stores into `short`: truncate to i16. + tmp[i] = (a1 + d1) as i16; + tmp[12 + i] = (a1 - d1) as i16; + tmp[4 + i] = (b1 + c1) as i16; + tmp[8 + i] = (b1 - c1) as i16; + } + + let mut output = [0i16; 16]; + + // Second pass: transform rows, rounding with (x + 4) >> 3. + for r in 0..4 { + let i = 4 * r; + let ip0 = tmp[i] as i32; + let ip1 = tmp[i + 1] as i32; + let ip2 = tmp[i + 2] as i32; + let ip3 = tmp[i + 3] as i32; + + let a1 = ip0 + ip2; + let b1 = ip0 - ip2; + + let temp1 = (ip1 * SINPI8SQRT2) >> 16; + let temp2 = ip3 + ((ip3 * COSPI8SQRT2MINUS1) >> 16); + let c1 = temp1 - temp2; + + let temp1 = ip1 + ((ip1 * COSPI8SQRT2MINUS1) >> 16); + let temp2 = (ip3 * SINPI8SQRT2) >> 16; + let d1 = temp1 + temp2; + + output[i] = ((a1 + d1 + 4) >> 3) as i16; + output[i + 3] = ((a1 - d1 + 4) >> 3) as i16; + output[i + 1] = ((b1 + c1 + 4) >> 3) as i16; + output[i + 2] = ((b1 - c1 + 4) >> 3) as i16; + } + + output +} + +/// DC-only inverse DCT shortcut (RFC 6386 §14.4 +/// `vp8_dc_only_idct_add_c` math; oracle `idctllm.c`): when position 0 is +/// the sole non-zero coefficient, every residual pixel is `(dc + 4) >> 3`. +/// +/// Bit-identical to `idct4x4` on such inputs. Not clamped; the caller +/// adds and clamps (or uses [`idct4x4_add`]). +#[inline] +pub fn idct4x4_dc(dc: i16) -> [i16; 16] { + let a1 = ((dc as i32 + 4) >> 3) as i16; + [a1; 16] +} + +/// Combined per-block reconstruction kernel (RFC 6386 §14.4/§14.5; oracle +/// `short_idct4x4llm_c` final loop in `idctllm.c`): inverse-transforms +/// `coeffs` and writes `clamp(predict + residual)` into `recon`. +/// +/// `coeffs` must already be dequantized (dequantization is applied before +/// the transform; for intra Y macroblocks the DC positions already hold +/// the [`iwht4x4`] output). `predict` and `recon` are row-major 4x4 +/// blocks of exactly 16 bytes each. Residuals are fully computed before +/// any output byte is written. +#[inline] +pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) { + let residual = idct4x4(coeffs); + for i in 0..16 { + let a = residual[i] as i32 + predict[i] as i32; + recon[i] = a.clamp(0, 255) as u8; + } +} + +/// Dequantization factors for one macroblock, indexed by plane and +/// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Dequant { + /// Y plane, DC coefficient (after inverse WHT for intra Y2 rows). + pub y1_dc: i16, + /// Y plane, AC coefficients. + pub y1_ac: i16, + /// Y2 plane (second-order) DC coefficient: `dc_qlookup[...] * 2`. + pub y2_dc: i16, + /// Y2 plane AC coefficient: `ac_qlookup[...] * 155 / 100`, floored at 8. + pub y2_ac: i16, + /// Chroma DC coefficient, capped at 132 after lookup. + pub uv_dc: i16, + /// Chroma AC coefficient. + pub uv_ac: i16, +} + +/// Computes the six dequantization factors for quantizer index `q` with +/// the per-frame delta updates (RFC 6386 §9.6 header fields applied per +/// §14.1; dixie `dequant_init`, oracle `vp8cx_init_quantizer` in +/// libvpx `decodframe.c` / `quant_common.c`). +/// +/// `q` is the per-macroblock segment-adjusted base qindex (already +/// absolute or offset by the segment level per the segment header); the +/// delta arguments are the frame-header updates. Each lookup clamps its +/// `q + delta` sum to `[0, 127]`. Semantics transcribed exactly: +/// - `y1_dc = dc_qlookup[clamp(q + y1_dc_delta)]`, +/// `y1_ac = ac_qlookup[clamp(q)]` (no delta exists for Y AC), +/// - `y2_dc = dc_qlookup[clamp(q + y2_dc_delta)] * 2`, +/// - `y2_ac = ac_qlookup[clamp(q + y2_ac_delta)] * 155 / 100` (integer +/// division), floored at 8, +/// - `uv_dc = min(dc_qlookup[clamp(q + uv_dc_delta)], 132)` (cap applied +/// after the lookup), +/// - `uv_ac = ac_qlookup[clamp(q + uv_ac_delta)]`. +#[must_use] +pub fn dequant( + q: i32, + y1_dc_delta: i32, + y2_dc_delta: i32, + y2_ac_delta: i32, + uv_dc_delta: i32, + uv_ac_delta: i32, +) -> Dequant { + Dequant { + y1_dc: dc_factor(q, y1_dc_delta), + y1_ac: ac_factor(q, 0), + y2_dc: dc_factor(q, y2_dc_delta) * 2, + y2_ac: { + let v = (ac_factor(q, y2_ac_delta) as i32 * 155) / 100; + (if v < 8 { 8 } else { v }) as i16 + }, + uv_dc: { + let v = dc_factor(q, uv_dc_delta); + if v > 132 { 132 } else { v } + }, + uv_ac: ac_factor(q, uv_ac_delta), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Hand-derived: impulse `input[0] = 8`, all else 0. First pass, the + /// only touched column (0) reads (8,0,0,0): a1 = 8+0 = 8, b1 = 0, + /// c1 = 0, d1 = 8, giving intermediate column 0 = [8,8,8,8]. Second + /// pass, every row reads (8,0,0,0): a2 = b2 = c2 = d2 = 8, and + /// (8 + 3) >> 3 = 1. Expected: all 16 outputs are 1. + #[test] + fn iwht_unit_impulse_yields_all_ones() { + let mut input = [0i16; 16]; + input[0] = 8; + assert_eq!(iwht4x4(&input), [1i16; 16]); + } + + /// Hand-derived: impulse `input[5] = 8` (row 1, col 1). First pass, + /// column 1 reads (0,8,0,0): a1 = 0, b1 = 8, c1 = 8, d1 = 0, giving + /// intermediate column 1 = [8, 8, -8, -8]. Second pass, rows 0-1 read + /// (0,8,0,0) → outputs (1, 1, -1, -1); rows 2-3 read (0,-8,0,0) → + /// (-1, -1, 1, 1) — the Hadamard basis pattern for position (1,1). + #[test] + fn iwht_impulse_at_row1_col1_yields_hadamard_pattern() { + let mut input = [0i16; 16]; + input[5] = 8; + assert_eq!( + iwht4x4(&input), + [ + 1, 1, -1, -1, // + 1, 1, -1, -1, // + -1, -1, 1, 1, // + -1, -1, 1, 1, + ] + ); + } + + /// Mixed-coefficient oracle: expected values computed with a Python + /// model of the exact libvpx integer algorithm (see the model in + /// `idct_mixed_block_matches_oracle` below — the WHT variant is the + /// same structure with §14.3 butterflies and `(x + 3) >> 3`). + #[test] + fn iwht_mixed_block_matches_oracle() { + let input = [ + 40, -13, 0, 7, 222, 5, -40, 1, 0, 0, 17, -9, 300, -250, 88, 3, + ]; + assert_eq!( + iwht4x4(&input), + [ + 46, 30, 95, 110, // + 9, 42, -15, -55, // + -3, -35, 37, 60, // + -36, -27, -86, -92, + ] + ); + } + + /// The `_dc` shortcut must agree with the full transform whenever + /// only `input[0]` is non-zero — across the whole practical range, + /// including negatives and both i16 extremes (arithmetic shifts are + /// floor rounding for negatives in both C and Rust). + #[test] + fn iwht_dc_shortcut_matches_full_transform() { + for v in [ + 0, + 1, + -1, + 3, + -3, + 8, + -8, + 100, + -100, + 1234, + -4321, + i16::MAX, + i16::MIN, + ] { + let input = { + let mut i = [0i16; 16]; + i[0] = v; + i + }; + assert_eq!(iwht4x4(&input), iwht4x4_dc(&input), "mismatch at dc={v}"); + } + } + + /// §14.4 DC-only math: input [40, 0, ...] gives every pixel + /// (40 + 4) >> 3 = 5. + #[test] + fn idct_dc_only_40_yields_five() { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = 40; + c + }; + assert_eq!(idct4x4(&coeffs), [5i16; 16]); + assert_eq!(idct4x4_dc(40), [5i16; 16]); + } + + /// Mixed-coefficient oracle. The Python model below is a line-for-line + /// transcription of libvpx `short_idct4x4llm_c` (same integer math, + /// `short` truncation between passes via `s16`); running it on + /// `coeffs` prints the expected block embedded in the assertion. + /// + /// ```python + /// COS, SIN = 20091, 35468 + /// def s16(x): + /// x &= 0xFFFF + /// return x - 0x10000 if x >= 0x8000 else x + /// def idct(inp): + /// out = [0] * 16 + /// for i in range(4): # pass 1: columns, transposed into rows + /// a1 = inp[i] + inp[8+i]; b1 = inp[i] - inp[8+i] + /// c1 = ((inp[4+i]*SIN) >> 16) - (inp[12+i] + ((inp[12+i]*COS) >> 16)) + /// d1 = (inp[4+i] + ((inp[4+i]*COS) >> 16)) + ((inp[12+i]*SIN) >> 16) + /// out[i] = s16(a1 + d1); out[12+i] = s16(a1 - d1) + /// out[4+i] = s16(b1 + c1); out[8+i] = s16(b1 - c1) + /// res = [0] * 16 + /// for i in range(4): # pass 2: rows, rounding (x + 4) >> 3 + /// ip = out[4*i:4*i+4] + /// a1 = ip[0] + ip[2]; b1 = ip[0] - ip[2] + /// c1 = ((ip[1]*SIN) >> 16) - (ip[3] + ((ip[3]*COS) >> 16)) + /// d1 = (ip[1] + ((ip[1]*COS) >> 16)) + ((ip[3]*SIN) >> 16) + /// res[4*i+0] = s16((a1 + d1 + 4) >> 3) + /// res[4*i+3] = s16((a1 - d1 + 4) >> 3) + /// res[4*i+1] = s16((b1 + c1 + 4) >> 3) + /// res[4*i+2] = s16((b1 - c1 + 4) >> 3) + /// return res + /// ``` + #[test] + fn idct_mixed_block_matches_oracle() { + let coeffs = [ + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, + ]; + assert_eq!( + idct4x4(&coeffs), + [ + 305, 108, 139, 72, // + -508, -228, -88, 303, // + 372, 85, -443, -640, // + -48, -41, 345, 441, + ] + ); + } + + /// The DC-only shortcut must equal the full transform for any value + /// at coefficient position 0 (with the rest zero), including the i16 + /// extremes where the intermediate still fits. + #[test] + fn idct_dc_shortcut_matches_full_transform() { + for v in [ + 0, + 1, + -1, + 8, + -8, + 40, + -40, + 100, + -100, + 4088, + i16::MAX, + i16::MIN, + ] { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = v; + c + }; + assert_eq!(idct4x4(&coeffs), idct4x4_dc(v), "mismatch at dc={v}"); + } + } + + /// §14.5: `idct4x4_add` is `clamp255(predict + idct4x4(coeffs))` + /// pixelwise. With a flat prediction of 100, every output byte must + /// be the saturated sum; extreme residuals clamp to 0 and 255. + #[test] + fn idct_add_equals_clamped_predict_plus_residual() { + let coeffs = [ + 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55, + ]; + let residual = idct4x4(&coeffs); + let predict = [100u8; 16]; + let mut recon = [0u8; 16]; + idct4x4_add(&coeffs, &predict, &mut recon); + for i in 0..16 { + let expected = (residual[i] as i32 + 100).clamp(0, 255) as u8; + assert_eq!(recon[i], expected, "pixel {i}"); + } + + // Saturation: DC 4088 → residual (4088 + 4) >> 3 = 511; 100 + 511 + // clamps to 255. Negative DC -32768 → residual (-32764) >> 3 = + // -4096; clamps to 0. + let mut hi = [0i16; 16]; + hi[0] = 4088; + let mut lo = [0i16; 16]; + lo[0] = i16::MIN; + let mut recon = [0u8; 16]; + idct4x4_add(&hi, &predict, &mut recon); + assert_eq!(recon, [255u8; 16]); + idct4x4_add(&lo, &predict, &mut recon); + assert_eq!(recon, [0u8; 16]); + } + + /// `idct4x4_add` over an existing recon block that already holds the + /// prediction (the common libvpx dst/pred shape). The `&[u8]` / + /// `&mut [u8]` signature statically excludes predict/recon aliasing. + #[test] + fn idct_add_updates_existing_recon_buffer() { + let coeffs = { + let mut c = [0i16; 16]; + c[0] = 40; + c + }; + let predict = [100u8; 16]; + let mut recon = [100u8; 16]; + idct4x4_add(&coeffs, &predict, &mut recon); + assert_eq!(recon, [105u8; 16]); + } + + /// §14.1 tables, transcribed from libvpx `quant_common.c`: exact + /// length plus boundary and known-trap entries (the duplicated 10 at + /// dc[6..7], the >89 acceleration at dc[95..96] and dc[111..112], and + /// the ac[54..55] and ac[84..85] jumps). + #[test] + fn quant_lookup_tables_match_libvpx() { + assert_eq!(DC_QLOOKUP.len(), 128); + assert_eq!(AC_QLOOKUP.len(), 128); + assert_eq!(&DC_QLOOKUP[..3], &[4, 5, 6]); + assert_eq!(DC_QLOOKUP[127], 157); + assert_eq!(AC_QLOOKUP[0], 4); + assert_eq!(AC_QLOOKUP[127], 284); + assert_eq!(&DC_QLOOKUP[6..=8], &[10, 10, 11]); + assert_eq!(&DC_QLOOKUP[95..=97], &[89, 91, 93]); + assert_eq!(&DC_QLOOKUP[111..=112], &[118, 122]); + assert_eq!(&AC_QLOOKUP[53..=55], &[57, 58, 60]); + assert_eq!(&AC_QLOOKUP[83..=85], &[116, 119, 122]); + } + + /// §14.1 boundary qindices: q=0 gives the minimum factors (with the + /// Y2 AC floor of 8 already active), q=127 gives the maxima including + /// the chroma DC cap at 132. + #[test] + fn dequant_at_qindex_boundaries() { + assert_eq!( + dequant(0, 0, 0, 0, 0, 0), + Dequant { + y1_dc: 4, + y1_ac: 4, + y2_dc: 8, + y2_ac: 8, + uv_dc: 4, + uv_ac: 4 + } + ); + assert_eq!( + dequant(127, 0, 0, 0, 0, 0), + Dequant { + y1_dc: 157, + y1_ac: 284, + y2_dc: 314, + y2_ac: 440, // 284 * 155 / 100 + uv_dc: 132, // 157 capped at 132 + uv_ac: 284, + } + ); + } + + /// Delta-adjusted qindices clamp to [0, 127] before each lookup, for + /// every delta channel (RFC 6386 §14.1 dixie `clamp_q`). + #[test] + fn dequant_delta_indices_clamp_to_qindex_range() { + let lo = dequant(0, -1000, -1000, -1000, -1000, -1000); + assert_eq!(lo.y1_dc, 4); + assert_eq!(lo.y2_dc, 8); // 4 * 2 + assert_eq!(lo.y2_ac, 8); // floor + assert_eq!(lo.uv_dc, 4); + assert_eq!(lo.uv_ac, 4); + + let hi = dequant(127, 1000, 1000, 1000, 1000, 1000); + assert_eq!(hi.y1_dc, 157); + assert_eq!(hi.y2_dc, 314); + assert_eq!(hi.y2_ac, 440); + assert_eq!(hi.uv_dc, 132); + assert_eq!(hi.uv_ac, 284); + + // A base q of 0 with positive deltas reaches mid-table: q=60 has + // dc_qlookup[60] = 55, ac_qlookup[60] = 70. + let mid = dequant(0, 60, 60, 60, 60, 60); + assert_eq!(mid.y1_dc, 55); + assert_eq!(mid.y1_ac, 4); // Y AC has no delta channel + assert_eq!(mid.y2_dc, 110); + assert_eq!(mid.y2_ac, 70 * 155 / 100); // 108 + assert_eq!(mid.uv_dc, 55); + assert_eq!(mid.uv_ac, 70); + } + + /// The Y2 AC floor: `x * 155 / 100 < 8` becomes 8. At q=0..4 + /// (ac = 4..8) the scaled values are 6, 7, 9, 10, 12 — only the first + /// two floor up. + #[test] + fn dequant_y2_ac_floor_at_eight() { + for q in 0..=4i32 { + let ac = AC_QLOOKUP[q as usize] as i32; + let scaled = ac * 155 / 100; + assert_eq!( + dequant(q, 0, 0, 0, 0, 0).y2_ac as i32, + scaled.max(8), + "q={q}" + ); + } + assert_eq!(dequant(0, 0, 0, 0, 0, 0).y2_ac, 8); // 4*155/100 = 6 → 8 + assert_eq!(dequant(1, 0, 0, 0, 0, 0).y2_ac, 8); // 5*155/100 = 7 → 8 + assert_eq!(dequant(2, 0, 0, 0, 0, 0).y2_ac, 9); // 6*155/100 = 9 + } + + /// libvpx computes the Y2 AC factor as `(x * 101581) >> 16` and its + /// comment asserts bitwise equality with `x * 155 / 100` for all + /// table entries; our transcription of dixie uses `* 155 / 100`, so + /// sweep the whole qindex range and prove the two agree through the + /// public API (with a matching delta for the Y2 AC channel). + #[test] + fn dequant_y2_ac_matches_libvpx_fixed_point_over_all_q() { + for q in 0..=127i32 { + for delta in [0, -q - 1, 127 - q] { + let x = AC_QLOOKUP[clamp_q(q + delta) as usize] as i32; + let expected = (((x * 101581) >> 16).max(8)) as i16; + assert_eq!( + dequant(q, 0, 0, delta, 0, 0).y2_ac, + expected, + "q={q}, delta={delta}" + ); + } + } + } +} diff --git a/crates/ec-vp8/tests/header_parse.rs b/crates/ec-vp8/tests/header_parse.rs new file mode 100644 index 00000000..37cc3aca --- /dev/null +++ b/crates/ec-vp8/tests/header_parse.rs @@ -0,0 +1,138 @@ +//! M1 witness: the header parser handles real libvpx-produced key frames +//! (and a VP8-in-WebP still) with no desync and the right dimensions. + +mod ivf; + +use ec_vp8::PersistedState; +use ec_vp8::frame::{FrameTag, FrameType, mb_geometry, parse_keyframe_dims}; +use ec_vp8::header::FrameHeader; + +const FIXTURES: &[(&str, u16, u16)] = &[ + ("kf-160x96-q20.ivf", 160, 96), + ("kf-160x96-q40.ivf", 160, 96), + ("kf-76x52-q30.ivf", 76, 52), + ("kf-32x16-q35.ivf", 32, 16), + ("kf-172x144-q25.ivf", 172, 144), + ("kf-96x80-q63.ivf", 96, 80), + ("mparts-160x96.ivf", 160, 96), +]; + +#[test] +fn parses_real_key_frame_headers() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + for (name, width, height) in FIXTURES { + let bytes = std::fs::read(dir.join(name)).unwrap(); + let (fourcc, w, h, frames) = ivf::parse_ivf(&bytes); + assert_eq!(fourcc, "VP80", "{name}"); + assert_eq!((w, h), (*width, *height), "{name} IVF dimensions"); + assert!(!frames.is_empty(), "{name} has no frames"); + + let first = &frames[0].data; + let tag = FrameTag::parse(first).unwrap(); + assert_eq!(tag.frame_type, FrameType::Key, "{name} first frame"); + assert!(tag.show_frame, "{name} first frame must be shown"); + assert_eq!(tag.version, 0, "{name}: default profile"); + let kf = parse_keyframe_dims(first).unwrap(); + assert_eq!((kf.width, kf.height), (*width, *height)); + assert_eq!((kf.h_scale, kf.v_scale), (0, 0), "{name} unscaled"); + + let mut state = PersistedState::default(); + let (header, _) = FrameHeader::parse(first, &mut state).unwrap(); + assert_eq!(header.token_data_offset - 10, tag.first_part_size as usize); + assert!(header.dims.is_some()); + assert_eq!(header.color_space, 0, "{name}: YUV colour space"); + assert_eq!( + header.partition_sizes.len(), + 1usize << header.log2_partitions, + "{name} partition count vs log2 field" + ); + let n_parts = header.partition_sizes.len(); + assert_eq!( + header.token_data_offset + + 3 * (n_parts - 1) + + header.partition_sizes.iter().sum::() as usize, + first.len(), + "{name}: partition sizes must tile the frame exactly" + ); + // The header partition must decode without reading past its end. + assert!( + header.quant.yac_qi <= 127, + "{name}: qindex sanity {}", + header.quant.yac_qi + ); + let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); + assert_eq!( + (mb_cols, mb_rows), + ( + (usize::from(*width) + 15) / 16, + (usize::from(*height) + 15) / 16 + ) + ); + } +} + +#[test] +fn parses_multi_partition_header() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("mparts-160x96.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut state = PersistedState::default(); + let (header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap(); + // vpxenc was asked for --token-parts=3 => 8 token partitions. + assert_eq!(header.log2_partitions, 3, "8 token partitions expected"); + assert_eq!(header.partition_sizes.len(), 8); + assert!(header.partition_sizes.iter().all(|&s| s > 0)); +} + +#[test] +fn parses_vp8_in_webp_still() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let Ok(bytes) = std::fs::read(dir.join("still.webp")) else { + panic!("still.webp missing (libwebp encoder unavailable at generation time)"); + }; + let vp8 = ivf::webp_vp8_chunk(&bytes); + let tag = FrameTag::parse(&vp8).unwrap(); + assert_eq!(tag.frame_type, FrameType::Key); + let kf = parse_keyframe_dims(&vp8).unwrap(); + assert_eq!((kf.width, kf.height), (96, 80)); + let mut state = PersistedState::default(); + let (header, _) = FrameHeader::parse(&vp8, &mut state).unwrap(); + assert!(header.dims.is_some()); +} + +#[test] +fn gop_key_frame_parses_and_coexists_with_inter() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + assert!(frames.len() >= 30); + + let mut state = PersistedState::default(); + let (kf_header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap(); + assert_eq!(kf_header.frame_type(), FrameType::Key); + assert!(kf_header.refresh.refresh_last && kf_header.refresh.refresh_gf); + + // First inter frame: header fields come from the same first partition, + // and the persisted entropy state has absorbed the key frame's updates. + let mut inter_seen = false; + for f in &frames[1..] { + let tag = FrameTag::parse(&f.data).unwrap(); + if tag.frame_type == FrameType::Key { + continue; + } + let (header, _) = FrameHeader::parse(&f.data, &mut state).unwrap(); + assert_eq!(header.frame_type(), FrameType::Inter); + assert!(header.dims.is_none(), "inter frames carry no dimensions"); + inter_seen = true; + break; + } + assert!(inter_seen, "gop fixture has no inter frame"); +} diff --git a/crates/ec-vp8/tests/ivf.rs b/crates/ec-vp8/tests/ivf.rs new file mode 100644 index 00000000..ef184c56 --- /dev/null +++ b/crates/ec-vp8/tests/ivf.rs @@ -0,0 +1,83 @@ +//! Minimal IVF demuxing for the ec-vp8 test fixtures (RFC's companion +//! container; only what the witnesses need). + +/// One IVF frame: (pts, payload). +pub struct IvfFrame { + /// Presentation timestamp from the IVF frame header. + #[allow(dead_code)] + pub pts: u64, + /// The compressed VP8 frame payload. + #[allow(dead_code)] // pts-only consumers exist in the stream witnesses + pub data: Vec, +} + +/// The frame tag's `show_frame` bit (RFC 6386 §9.1): hidden frames +/// (`false`) update the reference buffers but are never displayed. +#[allow(dead_code)] // not every witness binary needs the census +pub fn show_frame(data: &[u8]) -> bool { + (data[0] >> 4) & 1 == 1 +} + +/// Parse an IVF file into (fourcc, width, height, frames). +pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { + assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); + let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); + let width = u16::from_le_bytes([bytes[12], bytes[13]]); + let height = u16::from_le_bytes([bytes[14], bytes[15]]); + let mut pos = hdr_len; + let mut frames = Vec::new(); + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) + as usize; + let pts = u64::from_le_bytes([ + bytes[pos + 4], + bytes[pos + 5], + bytes[pos + 6], + bytes[pos + 7], + bytes[pos + 8], + bytes[pos + 9], + bytes[pos + 10], + bytes[pos + 11], + ]); + pos += 12; + if pos + sz > bytes.len() { + break; + } + frames.push(IvfFrame { + pts, + data: bytes[pos..pos + sz].to_vec(), + }); + pos += sz; + } + (fourcc, width, height, frames) +} + +/// Extract the VP8 payload from a lossy WebP file (RIFF/WEBP with a VP8 +/// chunk) — the same VP8 key-frame bytes in a different container. +#[allow(dead_code)] // only the keyframe_exact binary exercises WebP +pub fn webp_vp8_chunk(bytes: &[u8]) -> Vec { + assert_eq!(&bytes[0..4], b"RIFF"); + assert_eq!(&bytes[8..12], b"WEBP"); + let mut pos = 12; + while pos + 8 <= bytes.len() { + let tag = &bytes[pos..pos + 4]; + let sz = u32::from_le_bytes([ + bytes[pos + 4], + bytes[pos + 5], + bytes[pos + 6], + bytes[pos + 7], + ]) as usize; + if tag == b"VP8 " { + return bytes[pos + 8..pos + 8 + sz].to_vec(); + } + pos += 8 + sz + (sz & 1); // chunks are word-aligned + } + panic!("no VP8 chunk in webp"); +} + +/// Root of the workspace checkout this test runs in (crates/ec-vp8/../..). +pub fn fixture_dir() -> Option { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vp8"); + if dir.is_dir() { Some(dir) } else { None } +} diff --git a/crates/ec-vp8/tests/keyframe_exact.rs b/crates/ec-vp8/tests/keyframe_exact.rs new file mode 100644 index 00000000..41be707d --- /dev/null +++ b/crates/ec-vp8/tests/keyframe_exact.rs @@ -0,0 +1,156 @@ +//! M2 witness: key-frame decode is sample-exact against ffmpeg/libvpx +//! (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt yuv420p -`). + +mod ivf; + +use ec_vp8::decode::Decoder; + +/// ffmpeg's decoded rawvideo byte stream for the same file. +fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg must be on PATH for the witnesses"); + assert!(out.status.success(), "ffmpeg failed on {path:?}"); + out.stdout +} + +fn raw<'a>(pos: &mut usize, data: &'a [u8], len: usize) -> &'a [u8] { + let s = &data[*pos..*pos + len]; + *pos += len; + s +} + +/// Decode every frame of an IVF with our decoder and compare each SHOWN +/// frame's planes against ffmpeg's byte stream (ffmpeg skips hidden +/// `show_frame == 0` frames exactly like a player). +fn compare(name: &str, skip_if_missing: bool) { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let path = dir.join(name); + if skip_if_missing && !path.exists() { + panic!("{name} missing (regenerate fixtures)"); + } + let bytes = std::fs::read(&path).unwrap(); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let all = ffmpeg_raw_yuv(&path); + let frame_len = usize::from(w) * usize::from(h) * 3 / 2; + let shown: Vec<&ivf::IvfFrame> = + frames.iter().filter(|f| ivf::show_frame(&f.data)).collect(); + assert_eq!( + all.len(), + shown.len() * frame_len, + "{name}: ffmpeg output {}/{} not {} whole shown frames", + all.len(), + frame_len, + shown.len() + ); + + let mut dec = Decoder::new(); + let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2); + let mut shown_idx = 0; + for (i, f) in frames.iter().enumerate() { + match dec.decode(&f.data).expect("decode succeeds") { + Some(pic) => { + assert!(ivf::show_frame(&f.data), "{name} frame {i}: picture for hidden frame"); + assert_eq!(pic.width, w); + assert_eq!(pic.height, h); + let mut pos = shown_idx * frame_len; + shown_idx += 1; + let exp_y = raw(&mut pos, &all, usize::from(w) * usize::from(h)); + let exp_u = raw(&mut pos, &all, cw * ch); + let exp_v = raw(&mut pos, &all, cw * ch); + assert_eq!(pic.y, exp_y, "{name} frame {i}: luma mismatch"); + assert_eq!(pic.u, exp_u, "{name} frame {i}: U mismatch"); + assert_eq!(pic.v, exp_v, "{name} frame {i}: V mismatch"); + } + None => assert!( + !ivf::show_frame(&f.data), + "{name} frame {i}: shown frame produced no picture" + ), + } + } + assert_eq!(shown_idx, shown.len(), "{name}: shown picture count"); +} + +#[test] +fn keyframes_match_ffmpeg() { + for (name, _, _) in [ + ("kf-160x96-q20.ivf", 160, 96), + ("kf-160x96-q40.ivf", 160, 96), + ("kf-76x52-q30.ivf", 76, 52), + ("kf-32x16-q35.ivf", 32, 16), + ("kf-172x144-q25.ivf", 172, 144), + ("kf-96x80-q63.ivf", 96, 80), + ] { + compare(name, false); + } +} + +#[test] +fn multi_partition_keyframe_matches_ffmpeg() { + compare("mparts-160x96.ivf", false); +} + +/// M3 witness: full inter-frame streams — simple-filter GOP, multi-token- +/// partition, hidden-altref and the OBS screen-content clip — decode +/// byte-exact against ffmpeg, every frame. The altref vector must +/// actually CONTAIN hidden frames (census the tags; a shown-only stream +/// would silently stop exercising the hidden-frame contract). +#[test] +fn interframe_streams_match_ffmpeg() { + for name in [ + "gop-160x96.ivf", + "clip-obs-320x192.ivf", + "altref-160x96.ivf", + ] { + if name == "altref-160x96.ivf" { + let dir = ivf::fixture_dir().expect("fixtures dir"); + let bytes = std::fs::read(dir.join(name)).unwrap(); + let hidden = census_hidden(&bytes); + assert!( + hidden >= 6, + "{name}: only {hidden} hidden frames — regenerate with \ + scripts/gen_vp8_fixtures.sh (--auto-alt-ref=1 --passes=2)" + ); + } + compare(name, false); + } +} + +/// Number of hidden (`show_frame == 0`) frames in an IVF stream. +fn census_hidden(bytes: &[u8]) -> usize { + let (_, _, _, frames) = ivf::parse_ivf(bytes); + frames.iter().filter(|f| !ivf::show_frame(&f.data)).count() +} + +#[test] +fn vp8_in_webp_still_matches_ffmpeg() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("still.webp")).unwrap(); + let vp8 = ivf::webp_vp8_chunk(&bytes); + let reference = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(dir.join("still.webp")) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .unwrap(); + assert!(reference.status.success()); + let mut dec = Decoder::new(); + let pic = dec.decode(&vp8).expect("decode").expect("shown"); + assert_eq!( + pic.y.len() + pic.u.len() + pic.v.len(), + reference.stdout.len() + ); + let mut exp = &reference.stdout[..]; + assert_eq!(pic.y, &exp[..pic.y.len()]); + exp = &exp[pic.y.len()..]; + assert_eq!(pic.u, &exp[..pic.u.len()]); + exp = &exp[pic.u.len()..]; + assert_eq!(pic.v, exp); +} diff --git a/crates/ec-vp8/tests/stream_exact.rs b/crates/ec-vp8/tests/stream_exact.rs new file mode 100644 index 00000000..5fcba76d --- /dev/null +++ b/crates/ec-vp8/tests/stream_exact.rs @@ -0,0 +1,141 @@ +//! M4 witness: the whole-stream public API (`ec_vp8::stream`) decodes +//! every fixture byte-exact against ffmpeg and refuses malformed +//! containers with errors, not panics. + +mod ivf; + +use ec_vp8::decode::Decoder; +use ec_vp8::stream::decode_stream; + +/// Every IVF fixture in the witness set (the WebP still is covered by +/// `keyframe_exact::vp8_in_webp_still_matches_ffmpeg`). +const FIXTURES: &[&str] = &[ + "kf-16x16-black-q0.ivf", + "kf-32x16-q35.ivf", + "kf-76x52-q30.ivf", + "kf-96x80-q63.ivf", + "kf-160x96-q20.ivf", + "kf-160x96-q40.ivf", + "kf-172x144-q25.ivf", + "gop-96x80-v1.ivf", + "gop-160x96.ivf", + "mparts-160x96.ivf", + "altref-160x96.ivf", + "clip-obs-320x192.ivf", +]; + +#[test] +fn decode_stream_matches_ffmpeg_on_every_fixture() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + for name in FIXTURES { + let path = dir.join(name); + let bytes = std::fs::read(&path).unwrap(); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let all = ffmpeg_raw_yuv(&path); + let frame_len = usize::from(w) * usize::from(h) * 3 / 2; + let shown = frames.iter().filter(|f| ivf::show_frame(&f.data)).count(); + assert_eq!(all.len(), shown * frame_len, "{name}: ffmpeg output size"); + assert!(!frames[0].data.is_empty(), "{name}: empty first frame"); + + let pictures = + decode_stream(&bytes).unwrap_or_else(|e| panic!("{name}: decode failed: {e}")); + assert_eq!(pictures.len(), shown, "{name}: picture count (shown only)"); + for (i, pic) in pictures.iter().enumerate() { + let expect = &all[i * frame_len..(i + 1) * frame_len]; + let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2); + assert_eq!(pic.y, &expect[..usize::from(w) * usize::from(h)], "{name} frame {i}: Y"); + assert_eq!(pic.u, &expect[usize::from(w) * usize::from(h)..][..cw * ch], "{name} frame {i}: U"); + assert_eq!(pic.v, &expect[usize::from(w) * usize::from(h) + cw * ch..], "{name} frame {i}: V"); + } + } +} + +/// The hidden-frame contract, end to end on a REAL auto-alt-ref stream: +/// `Decoder::decode` returns `Ok(None)` for a hidden frame while its +/// reference content stays live — the frames that follow (which the +/// encoder predicted across the hidden altref) stay byte-exact against +/// ffmpeg. +#[test] +fn hidden_frames_update_references_and_produce_no_picture() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let path = dir.join("altref-160x96.ivf"); + let bytes = std::fs::read(&path).unwrap(); + let (_, w, h, frames) = ivf::parse_ivf(&bytes); + let hidden_at: Vec = frames + .iter() + .enumerate() + .filter(|(_, f)| !ivf::show_frame(&f.data)) + .map(|(i, _)| i) + .collect(); + assert!( + hidden_at.len() >= 6, + "altref-160x96.ivf lost its hidden frames ({}) — regenerate", + hidden_at.len() + ); + + // ffmpeg's display stream, shown-frame-indexed. + let all = ffmpeg_raw_yuv(&path); + let frame_len = usize::from(w) * usize::from(h) * 3 / 2; + let mut dec = Decoder::new(); + let mut shown_seen = 0; + for (i, f) in frames.iter().enumerate() { + let pic = dec.decode(&f.data).expect("hidden frame decodes"); + if ivf::show_frame(&f.data) { + let expect = &all[shown_seen * frame_len..(shown_seen + 1) * frame_len]; + let y = &pic.as_ref().expect("shown frame has picture").y; + assert_eq!(y, &expect[..usize::from(w) * usize::from(h)], "frame {i}: Y"); + // The frame right after the FIRST hidden altref must already + // be byte-exact: it predicts across the hidden reference. + if i == hidden_at[0] + 1 { + assert!( + y[..32] == expect[..32] && y == &expect[..y.len()], + "frame after hidden altref diverges" + ); + } + shown_seen += 1; + } else { + assert!(pic.is_none(), "hidden frame {i} produced a picture"); + } + } + assert_eq!(shown_seen * frame_len, all.len()); +} + +/// ffmpeg's decoded rawvideo byte stream for an IVF file. +fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec { + let out = std::process::Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + .output() + .expect("ffmpeg must be on PATH for the witnesses"); + assert!(out.status.success(), "ffmpeg failed on {path:?}"); + out.stdout +} + +#[test] +fn decode_stream_is_error_not_panic_on_bad_containers() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap(); + + // Missing magic. + let mut bad = bytes.clone(); + bad[0..4].copy_from_slice(b"JUNK"); + assert!(decode_stream(&bad).is_err(), "non-DKIF accepted"); + + // Wrong fourcc (a WebP-lossless VP8L tag is not a VP8 video stream). + let mut bad = bytes.clone(); + bad[8..12].copy_from_slice(b"VP8L"); + assert!(decode_stream(&bad).is_err(), "non-VP80 fourcc accepted"); + + // A frame header claiming more payload than the stream carries. + let mut bad = bytes.clone(); + bad[32..36].copy_from_slice(&u32::MAX.to_le_bytes()); + assert!(decode_stream(&bad).is_err(), "truncated frame accepted"); +} + diff --git a/lanes/vp8.report.md b/lanes/vp8.report.md new file mode 100644 index 00000000..262754b0 --- /dev/null +++ b/lanes/vp8.report.md @@ -0,0 +1,107 @@ +# lane-vp8 — native VP8 decoder (ec-vp8), RFC 6386 + +Base: `a8f2186a` (main), worktree `edith_codecs-vp8`, branch `lane-vp8`. +Never merged, never pushed. Pins untouched (no ec-av1 changes at all). + +## Milestone table + +| Milestone | State | Evidence | +|---|---|---| +| M1 bool decoder + frame tag + full first-partition header | **done/verified** | commit `57b5a53a`; 12 unit tests green; real vpxenc/ffmpeg streams (6 sizes/q, 8-token-partition, WebP still) parse with exact partition tiling, correct dims (incl. 76x52 non-MB-aligned), 0 desyncs | +| M2 key-frame-only decode, sample-exact vs ffmpeg | **root cause FIXED, verified at frame level** — decision-exact vs the reference model for the whole frame (19131 reads, 0 diffs) and frame-0 byte-exact vs ffmpeg on ALL 8 kf/mparts fixtures; the `keyframe_exact` suite goes 3/3 when inter frames land (each fixture carries 1 KF + inter frames), see M3 | commits `20f7d742`, `072f842f`, M2-fix commit (this one) | +| M3 inter frames | **done/verified — ALL fixtures byte-exact vs ffmpeg, every frame** | commits `151ef8ff`..`8e1a04a9` (M3 campaign) + `b0a648b0` (completion). Completion-pass fixes: (4) inter-frame B_PRED subblock modes use the FLAT vp8_bmode_prob `{120,90,79,133,87,85,80,111,151}` with no above/left context (libvpx decodemv.c:467 `fc.bmode_prob`; the kf_bmode context table is key-frame-only) — `decode.rs` `parse_inter_modes`; (5) MC filter is per-frame from the tag version bits (`vp8_setup_version`): version 0 = six-tap for BOTH planes — chroma was hardcoded bilinear; version 3 `fullpixel_mask` (~7) applied to chroma MV derivation (`decode.rs` Decoder::mc_bilinear/mc_fullpel, `mc.rs` sixtap/bilinear dispatch, `modes.rs` chroma_mv_*); (6) SPLITMV chroma quadrants are 4×4 CHROMA pixels at 4-px offsets predicted per quadrant — the old loop wrote 8×8 at 8-px offsets and the residual add read only the top-left quadrant's prediction (whole-MB modes masked it; every SPLITMV MB had wrong chroma); (7) key frame with refresh_entropy==0 reverts entropy to DEFAULTS (libvpx init_frame resets fc before lfc=fc), not the pre-keyframe context. Witnesses: `interframe_streams_match_ffmpeg` — gop-160x96 (60f), clip-obs-320x192 (169f), altref-160x96 (96f: 90 shown + 6 HIDDEN altrefs at decode-idx 1,17,33,49,65,81; frame-35 Err resolved) + mparts (30f) + all kf fixtures byte-exact; B-stream trace Rust↔model 0 diffs across full streams. Oracle model fixed to match libvpx (inter ymode/uv defaults [112,86,140,37]/[162,101,204], flat inter bmode). Suite 55 lib + 4 header_parse + 4 keyframe_exact, zero rustc warnings | +| M4 public API + docs | **done/verified** (review flags fixed: all 12 fixtures script-generated; hidden-frame coverage real) | commit `4b8b11d3` + review-fix commit: `stream::decode_stream(IVF) -> Result>` + `stream::decode_stream_with` sink form `(picture, decode_idx, pts)` (hidden frames produce no sink call); container validated as ec_core::Error (DKIF/VP80/framing); `Picture: Clone`. Witness `tests/stream_exact.rs`: byte-exact vs ffmpeg on ALL 12 IVF fixtures + malformed-container error tests + `hidden_frames_update_references_and_produce_no_picture` (real auto-alt-ref stream: hidden -> Ok(None), following frames byte-exact). Suite totals 55+4+4+3 green; every fixture now regenerated by `scripts/gen_vp8_fixtures.sh` (9/9 pre-existing outputs byte-identical on regen), zero warnings | + +## What shipped (M1 `57b5a53a`, M2 WIP `20f7d742`) + +- `bool.rs`: RFC §7.3 decoder verbatim (bool/literal/signed/maybe-signed/ + prob7/tree + EOB-skipping token form), zero-extend init for tiny + partitions, overread counter as desync detector; test-only RFC encoder. +- `frame.rs`/`header.rs`: 3-byte LE tag, key-frame start code/dims, + complete partition-1 header in dixie field order (colour space, + segmentation w/ cross-frame state, LF type/level/sharpness/deltas, + token partition size table, quant indices, reference refresh/copies/ + sign-bias, coef-prob updates, mb_no_skip_coeff, inter prob_intra/last/gf + + ymode/uv/MV updates). `PersistedState` carries entropy/segmentation/ + LF deltas across frames, resets at key frames. +- `tables.rs`: GENERATED from the RFC text by `scripts/extract_vp8_tables.py` + (element counts asserted; page-header stripping; Pcat sentinels kept): + default+update coefficient probs, kf_bmode_prob, coeff_bands, dequant + lookups, Pcat1-6, default+update MV probs. +- `tokens.rs`: §13 GetCoeffs port — bands incl. sentinel entry, 3-context + model (above/left per-plane, Y2 last-MB-with-Y2 semantics), EOB skipped + after zero, dequant-on-write (DC at first coded position), Y2-first + block order, dixie skip-MB reset (Y2 slots survive iff no Y2 block). +- `modes.rs`: all trees/tables; NOTE SPLITMV partition leaves use the RFC + enum values (top_bottom=0, left_right=1, quarters=2, MV_16=3). +- `transform.rs` (subagent): idct4x4/iwht4x4 + shortcuts + dequant; + 400,000-vector bit-exact fuzz vs verbatim libvpx idctllm.c; dequant + differentially fuzzed vs libvpx C over 528 q x 15 deltas x 5 channels. +- `intra.rs` (subagent): all 16x16/8x8/4x4 predictors; 20,000-stream + machine diff vs libvpx intrapred.c — 28.8M/28.8M samples equal; svg2p + RFC typo handled (avg2p). +- `loopfilter.rs` (subagent): normal+simple kernels and frame driver in + dixie order (V-MB, V-sub, H-MB, H-sub; level 0 skips; combined + blim/mblim for simple), dixie-table-exact limits, frame-type-exact hev + via `filter_frame_ex(..., is_keyframe)`; 10 tests incl. Python-oracle + full-frame driver order. +- `decode.rs`: per-row pipeline (modes -> tokens -> reconstruct), + bordered planes (127 top incl. corner / 129 left), above-right + synthesis (shared extras for right-edge subblocks, replicate on + rightmost MB, 127 on top row), B_PRED interleaved predict+residual + (subblocks chain through reconstructed pixels), Y2 WHT DC override, + per-MB LF level with dixie DOUBLE-clamp, LF post-pass (order-equivalent + to dixie's row-delayed filtering for non-threaded decode; frame-level + level==0 gate). +- Fixtures: `scripts/gen_vp8_fixtures.sh` + local libvpx build recipe + (`~/.cache/vp8/libvpx-src`, gives vpxenc for --token-parts; ffmpeg 8's + wrapper has no token-part option). CQ quirk: `-crf` inside the + qmin/qmax band is mandatory. + +## Witnesses + +- M1: `cargo test -p ec-vp8 --test header_parse` — 4 tests on real + libvpx/vpxenc bitstreams: dims, start code, partition tiling + (`token_data_offset + 3*(n-1) + sum(sizes) == frame len`), 8 + partitions, inter header coexists with persisted entropy, VP8-in-WebP + chunk parses. ALL PASS. +- M2 (this session): FULL-FRAME decision-exactness — `EC_VP8_TRACE=1` + example `dbg_first` vs `scripts/vp8ref_model.py`: 19131 token + decisions, identical `(n, band, ctx, prob, bit)` on every read, 0 + diffs (`kf-160x96-q20.ivf`). Pixel exactness: frame 0 of all 7 kf + fixtures + mparts dumped via `examples/dump_frame` and `cmp`-ed + against `ffmpeg -frames:v 1` — ALL EXACT. `cargo test -p ec-vp8`: + unit (49) + header_parse (4) + webp witness green; the remaining 2 + `keyframe_exact` cases decode every frame of each fixture and go + green with M3 inter frames. + +## M2 blocker — RESOLVED + +Root cause: `get_coeffs`' ONE-token path (`tokens.rs`). After the +`p[2]` decision selects value 1, the reference walk (libvpx +`detokenize.c` GetCoeffs, RFC §13.2) falls through to the SHARED +sign-read / coefficient-write / EOB-after-nonzero sequence — the ONE +and magnitude paths converge right after the tree decision. The Rust +port had the sign/write/EOB block nested inside the magnitude branch +only, so a ONE token skipped the sign read and the EOB check and +re-entered the walk at the ZERO node: same read count (positions +stayed in lockstep, hence "same (pos,bit_count), different table +entry"), different decoded stream from the first ONE token in a busy +block — invisible on the lossless single-MB black fixture (no ONE +tokens), fatal from ~28 reads into kf-160x96-q20's first block. + +Two reference-model bugs also fixed while instrumenting +(`scripts/vp8ref_model.py`): per-decision `G n/band/ctx/prob/bit` +lines replacing the DEC counter, and token-partition bool decoders +are now PERSISTENT across MB rows that share a partition (was: +re-created per row, which double-counted the walk on single-partition +streams). Trace protocol: diff `grep '^G '` of both sides; the first +differing line names decision, node and whether prob or bit diverges. + + +## Repro + +``` +CARGO_TARGET_DIR=~/.cache/cargo-target-vp8 cargo test -p ec-vp8 +scripts/gen_vp8_fixtures.sh # fixtures/vp8/*.ivf (gitignored) +``` diff --git a/scripts/extract_vp8_tables.py b/scripts/extract_vp8_tables.py new file mode 100755 index 00000000..61ca1950 --- /dev/null +++ b/scripts/extract_vp8_tables.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Extract the fixed probability/quant tables from the local RFC 6386 text +into a Rust module (crates/ec-vp8/src/tables.rs). + +The tables are transcribed VERBATIM from the RFC text; the script asserts +each table's element count so a parsing slip cannot produce a silently +wrong table. Run from the worktree root: + + python3 scripts/extract_vp8_tables.py [rfc.txt] [out.rs] +""" + +import re +import sys + +RFC = sys.argv[1] if len(sys.argv) > 1 else "/home/user/.cache/vp8/rfc6386.txt" +OUT = sys.argv[2] if len(sys.argv) > 2 else "crates/ec-vp8/src/tables.rs" + +text = open(RFC, encoding="utf-8").read() +# Strip RFC page furniture (running headers/footers land mid-table). +text = "\n".join( + l for l in text.splitlines() + if not re.search(r"RFC 6386\s+VP8 Data Format.*2011$", l) + and not re.search(r"Bankoski, et al\..*\[Page \d+\]$", l) +) +text = text.replace("\f", "") + +INT_RE = re.compile(r"-?\d+") + + +def collect(name: str, expect: int) -> list[int]: + """Find `name`'s C array DEFINITION -- '=' reachable from the name + through nothing but brackets, identifiers, spaces and hyphens (the + section-13.4 pseudocode mentions `coeff_update_probs [i] [j] [k] [t]))` + and must not match) -- and collect every integer between '=' and the + terminating '};'.""" + for m in re.finditer(rf"\b{re.escape(name)}\b[\[\]\w\s-]*?=", text): + body = text[m.end() : m.end() + 60000] + end = body.find("};") + assert end != -1, f"{name}: no terminator" + vals = [int(v) for v in INT_RE.findall(body[:end])] + if len(vals) != expect: + raise SystemExit( + f"{name}: expected {expect} ints, got {len(vals)}: {vals[:10]}..." + ) + return vals + raise SystemExit(f"{name}: definition not found") + + +# (rust name, RFC name, expected ints incl. Pcat sentinels, dims, type) +TABLES = [ + ("COEFF_UPDATE_PROBS", "coeff_update_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"), + ("DEFAULT_COEFF_PROBS", "default_coeff_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"), + ("KF_BMODE_PROB", "kf_bmode_prob", 10 * 10 * 9, (10, 10, 9), "u8"), + ("COEFF_BANDS", "coeff_bands", 16, (16,), "u8"), + ("DC_QLOOKUP", "dc_qlookup", 128, (128,), "i16"), + ("AC_QLOOKUP", "ac_qlookup", 128, (128,), "i16"), + ("PCAT1", "Pcat1", 2, (2,), "u8"), + ("PCAT2", "Pcat2", 3, (3,), "u8"), + ("PCAT3", "Pcat3", 4, (4,), "u8"), + ("PCAT4", "Pcat4", 5, (5,), "u8"), + ("PCAT5", "Pcat5", 6, (6,), "u8"), + ("PCAT6", "Pcat6", 12, (12,), "u8"), + ("DEFAULT_MV_PROBS", "k_default_mv_probs", 2 * 19, (2, 19), "u8"), + ("MV_UPDATE_PROBS", "k_mv_entropy_update_probs", 2 * 19, (2, 19), "u8"), +] + + +def rust_ty(ty: str, dims: tuple[int, ...]) -> str: + t = ty + for d in reversed(dims): + t = f"[{t}; {d}]" + return t + + +def nest(vals: list[int], dims: tuple[int, ...]) -> str: + if len(dims) == 1: + return "[" + ", ".join(str(v) for v in vals) + "]" + step = len(vals) // dims[0] + parts = [ + nest(vals[i * step : (i + 1) * step], dims[1:]) for i in range(dims[0]) + ] + if len(dims) == 2: + return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]" + return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]" + + +out = [ + "//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and", + "//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from", + "//! the RFC text; do not edit by hand. The extractor asserts every", + "//! table's element count, so a slip cannot drop or add values.", + "#![allow(clippy::all)]", + "", +] +for rust_name, rfc_name, expect, dims, ty in TABLES: + vals = collect(rfc_name, expect) + note = " (trailing 0 is the DCTextra sentinel)" if rfc_name.startswith("Pcat") else "" + out.append(f"/// RFC 6386 `{rfc_name}`{note}.") + out.append(f"pub const {rust_name}: {rust_ty(ty, dims)} = {nest(vals, dims)};\n") + +open(OUT, "w", encoding="utf-8").write("\n".join(out)) +print(f"wrote {OUT}") diff --git a/scripts/gen_vp8_fixtures.sh b/scripts/gen_vp8_fixtures.sh new file mode 100755 index 00000000..551064b9 --- /dev/null +++ b/scripts/gen_vp8_fixtures.sh @@ -0,0 +1,123 @@ +#!/usr/bin/env bash +# Generate the ec-vp8 test fixtures (gitignored, like the rest of the +# workspace's fixtures/). Every vector is libvpx-encoded via ffmpeg; the +# decoder's witnesses compare its raw YUV output against ffmpeg's. +# +# Usage: scripts/gen_vp8_fixtures.sh [worktree-root] +set -euo pipefail +ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}" +OUT="$ROOT/fixtures/vp8" +mkdir -p "$OUT" + +enc() { # name size frames q extra-source-args... + local name=$1 size=$2 frames=$3 q=$4 + shift 4 + ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i "$@" \ + -frames:v "$frames" -c:v libvpx -qmin "$q" -qmax "$q" -crf "$q" \ + -auto-alt-ref 0 -cpu-used 1 -g "$frames" \ + "$OUT/$name.ivf" + echo "wrote $OUT/$name.ivf" +} + +# Key-frame vectors (M2): several sizes incl. non-multiple-of-16, several q. +enc kf-160x96-q20 160x96 4 20 testsrc2=size=160x96:rate=30 +enc kf-160x96-q40 160x96 4 40 testsrc2=size=160x96:rate=30 +enc kf-76x52-q30 76x52 4 30 testsrc2=size=76x52:rate=30 +enc kf-32x16-q35 32x16 4 35 testsrc2=size=32x16:rate=30 +enc kf-172x144-q25 172x144 4 25 testsrc2=size=172x144:rate=30 +enc kf-96x80-q63 96x80 4 63 testsrc2=size=96x80:rate=30 + +# Multi-frame GOP (M3): keyframe + interframes, golden/altref in play. +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 \ + -frames:v 60 -c:v libvpx -qmin 30 -qmax 45 -crf 38 \ + -auto-alt-ref 0 -g 15 -keyint_min 15 -cpu-used 1 -lag-in-frames 0 \ + "$OUT/gop-160x96.ivf" +echo "wrote $OUT/gop-160x96.ivf" + +# Larger short GOP with the simple loop filter via profile (version 1)? +# libvpx picks profile 0 normally; the version field is exercised through +# -profile:v 1 (simple filter, bilinear reconstruction). +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=96x80:rate=30 \ + -frames:v 12 -c:v libvpx -qmin 30 -qmax 30 -crf 30 -auto-alt-ref 0 -g 6 \ + -profile:v 1 -cpu-used 1 -lag-in-frames 0 \ + "$OUT/gop-96x80-v1.ivf" 2>/dev/null || \ + echo "SKIP gop-96x80-v1 (profile 1 unsupported by this libvpx build)" + +# Multi-partition token partitions (M3): ffmpeg's libvpx wrapper has no +# token-part option, so this one vector comes from a locally built vpxenc +# (checked out at ~/.cache/vp8/libvpx-src; `./configure && make -j`). +VPXENC="$HOME/.cache/vp8/libvpx-src/vpxenc" +if [ -x "$VPXENC" ]; then + ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 30 \ + -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-mparts.raw + { printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n' + python3 - <<'PYEOF' +raw = open("/tmp/ecvp8-mparts.raw", "rb").read() +frame = 160 * 96 * 3 // 2 +for i in range(len(raw) // frame): + open("/dev/stdout", "wb").write(b"FRAME\n" + raw[i*frame:(i+1)*frame]) +PYEOF + } | "$VPXENC" --codec=vp8 -w 160 -h 96 --token-parts=3 --limit=30 \ + --ivf --cpu-used=1 --end-usage=q --cq-level=32 --min-q=30 --max-q=45 \ + --kf-max-dist=10 -o "$OUT/mparts-160x96.ivf" - 2>/dev/null + echo "wrote $OUT/mparts-160x96.ivf" +else + echo "SKIP mparts (build libvpx at ~/.cache/vp8/libvpx-src for vpxenc)" +fi + +# VP8-in-WebP still (same key-frame payload in a RIFF container). +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=96x80:rate=30 -frames:v 1 \ + "$OUT/still.png" +if ffmpeg -hide_banner -loglevel error -y -i "$OUT/still.png" -q:v 60 "$OUT/still.webp" 2>/dev/null; then + echo "wrote $OUT/still.webp" +else + echo "SKIP still.webp (libwebp support missing)" + rm -f "$OUT/still.png" +fi + +# Note on the three vectors below (review flag): every fixture in the set +# must come from THIS script — no ad-hoc leftovers. +# +# kf-16x16-black-q0: 1-MB all-black frame at q0 (the M2 "no ONE tokens" +# degenerate vector: exercises the zero-coefficient and overread paths). +enc kf-16x16-black-q0 16x16 1 0 color=black:size=16x16:rate=30 + +# clip-obs-320x192: screen-content-shaped 320x192 clip. The original was +# an OBS window capture; the recorded reproducible stand-in is testsrc2 +# at the same size (same decoder paths: 20x12 MB grid, small-MV motion). +enc clip-obs-320x192 320x192 169 28 testsrc2=size=320x192:rate=30 + +# altref-160x96: vpxenc --auto-alt-ref=1 in TWO passes (one-pass CQ/VBR +# never inserts hidden altrefs for this content) with --lag-in-frames, so +# libvpx emits HIDDEN alternate-reference frames (frame tag show_frame=0, +# currently 6 of 90 at decode indices 1,17,33,49,65,81). The witnesses +# census the tags and refuse a shown-only stream: the hidden-frame +# contract (no output, reference buffers still update, later frames +# reference the hidden altref) must be exercised. +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 90 \ + -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-altref.raw +# Two passes need a seekable input (stdin cannot rewind for pass 2), so +# the y4m goes through a temp FILE, not a pipe. +{ printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n' + cat /tmp/ecvp8-altref.raw | python3 -c ' +import sys +raw = sys.stdin.buffer.read() +frame = 160 * 96 * 3 // 2 +for i in range(len(raw) // frame): + sys.stdout.buffer.write(b"FRAME\n" + raw[i*frame:(i+1)*frame]) +' > /tmp/ecvp8-altref.y4m +} +"$VPXENC" --codec=vp8 -w 160 -h 96 --limit=90 --ivf --cpu-used=1 \ + --end-usage=vbr --target-bitrate=400 --kf-max-dist=15 \ + --auto-alt-ref=1 --lag-in-frames=15 --passes=2 --fpf=/tmp/ecvp8-altref.fpf \ + --quiet -o "$OUT/altref-160x96.ivf" /tmp/ecvp8-altref.y4m +rm -f /tmp/ecvp8-altref.raw /tmp/ecvp8-altref.y4m /tmp/ecvp8-altref.fpf +echo "wrote $OUT/altref-160x96.ivf" + +ls -la "$OUT" diff --git a/scripts/raw_to_y4m.py b/scripts/raw_to_y4m.py new file mode 100755 index 00000000..296ca2a9 --- /dev/null +++ b/scripts/raw_to_y4m.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc). + + ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m +""" +import sys + +w, h, fps, out = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4] +frame = int(w) * int(h) * 3 // 2 +raw = sys.stdin.buffer.read() +with open(out, "wb") as f: + f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 C420jpeg\n".encode()) + for i in range(len(raw) // frame): + f.write(b"FRAME\n") + f.write(raw[i * frame : (i + 1) * frame]) diff --git a/scripts/vp8ref_model.py b/scripts/vp8ref_model.py new file mode 100755 index 00000000..0975b231 --- /dev/null +++ b/scripts/vp8ref_model.py @@ -0,0 +1,646 @@ +#!/usr/bin/env python3 +"""Dixie-faithful multi-frame VP8 decode model (header + mode records + +tokens, no pixels) with per-read `B` and per-token-decision `G` tracing +that mirror the Rust decoder's EC_VP8_TRACE output byte-for-byte. + +Usage: python3 vp8ref_model.py frame.ivf [max-frames] +""" +import re +import sys + +TABLES_RS = "crates/ec-vp8/src/tables.rs" + + +class BD: + def __init__(self, data): + self.data = data + self.pos = 2 if len(data) >= 2 else len(data) + v = 0 + if len(data) >= 1: + v = data[0] << 8 + if len(data) >= 2: + v |= data[1] + self.value = v + self.range = 255 + self.bit_count = 0 + + def bool(self, prob): + split = 1 + (((self.range - 1) * prob) >> 8) + big = split << 8 + if self.value >= big: + self.range -= split + self.value -= big + bit = 1 + else: + self.range = split + bit = 0 + while self.range < 128: + self.value <<= 1 + self.range <<= 1 + self.bit_count += 1 + if self.bit_count == 8: + self.bit_count = 0 + if self.pos < len(self.data): + self.value |= self.data[self.pos] + self.pos += 1 + print(f"B {self.pos} {self.bit_count} {prob} {bit}") + return bit + + def lit(self, n): + v = 0 + for _ in range(n): + v = (v << 1) + self.bool(128) + return v + + def maybe_int(self, n): + if not self.bool(128): + return 0 + v = self.lit(n) + return -v if self.bool(128) else v + + def tree(self, tree, probs): + i = 0 + while True: + b = self.bool(probs[i >> 1]) + i = tree[i + b] + if i <= 0: + return -i + + +def table(name): + src = open(TABLES_RS).read() + m = re.search(rf"pub const {name}: [^=]+= ", src) + body = src[m.end(): src.index("];", m.end())] + return [int(x) for x in re.findall(r"-?\d+", body)] + + +# --------------------------------------------------------------------------- +# Inter-parse constants (RFC 6386; cross-checked against libvpx modecont.c / +# findnearmv.h / blockd.h — see managed skill ec-vp8-lane-recipe). +MODE_CONTEXTS = [ + [7, 1, 1, 143], + [14, 18, 14, 107], + [135, 64, 57, 68], + [60, 56, 128, 65], + [159, 134, 128, 34], + [234, 188, 128, 28], +] +SUB_MV_REF_PROBS = [ + [147, 136, 18], + [106, 145, 1], + [179, 121, 1], + [223, 1, 34], + [208, 1, 1], +] +MV_PARTITION_TREE = [-3, 2, -2, 4, 0, -1] +MV_PARTITION_PROBS = [110, 111, 150] +SUB_MV_REF_TREE = [0, 2, -1, 4, -2, -3] +SMALL_MV_TREE = [2, 8, 4, 6, 0, -1, -2, -3, 10, 12, -4, -5, -6, -7] +MBSPLIT_OFFSET = [ + [0, 8], [0, 2], [0, 2, 8, 10], list(range(16)), +] +MBSPLIT_FILL_COUNT = [8, 8, 4, 1] +MBSPLIT_FILL_OFFSET = [ + list(range(16)), + [0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15], + [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15], + list(range(16)), +] + + +def main(): + CUP = table("COEFF_UPDATE_PROBS") + KF_BMODE = table("KF_BMODE_PROB") + DEF_COEF = table("DEFAULT_COEFF_PROBS") + DEF_MV = table("DEFAULT_MV_PROBS") + MV_UP = table("MV_UPDATE_PROBS") + BANDS = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0] + ZIGZAG = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15] + CAT_EXTRA = [ + [173, 148, 140], + [176, 155, 140, 135], + [180, 157, 141, 134, 130], + [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129], + ] + KF_YMODE_TREE = [-4, 2, 4, 6, 0, -1, -2, -3] + BMODE_TREE = [0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9] + UV_MODE_TREE = [0, 2, -1, 4, -2, -3] + YMODE_TREE = [0, 2, 4, 6, -1, -2, -3, -4] + YMODE_MAP = {0: 0, 1: 2, 2: 3, 3: 1} + INTER_BMODE = [120, 90, 79, 133, 87, 85, 80, 111, 151] # libvpx vp8_bmode_prob + LEFT = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8] + ABOVE = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8] + + raw = open(sys.argv[1], "rb").read() + max_frames = int(sys.argv[2]) if len(sys.argv) > 2 else 2 + frames = [] + pos = 32 + while pos + 12 <= len(raw): + sz = int.from_bytes(raw[pos : pos + 4], "little") + frames.append(raw[pos + 12 : pos + 12 + sz]) + pos += 12 + sz + + w = h = 0 + cols = rows = 0 + ctx = { + "coef": DEF_COEF[:], + "mv": DEF_MV[:], + "ymode": [112, 86, 140, 37], + "uv": [162, 101, 204], + } + probs = None + seg_map = [0] * 65536 + + for fi, frame in enumerate(frames[:max_frames]): + tag = int.from_bytes(frame[0:3], "little") + kf = (frame[0] & 1) == 0 + part0_sz = tag >> 5 + # Uncompressed data chunk: key frames carry start code + dims + # (partition 0 at byte 10); inter frames start partition 0 at + # byte 3 (RFC 6386 §9.1). + hdr0 = 10 if kf else 3 + d = BD(frame[hdr0 : hdr0 + part0_sz]) + + if kf: + w = int.from_bytes(frame[6:8], "little") & 0x3FFF + h = int.from_bytes(frame[8:10], "little") & 0x3FFF + cols, rows = (w + 15) // 16, (h + 15) // 16 + d.lit(2) # colour space + clamping + ctx["coef"] = DEF_COEF[:] + + # segmentation + seg_enabled = d.bool(128) + seg_update_map = False + seg_tree_probs = [255, 255, 255] + if seg_enabled: + seg_update_map = d.bool(128) + if d.bool(128): + d.bool(128) + for _ in range(4): + d.maybe_int(7) + for _ in range(4): + d.maybe_int(6) + if seg_update_map: + seg_tree_probs = [d.lit(8) for _ in range(3)] + # loop filter header + d.lit(1) + d.lit(6) + d.lit(3) + if d.bool(128): + if d.bool(128): + for _ in range(4): + d.maybe_int(6) + for _ in range(4): + d.maybe_int(6) + # token partitions + log2 = d.lit(2) + nparts = 1 << log2 + off = hdr0 + part0_sz + sizes = [] + for i in range(nparts): + if i < nparts - 1: + sizes.append(int.from_bytes(frame[off : off + 3], "little")) + off += 3 + else: + sizes.append(len(frame) - off) + parts = [] + po = off + for i in range(nparts): + parts.append(frame[po : po + sizes[i]]) + po += sizes[i] + # quant + d.lit(7) + for _ in range(5): + d.maybe_int(4) + + # refresh header + if kf: + refresh_entropy = d.bool(128) + sb = [False, False] + else: + refresh_gf = d.bool(128) + if not refresh_gf: + d.lit(2) + refresh_arf = d.bool(128) + if not refresh_arf: + d.lit(2) + sb = [False, d.bool(128), d.bool(128)] + refresh_entropy = d.bool(128) + d.bool(128) # refresh_last + snapshot = (ctx["coef"][:], ctx["mv"][:], ctx["ymode"][:], ctx["uv"][:]) + + # coefficient probability updates + idx = 0 + for _i in range(4): + for _j in range(8): + for _k in range(3): + for _l in range(11): + if d.bool(CUP[idx]): + ctx["coef"][idx] = d.lit(8) + idx += 1 + # mb_no_skip_coeff + skip_enabled = d.bool(128) + prob_skip = d.lit(8) if skip_enabled else 128 + + probs = ctx["coef"] + prob_intra = prob_last = prob_gf = 128 + if not kf: + prob_intra = d.lit(8) + prob_last = d.lit(8) + prob_gf = d.lit(8) + yflag = d.bool(128) + print(f"HDR pi={prob_intra} pl={prob_last} pg={prob_gf} yflag={1 if yflag else 0}") + if yflag: + ctx["ymode"] = [d.lit(8) for _ in range(4)] + uflag = d.bool(128) + print(f"HDR uflag={1 if uflag else 0}") + if uflag: + ctx["uv"] = [d.lit(8) for _ in range(3)] + for c in range(2): + for j in range(19): + if d.bool(MV_UP[c * 19 + j]): + x = d.lit(7) + ctx["mv"][c * 19 + j] = (x << 1) if x else 1 + + if not kf: + print("YUV ymode =", ctx["ymode"], "uv =", ctx["uv"]) + print("MVT c0 =", ctx["mv"][0:19]) + print("MVT c1 =", ctx["mv"][19:38]) + + # per-MB state (row/col 0 = border) + mbmode = [[0] * (cols + 1) for _ in range(rows + 1)] + bmode = [[[0] * 16 for _ in range(cols + 1)] for _ in range(rows + 1)] + skips = [[False] * (cols + 1) for _ in range(rows + 1)] + hasy2 = [[True] * (cols + 1) for _ in range(rows + 1)] + mbref = [[0] * (cols + 1) for _ in range(rows + 1)] + mbmv = [[(0, 0)] * (cols + 1) for _ in range(rows + 1)] + mbsplit = [[False] * (cols + 1) for _ in range(rows + 1)] + mbbmi = [[[(0, 0)] * 16 for _ in range(cols + 1)] for _ in range(rows + 1)] + mbmvclamp = [[False] * (cols + 1) for _ in range(rows + 1)] + above_ctx = [[0] * 9 for _ in range(cols)] + + def clamp_mv2(mv, edges): + l, r, t, b = edges + if mv[1] < l - 128: + mv = (l - 128, mv[1]) + elif mv[1] > r + 128: + mv = (r + 128, mv[1]) + if mv[0] < t - 128: + mv = (t - 128, mv[1]) + elif mv[0] > b + 128: + mv = (b + 128, mv[1]) + return mv + + def oob(mv, edges): + l, r, t, b = edges + return mv[1] < l or mv[1] > r or mv[0] < t or mv[0] > b + + def read_mv_component(p): + if d.bool(p[0]): + x = 0 + for i in range(3): + x += d.bool(p[9 + i]) << i + for i in (9, 8, 7, 6, 5, 4): + x += d.bool(p[9 + i]) << i + if (x & 0xFFF0) == 0 or d.bool(p[9 + 3]): + x += 8 + else: + x = d.tree(SMALL_MV_TREE, p[2:9]) + if x and d.bool(p[1]): + x = -x + return x + + def read_mv(): + r = read_mv_component(ctx["mv"][0:19]) * 2 + c = read_mv_component(ctx["mv"][19:38]) * 2 + return (r, c) + + def find_near(above, left, aboveleft, to_bias): + mvs = [(0, 0), (0, 0), (0, 0), (0, 0)] + cnt = [0, 0, 0, 0] + ix = 0 + cx = 0 + + def bias(mv, from_b): + if from_b != to_bias: + return (-mv[0], -mv[1]) + return mv + + if not above["intra"]: + if above["mv"] != (0, 0): + ix += 1 + mvs[ix] = bias(above["mv"], above["sb"]) + cx += 1 + cnt[cx] += 2 + for mb, wgt in ((left, 2), (aboveleft, 1)): + if not mb["intra"]: + if mb["mv"] != (0, 0): + this = bias(mb["mv"], mb["sb"]) + if this != mvs[ix]: + ix += 1 + mvs[ix] = this + cx += 1 + cnt[cx] += wgt + else: + cnt[0] += wgt + # libvpx decodemv.c:366 — when the above-left pushed a THIRD + # distinct candidate it counted into cnt[CNT_SPLITMV] (cntx + # reached slot 3), and if that candidate equals the nearest, + # NEAREST absorbs it. Alive, not dead. + if cnt[3] != 0 and mvs[ix] == mvs[1]: + cnt[1] += 1 + cnt[3] = (above["split"] * 2) + (left["split"] * 2) + aboveleft["split"] + if cnt[2] > cnt[1]: + cnt[1], cnt[2] = cnt[2], cnt[1] + mvs[1], mvs[2] = mvs[2], mvs[1] + return mvs, cnt + + def parse_inter_modes(r, c): + mb_edge = ( + -(((c - 1) * 16) << 3), + (((cols - 1 - (c - 1)) * 16) << 3), + -(((r - 1) * 16) << 3), + (((rows - 1 - (r - 1)) * 16) << 3), + ) + to_bias = sb[mbref[r][c] - 1] + + def neigh(rr, cc): + if rr == 0 or cc == 0 or mbref[rr][cc] == 0: + return {"intra": True, "zero": False, "mv": (0, 0), "split": False, "sb": False} + return { + "intra": False, + "zero": mbmv[rr][cc] == (0, 0), + "mv": mbmv[rr][cc], + "split": mbsplit[rr][cc], + "sb": sb[mbref[rr][cc] - 1], + } + + near_mvs, cnt = find_near( + neigh(r - 1, c), neigh(r, c - 1), neigh(r - 1, c - 1), to_bias + ) + print(f"CNT r={r-1} c={c-1} cnt={cnt} mvs={near_mvs}") + MC = MODE_CONTEXTS + if not d.bool(MC[cnt[0]][0]): + mbmode[r][c] = -1 # ZEROMV marker + mbmv[r][c] = (0, 0) + mbref_marker = 1 + return + if not d.bool(MC[cnt[1]][1]): + mbmode[r][c] = -2 # NEAREST + mv = clamp_mv2(near_mvs[1], mb_edge) + mbmv[r][c] = mv + mbref_marker = 1 + return + if not d.bool(MC[cnt[2]][2]): + mbmode[r][c] = -3 # NEAR + mv = clamp_mv2(near_mvs[2], mb_edge) + mbmv[r][c] = mv + mbref_marker = 1 + return + ni = 1 if cnt[1] >= cnt[0] else 0 + near_mvs[ni] = clamp_mv2(near_mvs[ni], mb_edge) + best = near_mvs[ni] + if not d.bool(MC[cnt[3]][3]): + mbmode[r][c] = -4 # NEW + mv = read_mv() + mv = (mv[0] + best[0], mv[1] + best[1]) + mbmvclamp[r][c] = oob(mv, mb_edge) + mbmv[r][c] = mv + mbref_marker = 1 + return + # SPLITMV + s = d.tree(MV_PARTITION_TREE, MV_PARTITION_PROBS) + num_p = [2, 2, 4, 16][s] + bmi = [(0, 0)] * 16 + mbbmi[r][c] = bmi + for j in range(num_p): + k = MBSPLIT_OFFSET[s][j] + if k % 4 == 0: + lm = r, c - 1 + leftmv = ( + mbbmi[lm[0]][lm[1]][k + 3] + if mbsplit[lm[0]][lm[1]] + else mbmv[lm[0]][lm[1]] + ) + else: + leftmv = bmi[k - 1] + if k < 4: + am = r - 1, c + abovemv = ( + mbbmi[am[0]][am[1]][k + 12] + if mbsplit[am[0]][am[1]] + else mbmv[am[0]][am[1]] + ) + else: + abovemv = bmi[k - 4] + lez = leftmv == (0, 0) + aez = abovemv == (0, 0) + lea = leftmv == abovemv + ctxi = 4 if (lez and aez) else (3 if lea else (1 if lez else (2 if aez else 0))) + pr = d.tree(SUB_MV_REF_TREE, SUB_MV_REF_PROBS[ctxi]) + if pr == 0: + blockmv = leftmv + elif pr == 1: + blockmv = abovemv + elif pr == 2: + blockmv = (0, 0) + else: + mv = read_mv() + blockmv = (mv[0] + best[0], mv[1] + best[1]) + print( + f"SP r={r-1} c={c-1} j={j} k={k} l=({leftmv[0]},{leftmv[1]}) a=({abovemv[0]},{abovemv[1]}) ctx={ctxi} mv=({blockmv[0]},{blockmv[1]}) best=({best[0]},{best[1]})" + ) + mbmvclamp[r][c] = mbmvclamp[r][c] or oob(blockmv, mb_edge) + cntf = MBSPLIT_FILL_COUNT[s] + for o in MBSPLIT_FILL_OFFSET[s][j * cntf : (j + 1) * cntf]: + bmi[o] = blockmv + mbbmi[r][c] = bmi + mbsplit[r][c] = True + mbmode[r][c] = 4 + hasy2[r][c] = False + mbmv[r][c] = bmi[15] + return + + # ---- mode records + tokens ---------------------------------------- + # Key frames interleave per row (like the Rust decode_keyframe); + # inter frames read ALL mode records first, then token rows + # (like decode_interframe). B-line order must match Rust exactly. + d2s = [None] * nparts + + def row_modes(r): + for c in range(1, cols + 1): + if seg_enabled and seg_update_map: + seg_map[(r - 1) * cols + (c - 1)] = d.tree( + [2, 4, 0, -1, -2, -3], seg_tree_probs + ) + if skip_enabled: + skips[r][c] = bool(d.bool(prob_skip)) + if kf: + ym = d.tree(KF_YMODE_TREE, [145, 156, 163, 128]) + mbmode[r][c] = ym + hasy2[r][c] = ym != 4 + if ym == 4: + for j in range(16): + if j < 4: + am = mbmode[r - 1][c] + a = bmode[r - 1][c][j + 12] if am == 4 else YMODE_MAP[am] + else: + a = bmode[r][c][j - 4] + if j % 4 == 0: + lm = mbmode[r][c - 1] + l = bmode[r][c - 1][j + 3] if lm == 4 else YMODE_MAP[lm] + else: + l = bmode[r][c][j - 1] + bmode[r][c][j] = d.tree( + BMODE_TREE, KF_BMODE[(a * 10 + l) * 9 : (a * 10 + l) * 9 + 9] + ) + d.tree(UV_MODE_TREE, [142, 114, 183]) + else: + # ---- inter mode record (§16) ---- + if not d.bool(prob_intra): + mbref[r][c] = 0 + ym = d.tree(YMODE_TREE, ctx["ymode"]) + mbmode[r][c] = ym + if ym == 4: + # Interframe B_PRED subblocks: CONSTANT + # probs, no above/left context (libvpx + # decodemv.c:467 reads fc.bmode_prob = + # vp8_bmode_prob). + for j in range(16): + bmode[r][c][j] = d.tree(BMODE_TREE, INTER_BMODE) + d.tree(UV_MODE_TREE, ctx["uv"]) + else: + if not d.bool(prob_last): + mbref[r][c] = 1 + elif not d.bool(prob_gf): + mbref[r][c] = 2 + else: + mbref[r][c] = 3 + try: + parse_inter_modes(r, c) + except Exception as e: + import traceback; traceback.print_exc() + print(f"EXC at r={r} c={c}: {e}") + raise SystemExit(1) + mvref_print = 4 if mbsplit[r][c] else {-1: 0, -2: 1, -3: 2, -4: 3}.get( + mbmode[r][c], 0 + ) + print( + f"IMB r={r-1} c={c-1} ref={mbref[r][c]} mvref={mvref_print} " + f"mv=({mbmv[r][c][0]},{mbmv[r][c][1]}) clamp={mbmvclamp[r][c]}" + ) + if 0 < mbref[r][c] and mbmode[r][c] < 0: + hasy2[r][c] = True + + def row_tokens(r): + pi = (r - 1) % nparts + if d2s[pi] is None: + d2s[pi] = BD(parts[pi]) + d2 = d2s[pi] + left_ctx = [0] * 9 + + def get_coeffs(ptype, n0, ctx0, out): + base = ptype * 264 + n = n0 + band = BANDS[n0] + c = ctx0 + p = base + band * 33 + c * 11 + + def g(prob_): + bit = d2.bool(prob_) + print(f"G n={n} band={band} ctx={c} prob={prob_} bit={1 if bit else 0}") + return bit + + if not g(probs[p]): + return 0 + while True: + n += 1 + if not g(probs[p + 1]): + c = 0 + band = BANDS[n] + p = base + band * 33 + else: + if not g(probs[p + 2]): + c = 1 + band = BANDS[n] + p = base + band * 33 + 11 + v = 1 + else: + if not g(probs[p + 3]): + if not g(probs[p + 4]): + v = 2 + else: + v = 3 + (1 if g(probs[p + 5]) else 0) + else: + if not g(probs[p + 6]): + if not g(probs[p + 7]): + v = 5 + (1 if g(159) else 0) + else: + v = 7 + 2 * (1 if g(165) else 0) + v += 1 if g(145) else 0 + else: + bit1 = 1 if g(probs[p + 8]) else 0 + bit0 = 1 if g(probs[p + 9 + bit1]) else 0 + cat = 2 * bit1 + bit0 + v = 0 + for prob in CAT_EXTRA[cat]: + v += v + (1 if g(prob) else 0) + v += 3 + (8 << cat) + c = 2 + band = BANDS[n] + p = base + band * 33 + 22 + out[ZIGZAG[n - 1]] = -v if g(128) else v + if n < 16 and not g(probs[p]): + return n + if n == 16: + return 16 + + for c in range(1, cols + 1): + left_ctx = [0] * 9 if c == 1 else left_ctx + + def one(blkidx, ptype, n0): + o = [0] * 16 + ctxv = min(2, left_ctx[LEFT[blkidx]] + above_ctx[c - 1][ABOVE[blkidx]]) + print(f"TB {blkidx} ctx={ctxv} l={left_ctx[LEFT[blkidx]]} a={above_ctx[c - 1][ABOVE[blkidx]]}") + print(f"T {r-1} {c-1} {blkidx} {ptype} {ctxv}") + eob = get_coeffs(ptype, n0, ctxv, o) + print(f"TBE {blkidx} eob={eob}") + t = 1 if eob > 0 else 0 + left_ctx[LEFT[blkidx]] = t + above_ctx[c - 1][ABOVE[blkidx]] = t + + if skips[r][c]: + for i in range(8): + above_ctx[c - 1][i] = 0 + left_ctx[i] = 0 + if hasy2[r][c]: + above_ctx[c - 1][8] = 0 + left_ctx[8] = 0 + continue + if hasy2[r][c]: + one(24, 1, 0) + for b in range(16): + one(b, 0, 1) + else: + for b in range(16): + one(b, 3, 0) + for b in range(4): + one(16 + b, 2, 0) + for b in range(4): + one(20 + b, 2, 0) + + if kf: + for r in range(1, rows + 1): + row_modes(r) + row_tokens(r) + else: + for r in range(1, rows + 1): + row_modes(r) + for r in range(1, rows + 1): + row_tokens(r) + + if not refresh_entropy: + ctx["coef"], ctx["mv"], ctx["ymode"], ctx["uv"] = snapshot + + +main()