forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-vp8' (8a03b178): ec-vp8 -- a complete native VP8 decoder (RFC 6386): bool decoder, headers, intra, inter (modes/MV/MC/loopfilter/ref-buffer management/segment maps/entropy save-restore), public decode_stream API; byte-exact vs ffmpeg on every fixture (gop 60/60, obs 169/169, two-pass altref 96 with 6 censused hidden frames, mparts 30/30, 8 keyframe fixtures, webp still, malformed-container error paths); libvpx's seat in edith is the swap target

Browse files at this commit

781bd7a1457c82f7ee2f521f5e445e5b7a12bd8fAhmet Kaan GümüşParent: 5c8eff8733f426
Cargo.lockmodified+7 -0
@@ -485,6 +485,13 @@ dependencies = [
485 "ec-ogg",485 "ec-ogg",
486 ]486 ]
487 487
488+[[package]]
489+name = "ec-vp8"
490+version = "0.1.0"
491+dependencies = [
492+ "ec-core",
493+]
494+
488 [[package]]495 [[package]]
489 name = "ec-vp9-syntax"496 name = "ec-vp9-syntax"
490 version = "0.1.0"497 version = "0.1.0"
crates/ec-vp8/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-vp8"
3+description = "Native VP8 decoder (RFC 6386) — key-frame and inter-frame decoding of the full format, replacing the runtime-dlopen'd libvpx seat."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
crates/ec-vp8/examples/dbg_first.rsadded+18 -0
@@ -0,0 +1,18 @@
1+// Decode frame 0 of an IVF with decision tracing (EC_VP8_TRACE=1).
2+use ec_vp8::decode::Decoder;
3+
4+fn main() {
5+ let path = std::env::args().nth(1).expect("ivf path");
6+ let bytes = std::fs::read(path).unwrap();
7+ let sz = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize;
8+ let frame = &bytes[44..44 + sz];
9+ let mut dec = Decoder::new();
10+ match dec.decode(frame) {
11+ Ok(Some(pic)) => println!(
12+ "OUT {}x{} y[0..8]={:?}",
13+ pic.width, pic.height, &pic.y[..8]
14+ ),
15+ Ok(None) => println!("OUT hidden"),
16+ Err(e) => println!("OUT ERR {e}"),
17+ }
18+}
crates/ec-vp8/examples/dump_frame.rsadded+58 -0
@@ -0,0 +1,58 @@
1+//! Dump decoded frame N of an IVF as raw yuv420p (ffmpeg-comparable:
2+//! `ffmpeg -i in.ivf -f rawvideo -pix_fmt yuv420p -` streams the same
3+//! layout, frame after frame). Usage: `dump_frame <ivf> <frame-index>
4+//! <out.yuv>`. Decoding stops at the first frame the crate cannot yet
5+//! decode (e.g. inter frames before M3), reporting it on stderr.
6+
7+use ec_vp8::decode::Decoder;
8+
9+fn main() {
10+ let args: Vec<String> = std::env::args().collect();
11+ assert_eq!(args.len(), 4, "usage: dump_frame <ivf> <frame-index> <out.yuv>");
12+ let want: usize = args[2].parse().expect("frame index");
13+ let bytes = std::fs::read(&args[1]).unwrap();
14+
15+ // IVF: 32-byte file header, then (4-byte LE size, 8-byte pts, data).
16+ let mut frames = Vec::new();
17+ let mut pos = 32;
18+ while pos + 12 <= bytes.len() {
19+ let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
20+ frames.push(&bytes[pos + 12..pos + 12 + sz]);
21+ pos += 12 + sz;
22+ }
23+
24+ let mut dec = Decoder::new();
25+ for (i, f) in frames.iter().enumerate() {
26+ match dec.decode(f) {
27+ Ok(Some(pic)) if i == want => {
28+ let mut out = Vec::with_capacity(
29+ pic.y.len() + pic.u.len() + pic.v.len(),
30+ );
31+ for row in 0..usize::from(pic.height) {
32+ let s = row * pic.stride;
33+ out.extend_from_slice(&pic.y[s..s + usize::from(pic.width)]);
34+ }
35+ let (cw, ch) = (
36+ usize::from(pic.width + 1) / 2,
37+ usize::from(pic.height + 1) / 2,
38+ );
39+ for plane in [&pic.u, &pic.v] {
40+ for row in 0..ch {
41+ let s = row * pic.uv_stride;
42+ out.extend_from_slice(&plane[s..s + cw]);
43+ }
44+ }
45+ std::fs::write(&args[3], out).unwrap();
46+ return;
47+ }
48+ Ok(Some(_)) => {}
49+ Ok(None) => {}
50+ Err(e) => {
51+ eprintln!("frame {i}: {e}");
52+ std::process::exit(1);
53+ }
54+ }
55+ }
56+ eprintln!("no frame {want} decoded");
57+ std::process::exit(1);
58+}
crates/ec-vp8/src/bool.rsadded+444 -0
@@ -0,0 +1,444 @@
1+//! The boolean arithmetic decoder (RFC 6386 §7).
2+//!
3+//! VP8 codes almost the entire frame as a sequence of bools, each written
4+//! at an 8-bit zero-probability `p` (meaning `p/256`). The decoder mirrors
5+//! the encoder's interval state with two numbers — `range` (128..=255) and
6+//! `value` (the encoded number x minus the interval's left endpoint) — and
7+//! renormalises one bit at a time, shifting a fresh input byte into
8+//! `value` for every 8 bits consumed.
9+//!
10+//! Every function here is the direct inverse of the RFC's reference
11+//! `bool_encoder`; the tests drive them against a test-only re-implementation
12+//! of that encoder and assert bit-exact round-trips.
13+
14+use ec_core::Result;
15+
16+/// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3).
17+pub struct BoolDecoder<'a> {
18+ data: &'a [u8],
19+ /// Index of the next byte to shift into `value`.
20+ pos: usize,
21+ /// 128..=255; identical to the encoder's range.
22+ range: u32,
23+ /// Encoded number minus the current interval's left endpoint; the top
24+ /// bits hold what has been read, bytes shift in at the bottom.
25+ value: u32,
26+ /// Bits shifted out of `value` since the last byte was shifted in.
27+ bit_count: u32,
28+ /// Bytes consumed past the end of the partition (read as 0, per the
29+ /// spec's zero-extension of x). A healthy partition stays at 0.
30+ overreads: u32,
31+}
32+
33+impl<'a> BoolDecoder<'a> {
34+ /// Start decoding the partition `data` (RFC `init_bool_decoder`): the
35+ /// first two bytes are read into `value`, big-endian. A partition
36+ /// shorter than two bytes (legal for unused token partitions of
37+ /// multi-partition frames) is zero-extended like the reference
38+ /// decoder does, and the shortfall shows up in [`Self::overreads`].
39+ pub fn new(data: &'a [u8]) -> Result<Self> {
40+ if data.is_empty() {
41+ return Ok(Self {
42+ data,
43+ pos: 0,
44+ range: 255,
45+ value: 0,
46+ bit_count: 0,
47+ overreads: 0,
48+ });
49+ }
50+ let mut value = u32::from(data[0]) << 8;
51+ if data.len() > 1 {
52+ value |= u32::from(data[1]);
53+ }
54+ Ok(Self {
55+ data,
56+ pos: data.len().min(2),
57+ range: 255,
58+ value,
59+ bit_count: 0,
60+ overreads: 0,
61+ })
62+ }
63+
64+ /// Bytes consumed past the end of the partition, read as zero. Any
65+ /// non-zero value on a complete, valid partition is a desync symptom.
66+ pub fn overreads(&self) -> u32 {
67+ self.overreads
68+ }
69+
70+ /// Offset of the next unread input byte, for desync diagnostics.
71+ pub fn byte_offset(&self) -> usize {
72+ self.pos
73+ }
74+
75+ fn next_byte(&mut self) -> u32 {
76+ match self.data.get(self.pos) {
77+ Some(&b) => {
78+ self.pos += 1;
79+ u32::from(b)
80+ }
81+ None => {
82+ self.overreads += 1;
83+ 0
84+ }
85+ }
86+ }
87+
88+ /// Decode one bool whose zero-probability is `prob`/256
89+ /// (RFC `read_bool`). Under EC_VP8_TRACE, prints the decoder state
90+ /// after the read — `B <pos> <bit_count> <prob> <bit>`, byte-exact
91+ /// the same line scripts/vp8ref_model.py prints — so the two
92+ /// decoders can be diffed read-for-read.
93+ pub fn read_bool(&mut self, prob: u8) -> bool {
94+ let trace = std::env::var_os("EC_VP8_TRACE").is_some();
95+ let prob = u32::from(prob);
96+ let split = 1 + (((self.range - 1) * prob) >> 8);
97+ let bigsplit = split << 8;
98+ let bit = if self.value >= bigsplit {
99+ self.range -= split;
100+ self.value -= bigsplit;
101+ true
102+ } else {
103+ self.range = split;
104+ false
105+ };
106+ while self.range < 128 {
107+ self.value <<= 1;
108+ self.range <<= 1;
109+ self.bit_count += 1;
110+ if self.bit_count == 8 {
111+ self.bit_count = 0;
112+ self.value |= self.next_byte();
113+ }
114+ }
115+ if trace {
116+ eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
117+ }
118+ bit
119+ }
120+
121+ /// Unsigned `n`-bit literal, bits high- to low-order, each at
122+ /// probability 128 (RFC `read_literal`).
123+ pub fn read_literal(&mut self, n: u32) -> u32 {
124+ let mut v = 0;
125+ for _ in 0..n {
126+ v = (v << 1) + u32::from(self.read_bool(128));
127+ }
128+ v
129+ }
130+
131+ /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude
132+ /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0.
133+ pub fn read_signed_literal(&mut self, n: u32) -> i32 {
134+ if n == 0 {
135+ return 0;
136+ }
137+ let mut v: i32 = if self.read_bool(128) { -1 } else { 0 };
138+ for _ in 0..n - 1 {
139+ v = (v << 1) + i32::from(self.read_bool(128));
140+ }
141+ v
142+ }
143+ /// Presence-gated signed integer in the frame-header shape (RFC §9.3,
144+ /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an
145+ /// `n`-bit magnitude followed by a sign flag (1 = negative). This is
146+ /// every segment/quantizer/loop-filter delta in the frame header.
147+ pub fn read_maybe_signed(&mut self, n: u32) -> i32 {
148+ if !self.read_bool(128) {
149+ return 0;
150+ }
151+ let v = self.read_literal(n) as i32;
152+ if self.read_bool(128) { -v } else { v }
153+ }
154+
155+ /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1
156+ /// : 1` (RFC §8, MV probability updates use exactly this shape).
157+ pub fn read_prob7(&mut self) -> u8 {
158+ let x = self.read_literal(7);
159+ if x == 0 { 1 } else { (x << 1) as u8 }
160+ }
161+
162+ /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the
163+ /// left/right branch entries (positive = interior node index, negative
164+ /// `-leaf`), `probs[i]` is the probability of interior node `i` (the
165+ /// tree position halved).
166+ pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
167+ let mut i: i32 = 0;
168+ loop {
169+ let b = self.read_bool(probs[(i >> 1) as usize]);
170+ i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
171+ if i <= 0 {
172+ return (-i) as u8;
173+ }
174+ }
175+ }
176+
177+ /// Decode a tree-coded value, skipping the root's `dct_eob` branch —
178+ /// used for every token after a `DCT_0`, since EOB cannot follow a
179+ /// zero token (RFC §13.2). `tree` must be the full coefficient tree;
180+ /// decoding starts at interior node 1.
181+ pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
182+ // The coefficient tree's layout puts the EOB leaf at the root's
183+ // left branch; descending the right branch first is exactly
184+ // "start at the root with a read 1".
185+ let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch
186+ while {
187+ let b = self.read_bool(probs[(i >> 1) as usize]);
188+ i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
189+ i > 0
190+ } {}
191+ (-i) as u8
192+ }
193+}
194+
195+/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests
196+/// drive [`BoolDecoder`] against known bitstreams instead of trusting the
197+/// decoder to decode its own idea of the format.
198+#[cfg(test)]
199+pub(crate) struct BoolEncoder {
200+ out: Vec<u8>,
201+ range: u32,
202+ bottom: u32,
203+ bit_count: i32,
204+}
205+
206+#[cfg(test)]
207+impl BoolEncoder {
208+ pub(crate) fn new() -> Self {
209+ Self {
210+ out: Vec::new(),
211+ range: 255,
212+ bottom: 0,
213+ bit_count: 24,
214+ }
215+ }
216+
217+ pub(crate) fn write_bool(&mut self, val: bool, prob: u8) {
218+ let prob = u32::from(prob);
219+ let split = 1 + (((self.range - 1) * prob) >> 8);
220+ if val {
221+ self.bottom += split;
222+ self.range -= split;
223+ } else {
224+ self.range = split;
225+ }
226+ while self.range < 128 {
227+ self.range <<= 1;
228+ if self.bottom & (1 << 31) != 0 {
229+ Self::add_one_to_output(&mut self.out);
230+ }
231+ self.bottom <<= 1;
232+ self.bit_count -= 1;
233+ if self.bit_count == 0 {
234+ self.out.push((self.bottom >> 24) as u8);
235+ self.bottom &= (1 << 24) - 1;
236+ self.bit_count = 8;
237+ }
238+ }
239+ }
240+
241+ pub(crate) fn write_literal(&mut self, v: u32, n: u32) {
242+ for i in (0..n).rev() {
243+ self.write_bool((v >> i) & 1 != 0, 128);
244+ }
245+ }
246+
247+ fn add_one_to_output(out: &mut [u8]) {
248+ for b in out.iter_mut().rev() {
249+ if *b == 255 {
250+ *b = 0;
251+ } else {
252+ *b += 1;
253+ return;
254+ }
255+ }
256+ // Carry out of the beginning cannot happen: x < 1 always (RFC).
257+ unreachable!("bool encoder carry propagated past the first byte");
258+ }
259+
260+ /// RFC `flush_bool_encoder`.
261+ pub(crate) fn flush(mut self) -> Vec<u8> {
262+ let c = self.bit_count;
263+ let mut v = self.bottom;
264+ if v & (1 << (32 - c)) != 0 {
265+ Self::add_one_to_output(&mut self.out);
266+ }
267+ v <<= c & 7;
268+ let mut c = c >> 3;
269+ while c > 0 {
270+ v <<= 8;
271+ c -= 1;
272+ }
273+ for _ in 0..4 {
274+ self.out.push((v >> 24) as u8);
275+ v <<= 8;
276+ }
277+ self.out
278+ }
279+}
280+
281+#[cfg(test)]
282+mod tests {
283+ use super::*;
284+
285+ fn roundtrip_bools(pattern: &[(&[bool], u8)]) {
286+ let mut e = BoolEncoder::new();
287+ for (vals, p) in pattern {
288+ for &v in *vals {
289+ e.write_bool(v, *p);
290+ }
291+ }
292+ let data = e.flush();
293+ let mut d = BoolDecoder::new(&data).unwrap();
294+ for (vals, p) in pattern {
295+ for &v in *vals {
296+ assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p);
297+ }
298+ }
299+ assert_eq!(d.overreads(), 0);
300+ }
301+
302+ #[test]
303+ fn roundtrips_bools_at_every_extreme() {
304+ // p = 1 (all zeros essentially free) through p = 255, with 1s at
305+ // the most improbable settings to force carry propagation.
306+ roundtrip_bools(&[
307+ (&[false; 64], 1),
308+ (&[true], 1),
309+ (&[false, true, false, true], 128),
310+ (&[true; 3], 255),
311+ (&[false; 32], 255),
312+ (&[true; 16], 1),
313+ ]);
314+ }
315+
316+ #[test]
317+ fn roundtrips_long_random_streams() {
318+ // Deterministic LCG so failures reproduce.
319+ let mut state: u64 = 0x9E3779B97F4A7C15;
320+ let mut next = move || {
321+ state ^= state << 13;
322+ state ^= state >> 7;
323+ state ^= state << 17;
324+ state
325+ };
326+ let probs = [1u8, 2, 32, 128, 200, 254, 255];
327+ let mut e = BoolEncoder::new();
328+ let mut expected = Vec::new();
329+ for &p in &probs {
330+ for _ in 0..200 {
331+ let v = next() & 1 == 1;
332+ e.write_bool(v, p);
333+ expected.push((v, p));
334+ }
335+ }
336+ let data = e.flush();
337+ let mut d = BoolDecoder::new(&data).unwrap();
338+ for (v, p) in expected {
339+ assert_eq!(d.read_bool(p), v);
340+ }
341+ assert_eq!(d.overreads(), 0);
342+ }
343+
344+ #[test]
345+ fn roundtrips_literals() {
346+ let mut e = BoolEncoder::new();
347+ for n in 1..=19u32 {
348+ let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
349+ e.write_literal(ones, n);
350+ e.write_literal(0, n);
351+ e.write_literal(0x15 & ones, n); // 0b10101 truncated
352+ }
353+ let data = e.flush();
354+ let mut d = BoolDecoder::new(&data).unwrap();
355+ for n in 1..=19u32 {
356+ let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
357+ assert_eq!(d.read_literal(n), ones);
358+ assert_eq!(d.read_literal(n), 0);
359+ assert_eq!(d.read_literal(n), 0x15 & ones);
360+ }
361+ assert_eq!(d.overreads(), 0);
362+ }
363+
364+ #[test]
365+ fn roundtrips_signed_literals() {
366+ let mut e = BoolEncoder::new();
367+ // sign flag then 4 magnitude bits: the two's-complement value in
368+ // -16..=15 (RFC read_signed_literal shifts the sign-extended -1).
369+ for mag in 0..=15u32 {
370+ e.write_bool(true, 128);
371+ e.write_literal(mag, 4);
372+ e.write_bool(false, 128);
373+ e.write_literal(mag, 4);
374+ }
375+ let data = e.flush();
376+ let mut d = BoolDecoder::new(&data).unwrap();
377+ for mag in 0..=15i32 {
378+ assert_eq!(d.read_signed_literal(5), mag - 16);
379+ assert_eq!(d.read_signed_literal(5), mag);
380+ }
381+ assert_eq!(d.overreads(), 0);
382+ }
383+
384+ #[test]
385+ fn roundtrips_prob7() {
386+ let mut e = BoolEncoder::new();
387+ for x in 0..=127u32 {
388+ e.write_literal(x, 7);
389+ }
390+ let data = e.flush();
391+ let mut d = BoolDecoder::new(&data).unwrap();
392+ for x in 0..=127u32 {
393+ assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 });
394+ }
395+ }
396+
397+ #[test]
398+ fn roundtrips_tree_values() {
399+ // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2:
400+ // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}.
401+ let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3];
402+ let probs = [145u8, 156, 163, 128];
403+ // (bit path, leaf value) pairs of the kf ymode tree (§11.2):
404+ // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110",
405+ // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics.
406+ let leaves: [(&[bool], u8); 5] = [
407+ (&[false], 4),
408+ (&[true, false, false], 0),
409+ (&[true, false, true], 1),
410+ (&[true, true, false], 2),
411+ (&[true, true, true], 3),
412+ ];
413+ for (path, val) in leaves {
414+ let mut e = BoolEncoder::new();
415+ for (i, &b) in path.iter().enumerate() {
416+ e.write_bool(b, probs[i]);
417+ }
418+ let data = e.flush();
419+ let mut d = BoolDecoder::new(&data).unwrap();
420+ assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}");
421+ }
422+ }
423+
424+ #[test]
425+ fn short_partitions_zero_extend() {
426+ // Empty/1-byte partitions are legal for unused token partitions;
427+ // the init shortfall counts as overreads.
428+ let mut d = BoolDecoder::new(&[]).unwrap();
429+ assert_eq!(d.read_bool(128), false);
430+ let mut d = BoolDecoder::new(&[0]).unwrap();
431+ assert_eq!(d.read_bool(128), false);
432+ }
433+
434+ #[test]
435+ fn overreads_are_counted_not_panicked() {
436+ // Two bytes of init, then nothing: any read shifts in zeros.
437+ let data = [0u8, 0];
438+ let mut d = BoolDecoder::new(&data).unwrap();
439+ for _ in 0..100 {
440+ d.read_bool(128);
441+ }
442+ assert!(d.overreads() > 0);
443+ }
444+}
crates/ec-vp8/src/decode.rsadded+1329 -0
@@ -0,0 +1,1329 @@
1+//! Frame decoding: per-row mode parsing, token decoding, intra
2+//! prediction and reconstruction (RFC 6386 §5, §11, §12, §13, §14).
3+//!
4+//! The decoder mirrors the reference decoder's row pipeline: per
5+//! macroblock row, all first-partition mode records are parsed, then
6+//! each macroblock's tokens are decoded from its row-assigned token
7+//! partition (row `r` uses partition `r % partitions`, exactly like
8+//! libvpx/dixie) and immediately reconstructed. The loop filter runs as
9+//! a post-pass in raster MB order — for a non-threaded decode this is
10+//! edge-for-edge identical to the reference's row-delayed filtering,
11+//! because an MB's filter inputs only ever come from MBs already
12+//! filtered earlier in that order.
13+
14+use crate::bool::BoolDecoder;
15+use crate::frame::{FrameType, KeyFrameDims, mb_geometry};
16+use crate::header::FrameHeader;
17+use crate::mc;
18+use crate::intra;
19+use crate::loopfilter::{self, MbFilterInfo};
20+use crate::modes;
21+use crate::tables::KF_BMODE_PROB;
22+use crate::tokens::{self, Dq, MbCoeffs, TokenContexts};
23+use crate::transform;
24+use crate::transform::Dequant;
25+use crate::{Error, PersistedState, Result};
26+/// Copy a visible MB-aligned image out of the 1-pixel-bordered working
27+/// plane into the top-left visible corner of a bordered reference
28+/// buffer.
29+fn copy_plane(
30+ dst: &mut [u8],
31+ dst_stride: usize,
32+ src: &[u8],
33+ src_stride: usize,
34+ w: usize,
35+ h: usize,
36+) {
37+ for r in 0..h {
38+ let s = (1 + r) * src_stride + 1;
39+ let d = (MC_BORDER + r) * dst_stride + MC_BORDER;
40+ dst[d..d + w].copy_from_slice(&src[s..s + w]);
41+ }
42+}
43+
44+/// Reconstructed-image plane: a padded buffer with a 1-pixel left/top
45+/// border (127 on top including the corner, 129 on the left — RFC 6386
46+/// §12) so intra prediction reads neighbours without special cases.
47+struct Plane {
48+ data: Vec<u8>,
49+ /// Row pitch: `1 + mb_cols * mb_size`.
50+ stride: usize,
51+}
52+
53+impl Plane {
54+ fn new(mb_cols: usize, mb_rows: usize, mb_size: usize) -> Self {
55+ let stride = 1 + mb_cols * mb_size;
56+ let rows = 1 + mb_rows * mb_size;
57+ let mut data = vec![0u8; stride * rows];
58+ for cell in data[..stride].iter_mut() {
59+ *cell = 127;
60+ }
61+ for row in 1..rows {
62+ data[row * stride] = 129;
63+ }
64+ Plane { data, stride }
65+ }
66+
67+ fn resize(&mut self, mb_cols: usize, mb_rows: usize, mb_size: usize) {
68+ *self = Plane::new(mb_cols, mb_rows, mb_size);
69+ }
70+
71+ /// Offset of pixel (x, y); the border occupies x = -1 / y = -1.
72+ fn at(&self, x: usize, y: usize) -> usize {
73+ (1 + y) * self.stride + 1 + x
74+ }
75+
76+ /// Offset of the pixel row ABOVE pixel row `y` (the border row for
77+ /// y = 0), at pixel column `x`.
78+ fn at_above(&self, x: usize, y: usize) -> usize {
79+ y * self.stride + 1 + x
80+ }
81+
82+ /// Offset of the pixel column LEFT of pixel column `x` (the border
83+ /// column for x = 0), at pixel row `y`.
84+ fn at_left(&self, x: usize, y: usize) -> usize {
85+ (1 + y) * self.stride + x
86+ }
87+
88+ /// Offset of the above-left pixel (border corner for x = y = 0).
89+ fn at_above_left(&self, x: usize, y: usize) -> usize {
90+ y * self.stride + x
91+ }
92+}
93+
94+/// One macroblock's parsed prediction record.
95+#[derive(Clone, Default)]
96+struct MbInfo {
97+ /// [`modes::YMode`] as its coded integer.
98+ y_mode: u8,
99+ uv_mode: u8,
100+ b_modes: [u8; 16],
101+ segment_id: u8,
102+ skip: bool,
103+ /// 0 = intra, 1 = last, 2 = golden, 3 = altref (§16.2). Key-frame
104+ /// MBs and the border are intra.
105+ ref_frame: u8,
106+ /// Inter mv_ref leaf (§16.2): 0 = zero, 1 = nearest, 2 = near,
107+ /// 3 = new, 4 = split. 0 when intra.
108+ mv_ref: u8,
109+ /// Whole-MB motion vector in eighth-pels; the bottom-right subblock's
110+ /// vector for SPLITMV (what future neighbours' census sees).
111+ mv: (i16, i16),
112+ /// Per-subblock motion vectors (SPLITMV).
113+ bmi: [(i16, i16); 16],
114+ /// `need_to_clamp_mvs` (§16.2): the luma MC clamps this MV into the
115+ /// extended-frame range.
116+ mv_clamp: bool,
117+ /// Any non-zero coefficient decoded for this MB (bit 31 of dixie's
118+ /// eob_mask); decides the loop filter's interior edges (§15.1).
119+ has_nz: bool,
120+}
121+
122+/// One reference-frame slot: bordered planes, 32-pixel edge-replicated
123+/// borders around the MB-aligned image (dixie `extend_frame`).
124+#[derive(Clone)]
125+struct RefFrame {
126+ y: Vec<u8>,
127+ u: Vec<u8>,
128+ v: Vec<u8>,
129+ stride: usize,
130+ uv_stride: usize,
131+}
132+
133+/// MC border width in pixels (libvpx `VP8BORDERINPIXELS`).
134+const MC_BORDER: usize = 32;
135+
136+impl MbInfo {
137+ fn has_y2(&self) -> bool {
138+ self.y_mode != modes::YMode::BPred.as_u8()
139+ }
140+}
141+
142+/// The VP8 decoder. Feed complete frames (one full VP8 frame payload,
143+/// exactly what a container demuxer hands over for the `VP80`/`vp08`
144+/// codec).
145+pub struct Decoder {
146+ state: PersistedState,
147+ dims: KeyFrameDims,
148+ mb_cols: usize,
149+ mb_rows: usize,
150+ y: Plane,
151+ u: Plane,
152+ v: Plane,
153+ /// `(mb_rows + 1) * (mb_cols + 1)` records; row/column index 0 is the
154+ /// DC_PRED border (dixie's `mb_info` border trick).
155+ mb_info: Vec<MbInfo>,
156+ token_ctxs: TokenContexts,
157+ /// Reference frame slots: [unused, last, golden, altref] (§16.2
158+ /// indices). Empty until the first key frame.
159+ refs: [Option<RefFrame>; 4],
160+ /// Persisted per-MB segment ids, `mb_rows * mb_cols` (§9.3: when a
161+ /// frame does not re-code the map, ids carry over).
162+ segment_map: Vec<u8>,
163+ frame_decoded: bool,
164+ /// Per-frame MC filter selection (libvpx `vp8_setup_version`,
165+ /// alloccommon.c:131-167: version 0 and the reserved 4-7 use the
166+ /// six-tap filters, versions 1-3 the bilinear ones) and full-pel
167+ /// flag (version 3: `fullpixel_mask = ~7`). The decoder never reads
168+ /// `no_lpf` — dead there too.
169+ mc_bilinear: bool,
170+ mc_fullpel: bool,
171+}
172+
173+/// A decoded, displayable frame: cropped contiguous planes.
174+#[derive(Clone)]
175+pub struct Picture {
176+ /// Luma plane, `stride`-spaced rows of `width` pixels.
177+ pub y: Vec<u8>,
178+ /// U (Cb) plane, half resolution.
179+ pub u: Vec<u8>,
180+ /// V (Cr) plane, half resolution.
181+ pub v: Vec<u8>,
182+ /// Frame width in pixels.
183+ pub width: u16,
184+ /// Frame height in pixels.
185+ pub height: u16,
186+ /// Luma row pitch of the returned planes.
187+ pub stride: usize,
188+ /// Chroma row pitch of the returned planes.
189+ pub uv_stride: usize,
190+}
191+
192+impl Decoder {
193+ /// Create an empty decoder; the first key frame sets the size.
194+ pub fn new() -> Self {
195+ Self {
196+ state: PersistedState::default(),
197+ dims: KeyFrameDims {
198+ width: 0,
199+ height: 0,
200+ h_scale: 0,
201+ v_scale: 0,
202+ },
203+ mb_cols: 0,
204+ mb_rows: 0,
205+ y: Plane {
206+ data: Vec::new(),
207+ stride: 0,
208+ },
209+ u: Plane {
210+ data: Vec::new(),
211+ stride: 0,
212+ },
213+ v: Plane {
214+ data: Vec::new(),
215+ stride: 0,
216+ },
217+ mb_info: Vec::new(),
218+ token_ctxs: TokenContexts::new(0),
219+ refs: [None, None, None, None],
220+ segment_map: Vec::new(),
221+ frame_decoded: false,
222+ mc_bilinear: false,
223+ mc_fullpel: false,
224+ }
225+ }
226+
227+ /// Size of the frames this decoder produces, once known.
228+ pub fn dimensions(&self) -> Option<(u16, u16)> {
229+ self.frame_decoded
230+ .then_some((self.dims.width, self.dims.height))
231+ }
232+
233+ /// Decode one frame; returns the picture when it is for display
234+ /// (`show_frame`). Hidden frames still update the decode state.
235+ pub fn decode(&mut self, frame: &[u8]) -> Result<Option<Picture>> {
236+ // Entropy revert (§9.7, libvpx decodeframe.c:1156/1245): when
237+ // `refresh_entropy` is 0 the frame's probability updates are
238+ // transient — libvpx copies `fc` into `lfc` at this point in
239+ // the header and restores it after the frame. On a KEY frame
240+ // `fc` has already been reset to defaults by then (init_frame
241+ // runs before header parsing), so a key frame with
242+ // refresh_entropy == 0 reverts to DEFAULTS, not to whatever the
243+ // previous stream carried. Segmentation and loop-filter deltas
244+ // live outside `fc` and never revert.
245+ let key = frame.first().is_some_and(|b| b & 1 == 0);
246+ let defaults = PersistedState::default();
247+ let (coeff_probs, mv_probs, ymode_probs, uv_mode_probs) = if key {
248+ (
249+ defaults.coeff_probs,
250+ defaults.mv_probs,
251+ defaults.ymode_probs,
252+ defaults.uv_mode_probs,
253+ )
254+ } else {
255+ (
256+ self.state.coeff_probs,
257+ self.state.mv_probs,
258+ self.state.ymode_probs,
259+ self.state.uv_mode_probs,
260+ )
261+ };
262+ let (header, hdr_dec) = FrameHeader::parse(frame, &mut self.state)?;
263+ // vp8_setup_version (decodeframe.c:935): the tag's version bits
264+ // pick the MC interpolation filter and full-pel mode for this
265+ // frame (see the field docs on Decoder).
266+ self.mc_bilinear = matches!(header.tag.version, 1..=3);
267+ self.mc_fullpel = header.tag.version == 3;
268+ let refresh_entropy = header.refresh.refresh_entropy;
269+ let pic = match header.tag.frame_type {
270+ FrameType::Key => self.decode_keyframe(frame, header, hdr_dec),
271+ FrameType::Inter => self.decode_interframe(frame, header, hdr_dec),
272+ }?;
273+ if !refresh_entropy {
274+ self.state.coeff_probs = coeff_probs;
275+ self.state.mv_probs = mv_probs;
276+ self.state.ymode_probs = ymode_probs;
277+ self.state.uv_mode_probs = uv_mode_probs;
278+ }
279+ Ok(pic)
280+ }
281+
282+ fn ensure_buffers(&mut self, kf: KeyFrameDims) {
283+ let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height);
284+ if self.mb_cols != mb_cols || self.mb_rows != mb_rows {
285+ self.y.resize(mb_cols, mb_rows, 16);
286+ self.u.resize(mb_cols, mb_rows, 8);
287+ self.v.resize(mb_cols, mb_rows, 8);
288+ self.mb_info = vec![MbInfo::default(); (mb_cols + 1) * (mb_rows + 1)];
289+ self.token_ctxs = TokenContexts::new(mb_cols);
290+ }
291+ self.mb_cols = mb_cols;
292+ self.mb_rows = mb_rows;
293+ self.dims = kf;
294+ // Reset the mode border (row 0 / column 0) so the top-left mode
295+ // contexts read DC_PRED like a fresh decode.
296+ for col in 0..=mb_cols {
297+ self.mb_info[col] = MbInfo::default();
298+ }
299+ for row in 0..=mb_rows {
300+ self.mb_info[row * (mb_cols + 1)] = MbInfo::default();
301+ }
302+ }
303+
304+ /// Mode-record index for MB (row, col); row/col 0 is the border.
305+ fn mbi(&self, row: usize, col: usize) -> &MbInfo {
306+ &self.mb_info[row * (self.mb_cols + 1) + col]
307+ }
308+
309+ fn mbi_mut(&mut self, row: usize, col: usize) -> &mut MbInfo {
310+ let w = self.mb_cols + 1;
311+ &mut self.mb_info[row * w + col]
312+ }
313+
314+ fn decode_keyframe(
315+ &mut self,
316+ frame: &[u8],
317+ header: FrameHeader,
318+ mut hdr_dec: BoolDecoder<'_>,
319+ ) -> Result<Option<Picture>> {
320+ let kf = header.dims.expect("key frame header carries dimensions");
321+ self.ensure_buffers(kf);
322+
323+ // Token partition bool decoders (§9.5).
324+ let mut partitions = Vec::with_capacity(header.partition_sizes.len());
325+ let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1);
326+ for &sz in &header.partition_sizes {
327+ let end = off + sz as usize;
328+ let slice = frame
329+ .get(off..end)
330+ .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?;
331+ partitions.push(BoolDecoder::new(slice)?);
332+ off = end;
333+ }
334+
335+ // Dequant factors per segment (dixie dequant_init, §10/§14.1).
336+ let seg = &header.segmentation;
337+ let mut dqf = [Dequant {
338+ y1_dc: 0,
339+ y1_ac: 0,
340+ y2_dc: 0,
341+ y2_ac: 0,
342+ uv_dc: 0,
343+ uv_ac: 0,
344+ }; 4];
345+ for (i, dq) in dqf.iter_mut().enumerate() {
346+ let q = if seg.enabled {
347+ if seg.abs_delta {
348+ seg.quant_idx[i]
349+ } else {
350+ i32::from(header.quant.yac_qi) + seg.quant_idx[i]
351+ }
352+ } else {
353+ i32::from(header.quant.yac_qi)
354+ };
355+ *dq = transform::dequant(
356+ q,
357+ header.quant.ydc_delta,
358+ header.quant.y2dc_delta,
359+ header.quant.y2ac_delta,
360+ header.quant.uvdc_delta,
361+ header.quant.uvac_delta,
362+ );
363+ }
364+
365+ self.token_ctxs.reset_above_row();
366+
367+ for row in 1..=self.mb_rows {
368+ self.token_ctxs.reset_left();
369+ // Phase 1: parse every mode record of the row (partition 0).
370+ for col in 1..=self.mb_cols {
371+ let mut mb = MbInfo::default();
372+ if header.segmentation.enabled && header.segmentation.update_map {
373+ mb.segment_id =
374+ hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs);
375+ }
376+ if header.coeff_skip_enabled {
377+ mb.skip = hdr_dec.read_bool(header.prob_skip_false);
378+ }
379+ self.decode_kf_modes(&mut hdr_dec, row, col, &mut mb);
380+ *self.mbi_mut(row, col) = mb;
381+ }
382+
383+ // Phases 2+3 per MB: tokens then reconstruction. Token row
384+ // `r` (0-based) reads partition `r % n` like the reference.
385+ let part = (row - 1) % partitions.len();
386+ for col in 1..=self.mb_cols {
387+ if std::env::var_os("EC_VP8_TRACE").is_some() {
388+ eprintln!("M {} {}", row - 1, col - 1);
389+ }
390+ let mb = self.mbi(row, col).clone();
391+ let has_y2 = mb.has_y2();
392+ let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id);
393+ let dq = &dqf[seg_i];
394+ let mb_dq = Dq {
395+ y1_dc: dq.y1_dc,
396+ y1_ac: dq.y1_ac,
397+ uv_dc: dq.uv_dc,
398+ uv_ac: dq.uv_ac,
399+ y2_dc: dq.y2_dc,
400+ y2_ac: dq.y2_ac,
401+ };
402+ if std::env::var_os("EC_VP8_TRACE").is_some() {
403+ eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2);
404+ }
405+ let probs = self.state.coeff_probs;
406+ let coeffs = if mb.skip {
407+ tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2)
408+ } else {
409+ tokens::decode_mb_tokens(
410+ &mut partitions[part],
411+ &probs,
412+ &mb_dq,
413+ has_y2,
414+ &mut self.token_ctxs,
415+ col - 1,
416+ )
417+ };
418+ self.mb_info[row * (self.mb_cols + 1) + col].has_nz = coeffs.has_nonzero();
419+ self.reconstruct_intra_mb(row - 1, col - 1, &mb, &coeffs);
420+ }
421+ }
422+
423+ // Loop filter post-pass (see module docs for the ordering
424+ // equivalence argument).
425+ self.run_loopfilter(&header, true);
426+
427+ // A key frame refreshes every reference slot and clears the
428+ // persisted segment map (§9.3, §9.7).
429+ self.segment_map = vec![0; self.mb_cols * self.mb_rows];
430+ let rf = self.make_ref();
431+ self.refs[1] = Some(rf.clone());
432+ self.refs[2] = Some(rf.clone());
433+ self.refs[3] = Some(rf);
434+
435+ self.frame_decoded = true;
436+ Ok(header.tag.show_frame.then(|| self.crop()))
437+ }
438+
439+ /// Loop-filter post-pass over the whole frame (dixie order-equivalent
440+ /// driver; `inner_edges` follows libvpx's `skip_lf`: skipped MBs
441+ /// filter only their boundary edges, except 4x4-coded modes).
442+ fn run_loopfilter(&mut self, header: &FrameHeader, is_keyframe: bool) {
443+ if header.filter_level == 0 {
444+ return;
445+ }
446+ let infos: Vec<MbFilterInfo> = (0..self.mb_rows)
447+ .flat_map(|r| (0..self.mb_cols).map(move |c| (r, c)))
448+ .map(|(r, c)| {
449+ let mb = self.mbi(r + 1, c + 1);
450+ MbFilterInfo {
451+ level: self.mb_filter_level(header, mb),
452+ inner_edges: mb.has_nz || !mb.has_y2(),
453+ }
454+ })
455+ .collect();
456+ // The planes are bordered; the filter sees the unbordered
457+ // image (same row pitch) starting at pixel (0, 0).
458+ let (ystride, ustride, vstride) = (self.y.stride, self.u.stride, self.v.stride);
459+ let (mcols, mrows) = (self.mb_cols, self.mb_rows);
460+ let simple = header.filter_type == 1;
461+ let sharpness = header.sharpness_level;
462+ let yimg = &mut self.y.data[1 + ystride..];
463+ let uimg = &mut self.u.data[1 + ustride..];
464+ let vimg = &mut self.v.data[1 + vstride..];
465+ loopfilter::filter_frame_ex(
466+ yimg, uimg, vimg, ystride, ustride, mcols, mrows, sharpness, simple, &infos,
467+ is_keyframe,
468+ );
469+ }
470+
471+ /// Snapshot the reconstructed (post-LF) frame into a bordered
472+ /// reference buffer with 32-pixel edge-replicated borders.
473+ fn make_ref(&self) -> RefFrame {
474+ let w = self.mb_cols * 16;
475+ let h = self.mb_rows * 16;
476+ let (cw, ch) = (self.mb_cols * 8, self.mb_rows * 8);
477+ let mut rf = RefFrame {
478+ y: vec![0; (w + 2 * MC_BORDER) * (h + 2 * MC_BORDER)],
479+ u: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)],
480+ v: vec![0; (cw + 2 * MC_BORDER) * (ch + 2 * MC_BORDER)],
481+ stride: w + 2 * MC_BORDER,
482+ uv_stride: cw + 2 * MC_BORDER,
483+ };
484+ copy_plane(&mut rf.y, rf.stride, &self.y.data, self.y.stride, w, h);
485+ copy_plane(&mut rf.u, rf.uv_stride, &self.u.data, self.u.stride, cw, ch);
486+ copy_plane(&mut rf.v, rf.uv_stride, &self.v.data, self.v.stride, cw, ch);
487+ mc::extend_plane(&mut rf.y, rf.stride, w, h, MC_BORDER);
488+ mc::extend_plane(&mut rf.u, rf.uv_stride, cw, ch, MC_BORDER);
489+ mc::extend_plane(&mut rf.v, rf.uv_stride, cw, ch, MC_BORDER);
490+ rf
491+ }
492+
493+
494+ /// Per-MB loop filter level (libvpx `loop_filter_frame_init`):
495+ /// segment level (clamped), then the reference delta, then the mode
496+ /// delta, clamped again. Mode slots: intra B_PRED → 0, other intra
497+ /// and ZEROMV → 1 (no delta for other intra), the moving modes → 2,
498+ /// SPLITMV → 3.
499+ fn mb_filter_level(&self, header: &FrameHeader, mb: &MbInfo) -> u8 {
500+ let seg = &header.segmentation;
501+ let mut level = i32::from(header.filter_level);
502+ if seg.enabled {
503+ let d = seg.lf_level[usize::from(mb.segment_id)];
504+ level = if seg.abs_delta { d } else { level + d };
505+ }
506+ level = level.clamp(0, 63);
507+ if header.lf_delta_enabled {
508+ level += self.state.ref_lf_delta[usize::from(mb.ref_frame)];
509+ let mode_idx = if mb.ref_frame == 0 {
510+ if mb.y_mode == modes::YMode::BPred.as_u8() {
511+ Some(0)
512+ } else {
513+ None
514+ }
515+ } else {
516+ match mb.mv_ref {
517+ 0 => Some(1), // ZEROMV
518+ 4 => Some(3), // SPLITMV
519+ _ => Some(2), // NEAREST / NEAR / NEW
520+ }
521+ };
522+ if let Some(mode_idx) = mode_idx {
523+ level += self.state.mode_lf_delta[mode_idx];
524+ }
525+ level = level.clamp(0, 63);
526+ }
527+ level as u8
528+ }
529+ /// Decode one inter frame (§16): all mode records off partition 0
530+ /// (row-major), then per-row tokens and reconstruction off the row's
531+ /// token partition, loop filter, then the reference updates (§9.7).
532+ fn decode_interframe(
533+ &mut self,
534+ frame: &[u8],
535+ header: FrameHeader,
536+ mut hdr_dec: BoolDecoder<'_>,
537+ ) -> Result<Option<Picture>> {
538+ if self.mb_cols == 0 || self.refs[1..4].iter().any(|r| r.is_none()) {
539+ return Err(Error::corrupt("VP8 inter frame before the first key frame"));
540+ }
541+
542+ // Token partition bool decoders (§9.5) — identical tiling to
543+ // key frames.
544+ let mut partitions = Vec::with_capacity(header.partition_sizes.len());
545+ let mut off = header.token_data_offset + 3 * (header.partition_sizes.len() - 1);
546+ for &sz in &header.partition_sizes {
547+ let end = off + sz as usize;
548+ let slice = frame
549+ .get(off..end)
550+ .ok_or_else(|| Error::corrupt("VP8 token partition extends past frame end"))?;
551+ partitions.push(BoolDecoder::new(slice)?);
552+ off = end;
553+ }
554+
555+ // Dequant factors per segment (persisted segmentation state).
556+ let seg = &header.segmentation;
557+ let mut dqf = [Dequant {
558+ y1_dc: 0,
559+ y1_ac: 0,
560+ y2_dc: 0,
561+ y2_ac: 0,
562+ uv_dc: 0,
563+ uv_ac: 0,
564+ }; 4];
565+ for (i, dq) in dqf.iter_mut().enumerate() {
566+ let q = if seg.enabled {
567+ if seg.abs_delta {
568+ seg.quant_idx[i]
569+ } else {
570+ i32::from(header.quant.yac_qi) + seg.quant_idx[i]
571+ }
572+ } else {
573+ i32::from(header.quant.yac_qi)
574+ };
575+ *dq = transform::dequant(
576+ q,
577+ header.quant.ydc_delta,
578+ header.quant.y2dc_delta,
579+ header.quant.y2ac_delta,
580+ header.quant.uvdc_delta,
581+ header.quant.uvac_delta,
582+ );
583+ }
584+ let ymode_probs = self.state.ymode_probs;
585+ let uv_mode_probs = self.state.uv_mode_probs;
586+ let sign_bias = [
587+ false,
588+ header.refresh.sign_bias_golden,
589+ header.refresh.sign_bias_altref,
590+ ];
591+
592+ // §13.3: non-existent neighbours are empty — the above context
593+ // is cleared at every frame start, like the key-frame path.
594+ self.token_ctxs.reset_above_row();
595+
596+ // Phase 1: every mode record of the frame, row-major (§16).
597+ if std::env::var_os("EC_VP8_TRACE").is_some() {
598+ eprintln!("STAGE modes");
599+ }
600+ for row in 1..=self.mb_rows {
601+ for col in 1..=self.mb_cols {
602+ let mut mb = MbInfo::default();
603+ if header.segmentation.enabled {
604+ if header.segmentation.update_map {
605+ mb.segment_id =
606+ hdr_dec.read_tree(&SEGMENT_TREE, &header.segmentation.tree_probs);
607+ self.segment_map[(row - 1) * self.mb_cols + (col - 1)] = mb.segment_id;
608+ } else {
609+ mb.segment_id = self.segment_map[(row - 1) * self.mb_cols + (col - 1)];
610+ }
611+ }
612+ if header.coeff_skip_enabled {
613+ mb.skip = hdr_dec.read_bool(header.prob_skip_false);
614+ }
615+ self.parse_inter_modes(
616+ &mut hdr_dec,
617+ row,
618+ col,
619+ &mut mb,
620+ &header,
621+ &ymode_probs,
622+ &uv_mode_probs,
623+ &sign_bias,
624+ );
625+ *self.mbi_mut(row, col) = mb;
626+ }
627+ }
628+
629+ // Phases 2+3 per row: tokens, then reconstruction (MC or intra).
630+ for row in 1..=self.mb_rows {
631+ self.token_ctxs.reset_left();
632+ let part = (row - 1) % partitions.len();
633+ for col in 1..=self.mb_cols {
634+ let mb = self.mbi(row, col).clone();
635+ let has_y2 = mb.has_y2();
636+ let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id);
637+ let dq = &dqf[seg_i];
638+ let mb_dq = Dq {
639+ y1_dc: dq.y1_dc,
640+ y1_ac: dq.y1_ac,
641+ uv_dc: dq.uv_dc,
642+ uv_ac: dq.uv_ac,
643+ y2_dc: dq.y2_dc,
644+ y2_ac: dq.y2_ac,
645+ };
646+ let probs = self.state.coeff_probs;
647+ let coeffs = if mb.skip {
648+ tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2)
649+ } else {
650+ tokens::decode_mb_tokens(
651+ &mut partitions[part],
652+ &probs,
653+ &mb_dq,
654+ has_y2,
655+ &mut self.token_ctxs,
656+ col - 1,
657+ )
658+ };
659+ {
660+ // "Special case: force the loop filter to skip when
661+ // eobtotal is zero" (libvpx decodeframe.c): a decoded
662+ // MB without non-zero coefficients filters like a
663+ // skipped one.
664+ let slot = &mut self.mb_info[row * (self.mb_cols + 1) + col];
665+ slot.has_nz = coeffs.has_nonzero();
666+ slot.skip = mb.skip || !coeffs.has_nonzero();
667+ }
668+ self.reconstruct_inter_mb(row - 1, col - 1, &mb, &coeffs);
669+ }
670+ }
671+
672+ self.run_loopfilter(&header, false);
673+
674+ // Reference buffer updates, libvpx `swap_frame_buffers` order:
675+ // the copies run first (copy_gf = 2 must see a possibly
676+ // just-updated altref), then the refreshes, then last.
677+ let new = self.make_ref();
678+ match header.refresh.copy_arf {
679+ 1 => self.refs[3] = self.refs[1].clone(),
680+ 2 => self.refs[3] = self.refs[2].clone(),
681+ _ => {}
682+ }
683+ match header.refresh.copy_gf {
684+ 1 => self.refs[2] = self.refs[1].clone(),
685+ 2 => self.refs[2] = self.refs[3].clone(),
686+ _ => {}
687+ }
688+ if header.refresh.refresh_gf {
689+ self.refs[2] = Some(new.clone());
690+ }
691+ if header.refresh.refresh_arf {
692+ self.refs[3] = Some(new.clone());
693+ }
694+ if header.refresh.refresh_last {
695+ self.refs[1] = Some(new);
696+ }
697+
698+ self.frame_decoded = true;
699+ Ok(header.tag.show_frame.then(|| self.crop()))
700+ }
701+
702+ /// Inter-frame mode record (§16, libvpx `read_mb_modes_mv`): intra
703+ /// at the persisted mode probabilities, or an inter mode with its
704+ /// motion vectors off the neighborhood census.
705+ #[allow(clippy::too_many_arguments)]
706+ fn parse_inter_modes(
707+ &mut self,
708+ d: &mut BoolDecoder<'_>,
709+ row: usize,
710+ col: usize,
711+ mb: &mut MbInfo,
712+ header: &FrameHeader,
713+ ymode_probs: &[u8; 4],
714+ uv_mode_probs: &[u8; 3],
715+ sign_bias: &[bool; 3],
716+ ) {
717+ if !d.read_bool(header.prob_intra) {
718+ // Intra-coded MB inside an inter frame (§16.1). Subblock
719+ // modes decode at one CONSTANT probability array with no
720+ // above/left context (libvpx decodemv.c:467 reads
721+ // `fc.bmode_prob` — the flat vp8_bmode_prob default; the
722+ // context-dependent kf_bmode_prob table is key-frame-only).
723+ mb.ref_frame = 0;
724+ let ymode = modes::read_ymode(d, ymode_probs);
725+ mb.y_mode = ymode.as_u8();
726+ if ymode == modes::YMode::BPred {
727+ for j in 0..16usize {
728+ mb.b_modes[j] = modes::read_bmode(d, &modes::INTER_BMODE_PROBS).as_u8();
729+ }
730+ }
731+ mb.uv_mode = modes::read_uvmode(d, uv_mode_probs).as_u8();
732+ return;
733+ }
734+
735+ mb.ref_frame = if !d.read_bool(header.prob_last) {
736+ 1
737+ } else if !d.read_bool(header.prob_gf) {
738+ 2
739+ } else {
740+ 3
741+ };
742+ let to_bias = sign_bias[usize::from(mb.ref_frame) - 1];
743+
744+ let edges = modes::mb_edges(col - 1, row - 1, self.mb_cols, self.mb_rows);
745+ let above = self.mv_neighbor(row - 1, col, sign_bias);
746+ let left = self.mv_neighbor(row, col - 1, sign_bias);
747+ let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias);
748+ let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias);
749+ if std::env::var_os("EC_VP8_TRACE").is_some() {
750+ eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs);
751+ }
752+
753+ if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_INTRA] as usize][0]) {
754+ mb.mv_ref = 0; // ZEROMV
755+ return;
756+ }
757+ if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAREST] as usize][1]) {
758+ mb.mv_ref = 1; // NEARESTMV
759+ mb.mv = near_mvs[modes::CNT_NEAREST];
760+ modes::clamp_mv2(&mut mb.mv, edges);
761+ return;
762+ }
763+ if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_NEAR] as usize][2]) {
764+ mb.mv_ref = 2; // NEARMV
765+ mb.mv = near_mvs[modes::CNT_NEAR];
766+ modes::clamp_mv2(&mut mb.mv, edges);
767+ return;
768+ }
769+
770+ // NEWMV or SPLITMV: both code vectors as deltas off the best
771+ // candidate — the nearest one when it dominates the census —
772+ // clamped into range first (§16.2-§16.4).
773+ let near_index = usize::from(cnt[modes::CNT_NEAREST] >= cnt[modes::CNT_INTRA]);
774+ modes::clamp_mv2(&mut near_mvs[near_index], edges);
775+ let best = near_mvs[near_index];
776+ if !d.read_bool(modes::MODE_CONTEXTS[cnt[modes::CNT_SPLITMV] as usize][3]) {
777+ mb.mv_ref = 3; // NEWMV
778+ let mut mv = modes::read_mv(d, &self.state.mv_probs);
779+ mv.0 = mv.0.wrapping_add(best.0);
780+ mv.1 = mv.1.wrapping_add(best.1);
781+ mb.mv_clamp = modes::mv_out_of_bounds(mv, edges);
782+ mb.mv = mv;
783+ } else {
784+ self.parse_split_mv(d, row, col, mb, best, edges);
785+ }
786+ }
787+
788+ /// Census input from one neighbour slot (§16.3); border and intra
789+ /// MBs contribute nothing, zero-vector inter MBs count like intra.
790+ fn mv_neighbor(&self, row: usize, col: usize, sign_bias: &[bool; 3]) -> modes::MvNeighbor {
791+ if row == 0 || col == 0 || self.mbi(row, col).ref_frame == 0 {
792+ return modes::MvNeighbor {
793+ intra: true,
794+ zero: false,
795+ mv: (0, 0),
796+ is_split: false,
797+ sign_bias: false,
798+ };
799+ }
800+ let mb = self.mbi(row, col);
801+ modes::MvNeighbor {
802+ intra: false,
803+ zero: mb.mv == (0, 0),
804+ mv: mb.mv,
805+ is_split: mb.mv_ref == 4,
806+ sign_bias: sign_bias[usize::from(mb.ref_frame) - 1],
807+ }
808+ }
809+
810+ /// SPLITMV mode record (§16.4, libvpx `decode_split_mv`): partition
811+ /// shape, then one vector per subset coded against its left/above
812+ /// contexts, each filling a whole group of subblocks.
813+ fn parse_split_mv(
814+ &mut self,
815+ d: &mut BoolDecoder<'_>,
816+ row: usize,
817+ col: usize,
818+ mb: &mut MbInfo,
819+ best: (i16, i16),
820+ edges: (i32, i32, i32, i32),
821+ ) {
822+ let s = modes::read_mv_partition(d);
823+ let num_p = modes::MV_PARTITION_COUNT[s];
824+ let mv_probs = self.state.mv_probs;
825+ for j in 0..num_p {
826+ let k = usize::from(modes::MBSPLIT_OFFSET[s][j]);
827+ let leftmv = if k % 4 == 0 {
828+ let lm = self.mbi(row, col - 1);
829+ if lm.mv_ref == 4 {
830+ lm.bmi[k + 3]
831+ } else {
832+ lm.mv
833+ }
834+ } else {
835+ mb.bmi[k - 1]
836+ };
837+ let abovemv = if k < 4 {
838+ let am = self.mbi(row - 1, col);
839+ if am.mv_ref == 4 {
840+ am.bmi[k + 12]
841+ } else {
842+ am.mv
843+ }
844+ } else {
845+ mb.bmi[k - 4]
846+ };
847+ let ctx = modes::mv_cont(leftmv, abovemv);
848+ let blockmv = match modes::read_sub_mv_ref(d, ctx) {
849+ modes::SubMvRef::Left4x4 => leftmv,
850+ modes::SubMvRef::Above4x4 => abovemv,
851+ modes::SubMvRef::Zero4x4 => (0, 0),
852+ modes::SubMvRef::New4x4 => {
853+ let mut mv = modes::read_mv(d, &mv_probs);
854+ mv.0 = mv.0.wrapping_add(best.0);
855+ mv.1 = mv.1.wrapping_add(best.1);
856+ mv
857+ }
858+ };
859+ if std::env::var_os("EC_VP8_TRACE").is_some() {
860+ eprintln!(
861+ "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})",
862+ row - 1,
863+ col - 1,
864+ j,
865+ k,
866+ leftmv.0,
867+ leftmv.1,
868+ abovemv.0,
869+ abovemv.1,
870+ ctx,
871+ blockmv.0,
872+ blockmv.1,
873+ best.0,
874+ best.1
875+ );
876+ }
877+ mb.mv_clamp |= modes::mv_out_of_bounds(blockmv, edges);
878+ let count = modes::MBSPLIT_FILL_COUNT[s];
879+ for &off in &modes::MBSPLIT_FILL_OFFSET[s][j * count..(j + 1) * count] {
880+ mb.bmi[usize::from(off)] = blockmv;
881+ }
882+ }
883+ mb.mv_ref = 4;
884+ // 4x4 residual coding without a Y2 block (like B_PRED).
885+ mb.y_mode = modes::YMode::BPred.as_u8();
886+ // Neighbours' census sees the bottom-right subblock's vector.
887+ mb.mv = mb.bmi[15];
888+ }
889+
890+ /// Reconstruct one inter-frame MB: motion compensation from the
891+ /// reference (or intra prediction), then the residual (§16, §14).
892+ fn reconstruct_inter_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) {
893+ if mb.ref_frame == 0 {
894+ self.reconstruct_intra_mb(row, col, mb, coeffs);
895+ return;
896+ }
897+ if std::env::var_os("EC_VP8_TRACE").is_some() {
898+ eprintln!(
899+ "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}",
900+ row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip
901+ );
902+ }
903+ let reff = self.refs[usize::from(mb.ref_frame)]
904+ .as_ref()
905+ .expect("reference slots checked at frame start");
906+ let x = col * 16;
907+ let y = row * 16;
908+ let w = self.mb_cols * 16;
909+ let h = self.mb_rows * 16;
910+ // Luma: one 16x16 predict, or 16 independent 4x4 predicts for
911+ // SPLITMV (identical output to libvpx's grouped predicts). Each
912+ // predict lands at its own (bx, by) slot of one 16x16 patch.
913+ let mut py = [0u8; 256];
914+ if mb.mv_ref == 4 {
915+ for b in 0..16usize {
916+ let (bx, by) = ((b % 4) * 4, (b / 4) * 4);
917+ // reconinter.c:370-374: the four corner subblocks clamp
918+ // their MVs under need_to_clamp_mvs; the rest don't.
919+ let corner = matches!(b, 0 | 2 | 8 | 10);
920+ mc::predict_luma(
921+ &reff.y, reff.stride, MC_BORDER, w, h, x + bx, y + by, mb.bmi[b],
922+ mb.mv_clamp && corner,
923+ &mut py[by * 16 + bx..], 16, 4, 4, self.mc_bilinear,
924+ );
925+ }
926+ } else {
927+ mc::predict_luma(
928+ &reff.y, reff.stride, MC_BORDER, w, h, x, y, mb.mv, mb.mv_clamp, &mut py, 16,
929+ 16, 16, self.mc_bilinear,
930+ );
931+ }
932+
933+ // Chroma: libvpx predicts each plane as ONE 8x8 block for
934+ // whole-MB modes (vp8_build_inter16x16_predictors_mb) or four
935+ // independent 4x4 blocks for SPLITMV (build_inter4x4_predictors_mb,
936+ // each from its quadrant's build_4x4uvmvs vector). The whole-MB
937+ // path re-clamps UNCONDITIONALLY (reconinter.c: rounding the
938+ // derived chroma MV to full-pel can move it outside the tap
939+ // window even when the luma MV was in range); the SPLITMV path
940+ // clamps only under need_to_clamp_mvs.
941+ let mut pu = [0u8; 256];
942+ let mut pv = [0u8; 256];
943+ if mb.mv_ref == 4 {
944+ for q in 0..4usize {
945+ // Quadrant q: 4x4 chroma pixels at (qx4, qy4) in the MB.
946+ let (qx4, qy4) = ((q % 2) * 4, (q / 2) * 4);
947+ let (cx, cy) = (x / 2 + qx4, y / 2 + qy4);
948+ let (qx, qy) = ((q % 2) * 2, (q / 2) * 2);
949+ let uvmv = modes::chroma_mv_split(
950+ &[
951+ mb.bmi[qy * 4 + qx],
952+ mb.bmi[qy * 4 + qx + 1],
953+ mb.bmi[qy * 4 + qx + 4],
954+ mb.bmi[qy * 4 + qx + 5],
955+ ],
956+ self.mc_fullpel,
957+ );
958+ mc::predict_chroma(
959+ &reff.u, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv,
960+ mb.mv_clamp, &mut pu[qy4 * 16 + qx4..], 16, 4, 4,
961+ self.mc_bilinear,
962+ );
963+ mc::predict_chroma(
964+ &reff.v, reff.uv_stride, MC_BORDER, w, h, cx, cy, uvmv,
965+ mb.mv_clamp, &mut pv[qy4 * 16 + qx4..], 16, 4, 4,
966+ self.mc_bilinear,
967+ );
968+ }
969+ } else {
970+ let uvmv = modes::chroma_mv_whole(mb.mv, self.mc_fullpel);
971+ mc::predict_chroma(
972+ &reff.u, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true,
973+ &mut pu, 16, 8, 8, self.mc_bilinear,
974+ );
975+ mc::predict_chroma(
976+ &reff.v, reff.uv_stride, MC_BORDER, w, h, x / 2, y / 2, uvmv, true,
977+ &mut pv, 16, 8, 8, self.mc_bilinear,
978+ );
979+ }
980+ if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 {
981+ eprintln!(
982+ "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}",
983+ &pu[0..8],
984+ &reff.u[MC_BORDER * reff.uv_stride + MC_BORDER..MC_BORDER * reff.uv_stride + MC_BORDER + 8],
985+ coeffs.u[0].iter().sum::<i16>()
986+ );
987+ }
988+
989+ // Residual: every block adds onto its MC prediction.
990+ let y_dcs: [i16; 16] = if coeffs.has_y2 {
991+ transform::iwht4x4(&coeffs.y2)
992+ } else {
993+ [0; 16]
994+ };
995+ for b in 0..16usize {
996+ let (bx, by) = ((b % 4) * 4, (b / 4) * 4);
997+ let mut c = coeffs.y[b];
998+ if coeffs.has_y2 {
999+ c[0] = y_dcs[b];
1000+ }
1001+ let dst = self.y.at(x + bx, y + by);
1002+ idct_add_into(&mut self.y.data, &c, &py, 16, by * 16 + bx, dst, self.y.stride);
1003+ }
1004+ for (plane_data, coeffs_uv, pred, stride) in [
1005+ (&mut self.u.data, &coeffs.u, &pu, self.u.stride),
1006+ (&mut self.v.data, &coeffs.v, &pv, self.v.stride),
1007+ ] {
1008+ for b in 0..4usize {
1009+ let (bx, by) = ((b % 2) * 4, (b / 2) * 4);
1010+ let dst = (1 + y / 2 + by) * stride + 1 + x / 2 + bx;
1011+ idct_add_into(plane_data, &coeffs_uv[b], pred, 16, by * 16 + bx, dst, stride);
1012+ }
1013+ }
1014+ }
1015+
1016+ /// Key-frame mode record (§11): Y mode at fixed probabilities, then
1017+ /// 16 context-conditioned subblock modes for B_PRED, then chroma.
1018+ fn decode_kf_modes(
1019+ &mut self,
1020+ d: &mut BoolDecoder<'_>,
1021+ row: usize,
1022+ col: usize,
1023+ mb: &mut MbInfo,
1024+ ) {
1025+ let ymode = modes::read_kf_ymode(d);
1026+ mb.y_mode = ymode.as_u8();
1027+ if ymode == modes::YMode::BPred {
1028+ for j in 0..16u8 {
1029+ let a = self.above_block_mode(row, col, j, mb);
1030+ let l = self.left_block_mode(row, col, j, mb);
1031+ mb.b_modes[usize::from(j)] =
1032+ modes::read_bmode(d, &KF_BMODE_PROB[usize::from(a)][usize::from(l)]).as_u8();
1033+ }
1034+ }
1035+ mb.uv_mode = modes::read_uvmode(d, &modes::KF_UV_MODE_PROBS).as_u8();
1036+ }
1037+
1038+ /// Above subblock mode context (dixie `above_block_mode`): subblocks
1039+ /// 0-3 take the above MB's derived mode, inner subblocks the mode
1040+ /// `j-4` of this same MB (already decoded into `mb`).
1041+ fn above_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 {
1042+ if j < 4 {
1043+ let above = self.mbi(row - 1, col);
1044+ if above.y_mode == modes::YMode::BPred.as_u8() {
1045+ above.b_modes[usize::from(j) + 12]
1046+ } else {
1047+ ymode_as_bmode(above.y_mode)
1048+ }
1049+ } else {
1050+ mb.b_modes[usize::from(j) - 4]
1051+ }
1052+ }
1053+
1054+ /// Left subblock mode context (dixie `left_block_mode`).
1055+ fn left_block_mode(&self, row: usize, col: usize, j: u8, mb: &MbInfo) -> u8 {
1056+ if j % 4 == 0 {
1057+ let left = self.mbi(row, col - 1);
1058+ if left.y_mode == modes::YMode::BPred.as_u8() {
1059+ left.b_modes[usize::from(j) + 3]
1060+ } else {
1061+ ymode_as_bmode(left.y_mode)
1062+ }
1063+ } else {
1064+ mb.b_modes[usize::from(j) - 1]
1065+ }
1066+ }
1067+
1068+ /// Predict and reconstruct one intra key-frame MB at pixel (x, y).
1069+ ///
1070+ /// Whole-MB modes predict once from the pre-MB edges and then fold
1071+ /// the 24 residual blocks in; B_PRED interleaves: each 4x4 subblock
1072+ /// predicts from the reconstructed image (which already carries the
1073+ /// earlier subblocks' residuals, §12.3) and is written back before
1074+ /// the next subblock is predicted.
1075+ fn reconstruct_intra_mb(&mut self, row: usize, col: usize, mb: &MbInfo, coeffs: &MbCoeffs) {
1076+ let x = col * 16;
1077+ let y = row * 16;
1078+ let y_mode = mb.y_mode;
1079+ let uv_mode = mb.uv_mode;
1080+ let b_modes = mb.b_modes;
1081+ let have_above = row > 0;
1082+ let have_left = col > 0;
1083+
1084+ // The Y2 inverse WHT feeds the 16 Y subblock DCs (§14.2).
1085+ let y_dcs: [i16; 16] = if coeffs.has_y2 {
1086+ transform::iwht4x4(&coeffs.y2)
1087+ } else {
1088+ [0; 16]
1089+ };
1090+ if std::env::var_os("EC_VP8_DEBUG").is_some() {
1091+ eprintln!(
1092+ "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}",
1093+ y_mode,
1094+ uv_mode,
1095+ coeffs.y2,
1096+ coeffs.has_y2,
1097+ &coeffs.y[0][..4],
1098+ coeffs.eobs[24],
1099+ &y_dcs[..4]
1100+ );
1101+ }
1102+
1103+ if y_mode == modes::YMode::BPred.as_u8() {
1104+ for b in 0..16usize {
1105+ let bx = (b % 4) * 4;
1106+ let by = (b / 4) * 4;
1107+ // A row: 4 above pixels then 4 above-right (§12.3); the
1108+ // above-right extras are shared by right-edge subblocks
1109+ // 3, 7, 11 and 15.
1110+ let mut a8 = [0u8; 8];
1111+ let arow = self.y.at_above(x + bx, y + by);
1112+ a8[..4].copy_from_slice(&self.y.data[arow..arow + 4]);
1113+ if bx + 4 == 16 {
1114+ a8[4..].copy_from_slice(&self.above_right(x, y));
1115+ } else {
1116+ let ar = self.y.at_above(x + bx + 4, y + by);
1117+ a8[4..].copy_from_slice(&self.y.data[ar..ar + 4]);
1118+ }
1119+ let mut l4 = [0u8; 4];
1120+ for (i, cell) in l4.iter_mut().enumerate() {
1121+ *cell = self.y.data[self.y.at_left(x + bx, y + by + i)];
1122+ }
1123+ let p = self.y.data[self.y.at_above_left(x + bx, y + by)];
1124+ let mut block = [0u8; 16];
1125+ intra::predict4(b_modes[b], &a8, &l4, p, &mut block);
1126+ for i in 0..4 {
1127+ let d = self.y.at(x + bx, y + by + i);
1128+ self.y.data[d..d + 4].copy_from_slice(&block[i * 4..i * 4 + 4]);
1129+ }
1130+ let mut c = coeffs.y[b];
1131+ if coeffs.has_y2 {
1132+ c[0] = y_dcs[b];
1133+ }
1134+ if c.iter().any(|&v| v != 0) {
1135+ let dst = self.y.at(x + bx, y + by);
1136+ let stride = self.y.stride;
1137+ idct_add_into(&mut self.y.data, &c, &block, 4, 0, dst, stride);
1138+ }
1139+ }
1140+ } else {
1141+ // Gather luma edges (border cells carry the 127/129 fills).
1142+ let (above, left, above_left) = {
1143+ let ay = self.y.at_above(x, y);
1144+ let mut a = [0u8; 16];
1145+ let mut l = [0u8; 16];
1146+ a.copy_from_slice(&self.y.data[ay..ay + 16]);
1147+ for (i, cell) in l.iter_mut().enumerate() {
1148+ *cell = self.y.data[self.y.at_left(x, y + i)];
1149+ }
1150+ let al = self.y.data[self.y.at_above_left(x, y)];
1151+ (a, l, al)
1152+ };
1153+ let mut pred = [0u8; 256];
1154+ intra::predict16(
1155+ y_mode, have_above, have_left, &above, &left, above_left, &mut pred,
1156+ );
1157+ for b in 0..16usize {
1158+ let bx = (b % 4) * 4;
1159+ let by = (b / 4) * 4;
1160+ let mut c = coeffs.y[b];
1161+ if coeffs.has_y2 {
1162+ c[0] = y_dcs[b];
1163+ }
1164+ if c.iter().all(|&v| v == 0) {
1165+ for i in 0..4 {
1166+ let d = self.y.at(x + bx, y + by + i);
1167+ let s = (by + i) * 16 + bx;
1168+ self.y.data[d..d + 4].copy_from_slice(&pred[s..s + 4]);
1169+ }
1170+ } else {
1171+ let dst = self.y.at(x + bx, y + by);
1172+ let stride = self.y.stride;
1173+ idct_add_into(&mut self.y.data, &c, &pred, 16, by * 16 + bx, dst, stride);
1174+ }
1175+ }
1176+ }
1177+
1178+ // Chroma: 8x8 prediction then four residual blocks per plane.
1179+ let (above_u, left_u, al_u) = self.chroma_edges(col, row, 0);
1180+ let (above_v, left_v, al_v) = self.chroma_edges(col, row, 1);
1181+ let mut pred_u = [0u8; 64];
1182+ let mut pred_v = [0u8; 64];
1183+ intra::predict8(
1184+ uv_mode,
1185+ have_above,
1186+ have_left,
1187+ &above_u,
1188+ &left_u,
1189+ al_u,
1190+ &mut pred_u,
1191+ );
1192+ intra::predict8(
1193+ uv_mode,
1194+ have_above,
1195+ have_left,
1196+ &above_v,
1197+ &left_v,
1198+ al_v,
1199+ &mut pred_v,
1200+ );
1201+ let (cx, cy) = (x / 2, y / 2);
1202+ for (plane_data, coeffs_uv, pred8, stride) in [
1203+ (&mut self.u.data, &coeffs.u, &pred_u, self.u.stride),
1204+ (&mut self.v.data, &coeffs.v, &pred_v, self.v.stride),
1205+ ] {
1206+ for b in 0..4usize {
1207+ let bx = (b % 2) * 4;
1208+ let by = (b / 2) * 4;
1209+ let c = coeffs_uv[b];
1210+ let dst = (1 + cy + by) * stride + 1 + cx + bx;
1211+ if c.iter().all(|&v| v == 0) {
1212+ for i in 0..4 {
1213+ let s = (by + i) * 8 + bx;
1214+ let d = dst + i * stride;
1215+ plane_data[d..d + 4].copy_from_slice(&pred8[s..s + 4]);
1216+ }
1217+ } else {
1218+ idct_add_into(plane_data, &c, pred8, 8, by * 8 + bx, dst, stride);
1219+ }
1220+ }
1221+ }
1222+ }
1223+
1224+ /// Above-right extras (§12.3): real pixels from the above row,
1225+ /// replicated last pixel on the rightmost MB, 127 on the top row.
1226+ fn above_right(&self, x: usize, y: usize) -> [u8; 4] {
1227+ if y == 0 {
1228+ [127; 4]
1229+ } else if x + 16 >= self.mb_cols * 16 {
1230+ [self.y.data[self.y.at_above(x + 15, y)]; 4]
1231+ } else {
1232+ let off = self.y.at_above(x + 16, y);
1233+ [
1234+ self.y.data[off],
1235+ self.y.data[off + 1],
1236+ self.y.data[off + 2],
1237+ self.y.data[off + 3],
1238+ ]
1239+ }
1240+ }
1241+
1242+ fn chroma_edges(&self, col: usize, row: usize, plane: usize) -> ([u8; 8], [u8; 8], u8) {
1243+ let p = if plane == 0 { &self.u } else { &self.v };
1244+ let x = col * 8;
1245+ let y = row * 8;
1246+ let mut a = [0u8; 8];
1247+ let mut l = [0u8; 8];
1248+ let aoff = p.at_above(x, y);
1249+ a.copy_from_slice(&p.data[aoff..aoff + 8]);
1250+ for (i, cell) in l.iter_mut().enumerate() {
1251+ *cell = p.data[p.at_left(x, y + i)];
1252+ }
1253+ let al = p.data[p.at_above_left(x, y)];
1254+ (a, l, al)
1255+ }
1256+
1257+ /// Crop the padded planes to the real frame size.
1258+ fn crop(&self) -> Picture {
1259+ let w = usize::from(self.dims.width);
1260+ let h = usize::from(self.dims.height);
1261+ let mut y = Vec::with_capacity(w * h);
1262+ for row in 0..h {
1263+ let off = self.y.at(0, row);
1264+ y.extend_from_slice(&self.y.data[off..off + w]);
1265+ }
1266+ let (cw, ch) = ((w + 1) / 2, (h + 1) / 2);
1267+ let mut u = Vec::with_capacity(cw * ch);
1268+ let mut v = Vec::with_capacity(cw * ch);
1269+ for row in 0..ch {
1270+ let off = self.u.at(0, row);
1271+ u.extend_from_slice(&self.u.data[off..off + cw]);
1272+ let off = self.v.at(0, row);
1273+ v.extend_from_slice(&self.v.data[off..off + cw]);
1274+ }
1275+ Picture {
1276+ y,
1277+ u,
1278+ v,
1279+ width: self.dims.width,
1280+ height: self.dims.height,
1281+ stride: w,
1282+ uv_stride: cw,
1283+ }
1284+ }
1285+}
1286+
1287+impl Default for Decoder {
1288+ fn default() -> Self {
1289+ Self::new()
1290+ }
1291+}
1292+
1293+/// Segment-map coding tree (RFC 6386 §10): plain two-level split of 0-3.
1294+const SEGMENT_TREE: [i8; 6] = [2, 4, 0, -1, -2, -3];
1295+
1296+fn ymode_as_bmode(y: u8) -> u8 {
1297+ match y {
1298+ 0 => 0, // DC_PRED -> B_DC_PRED
1299+ 1 => 2, // V_PRED -> B_VE_PRED
1300+ 2 => 3, // H_PRED -> B_HE_PRED
1301+ 3 => 1, // TM_PRED -> B_TM_PRED
1302+ _ => unreachable!("non-B_PRED luma mode {y}"),
1303+ }
1304+}
1305+
1306+/// Add one 4x4 block's dequantized-coefficient residual to its
1307+/// prediction: reads the prediction patch from `pred`, clamps, writes
1308+/// into the strided plane (§14.4/§14.5).
1309+fn idct_add_into(
1310+ plane: &mut [u8],
1311+ coeffs: &[i16; 16],
1312+ pred: &[u8],
1313+ pred_stride: usize,
1314+ pred_off: usize,
1315+ dst_off: usize,
1316+ dst_stride: usize,
1317+) {
1318+ let mut p = [0u8; 16];
1319+ for i in 0..4 {
1320+ let s = pred_off + i * pred_stride;
1321+ p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]);
1322+ }
1323+ let mut out = [0u8; 16];
1324+ transform::idct4x4_add(coeffs, &p, &mut out);
1325+ for i in 0..4 {
1326+ let d = dst_off + i * dst_stride;
1327+ plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]);
1328+ }
1329+}
crates/ec-vp8/src/frame.rsadded+102 -0
@@ -0,0 +1,102 @@
1+//! Frame-level structures and the raw (uncompressed) frame tag
2+//! (RFC 6386 §9.1).
3+
4+use ec_core::{Error, Result};
5+
6+/// Key frame or interframe — the 1-bit frame type from the frame tag.
7+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8+pub enum FrameType {
9+ /// Key frame (`frame_type` bit 0).
10+ Key,
11+ /// Interframe (`frame_type` bit 1); predicted from earlier frames.
12+ Inter,
13+}
14+
15+/// The 3-byte frame tag every frame starts with (RFC 6386 §9.1 item 1-4):
16+/// 1 bit type, 3 bits version, 1 bit show_frame, 19 bits first-partition
17+/// size — all read out of one little-endian 24-bit word.
18+#[derive(Debug, Clone, Copy)]
19+pub struct FrameTag {
20+ /// Key or inter frame.
21+ pub frame_type: FrameType,
22+ /// 3-bit version (reconstruction-filter / loop-filter profile; only
23+ /// bits that matter historically — the header's own loop filter fields
24+ /// govern decoding).
25+ pub version: u8,
26+ /// Whether the decoded frame is for display.
27+ pub show_frame: bool,
28+ /// Size in bytes of the first (header/mode) data partition.
29+ pub first_part_size: u32,
30+}
31+
32+/// Bytes occupied by the 3-byte frame tag.
33+pub const FRAME_TAG_SZ: usize = 3;
34+
35+/// Bytes occupied by the key frame's start code + size fields (§9.1).
36+pub const KEYFRAME_HEADER_SZ: usize = 7;
37+
38+impl FrameTag {
39+ /// Parse the tag from the first 3 bytes of a frame.
40+ pub fn parse(data: &[u8]) -> Result<FrameTag> {
41+ if data.len() < FRAME_TAG_SZ {
42+ return Err(Error::corrupt("VP8 frame shorter than its 3-byte tag"));
43+ }
44+ let tag = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16);
45+ Ok(FrameTag {
46+ frame_type: if tag & 1 == 0 {
47+ FrameType::Key
48+ } else {
49+ FrameType::Inter
50+ },
51+ version: ((tag >> 1) & 7) as u8,
52+ show_frame: (tag >> 4) & 1 == 1,
53+ first_part_size: tag >> 5,
54+ })
55+ }
56+}
57+
58+/// Key-frame dimensions and scaling flags (RFC 6386 §9.1).
59+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60+pub struct KeyFrameDims {
61+ /// Encoded (pre-scaling) width in pixels, 14 bits.
62+ pub width: u16,
63+ /// Encoded height in pixels, 14 bits.
64+ pub height: u16,
65+ /// 2-bit horizontal scale (0 = none, 1 = 5/4, 2 = 5/3, 3 = 2).
66+ pub h_scale: u8,
67+ /// 2-bit vertical scale.
68+ pub v_scale: u8,
69+}
70+
71+/// Parse the key-frame start code (`9d 01 2a`) and dimensions that follow
72+/// the frame tag. `data` starts at the frame tag.
73+pub fn parse_keyframe_dims(data: &[u8]) -> Result<KeyFrameDims> {
74+ let dims_off = FRAME_TAG_SZ;
75+ if data.len() < dims_off + KEYFRAME_HEADER_SZ {
76+ return Err(Error::corrupt("VP8 key frame header truncated"));
77+ }
78+ let c = &data[dims_off..];
79+ if c[0] != 0x9d || c[1] != 0x01 || c[2] != 0x2a {
80+ return Err(Error::corrupt(format!(
81+ "VP8 key frame start code 9d 01 2a not found (got {:02x} {:02x} {:02x})",
82+ c[0], c[1], c[2]
83+ )));
84+ }
85+ let w = u16::from_le_bytes([c[3], c[4]]);
86+ let h = u16::from_le_bytes([c[5], c[6]]);
87+ Ok(KeyFrameDims {
88+ width: w & 0x3fff,
89+ height: h & 0x3fff,
90+ h_scale: (w >> 14) as u8,
91+ v_scale: (h >> 14) as u8,
92+ })
93+}
94+
95+/// Number of 16×16 macroblock columns/rows covering `width × height`
96+/// pixels (the encoded frame is padded up to whole macroblocks).
97+pub fn mb_geometry(width: u16, height: u16) -> (usize, usize) {
98+ (
99+ (usize::from(width) + 15) / 16,
100+ (usize::from(height) + 15) / 16,
101+ )
102+}
crates/ec-vp8/src/header.rsadded+475 -0
@@ -0,0 +1,475 @@
1+//! Uncompressed chunk and first-partition header parsing
2+//! (RFC 6386 §9-§10, following the reference decoder's field order).
3+//!
4+//! Three pieces of state persist across frames until the next key frame
5+//! resets them: the entropy context (coefficient, MV and intra-mode
6+//! probabilities), the segmentation feature data and the per-macroblock
7+//! loop-filter deltas. They live in [`PersistedState`]; every frame's
8+//! [`FrameHeader::parse`] folds that frame's updates into it.
9+
10+use crate::bool::BoolDecoder;
11+use crate::frame::{FrameTag, FrameType, KEYFRAME_HEADER_SZ, parse_keyframe_dims};
12+use crate::tables::{DEFAULT_COEFF_PROBS, DEFAULT_MV_PROBS, MV_UPDATE_PROBS};
13+use ec_core::{Error, Result};
14+
15+/// Probability-array length per MV component (dixie `MV_PROB_CNT`):
16+/// is_short, sign, 7 short-tree, 10 long-bits probabilities.
17+pub const MV_PROB_CNT: usize = 19;
18+
19+/// Everything that survives from frame to frame until a key frame.
20+#[derive(Debug, Clone)]
21+pub struct PersistedState {
22+ /// Token-tree probabilities, `[block_type][band][ctx][node]`
23+ /// (RFC 6386 §13.3).
24+ /// Token-tree probabilities `[block_type][band][ctx][node]` (§13.3).
25+ pub coeff_probs: [[[[u8; 11]; 3]; 8]; 4],
26+ /// Per-MV-component probabilities `[component][prob]` (RFC §17.2).
27+ /// Per-MV-component probabilities `[component][prob]` (§17.2).
28+ pub mv_probs: [[u8; MV_PROB_CNT]; 2],
29+ /// Interframe Y-mode tree probabilities (RFC §16.1).
30+ /// Interframe Y-mode tree probabilities (§16.1).
31+ pub ymode_probs: [u8; 4],
32+ /// Interframe chroma-mode tree probabilities (RFC §16.1).
33+ /// Interframe chroma-mode tree probabilities (§16.1).
34+ pub uv_mode_probs: [u8; 3],
35+ /// Segment feature state (RFC §10), zeroed at each key frame.
36+ /// Segment feature state (§10), zeroed at each key frame.
37+ pub segmentation: SegmentationState,
38+ /// Per-MB loop-filter deltas (RFC §9.4), zeroed at each key frame.
39+ /// Reference-frame-based loop-filter deltas (§9.4; intra, last,
40+ /// golden, altref order).
41+ pub ref_lf_delta: [i32; 4],
42+ /// Mode-based loop-filter deltas (§9.4; B_PRED, ZEROMV, MV,
43+ /// SPLITMV order).
44+ pub mode_lf_delta: [i32; 4],
45+}
46+
47+impl Default for PersistedState {
48+ fn default() -> Self {
49+ Self {
50+ coeff_probs: DEFAULT_COEFF_PROBS,
51+ mv_probs: DEFAULT_MV_PROBS,
52+ // Interframe tree defaults (libvpx vp8_ymode_prob /
53+ // vp8_uv_mode_prob); key frames reset these too.
54+ ymode_probs: [112, 86, 140, 37],
55+ uv_mode_probs: [162, 101, 204],
56+ segmentation: SegmentationState::default(),
57+ ref_lf_delta: [0; 4],
58+ mode_lf_delta: [0; 4],
59+ }
60+ }
61+}
62+
63+/// Segment feature state (RFC 6386 §10). `quant_idx`/`lf_level` hold the
64+/// raw transmitted values; they are absolute in absolute mode and deltas
65+/// in delta mode.
66+#[derive(Debug, Clone, Default)]
67+pub struct SegmentationState {
68+ /// Segment features active for the current frame.
69+ pub enabled: bool,
70+ /// The per-MB segment map is re-coded this frame.
71+ pub update_map: bool,
72+ /// Segment feature values are re-coded this frame.
73+ pub update_data: bool,
74+ /// 0 = absolute values, 1 = deltas against the frame baseline.
75+ /// 0 = absolute values, 1 = deltas against the frame baseline.
76+ pub abs_delta: bool,
77+ /// Per-segment quantizer value or delta (§10).
78+ pub quant_idx: [i32; 4],
79+ /// Per-segment loop-filter level or delta (§10).
80+ pub lf_level: [i32; 4],
81+ /// Segment-map decoding tree probabilities (default 255).
82+ /// Segment-map tree probabilities (default 255; §9.3 item 5).
83+ pub tree_probs: [u8; 3],
84+}
85+
86+/// Frame-level fields parsed from the uncompressed chunk and the first
87+/// data partition. Everything the per-macroblock decode needs.
88+#[derive(Debug, Clone)]
89+pub struct FrameHeader {
90+ /// Parsed 3-byte frame tag.
91+ pub tag: FrameTag,
92+ /// Key-frame dimensions (key frames only).
93+ pub dims: Option<crate::frame::KeyFrameDims>,
94+ /// Key-frame-only colour-space bit (0 = YUV; 1 is reserved).
95+ pub color_space: u8,
96+ /// Key-frame-only clamping bit (1 = reconstructed pixels guaranteed
97+ /// 0..255, clamping optional).
98+ pub clamping_type: u8,
99+ /// Segment feature snapshot this frame decodes under.
100+ pub segmentation: SegmentationState,
101+ /// Loop filter type/level/sharpness (§9.4).
102+ /// 0 = normal loop filter, 1 = simple (§9.4).
103+ pub filter_type: u8,
104+ /// Baseline loop filter strength 0-63 (0 disables filtering).
105+ pub filter_level: u8,
106+ /// Loop filter sharpness 0-7 (§9.4, §15.2).
107+ pub sharpness_level: u8,
108+ /// Per-MB loop-filter delta adjustment enabled for this frame.
109+ pub lf_delta_enabled: bool,
110+ /// This frame updated the (persisted) delta values.
111+ pub lf_delta_update: bool,
112+ /// log2 of the token partition count (1, 2, 4 or 8 partitions).
113+ pub log2_partitions: u8,
114+ /// Quantization indices (§9.6): base Y-AC index plus per-plane deltas.
115+ pub quant: QuantIndices,
116+ /// Probability an interframe MB is intra-coded (§9.10 `prob_intra`).
117+ pub prob_intra: u8,
118+ /// Probability an inter MB uses the last-frame reference.
119+ pub prob_last: u8,
120+ /// Probability an inter MB uses the golden rather than altref ref.
121+ pub prob_gf: u8,
122+ /// Whether this frame updated the interframe Y-mode probabilities.
123+ pub ymode_probs_updated: bool,
124+ /// Whether this frame updated the chroma-mode probabilities.
125+ pub uv_mode_probs_updated: bool,
126+ /// Reference-frame refresh/copies/sign-biases (§9.7-§9.8).
127+ pub refresh: RefreshHeader,
128+ /// mb_no_skip_coeff (§9.10/§9.11): per-MB "no non-zero coefficients"
129+ /// flag is coded at all.
130+ pub coeff_skip_enabled: bool,
131+ /// Probability for the per-MB skip flag (meaningful when enabled).
132+ pub prob_skip_false: u8,
133+ /// Offset of the first token partition from the start of `data`
134+ /// (i.e. uncompressed chunk + first partition).
135+ pub token_data_offset: usize,
136+ /// Token partition sizes in bytes; last entry is the remainder.
137+ pub partition_sizes: Vec<u32>,
138+}
139+
140+/// Six dequantization indices (§9.6): the always-coded Y-AC index plus
141+/// signed deltas for the other five factors.
142+#[derive(Debug, Clone, Copy, Default)]
143+pub struct QuantIndices {
144+ /// Base quantizer index for Y AC (7 bits).
145+ pub yac_qi: u8,
146+ /// Signed delta applied to the Y-DC dequant index (§9.6).
147+ pub ydc_delta: i32,
148+ /// Signed delta applied to the Y2-DC dequant index (§9.6).
149+ pub y2dc_delta: i32,
150+ /// Signed delta applied to the Y2-AC dequant index (§9.6).
151+ pub y2ac_delta: i32,
152+ /// Signed delta applied to the chroma-DC dequant index (§9.6).
153+ pub uvdc_delta: i32,
154+ /// Signed delta applied to the chroma-AC dequant index (§9.6).
155+ pub uvac_delta: i32,
156+}
157+
158+/// Reference-frame refresh state for one frame (§9.7-§9.8). Key frames
159+/// refresh every reference and read only `refresh_entropy`.
160+#[derive(Debug, Clone, Copy)]
161+pub struct RefreshHeader {
162+ /// The golden buffer is refreshed with the current frame.
163+ pub refresh_gf: bool,
164+ /// The altref buffer is refreshed with the current frame.
165+ pub refresh_arf: bool,
166+ /// 0 = none, 1 = copy last, 2 = copy altref (to golden).
167+ pub copy_gf: u8,
168+ /// 0 = none, 1 = copy last, 2 = copy golden (to altref).
169+ pub copy_arf: u8,
170+ /// Sign bias applied to MVs referencing the golden frame (§9.7).
171+ pub sign_bias_golden: bool,
172+ /// Sign bias applied to MVs referencing the altref frame (§9.7).
173+ pub sign_bias_altref: bool,
174+ /// Whether this frame's entropy updates persist to the next frame.
175+ pub refresh_entropy: bool,
176+ /// The last-frame buffer is refreshed with the current frame.
177+ pub refresh_last: bool,
178+}
179+
180+impl FrameHeader {
181+ /// The frame's type (key or inter), from the frame tag.
182+ pub fn frame_type(&self) -> FrameType {
183+ self.tag.frame_type
184+ }
185+
186+ /// Parse one frame's uncompressed chunk + first partition from
187+ /// `data`, folding entropy/segmentation/filter-delta updates into
188+ /// `state`. Returns the header and the partition-1 slice.
189+ ///
190+ /// `token_data_offset` + every `partition_sizes[i]` together describe
191+ /// the bytes after partition 1.
192+ pub fn parse<'a>(
193+ data: &'a [u8],
194+ state: &mut PersistedState,
195+ ) -> Result<(FrameHeader, BoolDecoder<'a>)> {
196+ let tag = FrameTag::parse(data)?;
197+ let key = tag.frame_type == FrameType::Key;
198+ let mut off = crate::frame::FRAME_TAG_SZ;
199+
200+ let mut dims = None;
201+ if key {
202+ let kf = parse_keyframe_dims(data)?;
203+ dims = Some(kf);
204+ off += KEYFRAME_HEADER_SZ;
205+ // A key frame resets every piece of persisted entropy and
206+ // segment/filter state (dixie `decode_frame`).
207+ *state = PersistedState::default();
208+ }
209+
210+ let part0_end = off + tag.first_part_size as usize;
211+ if data.len() < part0_end {
212+ return Err(Error::corrupt(format!(
213+ "VP8 first partition extends past end of frame \
214+ (need {part0_end} bytes, have {})",
215+ data.len()
216+ )));
217+ }
218+ let mut d = BoolDecoder::new(&data[off..part0_end])?;
219+
220+ // Colour space + clamping (key frames only): two literal bits;
221+ // the colour-space bit is reserved and must be 0 (dixie reads
222+ // both together and refuses any non-zero pair; we keep the
223+ // (legal) clamping bit decodable and refuse only the reserved
224+ // colour-space one).
225+ let (color_space, clamping_type) = if key {
226+ let cs = d.read_literal(1) as u8;
227+ let clamp = d.read_literal(1) as u8;
228+ if cs != 0 {
229+ return Err(Error::unsupported(
230+ "VP8 reserved colour-space bit",
231+ "bit 0 of the key-frame colour-space pair was set",
232+ ));
233+ }
234+ (cs, clamp)
235+ } else {
236+ (0, 0)
237+ };
238+
239+ // --- segmentation (§9.3, dixie decode_segmentation_header) ---
240+ let mut segmentation = if key {
241+ SegmentationState::default()
242+ } else {
243+ state.segmentation.clone()
244+ };
245+ segmentation.enabled = d.read_bool(128);
246+ if segmentation.enabled {
247+ segmentation.update_map = d.read_bool(128);
248+ segmentation.update_data = d.read_bool(128);
249+ if segmentation.update_data {
250+ segmentation.abs_delta = d.read_bool(128);
251+ for i in 0..4 {
252+ segmentation.quant_idx[i] = d.read_maybe_signed(7);
253+ }
254+ for i in 0..4 {
255+ segmentation.lf_level[i] = d.read_maybe_signed(6);
256+ }
257+ }
258+ if segmentation.update_map {
259+ for i in 0..3 {
260+ segmentation.tree_probs[i] = if d.read_bool(128) {
261+ d.read_literal(8) as u8
262+ } else {
263+ 255
264+ };
265+ }
266+ }
267+ } else {
268+ segmentation.update_map = false;
269+ segmentation.update_data = false;
270+ }
271+ state.segmentation = segmentation.clone();
272+
273+ // --- loop filter (§9.4, dixie decode_loopfilter_header) ---
274+ let mut ref_lf_delta = state.ref_lf_delta;
275+ let mut mode_lf_delta = state.mode_lf_delta;
276+ if key {
277+ ref_lf_delta = [0; 4];
278+ mode_lf_delta = [0; 4];
279+ }
280+ let filter_type = d.read_literal(1) as u8;
281+ let filter_level = d.read_literal(6) as u8;
282+ let sharpness_level = d.read_literal(3) as u8;
283+ let lf_delta_enabled = d.read_bool(128);
284+ let mut lf_delta_update = false;
285+ if lf_delta_enabled && d.read_bool(128) {
286+ lf_delta_update = true;
287+ for i in 0..4 {
288+ ref_lf_delta[i] = d.read_maybe_signed(6);
289+ }
290+ for i in 0..4 {
291+ mode_lf_delta[i] = d.read_maybe_signed(6);
292+ }
293+ }
294+ state.ref_lf_delta = ref_lf_delta;
295+ state.mode_lf_delta = mode_lf_delta;
296+
297+ // --- token partitions (§9.5) ---
298+ let log2_partitions = d.read_literal(2) as u8;
299+ let partitions = 1usize << log2_partitions;
300+ let sizes_area = 3 * (partitions - 1);
301+ if data.len() < part0_end + sizes_area {
302+ return Err(Error::corrupt(
303+ "VP8 token partition size table extends past end of frame",
304+ ));
305+ }
306+ let mut partition_sizes = Vec::with_capacity(partitions);
307+ let mut size_off = part0_end;
308+ let mut remaining = (data.len() - part0_end - sizes_area) as u32;
309+ for i in 0..partitions {
310+ if i < partitions - 1 {
311+ let sz = u32::from(data[size_off])
312+ | (u32::from(data[size_off + 1]) << 8)
313+ | (u32::from(data[size_off + 2]) << 16);
314+ size_off += 3;
315+ partition_sizes.push(sz);
316+ remaining = remaining
317+ .checked_sub(sz)
318+ .ok_or_else(|| Error::corrupt("VP8 token partitions exceed frame size"))?;
319+ } else {
320+ partition_sizes.push(remaining);
321+ }
322+ }
323+
324+ // --- quantization indices (§9.6) ---
325+ let mut quant = QuantIndices {
326+ yac_qi: d.read_literal(7) as u8,
327+ ..QuantIndices::default()
328+ };
329+ quant.ydc_delta = d.read_maybe_signed(4);
330+ quant.y2dc_delta = d.read_maybe_signed(4);
331+ quant.y2ac_delta = d.read_maybe_signed(4);
332+ quant.uvdc_delta = d.read_maybe_signed(4);
333+ quant.uvac_delta = d.read_maybe_signed(4);
334+
335+ // --- reference refresh (§9.7-§9.8) ---
336+ let refresh = if key {
337+ RefreshHeader {
338+ refresh_gf: true,
339+ refresh_arf: true,
340+ copy_gf: 0,
341+ copy_arf: 0,
342+ sign_bias_golden: false,
343+ sign_bias_altref: false,
344+ refresh_entropy: d.read_bool(128),
345+ refresh_last: true,
346+ }
347+ } else {
348+ let refresh_gf = d.read_bool(128);
349+ let refresh_arf = d.read_bool(128);
350+ let copy_gf = if refresh_gf {
351+ 0
352+ } else {
353+ d.read_literal(2) as u8
354+ };
355+ let copy_arf = if refresh_arf {
356+ 0
357+ } else {
358+ d.read_literal(2) as u8
359+ };
360+ RefreshHeader {
361+ refresh_gf,
362+ refresh_arf,
363+ copy_gf,
364+ copy_arf,
365+ sign_bias_golden: d.read_bool(128),
366+ sign_bias_altref: d.read_bool(128),
367+ refresh_entropy: d.read_bool(128),
368+ refresh_last: d.read_bool(128),
369+ }
370+ };
371+
372+ // --- entropy updates (§9.9; dixie decode_entropy_header) ---
373+ // Coefficient probability updates are read for every frame; on
374+ // key frames the tables were reset to defaults above.
375+ for i in 0..4 {
376+ for j in 0..8 {
377+ for k in 0..3 {
378+ for l in 0..11 {
379+ if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) {
380+ state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8;
381+ }
382+ }
383+ }
384+ }
385+ }
386+
387+ // mb_no_skip_coeff (§9.11 / inter §9.10).
388+ let coeff_skip_enabled = d.read_bool(128);
389+ let prob_skip_false = if coeff_skip_enabled {
390+ d.read_literal(8) as u8
391+ } else {
392+ 128
393+ };
394+ // Interframe-only probability updates.
395+ if std::env::var_os("EC_VP8_TRACE").is_some() {
396+ eprintln!("STAGE interprobs");
397+ }
398+ let mut ymode_probs_updated = false;
399+ let mut uv_mode_probs_updated = false;
400+ let (prob_intra, prob_last, prob_gf) = if !key {
401+ let probs = (
402+ d.read_literal(8) as u8,
403+ d.read_literal(8) as u8,
404+ d.read_literal(8) as u8,
405+ );
406+ ymode_probs_updated = d.read_bool(128);
407+ if ymode_probs_updated {
408+ for i in 0..4 {
409+ state.ymode_probs[i] = d.read_literal(8) as u8;
410+ }
411+ }
412+ uv_mode_probs_updated = d.read_bool(128);
413+ if uv_mode_probs_updated {
414+ for i in 0..3 {
415+ state.uv_mode_probs[i] = d.read_literal(8) as u8;
416+ }
417+ }
418+ // MV probability updates: P(7) form, x ? x << 1 : 1 (§17.2).
419+ for c in 0..2 {
420+ for j in 0..MV_PROB_CNT {
421+ if d.read_bool(MV_UPDATE_PROBS[c][j]) {
422+ state.mv_probs[c][j] = d.read_prob7();
423+ }
424+ }
425+ }
426+ if std::env::var_os("EC_VP8_TRACE").is_some() {
427+ eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs);
428+ eprintln!("MVT c0 = {:?}", state.mv_probs[0]);
429+ eprintln!("MVT c1 = {:?}", state.mv_probs[1]);
430+ }
431+ probs
432+ } else {
433+ (112, 86, 140) // placeholders; only read on inter frames
434+ };
435+
436+ // The reference decoder zero-fills past the end of a partition;
437+ // tiny partitions (e.g. one-MB key frames) can legitimately
438+ // overrun by a byte or two. Gross overruns are still desyncs.
439+ if d.overreads() > 16 {
440+ return Err(Error::corrupt(format!(
441+ "VP8 first partition over-read by {} bytes (header desync)",
442+ d.overreads()
443+ )));
444+ }
445+
446+ let header = FrameHeader {
447+ tag,
448+ dims,
449+ color_space,
450+ clamping_type,
451+ segmentation,
452+ filter_type,
453+ filter_level,
454+ sharpness_level,
455+ lf_delta_enabled,
456+ lf_delta_update,
457+ log2_partitions,
458+ quant,
459+ refresh,
460+ prob_intra,
461+ prob_last,
462+ prob_gf,
463+ ymode_probs_updated,
464+ uv_mode_probs_updated,
465+ coeff_skip_enabled,
466+ prob_skip_false,
467+ token_data_offset: part0_end,
468+ partition_sizes,
469+ };
470+ let _ = off;
471+ // The partition-0 decoder is returned mid-stream: the per-MB
472+ // mode records continue from exactly where the header stopped.
473+ Ok((header, d))
474+ }
475+}
crates/ec-vp8/src/intra.rsadded+711 -0
@@ -0,0 +1,711 @@
1+//! Intra-frame prediction for VP8 (RFC 6386, Section 12).
2+//!
3+//! This module implements the spatial predictors a VP8 decoder applies to
4+//! intra-coded macroblocks: the 16x16 luma predictors and 8x8 (per-plane)
5+//! chroma predictors of Section 12.2/12.3, and the ten 4x4 subblock
6+//! predictors of Section 12.3. All functions are dependency-free, `unsafe`-free,
7+//! allocate nothing, and are bit-exact against the normative integer math of
8+//! the RFC code listings (which are in turn identical to the libvpx oracle in
9+//! `vp8/common/reconintra.c`, `vp8/common/reconintra4x4.c` and
10+//! `vpx_dsp/intrapred.c`).
11+//!
12+//! # Edge-pixel conventions (RFC 6386 Section 12, p.50)
13+//!
14+//! Pixels outside the visible frame are pre-filled by the caller: 127 for the
15+//! row above the top row (including the above-left pixel `P`), 129 for the
16+//! column left of the leftmost column. V_PRED/H_PRED/TM_PRED consume those
17+//! fill values directly; DC_PRED instead decides from the availability flags
18+//! which genuinely-visible pixels to average (RFC Section 12.2, "Note that
19+//! the averages used in these exceptional cases are not the same as those
20+//! that would be arrived at by using the out-of-bounds A and L values").
21+//!
22+//! # 4x4 above-right synthesis
23+//!
24+//! The 4x4 predictors use an 8-pixel above row `A[0..8]`: the 4 pixels
25+//! immediately above the subblock plus the 4 "above-right" pixels
26+//! (frame positions (-1,16)..(-1,19) relative to the macroblock; RFC
27+//! Section 12.3, subblocks 3/7/11/15). Producing those extra four pixels is
28+//! the caller's job: for a macroblock not on the top frame row they come from
29+//! the row above (replicating pixel (-1,15) at the rightmost macroblock of a
30+//! row); on the top frame row they are 127. [`predict4`] only consumes
31+//! `A[0..8]` as given.
32+
33+#![deny(unsafe_code)]
34+
35+/// Weighted average of three adjacent pixels centered at `y`
36+/// (RFC 6386 Section 12.3 `avg3`: `(x + 2y + z + 2) >> 2`; libvpx `AVG3`).
37+///
38+/// Arguments are valid pixel values, so the result always fits in `u8` and no
39+/// clamp is needed (RFC Section 12.3, comment above `avg3`).
40+#[inline]
41+fn avg3(x: u8, y: u8, z: u8) -> u8 {
42+ ((u32::from(x) + 2 * u32::from(y) + u32::from(z) + 2) >> 2) as u8
43+}
44+
45+/// Simple average of two pixels (RFC 6386 Section 12.3 `avg2`:
46+/// `(x + y + 1) >> 1`; libvpx `AVG2`).
47+#[inline]
48+fn avg2(x: u8, y: u8) -> u8 {
49+ ((u32::from(x) + u32::from(y) + 1) >> 1) as u8
50+}
51+
52+/// `clamp255(v)`: clamp an integer pixel difference into the valid `u8` range
53+/// (RFC 6386 Section 12.2 `TMpred` / Section 12.3 `B_TM_PRED`).
54+#[inline]
55+fn clamp255(v: i32) -> u8 {
56+ v.clamp(0, 255) as u8
57+}
58+
59+/// Shared DC/V/H/TM core for the 16x16 luma and 8x8 chroma blocks
60+/// (RFC 6386 Section 12.2 semantics; Section 12.3 states 16x16 luma is
61+/// "essentially identical" with 16-pixel edges).
62+///
63+/// DC rounding follows the RFC formula `DCvalue = (sum + (1 << (shf-1))) >> shf`
64+/// with `shf` = log2 of the number of averaged pixels: 32/16 pixels for the
65+/// 16x16 both/single-edge cases, 16/8 for 8x8.
66+fn predict_block<const N: usize>(
67+ mode: u8,
68+ have_above: bool,
69+ have_left: bool,
70+ above: &[u8; N],
71+ left: &[u8; N],
72+ above_left: u8,
73+ out: &mut [u8],
74+) {
75+ match mode {
76+ // DC_PRED: fill the block with the average of the genuinely visible
77+ // edge pixels; availability flags alone decide which edges count
78+ // (RFC Section 12.2). Neither edge: constant 128.
79+ 0 => {
80+ let sum_above: u32 = above.iter().map(|&p| u32::from(p)).sum();
81+ let sum_left: u32 = left.iter().map(|&p| u32::from(p)).sum();
82+ let tz = N.trailing_zeros(); // log2(N)
83+ let v: u32 = match (have_above, have_left) {
84+ (true, true) => (sum_above + sum_left + N as u32) >> (tz + 1),
85+ (false, false) => 128,
86+ // Above available only: average the above row.
87+ (true, false) => (sum_above + (N as u32 >> 1)) >> tz,
88+ // Left column available only: average the left column.
89+ (false, true) => (sum_left + (N as u32 >> 1)) >> tz,
90+ };
91+ out.fill(v as u8);
92+ }
93+ // V_PRED: every row is a copy of the above row A (RFC Section 12.2).
94+ 1 => {
95+ for row in out.chunks_exact_mut(N) {
96+ row.copy_from_slice(above);
97+ }
98+ }
99+ // H_PRED: every column is a copy of the left column L (RFC Section 12.2).
100+ 2 => {
101+ for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) {
102+ row.fill(l);
103+ }
104+ }
105+ // TM_PRED: X_ij = clamp255(L_i + A_j - P) (RFC Section 12.2 `TMpred`).
106+ // Unlike DC_PRED this mode does use the 127/129 out-of-bounds fills.
107+ 3 => {
108+ for (row, &l) in out.chunks_exact_mut(N).zip(left.iter()) {
109+ for (o, &a) in row.iter_mut().zip(above.iter()) {
110+ *o = clamp255(i32::from(l) + i32::from(a) - i32::from(above_left));
111+ }
112+ }
113+ }
114+ _ => panic!("predict_block: invalid intra mode {mode} (expected 0..=3)"),
115+ }
116+}
117+
118+/// 16x16 luma prediction (RFC 6386 Section 12.3; predictor math per
119+/// Section 12.2).
120+///
121+/// `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. `above` holds the 16
122+/// reconstructed pixels of the row above the macroblock, `left` the 16 pixels
123+/// of the column to its left (adjacent entries separated by one frame row),
124+/// `above_left` is the corner pixel `P`. `have_above`/`have_left` state
125+/// whether those edges are genuinely in-frame.
126+///
127+/// For DC the flags alone decide what is averaged (the out-of-bounds fills
128+/// are NOT used); V/H/TM consume the caller-prepared out-of-bounds fills
129+/// (127 above/`above_left` on the top frame row, 129 on the left frame
130+/// column) written into `above`/`left`/`above_left`.
131+///
132+/// `out` receives 256 row-major prediction pixels.
133+pub fn predict16(
134+ mode: u8,
135+ have_above: bool,
136+ have_left: bool,
137+ above: &[u8; 16],
138+ left: &[u8; 16],
139+ above_left: u8,
140+ out: &mut [u8; 256],
141+) {
142+ predict_block::<16>(mode, have_above, have_left, above, left, above_left, out);
143+}
144+
145+/// 8x8 chroma prediction for one plane (RFC 6386 Section 12.2).
146+///
147+/// Identical semantics to [`predict16`] with 8-pixel edges; call it once for
148+/// U and once for V. `mode` is a u8 in `{0=DC, 1=V, 2=H, 3=TM}`. DC averages
149+/// 16 pixels (both edges: `(sumA + sumL + 8) >> 4`) or 8 pixels (one edge:
150+/// `(sum + 4) >> 3`), or fills 128.
151+///
152+/// `out` receives 64 row-major prediction pixels.
153+pub fn predict8(
154+ mode: u8,
155+ have_above: bool,
156+ have_left: bool,
157+ above: &[u8; 8],
158+ left: &[u8; 8],
159+ above_left: u8,
160+ out: &mut [u8; 64],
161+) {
162+ predict_block::<8>(mode, have_above, have_left, above, left, above_left, out);
163+}
164+
165+/// 4x4 subblock prediction (RFC 6386 Section 12.3 `subblock_intra_predict`).
166+///
167+/// `mode` is a BMode integer: `0=B_DC 1=B_TM 2=B_VE 3=B_HE 4=B_LD 5=B_RD
168+/// 6=B_VR 7=B_VL 8=B_HD 9=B_HU`. `above` is the 8-pixel row `A[0..8]`
169+/// (4 above + 4 above-right; see the [module docs](self) for the caller-side
170+/// synthesis rule), `left` is `L[0..4]`, `above_left` is `P = A[-1] = L[-1]`.
171+///
172+/// Both edges are always considered present for subblocks: the caller
173+/// pre-fills out-of-bounds pixels (127 above including P, 129 left) before
174+/// the call, which is why no availability flags exist here.
175+///
176+/// `out` receives 16 row-major prediction pixels.
177+///
178+/// # RFC typo
179+///
180+/// The RFC listing for `B_HD_PRED` contains the line
181+/// `B[2][0] = B[3][2] = svg2p(E + 1)`; `svg2p` is a typo for `avg2p` (there
182+/// is no `svg2p` definition; libvpx's `d153_predictor` computes `AVG2(K, J)`
183+/// there, confirming the correction implemented here).
184+pub fn predict4(mode: u8, above: &[u8; 8], left: &[u8; 4], above_left: u8, out: &mut [u8; 16]) {
185+ // The 9 already-constructed edge pixels in RFC scan order:
186+ // E[0..4] = L[3], L[2], L[1], L[0]; E[4] = P; E[5..9] = A[0..4].
187+ let e: [u8; 9] = [
188+ left[3], left[2], left[1], left[0], above_left, above[0], above[1], above[2], above[3],
189+ ];
190+ // Row-major B[r][c] = b[r * 4 + c].
191+ let mut b = [0u8; 16];
192+ // avg3p(E + k) = avg3(E[k-1], E[k], E[k+1]); avg2p(E + k) = avg2(E[k], E[k+1]).
193+ match mode {
194+ // B_DC_PRED: DC value = (sum(A[0..4]) + sum(L[0..4]) + 4) >> 3.
195+ 0 => {
196+ let mut v: u32 = 4;
197+ for i in 0..4 {
198+ v += u32::from(above[i]) + u32::from(left[i]);
199+ }
200+ v >>= 3;
201+ b.fill(v as u8);
202+ }
203+ // B_TM_PRED: just like 16x16 TM_PRED (RFC Section 12.3).
204+ 1 => {
205+ for r in 0..4 {
206+ for c in 0..4 {
207+ b[r * 4 + c] =
208+ clamp255(i32::from(left[r]) + i32::from(above[c]) - i32::from(above_left));
209+ }
210+ }
211+ }
212+ // B_VE_PRED: all four rows = smoothed top row avg3p(A + c), where
213+ // A[-1] = P participates in column 0 (libvpx `vpx_ve_predictor_4x4`).
214+ 2 => {
215+ for c in 0..4usize {
216+ let v = if c == 0 {
217+ avg3(above_left, above[0], above[1])
218+ } else {
219+ avg3(above[c - 1], above[c], above[c + 1])
220+ };
221+ b[c] = v;
222+ b[4 + c] = v;
223+ b[8 + c] = v;
224+ b[12 + c] = v;
225+ }
226+ }
227+ // B_HE_PRED: columns = smoothed left column; bottom row exceptional
228+ // because L[4] does not exist: avg3(L[2], L[3], L[3]).
229+ 3 => {
230+ let rows = [
231+ avg3(above_left, left[0], left[1]),
232+ avg3(left[0], left[1], left[2]),
233+ avg3(left[1], left[2], left[3]),
234+ avg3(left[2], left[3], left[3]),
235+ ];
236+ for (r, &v) in rows.iter().enumerate() {
237+ b[r * 4..r * 4 + 4].fill(v);
238+ }
239+ }
240+ // B_LD_PRED: southwest (left and down) 45-degree diagonals off the
241+ // above row; B[3][3] uses avg3(A[6], A[7], A[7]) because A[8] does
242+ // not exist (libvpx `d45e_predictor_4x4`).
243+ 4 => {
244+ b[0] = avg3(above[0], above[1], above[2]);
245+ b[1] = avg3(above[1], above[2], above[3]);
246+ b[4] = b[1];
247+ b[2] = avg3(above[2], above[3], above[4]);
248+ b[5] = b[2];
249+ b[8] = b[2];
250+ b[3] = avg3(above[3], above[4], above[5]);
251+ b[6] = b[3];
252+ b[9] = b[3];
253+ b[12] = b[3];
254+ b[7] = avg3(above[4], above[5], above[6]);
255+ b[10] = b[7];
256+ b[13] = b[7];
257+ b[11] = avg3(above[5], above[6], above[7]);
258+ b[14] = b[11];
259+ b[15] = avg3(above[6], above[7], above[7]);
260+ }
261+ // B_RD_PRED: southeast 45-degree diagonals off the whole E edge
262+ // (libvpx `d135_predictor_4x4`).
263+ 5 => {
264+ b[12] = avg3(e[0], e[1], e[2]);
265+ b[13] = avg3(e[1], e[2], e[3]);
266+ b[8] = b[13];
267+ b[14] = avg3(e[2], e[3], e[4]);
268+ b[9] = b[14];
269+ b[4] = b[14];
270+ b[15] = avg3(e[3], e[4], e[5]);
271+ b[10] = b[15];
272+ b[5] = b[15];
273+ b[0] = b[15];
274+ b[11] = avg3(e[4], e[5], e[6]);
275+ b[6] = b[11];
276+ b[1] = b[11];
277+ b[7] = avg3(e[5], e[6], e[7]);
278+ b[2] = b[7];
279+ b[3] = avg3(e[6], e[7], e[8]);
280+ }
281+ // B_VR_PRED: vertical-right diagonals mixing avg3/avg2 along E
282+ // (libvpx `d117_predictor_4x4`).
283+ 6 => {
284+ b[12] = avg3(e[1], e[2], e[3]);
285+ b[8] = avg3(e[2], e[3], e[4]);
286+ b[13] = avg3(e[3], e[4], e[5]);
287+ b[4] = b[13];
288+ b[9] = avg2(e[4], e[5]);
289+ b[0] = b[9];
290+ b[14] = avg3(e[4], e[5], e[6]);
291+ b[5] = b[14];
292+ b[10] = avg2(e[5], e[6]);
293+ b[1] = b[10];
294+ b[15] = avg3(e[5], e[6], e[7]);
295+ b[6] = b[15];
296+ b[11] = avg2(e[6], e[7]);
297+ b[2] = b[11];
298+ b[7] = avg3(e[6], e[7], e[8]);
299+ b[3] = avg2(e[7], e[8]);
300+ }
301+ // B_VL_PRED: vertical-left diagonals off the above row; the last two
302+ // values do not strictly follow the pattern (RFC Section 12.3;
303+ // libvpx `d63e_predictor_4x4`).
304+ 7 => {
305+ b[0] = avg2(above[0], above[1]);
306+ b[4] = avg3(above[0], above[1], above[2]);
307+ b[8] = avg2(above[1], above[2]);
308+ b[1] = b[8];
309+ b[5] = avg3(above[1], above[2], above[3]);
310+ b[12] = b[5];
311+ b[9] = avg2(above[2], above[3]);
312+ b[2] = b[9];
313+ b[13] = avg3(above[2], above[3], above[4]);
314+ b[6] = b[13];
315+ b[10] = avg2(above[3], above[4]);
316+ b[3] = b[10];
317+ b[14] = avg3(above[3], above[4], above[5]);
318+ b[7] = b[14];
319+ b[11] = avg3(above[4], above[5], above[6]);
320+ b[15] = avg3(above[5], above[6], above[7]);
321+ }
322+ // B_HD_PRED: horizontal-down diagonals; the RFC's `svg2p(E + 1)` is
323+ // the avg2p correction noted in this function's docs (libvpx
324+ // `d153_predictor_4x4`).
325+ 8 => {
326+ b[12] = avg2(e[0], e[1]);
327+ b[13] = avg3(e[0], e[1], e[2]);
328+ b[8] = avg2(e[1], e[2]); // corrected svg2p -> avg2p line
329+ b[14] = b[8];
330+ b[9] = avg3(e[1], e[2], e[3]);
331+ b[15] = b[9];
332+ b[10] = avg2(e[2], e[3]);
333+ b[4] = b[10];
334+ b[11] = avg3(e[2], e[3], e[4]);
335+ b[5] = b[11];
336+ b[6] = avg2(e[3], e[4]);
337+ b[0] = b[6];
338+ b[7] = avg3(e[3], e[4], e[5]);
339+ b[1] = b[7];
340+ b[2] = avg3(e[4], e[5], e[6]);
341+ b[3] = avg3(e[5], e[6], e[7]);
342+ }
343+ // B_HU_PRED: horizontal-up diagonals off the left column; the bottom
344+ // rows cannot follow the pattern and collapse to L[3] (RFC
345+ // Section 12.3; libvpx `d207_predictor_4x4`).
346+ 9 => {
347+ b[0] = avg2(left[0], left[1]);
348+ b[1] = avg3(left[0], left[1], left[2]);
349+ b[2] = avg2(left[1], left[2]);
350+ b[4] = b[2];
351+ b[3] = avg3(left[1], left[2], left[3]);
352+ b[5] = b[3];
353+ b[6] = avg2(left[2], left[3]);
354+ b[8] = b[6];
355+ b[7] = avg3(left[2], left[3], left[3]);
356+ b[9] = b[7];
357+ let v = left[3];
358+ b[10] = v;
359+ b[11] = v;
360+ b[12] = v;
361+ b[13] = v;
362+ b[14] = v;
363+ b[15] = v;
364+ }
365+ _ => panic!("predict4: invalid intra 4x4 mode {mode} (expected 0..=9)"),
366+ }
367+ out.copy_from_slice(&b);
368+}
369+
370+#[cfg(test)]
371+mod tests {
372+ use super::*;
373+
374+ // ---------------------------------------------------------------- --
375+ // Reference model used to derive the expected vectors below. It is a
376+ // verbatim Python transcription of RFC 6386 Section 12.3
377+ // subblock_intra_predict (with svg2p corrected to avg2p); outputs were
378+ // generated with it and then hand-spot-checked:
379+ //
380+ // def avg2(x, y): return (x + y + 1) >> 1
381+ // def avg3(x, y, z): return (x + 2*y + z + 2) >> 2
382+ // def clamp255(v): return max(0, min(255, v))
383+ // # A = A[0..8], L = L[0..4], P = above-left
384+ // E = [L[3], L[2], L[1], L[0], P, A[0], A[1], A[2], A[3]]
385+ // B_DC: v = (4 + sum(A[0:4]) + sum(L[0:4])) >> 3
386+ // B_TM: B[r][c] = clamp255(L[r] + A[c] - P)
387+ // B_VE: col c: avg3(P, A0, A1) then avg3(A[c-1], A[c], A[c+1])
388+ // B_HE: rows avg3(P, L0, L1), avg3(L0, L1, L2), avg3(L1, L2, L3),
389+ // avg3(L2, L3, L3)
390+ // B_LD: B[0][0]=avg3(A0,A1,A2); B[0][1]=B[1][0]=avg3(A1,A2,A3); ...
391+ // B[3][3]=avg3(A6,A7,A7)
392+ // B_RD: B[3][0]=avg3(E0,E1,E2); B[3][1]=B[2][0]=avg3(E1,E2,E3);
393+ // B[3][2]=B[2][1]=B[1][0]=avg3(E2,E3,E4);
394+ // diag=avg3(E3,E4,E5); ...; B[0][3]=avg3(E6,E7,E8)
395+ // B_VR: B[3][0]=avg3(E1,E2,E3); B[2][0]=avg3(E2,E3,E4);
396+ // B[3][1]=B[1][0]=avg3(E3,E4,E5); B[2][1]=B[0][0]=avg2(E4,E5);
397+ // B[3][2]=B[1][1]=avg3(E4,E5,E6); B[2][2]=B[0][1]=avg2(E5,E6);
398+ // B[3][3]=B[1][2]=avg3(E5,E6,E7); B[2][3]=B[0][2]=avg2(E6,E7);
399+ // B[1][3]=avg3(E6,E7,E8); B[0][3]=avg2(E7,E8)
400+ // B_VL: B[0][0]=avg2(A0,A1); B[1][0]=avg3(A0,A1,A2);
401+ // B[2][0]=B[0][1]=avg2(A1,A2); B[1][1]=B[3][0]=avg3(A1,A2,A3);
402+ // B[2][1]=B[0][2]=avg2(A2,A3); B[3][1]=B[1][2]=avg3(A2,A3,A4);
403+ // B[2][2]=B[0][3]=avg2(A3,A4); B[3][2]=B[1][3]=avg3(A3,A4,A5);
404+ // B[2][3]=avg3(A4,A5,A6); B[3][3]=avg3(A5,A6,A7)
405+ // B_HD: B[3][0]=avg2(E0,E1); B[3][1]=avg3(E0,E1,E2);
406+ // B[2][0]=B[3][2]=avg2(E1,E2) <- svg2p typo corrected
407+ // B[2][1]=B[3][3]=avg3(E1,E2,E3);
408+ // B[2][2]=B[1][0]=avg2(E2,E3);
409+ // B[2][3]=B[1][1]=avg3(E2,E3,E4);
410+ // B[1][2]=B[0][0]=avg2(E3,E4);
411+ // B[1][3]=B[0][1]=avg3(E3,E4,E5);
412+ // B[0][2]=avg3(E4,E5,E6); B[0][3]=avg3(E5,E6,E7)
413+ // B_HU: B[0][0]=avg2(L0,L1); B[0][1]=avg3(L0,L1,L2);
414+ // B[0][2]=B[1][0]=avg2(L1,L2); B[0][3]=B[1][1]=avg3(L1,L2,L3);
415+ // B[1][2]=B[2][0]=avg2(L2,L3);
416+ // B[1][3]=B[2][1]=avg3(L2,L3,L3);
417+ // B[2][2..4]=B[3][0..4]=L3
418+ // ---------------------------------------------------------------- --
419+
420+ /// Fixed edge pattern shared by all ten subblock tests:
421+ /// above = [10,20,30,40,50,60,70,80], left = [15,25,35,45], P = 5.
422+ const EDGE_A: [u8; 8] = [10, 20, 30, 40, 50, 60, 70, 80];
423+ const EDGE_L: [u8; 4] = [15, 25, 35, 45];
424+ const EDGE_P: u8 = 5;
425+
426+ fn assert_pred4(mode: u8, expected: [u8; 16]) {
427+ let mut out = [0u8; 16];
428+ predict4(mode, &EDGE_A, &EDGE_L, EDGE_P, &mut out);
429+ assert_eq!(out, expected, "predict4 mode {mode}");
430+ }
431+
432+ #[test]
433+ fn subblock_dc_constant() {
434+ // v = (4 + (10+20+30+40) + (15+25+35+45)) >> 3 = (4+100+120)>>3 = 28.
435+ assert_pred4(0, [28; 16]);
436+ }
437+
438+ #[test]
439+ fn subblock_tm_gradient() {
440+ // B[r][c] = L[r] + A[c] - P = L[r] + A[c] - 5.
441+ assert_pred4(
442+ 1,
443+ [
444+ 20, 30, 40, 50, // row 0: 15 + A[c] - 5
445+ 30, 40, 50, 60, // row 1: 25 + A[c] - 5
446+ 40, 50, 60, 70, // row 2
447+ 50, 60, 70, 80, // row 3
448+ ],
449+ );
450+ }
451+
452+ #[test]
453+ fn subblock_ve_smoothed_row() {
454+ // Row = avg3(A[c-1], A[c], A[c+1]) with A[-1] = P:
455+ // avg3(5,10,20)=11, avg3(10,20,30)=20, avg3(20,30,40)=30,
456+ // avg3(30,40,50)=40.
457+ let row = [11, 20, 30, 40];
458+ let mut expected = [0u8; 16];
459+ for r in 0..4 {
460+ expected[r * 4..r * 4 + 4].copy_from_slice(&row);
461+ }
462+ assert_pred4(2, expected);
463+ }
464+
465+ #[test]
466+ fn subblock_he_smoothed_column() {
467+ // Rows: avg3(5,15,25)=15, avg3(15,25,35)=25, avg3(25,35,45)=35,
468+ // avg3(35,45,45)=43 (bottom-row exception, L[4] absent).
469+ assert_pred4(
470+ 3,
471+ [
472+ 15, 15, 15, 15, 25, 25, 25, 25, 35, 35, 35, 35, 43, 43, 43, 43,
473+ ],
474+ );
475+ }
476+
477+ #[test]
478+ fn subblock_ld_downright_diagonal() {
479+ // B[3][3] = avg3(70,80,80) = (70 + 160 + 80 + 2) >> 2 = 78 (A[8]
480+ // does not exist).
481+ assert_pred4(
482+ 4,
483+ [
484+ 20, 30, 40, 50, // avg3(10,20,30)=20, avg3(20,30,40)=30, ...
485+ 30, 40, 50, 60, //
486+ 40, 50, 60, 70, //
487+ 50, 60, 70, 78, //
488+ ],
489+ );
490+ }
491+
492+ #[test]
493+ fn subblock_rd_downright_diagonal() {
494+ // E = [45,35,25,15,5,10,20,30,40].
495+ // B[3][0] = avg3(45,35,25) = 35; B[3][1]=B[2][0] = avg3(35,25,15) = 25;
496+ // B[3][2]=B[2][1]=B[1][0] = avg3(25,15,5) = 15;
497+ // main diagonal = avg3(15,5,10) = 9; B[2][3]=B[1][2]=B[0][1] =
498+ // avg3(5,10,20) = 11; B[1][3]=B[0][2] = avg3(10,20,30) = 20;
499+ // B[0][3] = avg3(20,30,40) = 30.
500+ assert_pred4(
501+ 5,
502+ [
503+ 9, 11, 20, 30, //
504+ 15, 9, 11, 20, //
505+ 25, 15, 9, 11, //
506+ 35, 25, 15, 9, //
507+ ],
508+ );
509+ }
510+
511+ #[test]
512+ fn subblock_vr_mixed_diagonal() {
513+ // E = [45,35,25,15,5,10,20,30,40].
514+ // B[0][0] = avg2(E4,E5) = avg2(5,10) = 8;
515+ // B[0][1] = avg2(10,20) = 15; B[0][2] = avg2(20,30) = 25;
516+ // B[0][3] = avg2(30,40) = 35; B[1][0] = avg3(15,5,10) = 9;
517+ // B[1][1] = avg3(5,10,20) = 11; B[1][2] = avg3(10,20,30) = 20;
518+ // B[1][3] = avg3(20,30,40) = 30; B[2][0] = avg3(25,15,5) = 15;
519+ // B[2][1] = 8; B[2][2] = 15; B[2][3] = 25;
520+ // B[3][0] = avg3(35,25,15) = 25; B[3][1] = 9; B[3][2] = 11; B[3][3] = 20.
521+ assert_pred4(
522+ 6,
523+ [
524+ 8, 15, 25, 35, //
525+ 9, 11, 20, 30, //
526+ 15, 8, 15, 25, //
527+ 25, 9, 11, 20, //
528+ ],
529+ );
530+ }
531+
532+ #[test]
533+ fn subblock_vl_downleft_diagonal() {
534+ // avg2/avg3 pairs along the above row:
535+ // cols: avg2(10,20)=15, avg2(20,30)=25, avg2(30,40)=35, avg2(40,50)=45;
536+ // rows shift by avg3: 20, 30, 40, 50; last column 45/50/60/70 with
537+ // B[2][3]=avg3(50,60,70)=60, B[3][3]=avg3(60,70,80)=70.
538+ assert_pred4(
539+ 7,
540+ [
541+ 15, 25, 35, 45, //
542+ 20, 30, 40, 50, //
543+ 25, 35, 45, 60, //
544+ 30, 40, 50, 70, //
545+ ],
546+ );
547+ }
548+
549+ #[test]
550+ fn subblock_hd_uses_avg2p_for_svg2p_typo_line() {
551+ // E = [45,35,25,15,5,10,20,30,40].
552+ // The RFC's `svg2p(E + 1)` line: B[2][0] = B[3][2] = avg2p(E+1) =
553+ // avg2(E[1], E[2]) = avg2(35,25) = 30. A mis-transcription (any
554+ // avg3-style or E-shifted variant) would not yield 30 here.
555+ // B[3][0] = avg2(45,35) = 40; B[3][1] = avg3(45,35,25) = 35;
556+ // B[2][1]=B[3][3] = avg3(35,25,15) = 25; B[2][2]=B[1][0] =
557+ // avg2(25,15) = 20; B[2][3]=B[1][1] = avg3(25,15,5) = 15;
558+ // B[1][2]=B[0][0] = avg2(15,5) = 10; B[1][3]=B[0][1] =
559+ // avg3(15,5,10) = 9; B[0][2] = avg3(5,10,20) = 11;
560+ // B[0][3] = avg3(10,20,30) = 20.
561+ assert_pred4(
562+ 8,
563+ [
564+ 10, 9, 11, 20, //
565+ 20, 15, 10, 9, //
566+ 30, 25, 20, 15, //
567+ 40, 35, 30, 25, //
568+ ],
569+ );
570+ // Directly pin the corrected-typo cells.
571+ let mut out = [0u8; 16];
572+ predict4(8, &EDGE_A, &EDGE_L, EDGE_P, &mut out);
573+ assert_eq!(
574+ (out[8], out[14]),
575+ (30, 30),
576+ "B[2][0] and B[3][2] = avg2(E1,E2)"
577+ );
578+ }
579+
580+ #[test]
581+ fn subblock_hu_up_diagonal() {
582+ // B[0][0] = avg2(15,25) = 20; B[0][1] = avg3(15,25,35) = 25;
583+ // B[0][2]=B[1][0] = avg2(25,35) = 30; B[0][3]=B[1][1] =
584+ // avg3(25,35,45) = 35; B[1][2]=B[2][0] = avg2(35,45) = 40;
585+ // B[1][3]=B[2][1] = avg3(35,45,45) = 43; bottom rows = L[3] = 45.
586+ assert_pred4(
587+ 9,
588+ [
589+ 20, 25, 30, 35, //
590+ 30, 35, 40, 43, //
591+ 40, 43, 45, 45, //
592+ 45, 45, 45, 45, //
593+ ],
594+ );
595+ }
596+
597+ #[test]
598+ fn dc16_all_availability_cases() {
599+ // above = [10; 16] (sum 160), left = [20; 16] (sum 320).
600+ let above = [10u8; 16];
601+ let left = [20u8; 16];
602+ let mut out = [0u8; 256];
603+
604+ // Both edges: (160 + 320 + 16) >> 5 = 15.
605+ predict16(0, true, true, &above, &left, 5, &mut out);
606+ assert_eq!(out, [15; 256]);
607+
608+ // Neither edge (top-left macroblock): constant 128. The array
609+ // contents are irrelevant here; availability flags decide.
610+ predict16(0, false, false, &above, &left, 5, &mut out);
611+ assert_eq!(out, [128; 256]);
612+
613+ // Above only (left frame column): (160 + 8) >> 4 = 10.
614+ predict16(0, true, false, &above, &left, 5, &mut out);
615+ assert_eq!(out, [10; 256]);
616+
617+ // Left only (top frame row): (320 + 8) >> 4 = 20.
618+ predict16(0, false, true, &above, &left, 5, &mut out);
619+ assert_eq!(out, [20; 256]);
620+ }
621+
622+ #[test]
623+ fn dc8_all_availability_cases() {
624+ // above = [10; 8] (sum 80), left = [20; 8] (sum 160).
625+ let above = [10u8; 8];
626+ let left = [20u8; 8];
627+ let mut out = [0u8; 64];
628+
629+ // Both: (80 + 160 + 8) >> 4 = 15.
630+ predict8(0, true, true, &above, &left, 5, &mut out);
631+ assert_eq!(out, [15; 64]);
632+
633+ // Neither: 128.
634+ predict8(0, false, false, &above, &left, 5, &mut out);
635+ assert_eq!(out, [128; 64]);
636+
637+ // Above only: (80 + 4) >> 3 = 10.
638+ predict8(0, true, false, &above, &left, 5, &mut out);
639+ assert_eq!(out, [10; 64]);
640+
641+ // Left only: (160 + 4) >> 3 = 20.
642+ predict8(0, false, true, &above, &left, 5, &mut out);
643+ assert_eq!(out, [20; 64]);
644+ }
645+
646+ #[test]
647+ fn tm16_clamps_both_directions() {
648+ let mut out = [0u8; 256];
649+
650+ // Negative difference clamps to 0: P high (250), L and A low (0)
651+ // gives L + A - P = -250 everywhere.
652+ predict16(3, true, true, &[0u8; 16], &[0u8; 16], 250, &mut out);
653+ assert_eq!(out, [0; 256]);
654+
655+ // Overflow clamps to 255: P = 0, L = A = 255 gives 510 everywhere.
656+ predict16(3, true, true, &[255u8; 16], &[255u8; 16], 0, &mut out);
657+ assert_eq!(out, [255; 256]);
658+
659+ // Exact in-range gradient: out[r][c] = 200 + c - 50 = 150 + c,
660+ // no clamping, verifies arithmetic (not just the clamps).
661+ let above: [u8; 16] = core::array::from_fn(|i| i as u8);
662+ predict16(3, true, true, &above, &[200u8; 16], 50, &mut out);
663+ for r in 0..16 {
664+ let row: [u8; 16] = core::array::from_fn(|c| (150 + c) as u8);
665+ assert_eq!(out[r * 16..r * 16 + 16], row, "TM16 row {r}");
666+ }
667+ }
668+
669+ #[test]
670+ fn tm4_clamps_via_predict4() {
671+ // Same clamp contract at 4x4 (RFC B_TM_PRED == clamp255(L + A - P)).
672+ let mut out = [0u8; 16];
673+ predict4(1, &[0u8; 8], &[0u8; 4], 250, &mut out);
674+ assert_eq!(out, [0; 16]);
675+ predict4(1, &[255u8; 8], &[255u8; 4], 0, &mut out);
676+ assert_eq!(out, [255; 16]);
677+ }
678+
679+ #[test]
680+ fn v_and_h_copy_edges() {
681+ // V_PRED: every 16x16 row equals the above row.
682+ let above: [u8; 16] = core::array::from_fn(|i| (i * 7 + 3) as u8);
683+ let mut out = [0u8; 256];
684+ predict16(1, true, true, &above, &[0u8; 16], 0, &mut out);
685+ for row in out.chunks_exact(16) {
686+ assert_eq!(row, above);
687+ }
688+
689+ // H_PRED: every 8x8 row is the constant left[r].
690+ let left: [u8; 8] = core::array::from_fn(|i| (i * 11 + 1) as u8);
691+ let mut out8 = [0u8; 64];
692+ predict8(2, true, true, &[0u8; 8], &left, 0, &mut out8);
693+ for (r, row) in out8.chunks_exact(8).enumerate() {
694+ assert_eq!(row, [left[r]; 8]);
695+ }
696+ }
697+
698+ #[test]
699+ #[should_panic(expected = "invalid intra mode")]
700+ fn predict16_rejects_invalid_mode() {
701+ let mut out = [0u8; 256];
702+ predict16(4, true, true, &[0u8; 16], &[0u8; 16], 0, &mut out);
703+ }
704+
705+ #[test]
706+ #[should_panic(expected = "invalid intra 4x4 mode")]
707+ fn predict4_rejects_invalid_mode() {
708+ let mut out = [0u8; 16];
709+ predict4(10, &[0u8; 8], &[0u8; 4], 0, &mut out);
710+ }
711+}
crates/ec-vp8/src/lib.rsadded+31 -0
@@ -0,0 +1,31 @@
1+//! Native VP8 (RFC 6386) decoder — the future replacement for edith's
2+//! runtime-dlopen'd libvpx seat.
3+//!
4+//! The crate is written from the specification ([RFC 6386]) alone; libvpx's
5+//! output is used only as a test oracle (sample-exactness witnesses), never
6+//! as code to port. Every module documents the spec section it implements.
7+//!
8+//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386
9+//!
10+//! # Unsafe
11+//!
12+//! This crate contains no `unsafe` code.
13+
14+#![deny(unsafe_code)]
15+#![warn(missing_docs)]
16+
17+pub mod bool;
18+pub mod decode;
19+pub mod frame;
20+pub mod header;
21+pub mod intra;
22+pub mod loopfilter;
23+mod mc;
24+pub mod modes;
25+pub mod stream;
26+pub mod tables;
27+pub mod tokens;
28+pub mod transform;
29+
30+pub use ec_core::{Error, Result};
31+pub use header::PersistedState;
crates/ec-vp8/src/loopfilter.rsadded+1064 -0
@@ -0,0 +1,1064 @@
1+//! VP8 in-loop deblocking filter — RFC 6386 Section 15.
2+//!
3+//! Implements the *normal* filter (§15.3), the *simple* filter (§15.2), the
4+//! per-frame macroblock-edge driver in the reference decoder's exact visit
5+//! order, and the per-sharpness limit-table construction of §15.4.
6+//!
7+//! The arithmetic is transcribed line-for-line from the normative reference
8+//! sources and is bit-identical between them (verified term-by-term):
9+//!
10+//! * `dixie_loopfilter.c` shipped with RFC 6386 (§20.6) — kernels
11+//! (`filter_common`, `filter_mb_edge`, thresholds) and the
12+//! `filter_row_normal` / `filter_row_simple` drivers,
13+//! * libvpx `vp8/common/loopfilter_filters.c` — the same kernels as
14+//! branch-free C, and `vp8/common/vp8_loopfilter.c`
15+//! (`vp8_loop_filter_update_sharpness`, `lf_init_lut`) — the limit and
16+//! high-edge-variance tables.
17+//!
18+//! C signed right-shifts are arithmetic (floor); Rust `i32 >>` has the same
19+//! semantics, so every `>>` below reproduces the C rounding exactly. No
20+//! allocation, no `unsafe`.
21+//!
22+//! Frame-type note: §15.4 (and libvpx `lf_init_lut`) makes `hev_threshold`
23+//! depend on whether the current frame is a key frame. [`filter_frame`]
24+//! keeps the crate-contract signature and applies the *inter-frame* table;
25+//! call [`filter_frame_ex`] with the decoded `is_keyframe` flag for fully
26+//! type-exact decoding (the two differ only for levels ≥ 15).
27+
28+/// Per-macroblock filter inputs the decoder derives from the frame header,
29+/// segmentation map and per-MB prediction info.
30+///
31+/// `level` is the *final* per-MB loop filter level (0..=63) after the
32+/// segment and ref/mode delta adjustments of RFC 6386 §15.4 (implemented
33+/// decoder-side in `decode.rs`, mirroring dixie `calculate_filter_parameters`).
34+/// A level of 0 disables all filtering of that macroblock (dixie:
35+/// `if (edge_limit) { ... }`).
36+///
37+/// `inner_edges` controls whether the subblock (interior) edges of the MB
38+/// are filtered: true iff the MB has any non-zero DCT coefficient or its
39+/// mode is `B_PRED`/`SPLITMV` (RFC §15.1; dixie's `eob_mask` condition,
40+/// `filter_row_normal` ~L9308 and `filter_row_simple` ~L9433).
41+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42+pub struct MbFilterInfo {
43+ /// Effective per-MB loop filter level after segment and ref/mode delta
44+ /// adjustments, clamped to 0..=63.
45+ pub level: u8,
46+ /// Filter interior (subblock) edges of this MB (any non-zero DCT
47+ /// coefficient, or `B_PRED`/`SPLITMV` mode).
48+ pub inner_edges: bool,
49+}
50+
51+/// Per-sharpness limit tables for levels 0..=63, in the order
52+/// `lim` / `blim` / `mblim` of libvpx `loop_filter_info_n`.
53+///
54+/// These are the combined edge limits of RFC §15.4:
55+/// `mblim[l] = (l + 2) * 2 + interior_limit(l)` (macroblock edges),
56+/// `blim[l] = l * 2 + interior_limit(l)` (subblock edges), and
57+/// `lim[l] = interior_limit(l)`. Both filter variants consume these exact
58+/// combined values (the simple filter directly, as dixie
59+/// `filter_v_edge_simple` does; the normal filter splits them back into
60+/// center + interior tests).
61+#[derive(Clone, Copy, Debug)]
62+pub struct LoopFilterTables {
63+ /// Interior-difference limit per level (dixie `interior_limit`).
64+ pub lim: [u8; 64],
65+ /// Combined subblock-edge center limit per level (dixie `b_limit`).
66+ pub blim: [u8; 64],
67+ /// Combined macroblock-edge center limit per level (dixie `mb_limit`).
68+ pub mblim: [u8; 64],
69+}
70+
71+impl LoopFilterTables {
72+ /// Build the three limit tables for one frame's sharpness level.
73+ ///
74+ /// Port of libvpx `vp8_loop_filter_update_sharpness`
75+ /// (vp8/common/vp8_loopfilter.c), which matches the RFC §15.4
76+ /// pseudocode:
77+ ///
78+ /// ```text
79+ /// inside = level >> (sharpness > 0) >> (sharpness > 4)
80+ /// if sharpness > 0 and inside > 9 - sharpness: inside = 9 - sharpness
81+ /// inside = max(inside, 1)
82+ /// ```
83+ pub fn update_sharpness(sharpness: u8) -> Self {
84+ let s = i32::from(sharpness);
85+ let mut t = LoopFilterTables {
86+ lim: [0; 64],
87+ blim: [0; 64],
88+ mblim: [0; 64],
89+ };
90+ for (lvl, slot) in t.lim.iter_mut().enumerate() {
91+ let filt_lvl = lvl as i32;
92+ // libvpx L59-60: two conditional single-bit shifts.
93+ let mut inside = filt_lvl;
94+ if s > 0 {
95+ inside >>= 1;
96+ }
97+ if s > 4 {
98+ inside >>= 1;
99+ }
100+ // libvpx L62-66: cap only applies when sharpness > 0.
101+ if s > 0 && inside > 9 - s {
102+ inside = 9 - s;
103+ }
104+ if inside < 1 {
105+ inside = 1;
106+ }
107+ *slot = inside as u8;
108+ t.blim[lvl] = (2 * filt_lvl + inside) as u8;
109+ t.mblim[lvl] = (2 * (filt_lvl + 2) + inside) as u8;
110+ }
111+ t
112+ }
113+}
114+
115+/// Interior-difference limit for one level/sharpness pair (RFC §15.4).
116+///
117+/// Same derivation as [`LoopFilterTables::update_sharpness`] for a single
118+/// level; provided for callers that need the value without the tables.
119+pub fn interior_limit(level: u8, sharpness: u8) -> i32 {
120+ let s = i32::from(sharpness);
121+ let mut il = i32::from(level);
122+ if s > 0 {
123+ // dixie: interior_limit >>= sharpness > 4 ? 2 : 1 — the two
124+ // conditional single-bit shifts of update_sharpness folded.
125+ il >>= if s > 4 { 2 } else { 1 };
126+ if il > 9 - s {
127+ il = 9 - s;
128+ }
129+ }
130+ if il < 1 {
131+ il = 1;
132+ }
133+ il
134+}
135+
136+/// High-edge-variance threshold for one level (RFC §15.4, last block; also
137+/// libvpx `lf_init_lut`'s `hev_thr_lut[KEY_FRAME|INTER_FRAME]`).
138+///
139+/// Key frames: 2 at level ≥ 40, 1 at level ≥ 15, else 0. Inter frames: 3 at
140+/// level ≥ 40, 2 at level ≥ 20, 1 at level ≥ 15, else 0.
141+pub fn hev_threshold(level: u8, is_keyframe: bool) -> i32 {
142+ let l = i32::from(level);
143+ if is_keyframe {
144+ if l >= 40 {
145+ 2
146+ } else if l >= 15 {
147+ 1
148+ } else {
149+ 0
150+ }
151+ } else if l >= 40 {
152+ 3
153+ } else if l >= 20 {
154+ 2
155+ } else if l >= 15 {
156+ 1
157+ } else {
158+ 0
159+ }
160+}
161+
162+/// Filter one frame's worth of macroblock edges, in the reference decoder's
163+/// exact order (dixie `filter_row_normal` / `filter_row_simple`, applied
164+/// row-major over MBs; each MB visits, when enabled: left MB V-edge, then
165+/// subblock V-edges at +4/+8/+12, then top MB H-edge, then subblock
166+/// H-edges at +4/+8/+12 rows).
167+///
168+/// `y`/`u`/`v` are unbordered plane buffers starting at pixel (0,0),
169+/// `stride`/`uv_stride` samples apart, sized `mb_cols*16 × mb_rows*16`
170+/// (and halved for chroma). Frame-boundary edges (column 0, row 0) are not
171+/// filtered. `mb_info` is indexed `row * mb_cols + col`; a level of 0
172+/// disables all filtering of that MB. The simple variant filters only the
173+/// Y plane (dixie `filter_row_simple`).
174+///
175+/// This applies the inter-frame `hev_threshold` table (see the module docs);
176+/// use [`filter_frame_ex`] for frame-type-exact decoding.
177+#[allow(clippy::too_many_arguments)]
178+pub fn filter_frame(
179+ y: &mut [u8],
180+ u: &mut [u8],
181+ v: &mut [u8],
182+ stride: usize,
183+ uv_stride: usize,
184+ mb_cols: usize,
185+ mb_rows: usize,
186+ sharpness: u8,
187+ simple_filter_type: bool,
188+ mb_info: &[MbFilterInfo],
189+) {
190+ filter_frame_ex(
191+ y,
192+ u,
193+ v,
194+ stride,
195+ uv_stride,
196+ mb_cols,
197+ mb_rows,
198+ sharpness,
199+ simple_filter_type,
200+ mb_info,
201+ false,
202+ );
203+}
204+
205+/// [`filter_frame`] with an explicit frame type: `is_keyframe` selects the
206+/// §15.4 key-frame `hev_threshold` table instead of the inter-frame table
207+/// (dixie `calculate_filter_parameters`:
208+/// `if (filter_level >= 20 && !is_keyframe) hev_threshold++`).
209+#[allow(clippy::too_many_arguments)]
210+pub fn filter_frame_ex(
211+ y: &mut [u8],
212+ u: &mut [u8],
213+ v: &mut [u8],
214+ stride: usize,
215+ uv_stride: usize,
216+ mb_cols: usize,
217+ mb_rows: usize,
218+ sharpness: u8,
219+ simple_filter_type: bool,
220+ mb_info: &[MbFilterInfo],
221+ is_keyframe: bool,
222+) {
223+ debug_assert_eq!(mb_info.len(), mb_cols * mb_rows);
224+ debug_assert!(y.len() >= stride * (mb_rows * 16 - 1) + mb_cols * 16);
225+ debug_assert!(u.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8);
226+ debug_assert!(v.len() >= uv_stride * (mb_rows * 8 - 1) + mb_cols * 8);
227+ debug_assert!(stride >= mb_cols * 16);
228+ debug_assert!(uv_stride >= mb_cols * 8);
229+
230+ let tables = LoopFilterTables::update_sharpness(sharpness);
231+
232+ for row in 0..mb_rows {
233+ for col in 0..mb_cols {
234+ let info = &mb_info[row * mb_cols + col];
235+ let level = info.level as usize;
236+ // dixie filter_row_normal L9280 / filter_row_simple L9425:
237+ // `if (edge_limit)` — level 0 filters nothing for this MB.
238+ if level == 0 {
239+ continue;
240+ }
241+ let hev = hev_threshold(info.level, is_keyframe);
242+ let mblim = i32::from(tables.mblim[level]);
243+ let blim = i32::from(tables.blim[level]);
244+ let lim = i32::from(tables.lim[level]);
245+ let ybase = row * 16 * stride + col * 16;
246+ let uvbase = row * 8 * uv_stride + col * 8;
247+
248+ if simple_filter_type {
249+ // dixie filter_row_simple L9436-9460. Y plane only.
250+ if col > 0 {
251+ filter_v_edge_simple(y, stride, ybase, mblim);
252+ }
253+ if info.inner_edges {
254+ filter_v_edge_simple(y, stride, ybase + 4, blim);
255+ filter_v_edge_simple(y, stride, ybase + 8, blim);
256+ filter_v_edge_simple(y, stride, ybase + 12, blim);
257+ }
258+ if row > 0 {
259+ filter_h_edge_simple(y, stride, ybase, mblim);
260+ }
261+ if info.inner_edges {
262+ filter_h_edge_simple(y, stride, ybase + 4 * stride, blim);
263+ filter_h_edge_simple(y, stride, ybase + 8 * stride, blim);
264+ filter_h_edge_simple(y, stride, ybase + 12 * stride, blim);
265+ }
266+ continue;
267+ }
268+
269+ // dixie filter_row_normal L9282-9378.
270+ if col > 0 {
271+ filter_mb_v_edge(y, stride, ybase, mblim, lim, hev, 2);
272+ filter_mb_v_edge(u, uv_stride, uvbase, mblim, lim, hev, 1);
273+ filter_mb_v_edge(v, uv_stride, uvbase, mblim, lim, hev, 1);
274+ }
275+ if info.inner_edges {
276+ filter_subblock_v_edge(y, stride, ybase + 4, blim, lim, hev, 2);
277+ filter_subblock_v_edge(y, stride, ybase + 8, blim, lim, hev, 2);
278+ filter_subblock_v_edge(y, stride, ybase + 12, blim, lim, hev, 2);
279+ filter_subblock_v_edge(u, uv_stride, uvbase + 4, blim, lim, hev, 1);
280+ filter_subblock_v_edge(v, uv_stride, uvbase + 4, blim, lim, hev, 1);
281+ }
282+ if row > 0 {
283+ filter_mb_h_edge(y, stride, ybase, mblim, lim, hev, 2);
284+ filter_mb_h_edge(u, uv_stride, uvbase, mblim, lim, hev, 1);
285+ filter_mb_h_edge(v, uv_stride, uvbase, mblim, lim, hev, 1);
286+ }
287+ if info.inner_edges {
288+ filter_subblock_h_edge(y, stride, ybase + 4 * stride, blim, lim, hev, 2);
289+ filter_subblock_h_edge(y, stride, ybase + 8 * stride, blim, lim, hev, 2);
290+ filter_subblock_h_edge(y, stride, ybase + 12 * stride, blim, lim, hev, 2);
291+ filter_subblock_h_edge(u, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1);
292+ filter_subblock_h_edge(v, uv_stride, uvbase + 4 * uv_stride, blim, lim, hev, 1);
293+ }
294+ }
295+ }
296+}
297+
298+// ---------------------------------------------------------------------------
299+// Kernels — transcriptions of dixie_loopfilter.c (RFC 6386 §20.6).
300+// Pixels are handled as raw unsigned samples widened to `i32`; every clamp
301+// is the exact dixie saturate_int8 / saturate_uint8.
302+// ---------------------------------------------------------------------------
303+
304+/// dixie `saturate_int8`.
305+#[inline]
306+fn sat_i8(x: i32) -> i32 {
307+ x.clamp(-128, 127)
308+}
309+
310+/// dixie `saturate_uint8` (result kept as `i32` in 0..=255).
311+#[inline]
312+fn sat_u8(x: i32) -> i32 {
313+ x.clamp(0, 255)
314+}
315+
316+/// dixie `simple_threshold` (RFC §15.2/§15.3): the center test
317+/// `|p0-q0|*2 + |p1-q1|/2 <= limit` with `limit` already the *combined*
318+/// edge limit (`2*E + I`, or the tables' `blim`/`mblim`).
319+#[inline]
320+fn simple_threshold(p1: i32, p0: i32, q0: i32, q1: i32, limit: i32) -> bool {
321+ (p0 - q0).abs() * 2 + ((p1 - q1).abs() >> 1) <= limit
322+}
323+
324+/// dixie `normal_threshold` (RFC §15.3 `filter_yes`): the combined center
325+/// test plus all six interior-difference tests against `interior`.
326+/// `px` is `[p3, p2, p1, p0, q0, q1, q2, q3]` across the edge.
327+#[inline]
328+fn normal_threshold(px: &[i32; 8], center_limit: i32, interior: i32) -> bool {
329+ let [_, p2, p1, p0, q0, q1, q2, _] = *px;
330+ simple_threshold(p1, p0, q0, q1, center_limit)
331+ && (px[0] - p2).abs() <= interior
332+ && (p2 - p1).abs() <= interior
333+ && (p1 - p0).abs() <= interior
334+ && (px[7] - q2).abs() <= interior
335+ && (q2 - q1).abs() <= interior
336+ && (q1 - q0).abs() <= interior
337+}
338+
339+/// dixie `high_edge_variance` (RFC §15.3 `hev`).
340+#[inline]
341+fn high_edge_variance(p1: i32, p0: i32, q0: i32, q1: i32, hev_threshold: i32) -> bool {
342+ (p1 - p0).abs() > hev_threshold || (q1 - q0).abs() > hev_threshold
343+}
344+
345+/// dixie `filter_common` (RFC §15.3 `common_adjust`).
346+///
347+/// `use_outer_taps` is true for the simple filter and for high-variance
348+/// edges. Returns `[p1, p0, q0, q1]`; the returned `p1`/`q1` equal the
349+/// inputs unless `!use_outer_taps` (subblock filter adjusts the inner
350+/// taps by half the edge adjustment).
351+fn filter_common(p1: i32, p0: i32, q0: i32, q1: i32, use_outer_taps: bool) -> [i32; 4] {
352+ let mut a = 3 * (q0 - p0);
353+ if use_outer_taps {
354+ a += sat_i8(p1 - q1);
355+ }
356+ a = sat_i8(a);
357+ // dixie clamps only the top here; a ≥ -128 makes a bottom clamp dead
358+ // code, and the arithmetic `>> 3` reproduces the C rounding exactly.
359+ let f1 = (if a + 4 > 127 { 127 } else { a + 4 }) >> 3;
360+ let f2 = (if a + 3 > 127 { 127 } else { a + 3 }) >> 3;
361+ let p0 = sat_u8(p0 + f2);
362+ let q0 = sat_u8(q0 - f1);
363+ let (p1, q1) = if !use_outer_taps {
364+ let a = (f1 + 1) >> 1;
365+ (sat_u8(p1 + a), sat_u8(q1 - a))
366+ } else {
367+ (p1, q1)
368+ };
369+ [p1, p0, q0, q1]
370+}
371+
372+/// dixie `filter_mb_edge` (RFC §15.3 `MBfilter`, non-hev branch): `w` is
373+/// "twice the edge difference" and the 27/18/9 coefficients approximate
374+/// 3/7, 2/7, 1/7 of it. Returns `[p2, p1, p0, q0, q1, q2]`.
375+fn filter_mb_edge(p2: i32, p1: i32, p0: i32, q0: i32, q1: i32, q2: i32) -> [i32; 6] {
376+ let w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0));
377+ let a = (27 * w + 63) >> 7;
378+ let (p0, q0) = (sat_u8(p0 + a), sat_u8(q0 - a));
379+ let a = (18 * w + 63) >> 7;
380+ let (p1, q1) = (sat_u8(p1 + a), sat_u8(q1 - a));
381+ let a = (9 * w + 63) >> 7;
382+ let (p2, q2) = (sat_u8(p2 + a), sat_u8(q2 - a));
383+ [p2, p1, p0, q0, q1, q2]
384+}
385+
386+// ---------------------------------------------------------------------------
387+// Edge walkers. `anchor` is the flat index of the edge's q0 sample in the
388+// first row (V edges) / column (H edges); `size` is the number of 8-pixel
389+// segments (2 = 16-pixel Y MB edge, 1 = 8-pixel chroma / subblock edge).
390+// Frame-boundary guarantees (anchor ≥ 4 samples from the plane edge) are
391+// established by `filter_frame_ex`'s `col > 0` / `row > 0` guards.
392+// ---------------------------------------------------------------------------
393+
394+/// dixie `filter_mb_v_edge`: vertical MB edge, normal filter.
395+fn filter_mb_v_edge(
396+ plane: &mut [u8],
397+ stride: usize,
398+ anchor: usize,
399+ center_limit: i32,
400+ interior: i32,
401+ hev: i32,
402+ size: usize,
403+) {
404+ for row in 0..8 * size {
405+ let a = anchor + row * stride;
406+ debug_assert!(a >= 4 && a + 3 < plane.len());
407+ let px = [
408+ i32::from(plane[a - 4]),
409+ i32::from(plane[a - 3]),
410+ i32::from(plane[a - 2]),
411+ i32::from(plane[a - 1]),
412+ i32::from(plane[a]),
413+ i32::from(plane[a + 1]),
414+ i32::from(plane[a + 2]),
415+ i32::from(plane[a + 3]),
416+ ];
417+ if !normal_threshold(&px, center_limit, interior) {
418+ continue;
419+ }
420+ let [_, p2, p1, p0, q0, q1, q2, _] = px;
421+ if high_edge_variance(p1, p0, q0, q1, hev) {
422+ // dixie: filter_common with outer taps (p1/q1 unchanged).
423+ let f = filter_common(p1, p0, q0, q1, true);
424+ plane[a - 2] = f[0] as u8;
425+ plane[a - 1] = f[1] as u8;
426+ plane[a] = f[2] as u8;
427+ plane[a + 1] = f[3] as u8;
428+ } else {
429+ let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);
430+ plane[a - 3] = m[0] as u8;
431+ plane[a - 2] = m[1] as u8;
432+ plane[a - 1] = m[2] as u8;
433+ plane[a] = m[3] as u8;
434+ plane[a + 1] = m[4] as u8;
435+ plane[a + 2] = m[5] as u8;
436+ }
437+ }
438+}
439+
440+/// dixie `filter_subblock_v_edge`: vertical subblock edge, normal filter.
441+fn filter_subblock_v_edge(
442+ plane: &mut [u8],
443+ stride: usize,
444+ anchor: usize,
445+ center_limit: i32,
446+ interior: i32,
447+ hev: i32,
448+ size: usize,
449+) {
450+ for row in 0..8 * size {
451+ let a = anchor + row * stride;
452+ debug_assert!(a >= 4 && a + 3 < plane.len());
453+ let px = [
454+ i32::from(plane[a - 4]),
455+ i32::from(plane[a - 3]),
456+ i32::from(plane[a - 2]),
457+ i32::from(plane[a - 1]),
458+ i32::from(plane[a]),
459+ i32::from(plane[a + 1]),
460+ i32::from(plane[a + 2]),
461+ i32::from(plane[a + 3]),
462+ ];
463+ if normal_threshold(&px, center_limit, interior) {
464+ let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev);
465+ let f = filter_common(px[2], px[3], px[4], px[5], outer);
466+ plane[a - 2] = f[0] as u8;
467+ plane[a - 1] = f[1] as u8;
468+ plane[a] = f[2] as u8;
469+ plane[a + 1] = f[3] as u8;
470+ }
471+ }
472+}
473+
474+/// dixie `filter_mb_h_edge`: horizontal MB edge, normal filter.
475+fn filter_mb_h_edge(
476+ plane: &mut [u8],
477+ stride: usize,
478+ anchor: usize,
479+ center_limit: i32,
480+ interior: i32,
481+ hev: i32,
482+ size: usize,
483+) {
484+ for i in 0..8 * size {
485+ let a = anchor + i;
486+ debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len());
487+ let px = [
488+ i32::from(plane[a - 4 * stride]),
489+ i32::from(plane[a - 3 * stride]),
490+ i32::from(plane[a - 2 * stride]),
491+ i32::from(plane[a - stride]),
492+ i32::from(plane[a]),
493+ i32::from(plane[a + stride]),
494+ i32::from(plane[a + 2 * stride]),
495+ i32::from(plane[a + 3 * stride]),
496+ ];
497+ if !normal_threshold(&px, center_limit, interior) {
498+ continue;
499+ }
500+ let [_, p2, p1, p0, q0, q1, q2, _] = px;
501+ if high_edge_variance(p1, p0, q0, q1, hev) {
502+ let f = filter_common(p1, p0, q0, q1, true);
503+ plane[a - 2 * stride] = f[0] as u8;
504+ plane[a - stride] = f[1] as u8;
505+ plane[a] = f[2] as u8;
506+ plane[a + stride] = f[3] as u8;
507+ } else {
508+ let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);
509+ plane[a - 3 * stride] = m[0] as u8;
510+ plane[a - 2 * stride] = m[1] as u8;
511+ plane[a - stride] = m[2] as u8;
512+ plane[a] = m[3] as u8;
513+ plane[a + stride] = m[4] as u8;
514+ plane[a + 2 * stride] = m[5] as u8;
515+ }
516+ }
517+}
518+
519+/// dixie `filter_subblock_h_edge`: horizontal subblock edge, normal filter.
520+fn filter_subblock_h_edge(
521+ plane: &mut [u8],
522+ stride: usize,
523+ anchor: usize,
524+ center_limit: i32,
525+ interior: i32,
526+ hev: i32,
527+ size: usize,
528+) {
529+ for i in 0..8 * size {
530+ let a = anchor + i;
531+ debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len());
532+ let px = [
533+ i32::from(plane[a - 4 * stride]),
534+ i32::from(plane[a - 3 * stride]),
535+ i32::from(plane[a - 2 * stride]),
536+ i32::from(plane[a - stride]),
537+ i32::from(plane[a]),
538+ i32::from(plane[a + stride]),
539+ i32::from(plane[a + 2 * stride]),
540+ i32::from(plane[a + 3 * stride]),
541+ ];
542+ if normal_threshold(&px, center_limit, interior) {
543+ let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev);
544+ let f = filter_common(px[2], px[3], px[4], px[5], outer);
545+ plane[a - 2 * stride] = f[0] as u8;
546+ plane[a - stride] = f[1] as u8;
547+ plane[a] = f[2] as u8;
548+ plane[a + stride] = f[3] as u8;
549+ }
550+ }
551+}
552+
553+/// dixie `filter_v_edge_simple`: vertical edge, simple filter (2-tap;
554+/// consumes the combined limit directly, touches only p0/q0).
555+fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) {
556+ for row in 0..16 {
557+ let a = anchor + row * stride;
558+ debug_assert!(a >= 2 && a + 1 < plane.len());
559+ let p1 = i32::from(plane[a - 2]);
560+ let p0 = i32::from(plane[a - 1]);
561+ let q0 = i32::from(plane[a]);
562+ let q1 = i32::from(plane[a + 1]);
563+ if simple_threshold(p1, p0, q0, q1, limit) {
564+ let f = filter_common(p1, p0, q0, q1, true);
565+ plane[a - 1] = f[1] as u8;
566+ plane[a] = f[2] as u8;
567+ }
568+ }
569+}
570+
571+/// dixie `filter_h_edge_simple`: horizontal edge, simple filter.
572+fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) {
573+ for i in 0..16 {
574+ let a = anchor + i;
575+ debug_assert!(a >= 2 * stride && a + stride < plane.len());
576+ let p1 = i32::from(plane[a - 2 * stride]);
577+ let p0 = i32::from(plane[a - stride]);
578+ let q0 = i32::from(plane[a]);
579+ let q1 = i32::from(plane[a + stride]);
580+ if simple_threshold(p1, p0, q0, q1, limit) {
581+ let f = filter_common(p1, p0, q0, q1, true);
582+ plane[a - stride] = f[1] as u8;
583+ plane[a] = f[2] as u8;
584+ }
585+ }
586+}
587+
588+#[cfg(test)]
589+mod tests {
590+ use super::*;
591+
592+ // -----------------------------------------------------------------------
593+ // Python reference model — the SAME integer math used to derive every
594+ // expected vector below (transcribed from dixie_loopfilter.c, RFC 6386
595+ // §20.6; control params from §15.4 / libvpx vp8_loopfilter.c). Run to
596+ // regenerate the constants in these tests.
597+ //
598+ // def sat_i8(x): return -128 if x < -128 else (127 if x > 127 else x)
599+ // def sat_u8(x): return 0 if x < 0 else (255 if x > 255 else x)
600+ //
601+ // def simple_threshold(p1, p0, q0, q1, limit):
602+ // return (abs(p0 - q0) * 2 + (abs(p1 - q1) >> 1)) <= limit
603+ //
604+ // def normal_threshold(p3, p2, p1, p0, q0, q1, q2, q3, E, I):
605+ // return simple_threshold(p1, p0, q0, q1, 2 * E + I) and \
606+ // abs(p3 - p2) <= I and abs(p2 - p1) <= I and abs(p1 - p0) <= I and \
607+ // abs(q3 - q2) <= I and abs(q2 - q1) <= I and abs(q1 - q0) <= I
608+ //
609+ // def high_edge_variance(p1, p0, q0, q1, t):
610+ // return abs(p1 - p0) > t or abs(q1 - q0) > t
611+ //
612+ // def filter_common(p1, p0, q0, q1, outer):
613+ // a = 3 * (q0 - p0)
614+ // if outer: a += sat_i8(p1 - q1)
615+ // a = sat_i8(a)
616+ // f1 = (127 if a + 4 > 127 else a + 4) >> 3
617+ // f2 = (127 if a + 3 > 127 else a + 3) >> 3
618+ // p0 = sat_u8(p0 + f2); q0 = sat_u8(q0 - f1)
619+ // if not outer:
620+ // a = (f1 + 1) >> 1
621+ // p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a)
622+ // return p1, p0, q0, q1
623+ //
624+ // def filter_mb_edge(p2, p1, p0, q0, q1, q2):
625+ // w = sat_i8(sat_i8(p1 - q1) + 3 * (q0 - p0))
626+ // a = (27 * w + 63) >> 7; p0 = sat_u8(p0 + a); q0 = sat_u8(q0 - a)
627+ // a = (18 * w + 63) >> 7; p1 = sat_u8(p1 + a); q1 = sat_u8(q1 - a)
628+ // a = (9 * w + 63) >> 7; p2 = sat_u8(p2 + a); q2 = sat_u8(q2 - a)
629+ // return p2, p1, p0, q0, q1, q2
630+ //
631+ // def interior_limit(level, sharpness):
632+ // il = level
633+ // if sharpness:
634+ // il >>= (2 if sharpness > 4 else 1)
635+ // if il > 9 - sharpness: il = 9 - sharpness
636+ // return il if il >= 1 else 1
637+ //
638+ // def hev_threshold(level, key):
639+ // if key: return 2 if level >= 40 else (1 if level >= 15 else 0)
640+ // return 3 if level >= 40 else (2 if level >= 20 else (1 if level >= 15 else 0))
641+ //
642+ // # update_sharpness: inside = lvl >> (s>0) >> (s>4), capped at 9-s
643+ // # (only when s>0), min 1; lim=inside, blim=2*lvl+inside,
644+ // # mblim=2*(lvl+2)+inside.
645+ // #
646+ // # Edge walkers mirror the Rust walkers: per row (V) / column (H),
647+ // # threshold -> hev ? filter_common(outer=True) : filter_mb_edge for
648+ // # MB edges, threshold -> filter_common(hev) for subblock edges,
649+ // # threshold -> filter_common(True) touching p0/q0 only for simple.
650+ // # Driver: row-major MBs, per MB [V-mb, V+4, V+8, V+12, H-mb,
651+ // # H+4r, H+8r, H+12r] guarded by col>0 / inner / row>0 / inner
652+ // # (dixie filter_row_normal / filter_row_simple).
653+ // -----------------------------------------------------------------------
654+
655+ /// Decode a (possibly newline-wrapped) hex string into bytes.
656+ fn unhex(s: &str) -> Vec<u8> {
657+ let hexed: String = s.chars().filter(char::is_ascii_hexdigit).collect();
658+ (0..hexed.len() / 2)
659+ .map(|i| u8::from_str_radix(&hexed[2 * i..2 * i + 2], 16).unwrap())
660+ .collect()
661+ }
662+
663+ /// The shared 2x2-MB driver scene: `y = (x*7) ^ (y*13 + 37)`,
664+ /// `u = x*3 + y*5 + 11`, `v = x*5 + y*3 + 77` (all mod 256).
665+ fn scene() -> (Vec<u8>, Vec<u8>, Vec<u8>) {
666+ let (stride, uv_stride) = (32usize, 16usize);
667+ let mut y = vec![0u8; stride * 32];
668+ let mut u = vec![0u8; uv_stride * 16];
669+ let mut v = vec![0u8; uv_stride * 16];
670+ for ty in 0..32usize {
671+ for tx in 0..32usize {
672+ y[ty * stride + tx] = (((tx * 7) ^ (ty * 13 + 37)) & 0xFF) as u8;
673+ }
674+ }
675+ for ty in 0..16usize {
676+ for tx in 0..16usize {
677+ u[ty * uv_stride + tx] = ((tx * 3 + ty * 5 + 11) & 0xFF) as u8;
678+ v[ty * uv_stride + tx] = ((tx * 5 + ty * 3 + 77) & 0xFF) as u8;
679+ }
680+ }
681+ (y, u, v)
682+ }
683+
684+ const NORMAL_Y: &str = "\
685+25222b3039060f141d1a6368717e474c55525ba0a9b6bf848d8a9398e1eef7fc32353c272e1118030a0d747f6669505b42454cb7bea1a8939a9d848ff6f9e0eb
686+3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4b4259506f667d74730a0118172e253c3b32c9c0dfd6ede4e3faf188879e95
687+595e574c457a736861661f140d023b30292e27dcd5cac3f8f1f6efe49d928b80666168737a454c575e59202b323d040f161118e3eaf5fcc7cec9d0dba2adb4bf
688+73747d666f5059424b4c353e2728111a03040df6ffe0e9d2dbdcc5ceb7b8a1aa80878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b5259
689+8d8a839891aea7bcb5b2cbc0d9d6efe4fdfaf308011e172c25223b3049465f549a9d948f86b9b0aba2a5dcd7cec1f8f3eaede41f1609003b32352c275e514843
690+a7a0a9b2bb848d969f98e1eaf3fcc5ced7d0d9222b343d060f08111a636c757eb4b3baa1a8979e858c8bf2f9e0efd6ddc4c3ca3138272e151c1b0209707f666d
691+c1c6cfd4dde2ebf0f9fe878c959aa3a8b1b6bf444d525b60696e777c050a1318cec9c0dbd2ede4fff6f188839a95aca7beb9b04b425d546f666178730a051c17
692+dbdcd5cec7f8f1eae3e49d968f80b9b2abaca55e5748417a73746d661f100902e8efe6fdf4cbc2d9d0d7aea5bcb38a81989f966d647b724940475e552c233a31
693+f5f2fbe0e9d6dfc4cdcab3b8a1ae979c85828b7079666f545d5a4348313e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db
694+0f08011a132c253e373049425b546d667f78718a839c95aea7a0b9b2cbc4ddd61c1b1209003f362d24235a5148477e756c6b6299908f86bdb4b3aaa1d8d7cec5
695+292e273c350a031811166f647d724b40595e57aca5bab38881869f94ede2fbf0363138232a151c070e09707b626d545f464148b3baa5ac979e99808bf2fde4ef
696+43444d565f6069727b7c050e1718212a33343dc6cfd0d9e2ebecf5fe8788919a50575e454c737a61686f161d040b323920272ed5dcc3caf1f8ffe6ed949b8289
697+5d5a5348417e776c65621b1009063f342d2a23d8d1cec7fcf5f2ebe099968f846a6d647f7649405b52552c273e3108031a1d14efe6f9f0cbc2c5dcd7aea1b8b3
698+777079626b545d464f48313a232c151e070009f2fbe4edd6dfd8c1cab3bca5ae84838a9198a7aeb5bcbbc2c9d0dfe6edf4f3fa0108171e252c2b3239404f565d
699+91969f848db2bba0a9aed7dcc5caf3f8e1e6ef141d020b30393e272c555a43489e99908b82bdb4afa6a1d8d3cac5fcf7eee9e01b120d043f363128235a554c47
700+abaca5beb788819a9394ede6fff0c9c2dbdcd52e2738310a03041d166f607972b8bfb6ada49b92898087fef5ece3dad1c8cfc63d342b221910170e057c736a61";
701+
702+ const NORMAL_U: &str = "\
703+0b0e1114171a1d202326292c2f323538101316191c1f2225282b2e3134373a3d15181b1e2124272a2d303336393c3f421a1d202326292c2f3235383b3e414447
704+1f2225282b2e3134373a3d404346494c24272a2d303336393c3f4245484b4e51292c2f3235383b3e4144474a4d5053562e3134373a3d404346494c4f5255585b
705+3336393c3f4245484b4e5154575a5d60383b3e4144474a4d505356595c5f62653d404346494c4f5255585b5e6164676a4245484b4e5154575a5d606366696c6f
706+474a4d505356595c5f6265686b6e71744c4f5255585b5e6164676a6d707376795154575a5d606366696c6f7275787b7e56595c5f6265686b6e7174777a7d8083";
707+
708+ const NORMAL_V: &str = "\
709+4d52575c61666b70757a7f84898e939850555a5f64696e73787d82878c91969b53585d62676c71767b80858a8f94999e565b60656a6f74797e83888d92979ca1
710+595e63686d72777c81868b90959a9fa45c61666b70757a7f84898e93989da2a75f64696e73787d82878c91969ba0a5aa62676c71767b80858a8f94999ea3a8ad
711+656a6f74797e83888d92979ca1a6abb0686d72777c81868b90959a9fa4a9aeb36b70757a7f84898e93989da2a7acb1b66e73787d82878c91969ba0a5aaafb4b9
712+71767b80858a8f94999ea3a8adb2b7bc74797e83888d92979ca1a6abb0b5babf777c81868b90959a9fa4a9aeb3b8bdc27a7f84898e93989da2a7acb1b6bbc0c5";
713+
714+ const SIMPLE_Y: &str = "\
715+25222b3831060f161b1a6368717e474e53525ba0a9b6bf8e838a9398e1eef7fc32353c2f26111807060d74776e6950534a454cafc6a1a897969d848ff6f9e0eb
716+3f38312a231c150e070079726b645d564f4841bab3aca59e97908982fbf4ede64c4d4250596e647879730a0816172e343a3d33cbc0dfd6e4eae3edf188949e95
717+595c57454c7b756762661f1507023b27252c26dad5cac3f3f9f6fce49d858b806661687a73454c585d59202a333d0410151118e3eaf5fcd0c5c9d0dba2adb4bf
718+73747d6f66505947464c35372e2811130a040df6ffe0e9d7d6dcc5c7beb8a1aa8083879096a39eb1adbfc6cdd4dbe2e9f0f7fe050c131a21282f363d4f4b5259
719+8d8e8a959faeb3b8c4b2cbc8d1d6efecf5faf308011e172829223b3836465f549a9d94878eb9b0a9a4a5dcd7cec1f8f1ecede41f160900313c352c275e514843
720+a7a0a9bab3848d989d98e1eaf3fcc5d0d5d0d9222b343d100508111a636c757eb4b5bfa8a1979e8a878bf2f0e9efd6d6cbc1cb333d272e1a171b0209707f666d
721+c1c4cad5dce2ebf1f8fe878d949aa3a9b0b8be4248525b61686e777c050a1318cec9c0d2dbede4fafbf1888a9395acaeb7b9b04b425d546a6b6178730a051c17
722+dbdcd5c7cef8f1e9e4e49d978e80b9b1acaca55e574841717c746d661f100902e8efe6fdf4cbc2d3d6d7bbb7b7b68a87979f976c627b664a3e475e552c233a31
723+f5f2fbe8e1d6dfcac7caa6a6a6ab979686828a7973667b5b575a4340393e272c02050c171e2128333a3d444f5659606b72757c878e9198a3aaadb4bfc6c9d0db
724+0f0801121b2c253a3b30494a53546d6e777871828b9c95aaaba0b9bac3c4ddd61c1d1200093f362c26235a5049477e746d6d6390988f86b4bdb3ada2d8d4cec5
725+292c273d340a031315166f6d74724b47525c56aca6bab38b7e869c93ede5fbf03631382a23151c0c090970726b6d54584d4148b3baa5ac9c9999808bf2fde4ef
726+43444d575e6069737a7c050f1618212b32343dc6cfd0d9e3eaecf5fe8788919a5053573e487a7e6b696f130f07063a3c292b2fd1d5c2c6f2ffffebed91968284
727+5d5e5a474d77736660621e160e0b3731242622dcd8cfcbeff7f2e6e09c9b8f896a6d647f7649405558552c2f36310809141d14efe6f9f0cdc0c5dcd7aea1b8b3
728+7770796a63545d4c494831322b2c15180d0009f2fbe4eddcd9d8c1c2bbbca5ae84858f898fa7aeb6bbbbc2c8d1dfe6eef3f3fa0108171e262b2b3238414f565d
729+91949a8c96b2bba5a4aed7d5cccaf3f1e8e6ef141d020b2d3c3e272c555a43489e9990828bbdb4aea7a1d8d2cbc5fcf6efe9e01b120d04363f3128235a554c47
730+abaca5bfb68881959894edeff6f0c9c9d4dcd52e2738310d00041d166f607972b8bfb6ada49b92878287fef5ece3dacfcacfc63d342b221712170e057c736a61";
731+
732+ /// Table sanity: lengths plus entries hand-derived from libvpx
733+ /// `vp8_loop_filter_update_sharpness` (vp8/common/vp8_loopfilter.c
734+ /// L49-75): inside = lvl >> (s>0) >> (s>4), capped at 9-s when s>0,
735+ /// min 1; lim=inside, blim=2*lvl+inside, mblim=2*(lvl+2)+inside.
736+ #[test]
737+ fn sharpness_tables_match_libvpx() {
738+ let t0 = LoopFilterTables::update_sharpness(0);
739+ assert_eq!(t0.lim.len(), 64);
740+ assert_eq!(t0.blim.len(), 64);
741+ assert_eq!(t0.mblim.len(), 64);
742+ // sharpness 0: lvl 0 -> (1, 1, 5), lvl 1 -> (1, 3, 7),
743+ // lvl 15 -> (15, 45, 49), lvl 63 -> (63, 189, 193).
744+ assert_eq!((t0.lim[0], t0.blim[0], t0.mblim[0]), (1, 1, 5));
745+ assert_eq!((t0.lim[1], t0.blim[1], t0.mblim[1]), (1, 3, 7));
746+ assert_eq!((t0.lim[15], t0.blim[15], t0.mblim[15]), (15, 45, 49));
747+ assert_eq!((t0.lim[63], t0.blim[63], t0.mblim[63]), (63, 189, 193));
748+ // sharpness 5: inside = lvl >> 2 capped at 4:
749+ // lvl 3 -> (1, 7, 11), lvl 20 -> (4, 44, 48), lvl 63 -> (4, 130, 134).
750+ let t5 = LoopFilterTables::update_sharpness(5);
751+ assert_eq!((t5.lim[3], t5.blim[3], t5.mblim[3]), (1, 7, 11));
752+ assert_eq!((t5.lim[20], t5.blim[20], t5.mblim[20]), (4, 44, 48));
753+ assert_eq!((t5.lim[63], t5.blim[63], t5.mblim[63]), (4, 130, 134));
754+ // sharpness 7: inside capped at 2:
755+ // lvl 4 -> (1, 9, 13), lvl 20 -> (2, 42, 46).
756+ let t7 = LoopFilterTables::update_sharpness(7);
757+ assert_eq!((t7.lim[4], t7.blim[4], t7.mblim[4]), (1, 9, 13));
758+ assert_eq!((t7.lim[20], t7.blim[20], t7.mblim[20]), (2, 42, 46));
759+ // The standalone helper must agree with the table for every level.
760+ for sharpness in 0..=7u8 {
761+ let t = LoopFilterTables::update_sharpness(sharpness);
762+ for level in 0..=63u8 {
763+ assert_eq!(
764+ interior_limit(level, sharpness),
765+ i32::from(t.lim[level as usize])
766+ );
767+ }
768+ }
769+ }
770+
771+ /// §15.4 hev table (libvpx `lf_init_lut`): key 0/1/1/2 and inter
772+ /// 0/1/2/3 at levels 0/15/20/40 respectively.
773+ #[test]
774+ fn hev_threshold_table() {
775+ for level in [0u8, 14, 15, 19, 20, 39, 40, 63] {
776+ let l = i32::from(level);
777+ let want_key = if l >= 40 {
778+ 2
779+ } else if l >= 15 {
780+ 1
781+ } else {
782+ 0
783+ };
784+ let want_inter = if l >= 40 {
785+ 3
786+ } else if l >= 20 {
787+ 2
788+ } else if l >= 15 {
789+ 1
790+ } else {
791+ 0
792+ };
793+ assert_eq!(hev_threshold(level, true), want_key);
794+ assert_eq!(hev_threshold(level, false), want_inter);
795+ }
796+ assert_eq!(hev_threshold(39, true), 1);
797+ assert_eq!(hev_threshold(39, false), 2);
798+ }
799+
800+ /// Level 0 disables all filtering: a noisy frame is byte-identical.
801+ #[test]
802+ fn level_zero_disables_filtering() {
803+ let (y0, u0, v0) = scene();
804+ let mut y = y0.clone();
805+ let mut u = u0.clone();
806+ let mut v = v0.clone();
807+ filter_frame(
808+ &mut y,
809+ &mut u,
810+ &mut v,
811+ 32,
812+ 16,
813+ 2,
814+ 2,
815+ 1,
816+ false,
817+ &[MbFilterInfo {
818+ level: 0,
819+ inner_edges: true,
820+ }; 4],
821+ );
822+ assert_eq!(y, y0);
823+ assert_eq!(u, u0);
824+ assert_eq!(v, v0);
825+ }
826+
827+ /// Kernel: normal filter, vertical MB edge, non-hev wide path.
828+ /// Level 30, sharpness 0 -> interior 30, mblim = 2*32+30 = 94, hev = 2.
829+ /// Patch: cols < 16 = 110, cols >= 16 = 130. Python model row:
830+ /// w = sat_i8(-20 + 3*20) = 40; a27 = (1080+63)>>7 = 8, a18 = 6,
831+ /// a9 = 3 -> [110, 113, 116, 118 | 122, 124, 127, 130] at cols 12..19.
832+ #[test]
833+ fn mb_v_edge_normal_filter_kernel() {
834+ let mut y = vec![0u8; 32 * 16];
835+ for r in 0..16 {
836+ for c in 0..32 {
837+ y[r * 32 + c] = if c < 16 { 110 } else { 130 };
838+ }
839+ }
840+ let mut u = vec![128u8; 16 * 8];
841+ let mut v = vec![128u8; 16 * 8];
842+ filter_frame(
843+ &mut y,
844+ &mut u,
845+ &mut v,
846+ 32,
847+ 16,
848+ 2,
849+ 1,
850+ 0,
851+ false,
852+ &[MbFilterInfo {
853+ level: 30,
854+ inner_edges: false,
855+ }; 2],
856+ );
857+ for r in 0..16 {
858+ assert_eq!(
859+ &y[r * 32 + 12..r * 32 + 20],
860+ &[110, 113, 116, 118, 122, 124, 127, 130],
861+ "row {r}"
862+ );
863+ }
864+ // Flat chroma planes are untouched (all filter deltas are 0).
865+ assert!(u.iter().all(|&b| b == 128));
866+ assert!(v.iter().all(|&b| b == 128));
867+ }
868+
869+ /// Kernel: hev edge takes the simple ±f path (p1/q1 unchanged).
870+ /// Level 15, sharpness 0 -> interior 15, mblim = 2*17+15 = 49, hev = 1.
871+ /// |p1-p0| = 2 > 1 triggers hev; Python model: a = 3*16 - 10 = 38,
872+ /// f1 = 42>>3 = 5, f2 = 41>>3 = 5.
873+ #[test]
874+ fn hev_edge_takes_short_path() {
875+ let mut plane = vec![0u8; 8 * 8];
876+ for r in 0..8 {
877+ plane[r * 8..r * 8 + 8].copy_from_slice(&[101, 101, 102, 100, 116, 112, 112, 113]);
878+ }
879+ // Anchor: q0 at (row 0, col 4); 8 rows, one segment.
880+ filter_mb_v_edge(
881+ &mut plane,
882+ 8,
883+ 4,
884+ 2 * (15 + 2) + 15,
885+ 15,
886+ hev_threshold(15, false),
887+ 1,
888+ );
889+ assert_eq!(&plane[0..8], &[101, 101, 102, 105, 111, 112, 112, 113]);
890+ // Outer-tap path leaves the inner taps alone.
891+ assert_eq!(plane[8 + 2], 102);
892+ assert_eq!(plane[8 + 5], 112);
893+ }
894+
895+ /// Kernel: non-hev subblock edge runs the full path incl. p1/q1.
896+ /// Level 15, sharpness 0 -> interior 15, blim = 2*15+15 = 45.
897+ /// Python model: a = 3*10 = 30, f1 = 34>>3 = 4, f2 = 33>>3 = 4,
898+ /// inner a = (4+1)>>1 = 2.
899+ #[test]
900+ fn subblock_edge_takes_full_three_tap_path() {
901+ let mut plane = vec![0u8; 8 * 8];
902+ for r in 0..8 {
903+ plane[r * 8..r * 8 + 8].copy_from_slice(&[100, 100, 100, 100, 110, 111, 111, 111]);
904+ }
905+ filter_subblock_v_edge(
906+ &mut plane,
907+ 8,
908+ 4,
909+ 2 * 15 + 15,
910+ 15,
911+ hev_threshold(15, false),
912+ 1,
913+ );
914+ assert_eq!(&plane[0..8], &[100, 100, 102, 104, 106, 109, 111, 111]);
915+ }
916+
917+ /// Simple filter: MB edge gets f = 5 (mb_limit = 94), subblock edges
918+ /// are filtered too (no-op on flat interiors), chroma is untouched.
919+ #[test]
920+ fn simple_filter_leaves_chroma_untouched() {
921+ let mut y = vec![0u8; 32 * 16];
922+ for r in 0..16 {
923+ for c in 0..32 {
924+ y[r * 32 + c] = if c < 16 { 110 } else { 130 };
925+ }
926+ }
927+ let mut u = vec![0u8; 16 * 8];
928+ let mut v = vec![0u8; 16 * 8];
929+ for r in 0..8 {
930+ for c in 0..16 {
931+ u[r * 16 + c] = if c < 8 { 100 } else { 150 };
932+ v[r * 16 + c] = if c < 8 { 90 } else { 170 };
933+ }
934+ }
935+ let u_orig = u.clone();
936+ let v_orig = v.clone();
937+ filter_frame(
938+ &mut y,
939+ &mut u,
940+ &mut v,
941+ 32,
942+ 16,
943+ 2,
944+ 1,
945+ 0,
946+ true,
947+ &[MbFilterInfo {
948+ level: 30,
949+ inner_edges: true,
950+ }; 2],
951+ );
952+ // a = 3*20 - 20 = 40 -> f1 = 44>>3 = 5, f2 = 43>>3 = 5.
953+ for r in 0..16 {
954+ assert_eq!(
955+ &y[r * 32 + 12..r * 32 + 20],
956+ &[110, 110, 110, 115, 125, 130, 130, 130],
957+ "row {r}"
958+ );
959+ }
960+ assert_eq!(u, u_orig);
961+ assert_eq!(v, v_orig);
962+ }
963+
964+ /// Full-frame driver, normal filter: 2x2 MBs, level 25, sharpness 1,
965+ /// inner edges on. The whole frame must equal the Python model output
966+ /// byte-for-byte. Sample (17,17) is q1 of MB(1,1)'s V edge and then q1
967+ /// of its H edge — the match proves the dixie visit order
968+ /// (V-MB, subblock-V, H-MB, subblock-H) is reproduced.
969+ #[test]
970+ fn driver_normal_filter_frame_order() {
971+ let (y0, u0, v0) = scene();
972+ let mut y = y0;
973+ let mut u = u0;
974+ let mut v = v0;
975+ filter_frame_ex(
976+ &mut y,
977+ &mut u,
978+ &mut v,
979+ 32,
980+ 16,
981+ 2,
982+ 2,
983+ 1,
984+ false,
985+ &[MbFilterInfo {
986+ level: 25,
987+ inner_edges: true,
988+ }; 4],
989+ false,
990+ );
991+ assert_eq!(y, unhex(NORMAL_Y));
992+ assert_eq!(u, unhex(NORMAL_U));
993+ assert_eq!(v, unhex(NORMAL_V));
994+ assert_eq!(y[17 * 32 + 17], 0x75, "order-probe pixel (17,17)");
995+ }
996+
997+ /// Full-frame driver, simple filter: same scene, Y-only output.
998+ #[test]
999+ fn driver_simple_filter_frame() {
1000+ let (_, u0, v0) = scene();
1001+ let (mut y, _, _) = scene();
1002+ let mut u = u0.clone();
1003+ let mut v = v0.clone();
1004+ filter_frame(
1005+ &mut y,
1006+ &mut u,
1007+ &mut v,
1008+ 32,
1009+ 16,
1010+ 2,
1011+ 2,
1012+ 1,
1013+ true,
1014+ &[MbFilterInfo {
1015+ level: 25,
1016+ inner_edges: true,
1017+ }; 4],
1018+ );
1019+ assert_eq!(y, unhex(SIMPLE_Y));
1020+ assert_eq!(u, u0);
1021+ assert_eq!(v, v0);
1022+ }
1023+
1024+ /// Frame type matters at level 25 (hev 2 inter / 1 key): a near-tap
1025+ /// difference of exactly 2 takes the wide MBfilter path on inter
1026+ /// frames and the hev ±f path on key frames. Python model rows:
1027+ /// inter 6e6f71706f707071, key 6e6e706f70717171.
1028+ #[test]
1029+ fn frame_type_changes_hev_path() {
1030+ let build = || {
1031+ let mut y = vec![0u8; 32 * 16];
1032+ for r in 0..16 {
1033+ for c in 0..32 {
1034+ y[r * 32 + c] = if c == 14 {
1035+ 112
1036+ } else if c < 16 {
1037+ 110
1038+ } else {
1039+ 113
1040+ };
1041+ }
1042+ }
1043+ y
1044+ };
1045+ let mut uy = vec![128u8; 16 * 8];
1046+ let mut vy = vec![128u8; 16 * 8];
1047+ let mut ky = build();
1048+ let mut uk = uy.clone();
1049+ let mut vk = vy.clone();
1050+ let info = [MbFilterInfo {
1051+ level: 25,
1052+ inner_edges: false,
1053+ }; 2];
1054+ let mut inter = build();
1055+ filter_frame_ex(
1056+ &mut inter, &mut uy, &mut vy, 32, 16, 2, 1, 1, false, &info, false,
1057+ );
1058+ filter_frame_ex(
1059+ &mut ky, &mut uk, &mut vk, 32, 16, 2, 1, 1, false, &info, true,
1060+ );
1061+ assert_eq!(&inter[12..20], &[110, 111, 113, 112, 111, 112, 112, 113]);
1062+ assert_eq!(&ky[12..20], &[110, 110, 112, 111, 112, 113, 113, 113]);
1063+ }
1064+}
crates/ec-vp8/src/mc.rsadded+763 -0
@@ -0,0 +1,763 @@
1+//! Motion-compensation inter predictors: reference border extension, 6-tap
2+//! luma prediction, bilinear chroma prediction, and the UMV-border motion
3+//! vector clamps.
4+//!
5+//! Normative source: [RFC 6386] §18.3 (sub-pixel interpolation, two
6+//! separable 1-D passes, each sample `clamp255((a + 64) >> 7)`). The loop
7+//! structure, intermediate widths and the border clamps follow the libvpx
8+//! reference implementation (`vp8/common/filter.c`, `vp8/common/
9+//! reconinter.c`, `vp8/common/extend.c`) sample-for-sample; the per-pass
10+//! 0..=255 clamping of the 6-tap intermediate is mandated by the RFC's
11+//! `interp()` and is what the integer test vectors below pin down.
12+//!
13+//! Reference planes arrive already border-extended by [`extend_plane`]
14+//! (edge replication, `border` = 32 like libvpx's `VP8BORDERINPIXELS`);
15+//! `src` starts at the first byte of the bordered buffer (top-left border
16+//! corner) and visible pixel `(px, py)` therefore lives at
17+//! `src[(py + border) * stride + (px + border)]`.
18+//!
19+//! Motion vectors are `(row, col)` pairs in eighth-pel units (`i16`), and
20+//! the C arithmetic right shifts / two's-complement `& 7` phase extraction
21+//! are reproduced exactly (`i32 >> 3` and `& 7` on negatives).
22+//!
23+//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386
24+
25+/// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes.
26+const VP8_FILTER_WEIGHT: i32 = 128;
27+/// `VP8_FILTER_SHIFT` (filter.c): normalize the 7-bit-precision result.
28+const VP8_FILTER_SHIFT: i32 = 7;
29+
30+/// `vp8_sub_pel_filters[8][6]` (filter.c), indexed by the 0..8 sub-pel phase.
31+const SUB_PEL_FILTERS: [[i32; 6]; 8] = [
32+ [0, 0, 128, 0, 0, 0], // degenerate whole-pel (RFC 6386 §18.3 "filters[0]")
33+ [0, -6, 123, 12, -1, 0],
34+ [2, -11, 108, 36, -8, 1],
35+ [0, -9, 93, 50, -6, 0],
36+ [3, -16, 77, 77, -16, 3],
37+ [0, -6, 50, 93, -9, 0],
38+ [1, -8, 36, 108, -11, 2],
39+ [0, -1, 12, 123, -6, 0],
40+];
41+
42+/// `vp8_bilinear_filters[8][2]` (filter.c); chroma prediction is always
43+/// bilinear (RFC 6386 §19.2).
44+const BILINEAR_FILTERS: [[i32; 2]; 8] = [
45+ [128, 0],
46+ [112, 16],
47+ [96, 32],
48+ [80, 48],
49+ [64, 64],
50+ [48, 80],
51+ [32, 96],
52+ [16, 112],
53+];
54+
55+#[inline]
56+fn clamp255(v: i32) -> i32 {
57+ if v < 0 {
58+ 0
59+ } else if v > 255 {
60+ 255
61+ } else {
62+ v
63+ }
64+}
65+
66+/// Extends the visible `vis_w` x `vis_h` region of `plane` into the `border`
67+/// ring on all four sides by edge replication: every out-of-image sample
68+/// becomes the nearest in-image sample.
69+///
70+/// Port of `copy_and_extend_plane` (extend.c) with `et = el = eb = er =
71+/// border` and `interleave_step = 1`, in place: first the left/right border
72+/// of every visible row is filled from the row's first/last column, then the
73+/// (already side-extended) top and bottom rows are copied into the top and
74+/// bottom borders — which gives the corners their corner pixels, matching
75+/// the C exactly.
76+pub(crate) fn extend_plane(plane: &mut [u8], stride: usize, vis_w: usize, vis_h: usize, border: usize) {
77+ debug_assert!(vis_w >= 1 && vis_h >= 1);
78+ debug_assert!(stride >= border * 2 + vis_w);
79+
80+ let line = border + vis_w + border;
81+
82+ // extend.c: "copy the left and right most columns out".
83+ for r in 0..vis_h {
84+ let base = (border + r) * stride + border;
85+ let first = plane[base];
86+ let last = plane[base + vis_w - 1];
87+ plane[base - border..base].fill(first);
88+ plane[base + vis_w..base + vis_w + border].fill(last);
89+ }
90+
91+ // extend.c: "Now copy the top and bottom lines into each line of the
92+ // respective borders" — src rows are the already side-extended lines.
93+ let top = border * stride;
94+ let bottom = (border + vis_h - 1) * stride;
95+ for i in 0..border {
96+ plane.copy_within(top..top + line, (border - 1 - i) * stride);
97+ plane.copy_within(bottom..bottom + line, (border + vis_h + i) * stride);
98+ }
99+}
100+
101+/// Luma predictor for one `bw` x `bh` block (`bw`,`bh` in 4..=16, multiples
102+/// of 4) whose visible-image top-left pixel is `(x, y)`.
103+///
104+/// Semantics of `vp8_build_inter_predictors_b` /
105+/// `vp8_build_inter16x16_predictors_mby` + `vp8_sixtap_predict*` (reconinter.c,
106+/// filter.c): full-pel start `(x + (mv.1 >> 3), y + (mv.0 >> 3))`, phases
107+/// `fx = mv.1 & 7`, `fy = mv.0 & 7`; a whole-pel MV is a plain copy,
108+/// otherwise the separable 6-tap filter runs horizontally into an `i32`
109+/// intermediate — clamped to 0..=255 per pass like libvpx's `int` `FData` —
110+/// then vertically, both passes computing `(dot + 64) >> 7` and clamping.
111+///
112+/// When `need_clamp` is set, the MV is first passed through
113+/// [`clamp_mv_to_umv_border`].
114+pub(crate) fn predict_luma(
115+ src: &[u8],
116+ stride: usize,
117+ border: usize,
118+ vis_w: usize,
119+ vis_h: usize,
120+ x: usize,
121+ y: usize,
122+ mv: (i16, i16),
123+ need_clamp: bool,
124+ dst: &mut [u8],
125+ dst_stride: usize,
126+ bw: usize,
127+ bh: usize,
128+ bilinear: bool,
129+) {
130+ debug_assert!(bw >= 4 && bw <= 16 && bw % 4 == 0);
131+ debug_assert!(bh >= 4 && bh <= 16 && bh % 4 == 0);
132+
133+ let mut mv = (i32::from(mv.0), i32::from(mv.1));
134+ if need_clamp {
135+ clamp_mv_to_umv_border(&mut mv, x >> 4, y >> 4, vis_w, vis_h);
136+ }
137+
138+ let fx = (mv.1 & 7) as usize;
139+ let fy = (mv.0 & 7) as usize;
140+ let sx = border as i32 + x as i32 + (mv.1 >> 3);
141+ let sy = border as i32 + y as i32 + (mv.0 >> 3);
142+ // 6-tap reads reach 2 before / 3 after the start; the libvpx clamp
143+ // arithmetic keeps those inside the 32-px border.
144+ debug_assert!(sx >= 2 && sy >= 2, "reference read outside bordered plane");
145+ let (sx, sy) = (sx as usize, sy as usize);
146+
147+ if bilinear {
148+ bilinear_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
149+ } else {
150+ sixtap_block(src, stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
151+ }
152+}
153+
154+/// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*,
155+/// filter.c). `(sx, sy)` is the full-pel block origin in the bordered
156+/// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy).
157+fn sixtap_block(
158+ src: &[u8],
159+ stride: usize,
160+ sx: usize,
161+ sy: usize,
162+ fx: usize,
163+ fy: usize,
164+ dst: &mut [u8],
165+ dst_stride: usize,
166+ bw: usize,
167+ bh: usize,
168+) {
169+ if fx == 0 && fy == 0 {
170+ // reconinter.c build_inter_predictors_b / vp8_copy_mem*.
171+ for r in 0..bh {
172+ let s = (sy + r) * stride + sx;
173+ dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]);
174+ }
175+ return;
176+ }
177+
178+ let hf = &SUB_PEL_FILTERS[fx];
179+ let vf = &SUB_PEL_FILTERS[fy];
180+
181+ // filter.c filter_block2d_first_pass on `src - 2*stride`: `bh + 5`
182+ // horizontal lines (2 above the block, 3 below, for the vertical taps).
183+ // Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the
184+ // uniform loop reproduces the C for every phase combination.
185+ let mut tmp = [0i32; 21 * 16]; // C: int FData[21 * 24]
186+ for i in 0..bh + 5 {
187+ let row = (sy + i - 2) * stride + sx - 2;
188+ for j in 0..bw {
189+ let p = row + j;
190+ let acc = i32::from(src[p]) * hf[0]
191+ + i32::from(src[p + 1]) * hf[1]
192+ + i32::from(src[p + 2]) * hf[2]
193+ + i32::from(src[p + 3]) * hf[3]
194+ + i32::from(src[p + 4]) * hf[4]
195+ + i32::from(src[p + 5]) * hf[5]
196+ + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
197+ tmp[i * bw + j] = clamp255(acc >> VP8_FILTER_SHIFT);
198+ }
199+ }
200+
201+ // filter.c filter_block2d_second_pass on `FData + 2*bw`: taps read the
202+ // intermediate rows `r .. r + 5`.
203+ for r in 0..bh {
204+ for c in 0..bw {
205+ let acc = tmp[r * bw + c] * vf[0]
206+ + tmp[(r + 1) * bw + c] * vf[1]
207+ + tmp[(r + 2) * bw + c] * vf[2]
208+ + tmp[(r + 3) * bw + c] * vf[3]
209+ + tmp[(r + 4) * bw + c] * vf[4]
210+ + tmp[(r + 5) * bw + c] * vf[5]
211+ + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
212+ dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;
213+ }
214+ }
215+}
216+
217+/// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*,
218+/// filter.c). The dot products are provably in 0..=255 (taps are
219+/// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's
220+/// bilinear passes store `unsigned short` intermediates and skip the clamp.
221+fn bilinear_block(
222+ src: &[u8],
223+ stride: usize,
224+ sx: usize,
225+ sy: usize,
226+ fx: usize,
227+ fy: usize,
228+ dst: &mut [u8],
229+ dst_stride: usize,
230+ bw: usize,
231+ bh: usize,
232+) {
233+ if fx == 0 && fy == 0 {
234+ for r in 0..bh {
235+ let s = (sy + r) * stride + sx;
236+ dst[r * dst_stride..r * dst_stride + bw].copy_from_slice(&src[s..s + bw]);
237+ }
238+ return;
239+ }
240+
241+ let hf = &BILINEAR_FILTERS[fx];
242+ let vf = &BILINEAR_FILTERS[fy];
243+
244+ // filter.c filter_block2d_bil_first_pass: `bh + 1` rows, horizontal
245+ // taps [0] and [1]. Phase 0 is the exact identity, as above.
246+ let mut tmp = [0u16; 17 * 16]; // C: unsigned short FData[17 * 16]
247+ for i in 0..bh + 1 {
248+ let row = (sy + i) * stride + sx;
249+ for j in 0..bw {
250+ let p = row + j;
251+ let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1]
252+ + (VP8_FILTER_WEIGHT / 2); /* Rounding */
253+ tmp[i * bw + j] = (acc >> VP8_FILTER_SHIFT) as u16;
254+ }
255+ }
256+
257+ // filter.c filter_block2d_bil_second_pass: vertical taps [0] and
258+ // `[width]` (the next intermediate row).
259+ for r in 0..bh {
260+ for c in 0..bw {
261+ let acc = i32::from(tmp[r * bw + c]) * vf[0]
262+ + i32::from(tmp[(r + 1) * bw + c]) * vf[1]
263+ + (VP8_FILTER_WEIGHT / 2); /* Rounding */
264+ dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8;
265+ }
266+ }
267+}
268+
269+/// Chroma predictor for one `bw` x `bh` block whose visible-image top-left
270+/// chroma pixel is `(x, y)`.
271+///
272+/// `mv` is the chroma MV in eighth-CHROMA-pel units (the caller derives it
273+/// from luma per libvpx: round-half-away-from-zero division by 2 (whole MB)
274+/// or sum-then-divide-by-8 (SPLITMV), `& fullpixel_mask`).
275+///
276+/// The interpolation filter is the FRAME's MC filter, exactly like luma:
277+/// `vp8_setup_version` picks six-tap for version 0 (and reserved 4-7) and
278+/// bilinear for versions 1-3 (decodeframe.c:851-860 assigns BOTH
279+/// `subpixel_predict` and `subpixel_predict8x8` from that one switch, and
280+/// reconinter.c uses them for the chroma predicts). `bilinear` is that
281+/// per-frame selection.
282+///
283+/// When `need_clamp` is set, the MV is first passed through
284+/// [`clamp_uvmv_to_umv_border`].
285+pub(crate) fn predict_chroma(
286+ src: &[u8],
287+ uv_stride: usize,
288+ border: usize,
289+ vis_w: usize,
290+ vis_h: usize,
291+ x: usize,
292+ y: usize,
293+ mv: (i16, i16),
294+ need_clamp: bool,
295+ dst: &mut [u8],
296+ dst_stride: usize,
297+ bw: usize,
298+ bh: usize,
299+ bilinear: bool,
300+) {
301+ debug_assert!(bw >= 2 && bw <= 16 && bw % 2 == 0);
302+ debug_assert!(bh >= 2 && bh <= 16 && bh % 2 == 0);
303+
304+ let mut mv = (i32::from(mv.0), i32::from(mv.1));
305+ if need_clamp {
306+ // A right/bottom chroma quadrant starts at x == vis_w; it still
307+ // lives in the last MB, so clamp the derived MB index.
308+ let mb_cols = (vis_w + 15) >> 4;
309+ let mb_rows = (vis_h + 15) >> 4;
310+ let mbc = (x >> 3).min(mb_cols - 1);
311+ let mbr = (y >> 3).min(mb_rows - 1);
312+ clamp_uvmv_to_umv_border(&mut mv, mbc, mbr, vis_w, vis_h);
313+ }
314+
315+ let fx = (mv.1 & 7) as usize;
316+ let fy = (mv.0 & 7) as usize;
317+ let sx = border as i32 + x as i32 + (mv.1 >> 3);
318+ let sy = border as i32 + y as i32 + (mv.0 >> 3);
319+ // 6-tap reads reach 2 before / 3 after the origin.
320+ debug_assert!(sx >= 2 && sy >= 2, "reference read outside bordered plane");
321+ let (sx, sy) = (sx as usize, sy as usize);
322+
323+ if bilinear {
324+ bilinear_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
325+ } else {
326+ sixtap_block(src, uv_stride, sx, sy, fx, fy, dst, dst_stride, bw, bh);
327+ }
328+}
329+
330+/// The macroblock-level UMV border edges in eighth-pel units, exactly the
331+/// decoder's `xd->mb_to_{left,right,top,bottom}_edge` (decodeframe.c:503-532):
332+///
333+/// ```c
334+/// xd->mb_to_top_edge = -((mb_row * 16) << 3);
335+/// xd->mb_to_bottom_edge = ((mb_rows - 1 - mb_row) * 16) << 3;
336+/// xd->mb_to_left_edge = -((mb_col * 16) << 3);
337+/// xd->mb_to_right_edge = ((mb_cols - 1 - mb_col) * 16) << 3;
338+/// ```
339+///
340+/// with `mb_rows`/`mb_cols` the full (partial MB inclusive) MB counts of the
341+/// visible frame. Returns `(left, right, top, bottom)`.
342+fn mb_edges(mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) -> (i32, i32, i32, i32) {
343+ let mb_cols = (vis_w + 15) >> 4;
344+ let mb_rows = (vis_h + 15) >> 4;
345+ debug_assert!(mb_col < mb_cols && mb_row < mb_rows);
346+ let left = -(((mb_col * 16) as i32) << 3);
347+ let right = (((mb_cols - 1 - mb_col) * 16) as i32) << 3;
348+ let top = -(((mb_row * 16) as i32) << 3);
349+ let bottom = (((mb_rows - 1 - mb_row) * 16) as i32) << 3;
350+ (left, right, top, bottom)
351+}
352+
353+/// Port of `clamp_mv_to_umv_border` (reconinter.c:257-278), luma MV in
354+/// eighth-pel units:
355+///
356+/// ```c
357+/// if (mv->col < (xd->mb_to_left_edge - (19 << 3))) {
358+/// mv->col = xd->mb_to_left_edge - (16 << 3);
359+/// } else if (mv->col > xd->mb_to_right_edge + (18 << 3)) {
360+/// mv->col = xd->mb_to_right_edge + (16 << 3);
361+/// }
362+/// /* same for row with top/bottom edges */
363+/// ```
364+///
365+/// 19 px slack toward left/top (16 px + 3 taps right of the central pixel),
366+/// 18 px toward right/bottom (16 px + 2 taps left of it); the clamp anchor
367+/// is 16 px inside the border. `mb_col`/`mb_row` locate the block's
368+/// macroblock; libvpx clamps with these MB-level edges for whole-MB MVs and,
369+/// when `need_to_clamp_mvs` is set, for each SPLITMV subblock MV too
370+/// (reconinter.c:370-375, 397-400).
371+fn clamp_mv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) {
372+ let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h);
373+ if mv.1 < left - (19 << 3) {
374+ mv.1 = left - (16 << 3);
375+ } else if mv.1 > right + (18 << 3) {
376+ mv.1 = right + (16 << 3);
377+ }
378+
379+ if mv.0 < top - (19 << 3) {
380+ mv.0 = top - (16 << 3);
381+ } else if mv.0 > bottom + (18 << 3) {
382+ mv.0 = bottom + (16 << 3);
383+ }
384+}
385+
386+/// Port of `clamp_uvmv_to_umv_border` (reconinter.c:281-295), chroma MV in
387+/// eighth-CHROMA-pel units. The comparison doubles the chroma MV back into
388+/// luma eighth-pel units (`2 * mv->col`, the "different divisor": the
389+/// chroma border reach is half the luma one) and the clamp target is the
390+/// luma anchor halved:
391+///
392+/// ```c
393+/// mv->col = (2 * mv->col < (xd->mb_to_left_edge - (19 << 3)))
394+/// ? (xd->mb_to_left_edge - (16 << 3)) >> 1
395+/// : mv->col;
396+/// mv->col = (2 * mv->col > xd->mb_to_right_edge + (18 << 3))
397+/// ? (xd->mb_to_right_edge + (16 << 3)) >> 1
398+/// : mv->col;
399+/// /* same for row */
400+/// ```
401+///
402+/// The C applies the two ternaries in sequence (right check sees the
403+/// left-clamped value, which cannot trip it); the sequential `if`s here are
404+/// that verbatim. `(left - (16 << 3))` is a multiple of 256 so `>> 1` is
405+/// exact. Callers must re-apply this clamp AFTER full-pel rounding of a
406+/// derived chroma MV: rounding to full-pel can move the MV outside the
407+/// border tap window even though the luma MV was already clamped
408+/// (reconinter.c:336-339 — the 16x16 path clamps the chroma MV
409+/// unconditionally for exactly this reason).
410+fn clamp_uvmv_to_umv_border(mv: &mut (i32, i32), mb_col: usize, mb_row: usize, vis_w: usize, vis_h: usize) {
411+ let (left, right, top, bottom) = mb_edges(mb_col, mb_row, vis_w, vis_h);
412+
413+ if 2 * mv.1 < left - (19 << 3) {
414+ mv.1 = (left - (16 << 3)) >> 1;
415+ }
416+ if 2 * mv.1 > right + (18 << 3) {
417+ mv.1 = (right + (16 << 3)) >> 1;
418+ }
419+
420+ if 2 * mv.0 < top - (19 << 3) {
421+ mv.0 = (top - (16 << 3)) >> 1;
422+ }
423+ if 2 * mv.0 > bottom + (18 << 3) {
424+ mv.0 = (bottom + (16 << 3)) >> 1;
425+ }
426+}
427+
428+#[cfg(test)]
429+mod tests {
430+ use super::*;
431+
432+ /// Deterministic plane fill shared by every test (LCG, same sequence in
433+ /// the hand-computed literals below).
434+ fn lcg_plane(seed: u32, len: usize) -> Vec<u8> {
435+ let mut out = vec![0u8; len];
436+ let mut s = seed;
437+ for b in out.iter_mut() {
438+ s = s.wrapping_mul(1664525).wrapping_add(1013904223);
439+ *b = (s >> 16) as u8;
440+ }
441+ out
442+ }
443+
444+ const BORDER: usize = 32;
445+ const STRIDE: usize = 104; // 40 visible + 2 * 32 border
446+ const VIS_W: usize = 40; // 3 MB columns, last one partial
447+ const VIS_H: usize = 36; // 3 MB rows, last one partial
448+ const ROWS: usize = VIS_H + 2 * BORDER;
449+
450+ fn plane() -> Vec<u8> {
451+ lcg_plane(0x1234, STRIDE * ROWS)
452+ }
453+
454+ /// Reads visible-image pixel (`vx`, `vy`) out of a bordered plane.
455+ fn vis(plane: &[u8], vx: usize, vy: usize) -> u8 {
456+ plane[(vy + BORDER) * STRIDE + (vx + BORDER)]
457+ }
458+
459+ #[test]
460+ fn extend_plane_replicates_edges_and_corners() {
461+ let mut p = plane();
462+ // Distinct visible values, sentinel everywhere else.
463+ for r in 0..VIS_H {
464+ for c in 0..VIS_W {
465+ p[(BORDER + r) * STRIDE + BORDER + c] = ((r * 7 + c * 3) % 251 + 4) as u8;
466+ }
467+ }
468+ p[..BORDER * STRIDE].fill(0xEE);
469+ p[(BORDER + VIS_H) * STRIDE..].fill(0xEE);
470+ for r in 0..VIS_H {
471+ let row = &mut p[(BORDER + r) * STRIDE..(BORDER + r) * STRIDE + STRIDE];
472+ row[..BORDER].fill(0xEE);
473+ row[BORDER + VIS_W..].fill(0xEE);
474+ }
475+
476+ extend_plane(&mut p, STRIDE, VIS_W, VIS_H, BORDER);
477+
478+ // Every sample of the bordered plane equals the nearest in-image sample.
479+ for r in 0..ROWS {
480+ for c in 0..STRIDE {
481+ let vr = r.saturating_sub(BORDER).min(VIS_H - 1);
482+ let vc = c.saturating_sub(BORDER).min(VIS_W - 1);
483+ assert_eq!(p[r * STRIDE + c], vis(&p, vc, vr), "sample ({r},{c})");
484+ }
485+ }
486+ // Explicit corners (worst case of the rule above).
487+ assert_eq!(p[0], vis(&p, 0, 0)); // top-left
488+ assert_eq!(p[line_len() - 1], vis(&p, VIS_W - 1, 0)); // top-right
489+ assert_eq!(p[(ROWS - 1) * STRIDE], vis(&p, 0, VIS_H - 1)); // bottom-left
490+ assert_eq!(
491+ p[ROWS * STRIDE - 1],
492+ vis(&p, VIS_W - 1, VIS_H - 1) // bottom-right
493+ );
494+ // The visible region itself is untouched.
495+ for r in 0..VIS_H {
496+ for c in 0..VIS_W {
497+ assert_eq!(
498+ p[(BORDER + r) * STRIDE + BORDER + c],
499+ ((r * 7 + c * 3) % 251 + 4) as u8
500+ );
501+ }
502+ }
503+ }
504+
505+ fn line_len() -> usize {
506+ BORDER + VIS_W + BORDER
507+ }
508+
509+ #[test]
510+ fn integer_mv_predict_is_a_plain_copy() {
511+ let p = plane();
512+ let mut dst = [0u8; 16 * 16];
513+
514+ // Whole-pel luma MV (row=16, col=-8) → full-pel offset (x-1, y+2).
515+ // mv.0 is the row component, mv.1 the column component. x=y=8 keeps
516+ // every read inside the visible region of the unextended plane.
517+ predict_luma(
518+ &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (16, -8), false, &mut dst, 16, 16, 16,
519+ false);
520+ for r in 0..16 {
521+ for c in 0..16 {
522+ assert_eq!(dst[r * 16 + c], vis(&p, 8 - 1 + c, 8 + 2 + r), "({r},{c})");
523+ }
524+ }
525+
526+ // Zero MV → identity copy.
527+ predict_luma(
528+ &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (0, 0), false, &mut dst, 16, 16, 16,
529+ false);
530+ for r in 0..16 {
531+ for c in 0..16 {
532+ assert_eq!(dst[r * 16 + c], vis(&p, 8 + c, 8 + r), "({r},{c})");
533+ }
534+ }
535+
536+ // Chroma copy path, whole-pel chroma MV (row=-16, col=+8)
537+ // → full-pel offset (x+1, y-2).
538+ let mut dst8 = [0u8; 8 * 8];
539+ predict_chroma(
540+ &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 4, (-16, 8), false, &mut dst8, 8, 8, 8,
541+ false);
542+ for r in 0..8 {
543+ for c in 0..8 {
544+ assert_eq!(dst8[r * 8 + c], vis(&p, 4 + 1 + c, 4 - 2 + r), "({r},{c})");
545+ }
546+ }
547+ }
548+
549+ #[test]
550+ fn sixtap_pure_horizontal_matches_hand_computed_values() {
551+ let p = plane();
552+ let mut dst = [0u8; 4 * 4];
553+
554+ // mv = (0, 4): full-pel start (16, 12), fx = 4, fy = 0.
555+ predict_luma(
556+ &p, STRIDE, BORDER, VIS_W, VIS_H, 16, 12, (0, 4), false, &mut dst, 4, 4, 4, false,
557+ );
558+
559+ // Hand-computed from vp8_sub_pel_filters[4] = { 3, -16, 77, 77, -16, 3 }
560+ // and vp8_sub_pel_filters[0] = { 0, 0, 128, 0, 0, 0 } (vertical is the
561+ // exact identity over the clamped horizontal intermediate).
562+ // out[0][0]: taps are visible pixels (12, 14..19) = [183, 106, 2, 87, 75, 198]:
563+ // 183*3 - 106*16 + 2*77 + 87*77 - 75*16 + 198*3 + 64 = 5164
564+ // 5164 >> 7 = 40, already in 0..=255.
565+ // out[1][2]: taps (13, 17..22) = [153, 188, 219, 13, 86, 194]:
566+ // 153*3 - 188*16 + 219*77 + 13*77 - 86*16 + 194*3 + 64 = 14585
567+ // 14585 >> 7 = 113.
568+ assert_eq!(dst[0], 40);
569+ assert_eq!(dst[1 * 4 + 2], 113);
570+
571+ // Full block against the tap-table reference formula.
572+ for r in 0..4 {
573+ for c in 0..4 {
574+ let taps: Vec<i32> = (0..6)
575+ .map(|k| i32::from(vis(&p, 16 + c - 2 + k as usize, 12 + r)))
576+ .collect();
577+ let acc: i32 = taps
578+ .iter()
579+ .zip(SUB_PEL_FILTERS[4])
580+ .map(|(t, f)| t * f)
581+ .sum::<i32>()
582+ + 64;
583+ assert_eq!(
584+ dst[r * 4 + c],
585+ (acc >> 7).clamp(0, 255) as u8,
586+ "out[{r}][{c}] taps={taps:?} acc={acc}"
587+ );
588+ }
589+ }
590+ }
591+
592+ #[test]
593+ fn sixtap_combined_phase_16x16_matches_hand_computed_values() {
594+ let p = plane();
595+ let mut dst = [0u8; 16 * 16];
596+
597+ // mv = (14, 18): full-pel start (10, 9), fx = 2, fy = 6.
598+ predict_luma(
599+ &p, STRIDE, BORDER, VIS_W, VIS_H, 8, 8, (14, 18), false, &mut dst, 16, 16, 16, false,
600+ );
601+
602+ // vp8_sub_pel_filters[2] = { 2, -11, 108, 36, -8, 1 }, each
603+ // intermediate clamped to 0..=255 (e.g. tmp[3][10] taps
604+ // [75, 190, 18, 15, 104, 40], raw dot -184, -184 >> 7 = -2, clamped 0);
605+ // vertical pass with vp8_sub_pel_filters[6] = { 1, -8, 36, 108, -11, 2 }.
606+ //
607+ // out[0][0]: horizontal taps are visible pixels (7, 8..13), giving the
608+ // post-clamp intermediate column h_tmp = [41, 186, 229, 210, 95, 185]:
609+ // 41*1 - 186*8 + 229*36 + 210*108 - 95*11 + 185*2 + 64 = 28866
610+ // 28866 >> 7 = 225, already in 0..=255.
611+ //
612+ // out[5][9]: horizontal taps are visible pixels (11, 15..20),
613+ // h_tmp = [205, 8, 14, 189, 108, 4]:
614+ // 205*1 - 8*8 + 14*36 + 189*108 - 108*11 + 4*2 + 64 = 19941
615+ // 19941 >> 7 = 155.
616+ assert_eq!(dst[0], 225);
617+ assert_eq!(dst[5 * 16 + 9], 155);
618+
619+ // Full block against the two-pass reference formula.
620+ let mut tmp = [0i32; 21 * 16];
621+ for i in 0..21 {
622+ for j in 0..16 {
623+ let acc: i32 = (0..6)
624+ .map(|k| i32::from(vis(&p, 10 - 2 + j + k, 9 - 2 + i)))
625+ .zip(SUB_PEL_FILTERS[2])
626+ .map(|(t, f)| t * f)
627+ .sum::<i32>()
628+ + 64;
629+ tmp[i * 16 + j] = (acc >> 7).clamp(0, 255);
630+ }
631+ }
632+ for r in 0..16 {
633+ for c in 0..16 {
634+ let acc: i32 = (0..6)
635+ .map(|k| tmp[(r + k) * 16 + c])
636+ .zip(SUB_PEL_FILTERS[6])
637+ .map(|(t, f)| t * f)
638+ .sum::<i32>()
639+ + 64;
640+ assert_eq!(
641+ dst[r * 16 + c],
642+ (acc >> 7).clamp(0, 255) as u8,
643+ "out[{r}][{c}]"
644+ );
645+ }
646+ }
647+ }
648+
649+ #[test]
650+ fn bilinear_chroma_matches_hand_computed_values() {
651+ let p = plane();
652+ let mut dst = [0u8; 8 * 8];
653+
654+ // mv = (11, 5): full-pel start (4, 7), fx = 5, fy = 3.
655+ predict_chroma(
656+ &p, STRIDE, BORDER, VIS_W, VIS_H, 4, 6, (11, 5), false, &mut dst, 8, 8, 8, true,
657+ );
658+
659+ // Horizontal taps { 48, 80 } (phase 5), vertical { 80, 48 } (phase 3),
660+ // both passes (dot + 64) >> 7, no clamp (provably in range).
661+ //
662+ // out[0][0]: tmp[0][0] = (160*48 + 96*80 + 64) >> 7 = 120 from visible
663+ // pixels (4,7),(5,7); tmp[1][0] = (107*48 + 42*80 + 64) >> 7 = 66
664+ // from (4,8),(5,8).
665+ // 120*80 + 66*48 + 64 = 12832, 12832 >> 7 = 100.
666+ // out[3][7]: tmp[3][7] = 84, tmp[4][7] = 189;
667+ // 84*80 + 189*48 + 64 = 15856, 15856 >> 7 = 123.
668+ assert_eq!(dst[0], 100);
669+ assert_eq!(dst[3 * 8 + 7], 123);
670+
671+ // Full block against the two-pass reference formula.
672+ let mut tmp = [0u16; 9 * 8];
673+ for i in 0..9 {
674+ for j in 0..8 {
675+ tmp[i * 8 + j] = ((i32::from(vis(&p, 4 + j, 7 + i)) * 48
676+ + i32::from(vis(&p, 4 + j + 1, 7 + i)) * 80
677+ + 64)
678+ >> 7) as u16;
679+ }
680+ }
681+ for r in 0..8 {
682+ for c in 0..8 {
683+ let acc = i32::from(tmp[r * 8 + c]) * 80 + i32::from(tmp[(r + 1) * 8 + c]) * 48 + 64;
684+ assert_eq!(dst[r * 8 + c], (acc >> 7) as u8, "out[{r}][{c}]");
685+ }
686+ }
687+ }
688+
689+ #[test]
690+ fn umv_border_clamps_match_libvpx_arithmetic() {
691+ let p = plane();
692+ let mut a = [0u8; 16 * 16];
693+ let mut b = [0u8; 16 * 16];
694+
695+ // Single-MB frame (vis 16x16): mb_to_left_edge = mb_to_top_edge = 0,
696+ // mb_to_right_edge = mb_to_bottom_edge = 0.
697+ //
698+ // Luma: mv (-1000, -1000) < 0 - 152 → both components set to -128
699+ // (left - (16 << 3)); prediction must equal an explicit (-128, -128).
700+ predict_luma(
701+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-1000, -1000), true, &mut a, 16, 16, 16,
702+ false);
703+ predict_luma(
704+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16,
705+ false);
706+ assert_eq!(a, b);
707+
708+ // Strict threshold: (-152, -152) is NOT clamped (condition is strict
709+ // `<`), (-153, -153) IS clamped to (-128, -128).
710+ predict_luma(
711+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), true, &mut a, 16, 16, 16,
712+ false);
713+ predict_luma(
714+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-152, -152), false, &mut b, 16, 16, 16,
715+ false);
716+ assert_eq!(a, b);
717+ predict_luma(
718+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-153, -153), true, &mut a, 16, 16, 16,
719+ false);
720+ predict_luma(
721+ &p, STRIDE, BORDER, 16, 16, 0, 0, (-128, -128), false, &mut b, 16, 16, 16,
722+ false);
723+ assert_eq!(a, b);
724+
725+ // Right/bottom: mv (4000, 4000) > 0 + 144 → set to +128.
726+ predict_luma(
727+ &p, STRIDE, BORDER, 16, 16, 0, 0, (4000, 4000), true, &mut a, 16, 16, 16,
728+ false);
729+ predict_luma(
730+ &p, STRIDE, BORDER, 16, 16, 0, 0, (128, 128), false, &mut b, 16, 16, 16,
731+ false);
732+ assert_eq!(a, b);
733+
734+ // Chroma: 2 * (-2000) < -152 → (-128 >> 1) = -64 per component.
735+ let mut ca = [0u8; 8 * 8];
736+ let mut cb = [0u8; 8 * 8];
737+ predict_chroma(
738+ &p, STRIDE, BORDER, 8, 8, 0, 0, (-2000, -2000), true, &mut ca, 8, 8, 8,
739+ false);
740+ predict_chroma(
741+ &p, STRIDE, BORDER, 8, 8, 0, 0, (-64, -64), false, &mut cb, 8, 8, 8,
742+ false);
743+ assert_eq!(ca, cb);
744+
745+ // Chroma right/bottom: 2 * 2000 > 144 → (128 >> 1) = 64.
746+ predict_chroma(
747+ &p, STRIDE, BORDER, 8, 8, 0, 0, (2000, 2000), true, &mut ca, 8, 8, 8,
748+ false);
749+ predict_chroma(
750+ &p, STRIDE, BORDER, 8, 8, 0, 0, (64, 64), false, &mut cb, 8, 8, 8,
751+ false);
752+ assert_eq!(ca, cb);
753+
754+ // An in-range MV with need_clamp=true must pass through untouched.
755+ predict_luma(
756+ &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), true, &mut a, 16, 16, 16, false,
757+ );
758+ predict_luma(
759+ &p, STRIDE, BORDER, 16, 16, 0, 0, (10, -10), false, &mut b, 16, 16, 16, false,
760+ );
761+ assert_eq!(a, b);
762+ }
763+}
crates/ec-vp8/src/modes.rsadded+567 -0
@@ -0,0 +1,567 @@
1+//! Macroblock prediction modes and their coding trees
2+//! (RFC 6386 §8.2, §11.2, §11.4, §16.1).
3+
4+use crate::bool::BoolDecoder;
5+
6+/// Intra macroblock luma modes (RFC 6386 §8.2 enum values are normative;
7+/// chroma modes are the first four).
8+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9+#[repr(u8)]
10+pub enum YMode {
11+ /// Predict DC from the row above and column to the left.
12+ DcPred = 0,
13+ /// Predict rows from the row above.
14+ VPred = 1,
15+ /// Predict columns from the column to the left.
16+ HPred = 2,
17+ /// True-motion (second-difference) prediction.
18+ TmPred = 3,
19+ /// Each 4x4 Y subblock is independently predicted.
20+ BPred = 4,
21+}
22+
23+impl YMode {
24+ /// Value as coded in the trees (the RFC's enum integers).
25+ pub fn as_u8(self) -> u8 {
26+ self as u8
27+ }
28+
29+ /// The subblock mode a 16x16 mode masquerades as for B_PRED context
30+ /// purposes (RFC 6386 §11.3 item 4).
31+ pub fn as_bmode(self) -> BMode {
32+ match self {
33+ YMode::DcPred => BMode::BDCPred,
34+ YMode::VPred => BMode::BVEPred,
35+ YMode::HPred => BMode::BHEPred,
36+ YMode::TmPred => BMode::BTMPred,
37+ YMode::BPred => unreachable!("B_PRED has no single subblock mode"),
38+ }
39+ }
40+}
41+
42+/// The ten 4x4 subblock prediction modes (RFC 6386 §11.2).
43+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44+#[repr(u8)]
45+pub enum BMode {
46+ /// DC from above row and left column.
47+ BDCPred = 0,
48+ /// True-motion.
49+ BTMPred = 1,
50+ /// Vertical from smoothed above row.
51+ BVEPred = 2,
52+ /// Horizontal from smoothed left column.
53+ BHEPred = 3,
54+ /// Down-left diagonal.
55+ BLDPred = 4,
56+ /// Down-right diagonal.
57+ BRDPred = 5,
58+ /// Vertical-right diagonal.
59+ BVRPred = 6,
60+ /// Vertical-left diagonal.
61+ BVLPred = 7,
62+ /// Horizontal-down diagonal.
63+ BHDPred = 8,
64+ /// Horizontal-up diagonal.
65+ BHUPred = 9,
66+}
67+
68+impl BMode {
69+ /// Value as coded in the bmode tree (the RFC's enum integers).
70+ pub fn as_u8(self) -> u8 {
71+ self as u8
72+ }
73+}
74+
75+/// Key-frame Y-mode coding tree (RFC 6386 §11.2): B_PRED, then the four
76+/// full-block modes. Leaf values are the [`YMode`] enum integers.
77+pub const KF_YMODE_TREE: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3];
78+
79+/// Key-frame Y-mode probabilities (fixed; RFC 6386 §11.2 and the
80+/// reference decoder's `kf_y_mode_probs`).
81+pub const KF_YMODE_PROBS: [u8; 4] = [145, 156, 163, 128];
82+
83+/// Interframe Y-mode coding tree (RFC 6386 §8.2).
84+pub const YMODE_TREE: [i8; 8] = [0, 2, 4, 6, -1, -2, -3, -4];
85+
86+/// Chroma-mode coding tree (RFC 6386 §8.2/§11.4): DC, V, H, TM.
87+pub const UV_MODE_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3];
88+
89+/// Key-frame chroma-mode probabilities (fixed; RFC 6386 §11.4).
90+pub const KF_UV_MODE_PROBS: [u8; 3] = [142, 114, 183];
91+
92+/// 4x4 subblock-mode coding tree (RFC 6386 §11.2). Leaf values are the
93+/// [`BMode`] enum integers; note the leaf 0 (B_DC_PRED) relies on the
94+/// tree reader's `i <= 0` leaf test.
95+pub const BMODE_TREE: [i8; 18] = [
96+ 0, 2, // B_DC_PRED = "0"
97+ -1, 4, // B_TM = "10"
98+ -2, 6, // B_VE = "110"
99+ 8, 12, // inner
100+ -3, 10, // B_HE = "11100"
101+ -5, -6, // B_RD = "111010", B_VR = "111011"
102+ -4, 14, // B_LD = "111110"
103+ -7, 16, // B_VL = "1111110"
104+ -8, -9, // B_HD = "11111110", B_HU = "11111111"
105+];
106+
107+/// Subblock modes in interframes decode with this constant probability
108+/// array, no context (RFC 6386 §11.3 item 5 / §16).
109+pub const INTER_BMODE_PROBS: [u8; 9] = [120, 90, 79, 133, 87, 85, 80, 111, 151];
110+
111+/// Decode a key-frame Y mode (RFC 6386 §11.2).
112+pub fn read_kf_ymode(d: &mut BoolDecoder<'_>) -> YMode {
113+ YMode::from_u8(d.read_tree(&KF_YMODE_TREE, &KF_YMODE_PROBS))
114+}
115+
116+/// Decode an interframe Y mode at the persisted probabilities
117+/// (RFC 6386 §16.1; `probs` is the frame header's updated array).
118+pub fn read_ymode(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> YMode {
119+ YMode::from_u8(d.read_tree(&YMODE_TREE, probs))
120+}
121+
122+/// Decode a chroma mode at the given (key-frame fixed or persisted
123+/// interframe) probabilities.
124+pub fn read_uvmode(d: &mut BoolDecoder<'_>, probs: &[u8; 3]) -> YMode {
125+ YMode::from_u8(d.read_tree(&UV_MODE_TREE, probs))
126+}
127+
128+/// Decode a 4x4 subblock mode at `probs` (RFC 6386 §11.3: in key frames
129+/// the probabilities come from the above/left context table).
130+pub fn read_bmode(d: &mut BoolDecoder<'_>, probs: &[u8]) -> BMode {
131+ BMode::from_u8(d.read_tree(&BMODE_TREE, probs))
132+}
133+
134+impl YMode {
135+ fn from_u8(v: u8) -> YMode {
136+ match v {
137+ 0 => YMode::DcPred,
138+ 1 => YMode::VPred,
139+ 2 => YMode::HPred,
140+ 3 => YMode::TmPred,
141+ 4 => YMode::BPred,
142+ _ => unreachable!("tree cannot produce mode {v}"),
143+ }
144+ }
145+}
146+
147+impl BMode {
148+ fn from_u8(v: u8) -> BMode {
149+ match v {
150+ 0 => BMode::BDCPred,
151+ 1 => BMode::BTMPred,
152+ 2 => BMode::BVEPred,
153+ 3 => BMode::BHEPred,
154+ 4 => BMode::BLDPred,
155+ 5 => BMode::BRDPred,
156+ 6 => BMode::BVRPred,
157+ 7 => BMode::BVLPred,
158+ 8 => BMode::BHDPred,
159+ 9 => BMode::BHUPred,
160+ _ => unreachable!("tree cannot produce bmode {v}"),
161+ }
162+ }
163+}
164+
165+/// Inter-frame motion-vector reference modes (RFC 6386 §16.2), offset
166+/// from the intra modes by `num_ymodes` in the reference enum; here they
167+/// are their own small enum with the RFC's tree integers.
168+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169+#[repr(u8)]
170+pub enum MvRef {
171+ /// Zero motion vector ("10" second branch; coded 0).
172+ Zero = 0,
173+ /// "Nearest" vector (coded 1).
174+ Nearest = 1,
175+ /// "Near" vector (coded 2).
176+ Near = 2,
177+ /// Explicit offset from best (coded 3).
178+ New = 3,
179+ /// Per-subblock vectors (coded 4).
180+ Split = 4,
181+}
182+
183+/// mv_ref coding tree (RFC 6386 §16.2): leaves are [`MvRef`] integers.
184+/// mv_ref coding tree (RFC 6386 §16.2); leaves are [`MvRef`] integers.
185+pub const MV_REF_TREE: [i8; 8] = [0, 2, -1, 4, -2, 6, -3, -4];
186+
187+/// Motion-vector component: row then column, each with the 19-probability
188+/// table (§17.1).
189+/// Probability-table offsets of one MV component (RFC 6386 §17.1).
190+pub const MVP_IS_SHORT: usize = 0;
191+/// Sign probability offset (§17.1).
192+pub const MVP_SIGN: usize = 1;
193+/// Short-value tree offset (§17.1).
194+/// Short-value tree offset (§17.1).
195+pub const MVP_SHORT: usize = 2;
196+/// Long-value bit probabilities offset (§17.1).
197+/// Long-value bit probabilities offset (§17.1).
198+pub const MVP_BITS: usize = MVP_SHORT + 7;
199+/// Total probabilities per MV component (§17.1).
200+/// Total probabilities per MV component (§17.1).
201+pub const MVP_COUNT: usize = MVP_BITS + 10;
202+
203+/// Small-value coding tree for MV components (§17.1 `small_mvtree`).
204+/// Small-value coding tree for MV components (§17.1).
205+pub const SMALL_MV_TREE: [i8; 14] = [
206+ 2, 8, // "0" / "1" subtrees
207+ 4, 6, // "00" / "01"
208+ 0, -1, // 0 = "000", 1 = "001"
209+ -2, -3, // 2, 3
210+ 10, 12, // "10" / "11"
211+ -4, -5, // 4, 5
212+ -6, -7, // 6, 7
213+];
214+
215+/// SPLITMV partition shapes tree + fixed probs (§16.4). Leaves are the
216+/// RFC's `MVpartition` integers: 0 = top/bottom, 1 = left/right,
217+/// 2 = quarters, 3 = MV_16.
218+pub const MV_PARTITION_TREE: [i8; 6] = [-3, 2, -2, 4, 0, -1];
219+/// SPLITMV partition tree fixed probabilities (§16.4).
220+pub const MV_PARTITION_PROBS: [u8; 3] = [110, 111, 150];
221+
222+/// The four SPLITMV partitionings as subblock groups (§16.4), indexed
223+/// by the `MVpartition` integer: each group shares one motion vector,
224+/// decoded in the listed (leader) order.
225+pub const MV_PARTITIONS: [&[usize]; 4] = [
226+ // mv_top_bottom: {0..7} then {8..15}.
227+ &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
228+ // mv_left_right: {0,1,4,5,8,9,12,13} then {2,3,6,7,10,11,14,15}.
229+ &[0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15],
230+ // mv_quarters: {0,1,4,5} {2,3,6,7} {8,9,12,13} {10,11,14,15}.
231+ &[0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15],
232+ // MV_16: every subblock gets its own vector, raster order.
233+ &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
234+];
235+
236+/// Number of distinct vectors per partition shape (§16.4).
237+pub const MV_PARTITION_COUNT: [usize; 4] = [2, 2, 4, 16];
238+
239+/// Inter subblock modes (§16.4): reuse the already-coded MV left/above,
240+/// zero, or an explicit offset.
241+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242+#[repr(u8)]
243+pub enum SubMvRef {
244+ /// Copy the left neighbour's MV (coded 0).
245+ Left4x4 = 0,
246+ /// Copy the above neighbour's MV (coded 1).
247+ Above4x4 = 1,
248+ /// Zero MV (coded 2).
249+ Zero4x4 = 2,
250+ /// Explicit offset from best (coded 3).
251+ New4x4 = 3,
252+}
253+
254+/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers.
255+/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers.
256+pub const SUB_MV_REF_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3];
257+
258+/// Context-conditioned sub-MV probabilities (§16.4 `sub_mv_ref_prob`).
259+pub const SUB_MV_REF_PROBS: [[u8; 3]; 5] = [
260+ [147, 136, 18],
261+ [106, 145, 1],
262+ [179, 121, 1],
263+ [223, 1, 34],
264+ [208, 1, 1],
265+];
266+
267+/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero,
268+/// 3 = left==above, 2 = above zero, 1 = left zero, 0 = normal.
269+/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero,
270+pub fn mv_cont(l: (i16, i16), a: (i16, i16)) -> usize {
271+ let lez = l == (0, 0);
272+ let aez = a == (0, 0);
273+ let lea = l == a;
274+ if lea && lez {
275+ 4
276+ } else if lea {
277+ 3
278+ } else if aez {
279+ 2
280+ } else if lez {
281+ 1
282+ } else {
283+ 0
284+ }
285+}
286+
287+/// Weighted-census probability table for the mv_ref tree
288+/// (§16.3 `vp8_mode_contexts`, indexed by clamped count per slot).
289+pub const MODE_CONTEXTS: [[u8; 4]; 6] = [
290+ [7, 1, 1, 143],
291+ [14, 18, 14, 107],
292+ [135, 64, 57, 68],
293+ [60, 56, 128, 65],
294+ [159, 134, 128, 34],
295+ [234, 188, 128, 28],
296+];
297+
298+/// Decode an mv_ref at the census-derived probabilities (§16.2/§16.3).
299+pub fn read_mv_ref(d: &mut BoolDecoder<'_>, probs: &[u8; 4]) -> MvRef {
300+ match d.read_tree(&MV_REF_TREE, probs) {
301+ 0 => MvRef::Zero,
302+ 1 => MvRef::Nearest,
303+ 2 => MvRef::Near,
304+ 3 => MvRef::New,
305+ 4 => MvRef::Split,
306+ v => unreachable!("mv_ref tree produced {v}"),
307+ }
308+}
309+
310+/// Decode a SPLITMV partition shape (§16.4); returns the `MVpartition`
311+/// integer indexing [`MV_PARTITIONS`].
312+pub fn read_mv_partition(d: &mut BoolDecoder<'_>) -> usize {
313+ usize::from(d.read_tree(&MV_PARTITION_TREE, &MV_PARTITION_PROBS))
314+}
315+
316+/// Decode a sub-MV reference (§16.4) at the context's probabilities.
317+pub fn read_sub_mv_ref(d: &mut BoolDecoder<'_>, ctx: usize) -> SubMvRef {
318+ match d.read_tree(&SUB_MV_REF_TREE, &SUB_MV_REF_PROBS[ctx]) {
319+ 0 => SubMvRef::Left4x4,
320+ 1 => SubMvRef::Above4x4,
321+ 2 => SubMvRef::Zero4x4,
322+ 3 => SubMvRef::New4x4,
323+ v => unreachable!("sub_mv_ref tree produced {v}"),
324+ }
325+}
326+
327+/// First subblock of each SPLITMV subset, per partition shape (libvpx
328+/// `vp8_mbsplit_offset`; shapes 16x8, 8x16, 8x8, 4x4).
329+pub const MBSPLIT_OFFSET: [[u8; 16]; 4] = [
330+ [0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
331+ [0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
332+ [0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
333+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
334+];
335+
336+/// Subblocks filled by one subset, per partition shape (libvpx
337+/// `mbsplit_fill_count`).
338+pub const MBSPLIT_FILL_COUNT: [usize; 4] = [8, 8, 4, 1];
339+
340+/// Subblock indices each subset fills, per shape (libvpx
341+/// `mbsplit_fill_offset`; subset j starts at j * fill_count).
342+pub const MBSPLIT_FILL_OFFSET: [[u8; 16]; 4] = [
343+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
344+ [0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15],
345+ [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15],
346+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
347+];
348+
349+/// Decode one motion-vector component (§17.1, libvpx `read_mvcomponent`):
350+/// either a 3-bit small value off [`SMALL_MV_TREE`] or a 9-bit long form
351+/// whose bit 3 is sometimes implicit, then a sign flag.
352+pub fn read_mv_component(d: &mut BoolDecoder<'_>, probs: &[u8; MVP_COUNT]) -> i16 {
353+ let mut x: i32 = 0;
354+ if d.read_bool(probs[MVP_IS_SHORT]) {
355+ // Large: bits 0..2, then 8..4 (bit 3 is implicit below).
356+ for i in 0..3 {
357+ x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i;
358+ }
359+ let mut i = 9;
360+ loop {
361+ x += i32::from(d.read_bool(probs[MVP_BITS + i])) << i;
362+ i -= 1;
363+ if i <= 3 {
364+ break;
365+ }
366+ }
367+ if (x & 0xFFF0) == 0 || d.read_bool(probs[MVP_BITS + 3]) {
368+ x += 8;
369+ }
370+ } else {
371+ x = i32::from(d.read_tree(&SMALL_MV_TREE, &probs[MVP_SHORT..MVP_SHORT + 7]));
372+ }
373+ if x != 0 && d.read_bool(probs[MVP_SIGN]) {
374+ x = -x;
375+ }
376+ x as i16
377+}
378+
379+/// Both components of a whole-block motion vector (§17.1); the decoded
380+/// quarter-pel components double into the decoder's eighth-pel units.
381+pub fn read_mv(d: &mut BoolDecoder<'_>, probs: &[[u8; MVP_COUNT]; 2]) -> (i16, i16) {
382+ (
383+ read_mv_component(d, &probs[0]).wrapping_mul(2),
384+ read_mv_component(d, &probs[1]).wrapping_mul(2),
385+ )
386+}
387+
388+/// Flip a candidate motion vector when the reference it was coded
389+/// against has a different sign bias than the current reference
390+/// (§16.3, libvpx `mv_bias`).
391+pub fn mv_bias(from_bias: bool, to_bias: bool, mv: (i16, i16)) -> (i16, i16) {
392+ if from_bias != to_bias {
393+ (-mv.0, -mv.1)
394+ } else {
395+ mv
396+ }
397+}
398+
399+/// One neighbour macroblock's motion-vector census input (§16.3).
400+pub struct MvNeighbor {
401+ /// The MB is intra-coded (no MV contribution at all).
402+ pub intra: bool,
403+ /// The MB is inter-coded with a zero motion vector (counts like
404+ /// intra in the census).
405+ pub zero: bool,
406+ /// The MB's motion vector (already sign-bias-adjusted if applicable
407+ /// — pass `sign_bias` and the census applies it).
408+ pub mv: (i16, i16),
409+ /// The MB is SPLITMV (feeds the split census count).
410+ pub is_split: bool,
411+ /// The sign bias of the reference the MB's MV points into.
412+ pub sign_bias: bool,
413+}
414+
415+/// Slot indices of the census result (§16.3).
416+pub const CNT_INTRA: usize = 0;
417+/// Slot index: nearest-candidate count.
418+pub const CNT_NEAREST: usize = 1;
419+/// Slot index: near-candidate count.
420+pub const CNT_NEAR: usize = 2;
421+/// Slot index: split-neighbour count.
422+pub const CNT_SPLITMV: usize = 3;
423+
424+/// The neighborhood motion-vector census (§16.3, libvpx
425+/// `find_near_mvs` inlined in `read_mb_modes_mv`): up to three distinct
426+/// candidate vectors with per-slot counts, scanned above, left,
427+/// above-left; each inter neighbour counts 2/2/1 toward either the
428+/// candidate slot it extends or the zero/intra count.
429+pub fn find_near_mvs(
430+ above: MvNeighbor,
431+ left: MvNeighbor,
432+ aboveleft: MvNeighbor,
433+ to_bias: bool,
434+) -> ([(i16, i16); 4], [i32; 4]) {
435+ let mut mvs = [(0i16, 0i16); 4];
436+ let mut cnt = [0i32; 4];
437+ let mut idx = 0usize;
438+ let mut cntx = 0usize;
439+
440+ // Above: the first candidate is pushed unconditionally.
441+ if !above.intra {
442+ if !above.zero {
443+ idx += 1;
444+ mvs[idx] = mv_bias(above.sign_bias, to_bias, above.mv);
445+ cntx += 1;
446+ }
447+ cnt[cntx] += 2;
448+ }
449+ for (mb, w) in [(&left, 2), (&aboveleft, 1)] {
450+ if !mb.intra {
451+ if !mb.zero {
452+ let this = mv_bias(mb.sign_bias, to_bias, mb.mv);
453+ if this != mvs[idx] {
454+ idx += 1;
455+ mvs[idx] = this;
456+ cntx += 1;
457+ }
458+ cnt[cntx] += w;
459+ } else {
460+ cnt[CNT_INTRA] += i32::from(w);
461+ }
462+ }
463+ }
464+
465+ // Above-left merge (libvpx decodemv.c:366): when the above-left
466+ // pushed a THIRD distinct candidate, its count landed in
467+ // cnt[CNT_SPLITMV] (cntx reached slot 3), and if that candidate
468+ // equals the nearest candidate, NEAREST absorbs it. The split count
469+ // is then overwritten with the SPLITMV-neighbour census below.
470+ if cnt[CNT_SPLITMV] != 0 && mvs[idx] == mvs[CNT_NEAREST] {
471+ cnt[CNT_NEAREST] += 1;
472+ }
473+ cnt[CNT_SPLITMV] = i32::from(above.is_split) * 2
474+ + i32::from(left.is_split) * 2
475+ + i32::from(aboveleft.is_split);
476+
477+ if cnt[CNT_NEAR] > cnt[CNT_NEAREST] {
478+ cnt.swap(CNT_NEAR, CNT_NEAREST);
479+ mvs.swap(CNT_NEAR, CNT_NEAREST);
480+ }
481+ (mvs, cnt)
482+}
483+
484+/// Per-MB motion-vector clamp edges in eighth-pels (libvpx
485+/// `mb_to_*_edge`): distance from the MB's edge to the frame edge.
486+pub fn mb_edges(col: usize, row: usize, mb_cols: usize, mb_rows: usize) -> (i32, i32, i32, i32) {
487+ (
488+ -((i32::try_from(col).unwrap() * 16) << 3),
489+ ((i32::try_from(mb_cols - 1 - col).unwrap() * 16) << 3),
490+ -((i32::try_from(row).unwrap() * 16) << 3),
491+ ((i32::try_from(mb_rows - 1 - row).unwrap() * 16) << 3),
492+ )
493+}
494+
495+/// Clamp a candidate MV into the current MB's allowed range plus a
496+/// 128-eighth-pel margin (§16.2, libvpx `vp8_clamp_mv2`).
497+pub fn clamp_mv2(mv: &mut (i16, i16), edges: (i32, i32, i32, i32)) {
498+ let (l, r, t, b) = edges;
499+ let c = i32::from(mv.1);
500+ if c < l - 128 {
501+ mv.1 = (l - 128) as i16;
502+ } else if c > r + 128 {
503+ mv.1 = (r + 128) as i16;
504+ }
505+ let ro = i32::from(mv.0);
506+ if ro < t - 128 {
507+ mv.0 = (t - 128) as i16;
508+ } else if ro > b + 128 {
509+ mv.0 = (b + 128) as i16;
510+ }
511+}
512+
513+/// Whether an explicit MV exceeds the MB's bounds (libvpx
514+/// `vp8_check_mv_bounds`): strictly outside, no margin.
515+pub fn mv_out_of_bounds(mv: (i16, i16), edges: (i32, i32, i32, i32)) -> bool {
516+ let (l, r, t, b) = edges;
517+ i32::from(mv.1) < l || i32::from(mv.1) > r || i32::from(mv.0) < t || i32::from(mv.0) > b
518+}
519+
520+/// Chroma motion vector for a whole-MB mode (libvpx
521+/// `vp8_build_inter16x16_predictors_mb`): halve each component with
522+/// round-half-away-from-zero (`x += 1 | (x >> 31); x /= 2`).
523+pub fn chroma_mv_whole(mv: (i16, i16), fullpel: bool) -> (i16, i16) {
524+ fn half(x: i16, fullpel: bool) -> i16 {
525+ let x = i32::from(x);
526+ let v = ((x + (1 | (x >> 31))) / 2) as i16;
527+ // `& fullpixel_mask` (reconinter.c:333-334): version-3 streams
528+ // are full-pel, so the sub-pel bits are cleared after rounding.
529+ if fullpel {
530+ v & !7
531+ } else {
532+ v
533+ }
534+ }
535+ (half(mv.0, fullpel), half(mv.1, fullpel))
536+}
537+
538+/// Chroma motion vector for one 8x8 quadrant of a SPLITMB (libvpx
539+/// `build_4x4uvmvs`): sum the quadrant's four subblock vectors, then
540+/// divide by 8 with round-half-away-from-zero
541+/// (`t += 4 + (t >> 31) * 8; t /= 8`).
542+pub fn chroma_mv_split(quadrant: &[(i16, i16); 4], fullpel: bool) -> (i16, i16) {
543+ fn eighth(parts: [i16; 4], fullpel: bool) -> i16 {
544+ let t = i32::from(parts[0])
545+ + i32::from(parts[1])
546+ + i32::from(parts[2])
547+ + i32::from(parts[3]);
548+ let t = t + 4 + (t >> 31) * 8;
549+ let v = (t / 8) as i16;
550+ // `& fullpixel_mask` (reconinter.c:472-481).
551+ if fullpel {
552+ v & !7
553+ } else {
554+ v
555+ }
556+ }
557+ (
558+ eighth(
559+ [quadrant[0].0, quadrant[1].0, quadrant[2].0, quadrant[3].0],
560+ fullpel,
561+ ),
562+ eighth(
563+ [quadrant[0].1, quadrant[1].1, quadrant[2].1, quadrant[3].1],
564+ fullpel,
565+ ),
566+ )
567+}
crates/ec-vp8/src/stream.rsadded+134 -0
@@ -0,0 +1,134 @@
1+//! Whole-stream decoding: an IVF file in, decoded pictures out.
2+//!
3+//! VP8 frames are not self-delimiting — a bare frame is a 3-byte
4+//! uncompressed tag followed by partitions whose total size only the
5+//! container knows — so the whole-stream API takes the stream in the
6+//! container VP8 actually ships in: IVF (the RFC's companion container,
7+//! `DKIF`/`VP80`; also what vpxenc, ffmpeg and the WebM toolchain emit
8+//! for raw VP8 elementaries). Single frames from any other demuxer feed
9+//! [`crate::decode::Decoder::decode`] directly.
10+//!
11+//! The shape mirrors `ec_av1::stream`: [`decode_stream`] collects every
12+//! shown picture into a `Vec`, and [`decode_stream_with`] hands each
13+//! picture to a sink the moment it exists.
14+
15+use crate::decode::{Decoder, Picture};
16+use crate::{Error, Result};
17+
18+/// The IVF file magic, `DKIF`.
19+const DKIF: &[u8; 4] = b"DKIF";
20+/// The fourcc for VP8 video (`VP80`; `VP8L`/`VP8x` are WebP-lossless/alpha).
21+const VP80: &[u8; 4] = b"VP80";
22+
23+/// One demuxed IVF frame: presentation timestamp plus the compressed
24+/// VP8 payload.
25+struct IvfFrame<'a> {
26+ pts: u64,
27+ data: &'a [u8],
28+}
29+
30+/// Split an IVF byte stream into its frames, validating the container
31+/// envelope (magic, fourcc, framing arithmetic) as [`Error`]s rather
32+/// than panics.
33+fn demux(data: &[u8]) -> Result<Vec<IvfFrame<'_>>> {
34+ if data.len() < 32 || &data[0..4] != DKIF {
35+ return Err(Error::corrupt("not an IVF stream (missing DKIF magic)"));
36+ }
37+ // Bytes 4..6 version (informational), 6..8 header length, 8..12 fourcc.
38+ let hdr_len = u16::from_le_bytes([data[6], data[7]]) as usize;
39+ if data.len() < hdr_len || hdr_len < 12 {
40+ return Err(Error::corrupt("IVF header length out of range"));
41+ }
42+ if &data[8..12] != VP80 {
43+ return Err(Error::unsupported(
44+ "IVF fourcc",
45+ "the stream is not VP80 (VP8 video)",
46+ ));
47+ }
48+ // Bytes 12..16 carry the nominal width/height; VP8 streams set them
49+ // to 0 and take the real dimensions from the key frame, so the
50+ // decoder does not consult them.
51+ let _ = u16::from_le_bytes([data[12], data[13]]);
52+ let _ = u16::from_le_bytes([data[14], data[15]]);
53+ let mut frames = Vec::new();
54+ let mut pos = hdr_len;
55+ while pos + 12 <= data.len() {
56+ let sz =
57+ u32::from_le_bytes([data[pos], data[pos + 1], data[pos + 2], data[pos + 3]])
58+ as usize;
59+ let pts = u64::from_le_bytes([
60+ data[pos + 4],
61+ data[pos + 5],
62+ data[pos + 6],
63+ data[pos + 7],
64+ data[pos + 8],
65+ data[pos + 9],
66+ data[pos + 10],
67+ data[pos + 11],
68+ ]);
69+ pos += 12;
70+ if pos + sz > data.len() {
71+ return Err(Error::corrupt(format!(
72+ "IVF frame {} extends past end of stream (need {} bytes \
73+ at offset {})",
74+ frames.len(),
75+ sz,
76+ pos
77+ )));
78+ }
79+ frames.push(IvfFrame {
80+ pts,
81+ data: &data[pos..pos + sz],
82+ });
83+ pos += sz;
84+ }
85+ Ok(frames)
86+}
87+
88+/// Decode every frame in an IVF VP8 stream, in presentation order.
89+///
90+/// The stream must start with a key frame; hidden frames (alternate
91+/// references, `show_frame == 0`) update the reference buffers but are
92+/// not part of the output, exactly as a player would not display them.
93+///
94+/// # Errors
95+/// Returns an error when the container is truncated or not VP80 (as
96+/// [`demux`] reports it), when a frame is malformed (as
97+/// [`crate::decode::Decoder::decode`] reports it), or when an inter
98+/// frame appears before any key frame has supplied references.
99+pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
100+ let mut pictures: Vec<Picture> = Vec::new();
101+ decode_stream_with(data, |picture, _decode_idx, _pts| {
102+ pictures.push(picture.clone());
103+ Ok(())
104+ })?;
105+ Ok(pictures)
106+}
107+
108+/// Streaming form of [`decode_stream`]: hand every shown picture to
109+/// `sink` the moment it exists and drop it right after, so peak memory
110+/// is one output picture plus the reference frames instead of the whole
111+/// decoded stream. `decode_stream` itself is this function collecting
112+/// into a `Vec`.
113+///
114+/// `sink` is called with the picture, the decode-order index of the
115+/// coded frame it came from, and the IVF presentation timestamp. A
116+/// hidden frame (`show_frame == 0`) updates the decoder state but
117+/// produces no picture, so the sink is not called for it. An `Err` the
118+/// sink returns aborts the decode and is returned unchanged.
119+///
120+/// # Errors
121+/// As [`decode_stream`], plus whatever `sink` returns.
122+pub fn decode_stream_with(
123+ data: &[u8],
124+ mut sink: impl FnMut(&Picture, usize, u64) -> Result<()>,
125+) -> Result<()> {
126+ let frames = demux(data)?;
127+ let mut dec = Decoder::new();
128+ for (decode_idx, frame) in frames.iter().enumerate() {
129+ if let Some(picture) = dec.decode(frame.data)? {
130+ sink(&picture, decode_idx, frame.pts)?;
131+ }
132+ }
133+ Ok(())
134+}
crates/ec-vp8/src/tables.rsadded+537 -0
@@ -0,0 +1,537 @@
1+//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and
2+//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from
3+//! the RFC text; do not edit by hand. The extractor asserts every
4+//! table's element count, so a slip cannot drop or add values.
5+#![allow(clippy::all)]
6+
7+/// RFC 6386 `coeff_update_probs`.
8+pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
9+ [
10+ [
11+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
12+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
13+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
14+ ],
15+ [
16+ [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255],
17+ [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255],
18+ [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
19+ ],
20+ [
21+ [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255],
22+ [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
23+ [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
24+ ],
25+ [
26+ [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255],
27+ [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
28+ [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
29+ ],
30+ [
31+ [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
32+ [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
33+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
34+ ],
35+ [
36+ [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
37+ [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
38+ [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
39+ ],
40+ [
41+ [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255],
42+ [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255],
43+ [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
44+ ],
45+ [
46+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
47+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
48+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
49+ ],
50+ ],
51+ [
52+ [
53+ [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
54+ [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255],
55+ [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255],
56+ ],
57+ [
58+ [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
59+ [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
60+ [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255],
61+ ],
62+ [
63+ [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255],
64+ [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
65+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
66+ ],
67+ [
68+ [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255],
69+ [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
70+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
71+ ],
72+ [
73+ [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
74+ [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
75+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
76+ ],
77+ [
78+ [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
79+ [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
80+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
81+ ],
82+ [
83+ [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
84+ [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
85+ [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
86+ ],
87+ [
88+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
89+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
90+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
91+ ],
92+ ],
93+ [
94+ [
95+ [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255],
96+ [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255],
97+ [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255],
98+ ],
99+ [
100+ [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
101+ [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
102+ [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255],
103+ ],
104+ [
105+ [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
106+ [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255],
107+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
108+ ],
109+ [
110+ [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
111+ [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
112+ [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
113+ ],
114+ [
115+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
116+ [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
117+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
118+ ],
119+ [
120+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
121+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
122+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
123+ ],
124+ [
125+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
126+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
127+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
128+ ],
129+ [
130+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
131+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
132+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
133+ ],
134+ ],
135+ [
136+ [
137+ [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
138+ [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255],
139+ [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255],
140+ ],
141+ [
142+ [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
143+ [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255],
144+ [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255],
145+ ],
146+ [
147+ [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255],
148+ [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255],
149+ [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255],
150+ ],
151+ [
152+ [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
153+ [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255],
154+ [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
155+ ],
156+ [
157+ [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255],
158+ [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255],
159+ [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255],
160+ ],
161+ [
162+ [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255],
163+ [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
164+ [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255],
165+ ],
166+ [
167+ [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255],
168+ [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
169+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
170+ ],
171+ [
172+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
173+ [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
174+ [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255],
175+ ],
176+ ],
177+];
178+
179+/// RFC 6386 `default_coeff_probs`.
180+pub const DEFAULT_COEFF_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [
181+ [
182+ [
183+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
184+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
185+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
186+ ],
187+ [
188+ [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128],
189+ [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128],
190+ [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128],
191+ ],
192+ [
193+ [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128],
194+ [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128],
195+ [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128],
196+ ],
197+ [
198+ [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128],
199+ [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128],
200+ [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128],
201+ ],
202+ [
203+ [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128],
204+ [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128],
205+ [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128],
206+ ],
207+ [
208+ [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128],
209+ [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128],
210+ [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128],
211+ ],
212+ [
213+ [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128],
214+ [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128],
215+ [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128],
216+ ],
217+ [
218+ [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
219+ [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
220+ [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
221+ ],
222+ ],
223+ [
224+ [
225+ [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62],
226+ [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1],
227+ [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128],
228+ ],
229+ [
230+ [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128],
231+ [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128],
232+ [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128],
233+ ],
234+ [
235+ [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128],
236+ [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128],
237+ [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128],
238+ ],
239+ [
240+ [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128],
241+ [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128],
242+ [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128],
243+ ],
244+ [
245+ [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128],
246+ [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128],
247+ [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128],
248+ ],
249+ [
250+ [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128],
251+ [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128],
252+ [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128],
253+ ],
254+ [
255+ [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128],
256+ [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128],
257+ [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128],
258+ ],
259+ [
260+ [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128],
261+ [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128],
262+ [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128],
263+ ],
264+ ],
265+ [
266+ [
267+ [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128],
268+ [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128],
269+ [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128],
270+ ],
271+ [
272+ [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128],
273+ [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128],
274+ [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128],
275+ ],
276+ [
277+ [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128],
278+ [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128],
279+ [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128],
280+ ],
281+ [
282+ [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128],
283+ [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128],
284+ [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128],
285+ ],
286+ [
287+ [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128],
288+ [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128],
289+ [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
290+ ],
291+ [
292+ [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128],
293+ [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128],
294+ [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128],
295+ ],
296+ [
297+ [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128],
298+ [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128],
299+ [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128],
300+ ],
301+ [
302+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
303+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
304+ [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
305+ ],
306+ ],
307+ [
308+ [
309+ [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255],
310+ [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128],
311+ [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128],
312+ ],
313+ [
314+ [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128],
315+ [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128],
316+ [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128],
317+ ],
318+ [
319+ [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128],
320+ [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128],
321+ [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128],
322+ ],
323+ [
324+ [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128],
325+ [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128],
326+ [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128],
327+ ],
328+ [
329+ [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128],
330+ [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128],
331+ [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128],
332+ ],
333+ [
334+ [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128],
335+ [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128],
336+ [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128],
337+ ],
338+ [
339+ [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128],
340+ [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128],
341+ [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128],
342+ ],
343+ [
344+ [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
345+ [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
346+ [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
347+ ],
348+ ],
349+];
350+
351+/// RFC 6386 `kf_bmode_prob`.
352+pub const KF_BMODE_PROB: [[[u8; 9]; 10]; 10] = [
353+ [
354+ [231, 120, 48, 89, 115, 113, 120, 152, 112],
355+ [152, 179, 64, 126, 170, 118, 46, 70, 95],
356+ [175, 69, 143, 80, 85, 82, 72, 155, 103],
357+ [56, 58, 10, 171, 218, 189, 17, 13, 152],
358+ [144, 71, 10, 38, 171, 213, 144, 34, 26],
359+ [114, 26, 17, 163, 44, 195, 21, 10, 173],
360+ [121, 24, 80, 195, 26, 62, 44, 64, 85],
361+ [170, 46, 55, 19, 136, 160, 33, 206, 71],
362+ [63, 20, 8, 114, 114, 208, 12, 9, 226],
363+ [81, 40, 11, 96, 182, 84, 29, 16, 36],
364+ ],
365+ [
366+ [134, 183, 89, 137, 98, 101, 106, 165, 148],
367+ [72, 187, 100, 130, 157, 111, 32, 75, 80],
368+ [66, 102, 167, 99, 74, 62, 40, 234, 128],
369+ [41, 53, 9, 178, 241, 141, 26, 8, 107],
370+ [104, 79, 12, 27, 217, 255, 87, 17, 7],
371+ [74, 43, 26, 146, 73, 166, 49, 23, 157],
372+ [65, 38, 105, 160, 51, 52, 31, 115, 128],
373+ [87, 68, 71, 44, 114, 51, 15, 186, 23],
374+ [47, 41, 14, 110, 182, 183, 21, 17, 194],
375+ [66, 45, 25, 102, 197, 189, 23, 18, 22],
376+ ],
377+ [
378+ [88, 88, 147, 150, 42, 46, 45, 196, 205],
379+ [43, 97, 183, 117, 85, 38, 35, 179, 61],
380+ [39, 53, 200, 87, 26, 21, 43, 232, 171],
381+ [56, 34, 51, 104, 114, 102, 29, 93, 77],
382+ [107, 54, 32, 26, 51, 1, 81, 43, 31],
383+ [39, 28, 85, 171, 58, 165, 90, 98, 64],
384+ [34, 22, 116, 206, 23, 34, 43, 166, 73],
385+ [68, 25, 106, 22, 64, 171, 36, 225, 114],
386+ [34, 19, 21, 102, 132, 188, 16, 76, 124],
387+ [62, 18, 78, 95, 85, 57, 50, 48, 51],
388+ ],
389+ [
390+ [193, 101, 35, 159, 215, 111, 89, 46, 111],
391+ [60, 148, 31, 172, 219, 228, 21, 18, 111],
392+ [112, 113, 77, 85, 179, 255, 38, 120, 114],
393+ [40, 42, 1, 196, 245, 209, 10, 25, 109],
394+ [100, 80, 8, 43, 154, 1, 51, 26, 71],
395+ [88, 43, 29, 140, 166, 213, 37, 43, 154],
396+ [61, 63, 30, 155, 67, 45, 68, 1, 209],
397+ [142, 78, 78, 16, 255, 128, 34, 197, 171],
398+ [41, 40, 5, 102, 211, 183, 4, 1, 221],
399+ [51, 50, 17, 168, 209, 192, 23, 25, 82],
400+ ],
401+ [
402+ [125, 98, 42, 88, 104, 85, 117, 175, 82],
403+ [95, 84, 53, 89, 128, 100, 113, 101, 45],
404+ [75, 79, 123, 47, 51, 128, 81, 171, 1],
405+ [57, 17, 5, 71, 102, 57, 53, 41, 49],
406+ [115, 21, 2, 10, 102, 255, 166, 23, 6],
407+ [38, 33, 13, 121, 57, 73, 26, 1, 85],
408+ [41, 10, 67, 138, 77, 110, 90, 47, 114],
409+ [101, 29, 16, 10, 85, 128, 101, 196, 26],
410+ [57, 18, 10, 102, 102, 213, 34, 20, 43],
411+ [117, 20, 15, 36, 163, 128, 68, 1, 26],
412+ ],
413+ [
414+ [138, 31, 36, 171, 27, 166, 38, 44, 229],
415+ [67, 87, 58, 169, 82, 115, 26, 59, 179],
416+ [63, 59, 90, 180, 59, 166, 93, 73, 154],
417+ [40, 40, 21, 116, 143, 209, 34, 39, 175],
418+ [57, 46, 22, 24, 128, 1, 54, 17, 37],
419+ [47, 15, 16, 183, 34, 223, 49, 45, 183],
420+ [46, 17, 33, 183, 6, 98, 15, 32, 183],
421+ [65, 32, 73, 115, 28, 128, 23, 128, 205],
422+ [40, 3, 9, 115, 51, 192, 18, 6, 223],
423+ [87, 37, 9, 115, 59, 77, 64, 21, 47],
424+ ],
425+ [
426+ [104, 55, 44, 218, 9, 54, 53, 130, 226],
427+ [64, 90, 70, 205, 40, 41, 23, 26, 57],
428+ [54, 57, 112, 184, 5, 41, 38, 166, 213],
429+ [30, 34, 26, 133, 152, 116, 10, 32, 134],
430+ [75, 32, 12, 51, 192, 255, 160, 43, 51],
431+ [39, 19, 53, 221, 26, 114, 32, 73, 255],
432+ [31, 9, 65, 234, 2, 15, 1, 118, 73],
433+ [88, 31, 35, 67, 102, 85, 55, 186, 85],
434+ [56, 21, 23, 111, 59, 205, 45, 37, 192],
435+ [55, 38, 70, 124, 73, 102, 1, 34, 98],
436+ ],
437+ [
438+ [102, 61, 71, 37, 34, 53, 31, 243, 192],
439+ [69, 60, 71, 38, 73, 119, 28, 222, 37],
440+ [68, 45, 128, 34, 1, 47, 11, 245, 171],
441+ [62, 17, 19, 70, 146, 85, 55, 62, 70],
442+ [75, 15, 9, 9, 64, 255, 184, 119, 16],
443+ [37, 43, 37, 154, 100, 163, 85, 160, 1],
444+ [63, 9, 92, 136, 28, 64, 32, 201, 85],
445+ [86, 6, 28, 5, 64, 255, 25, 248, 1],
446+ [56, 8, 17, 132, 137, 255, 55, 116, 128],
447+ [58, 15, 20, 82, 135, 57, 26, 121, 40],
448+ ],
449+ [
450+ [164, 50, 31, 137, 154, 133, 25, 35, 218],
451+ [51, 103, 44, 131, 131, 123, 31, 6, 158],
452+ [86, 40, 64, 135, 148, 224, 45, 183, 128],
453+ [22, 26, 17, 131, 240, 154, 14, 1, 209],
454+ [83, 12, 13, 54, 192, 255, 68, 47, 28],
455+ [45, 16, 21, 91, 64, 222, 7, 1, 197],
456+ [56, 21, 39, 155, 60, 138, 23, 102, 213],
457+ [85, 26, 85, 85, 128, 128, 32, 146, 171],
458+ [18, 11, 7, 63, 144, 171, 4, 4, 246],
459+ [35, 27, 10, 146, 174, 171, 12, 26, 128],
460+ ],
461+ [
462+ [190, 80, 35, 99, 180, 80, 126, 54, 45],
463+ [85, 126, 47, 87, 176, 51, 41, 20, 32],
464+ [101, 75, 128, 139, 118, 146, 116, 128, 85],
465+ [56, 41, 15, 176, 236, 85, 37, 9, 62],
466+ [146, 36, 19, 30, 171, 255, 97, 27, 20],
467+ [71, 30, 17, 119, 118, 255, 17, 18, 138],
468+ [101, 38, 60, 138, 55, 70, 43, 26, 142],
469+ [138, 45, 61, 62, 219, 1, 81, 188, 64],
470+ [32, 41, 20, 117, 151, 142, 20, 21, 163],
471+ [112, 19, 12, 61, 195, 128, 48, 4, 24],
472+ ],
473+];
474+
475+/// RFC 6386 `coeff_bands`.
476+pub const COEFF_BANDS: [u8; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7];
477+
478+/// RFC 6386 `dc_qlookup`.
479+pub const DC_QLOOKUP: [i16; 128] = [
480+ 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,
481+ 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44,
482+ 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
483+ 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91,
484+ 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130,
485+ 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
486+];
487+
488+/// RFC 6386 `ac_qlookup`.
489+pub const AC_QLOOKUP: [i16; 128] = [
490+ 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,
491+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
492+ 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94,
493+ 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140,
494+ 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205,
495+ 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
496+];
497+
498+/// RFC 6386 `Pcat1` (trailing 0 is the DCTextra sentinel).
499+pub const PCAT1: [u8; 2] = [159, 0];
500+
501+/// RFC 6386 `Pcat2` (trailing 0 is the DCTextra sentinel).
502+pub const PCAT2: [u8; 3] = [165, 145, 0];
503+
504+/// RFC 6386 `Pcat3` (trailing 0 is the DCTextra sentinel).
505+pub const PCAT3: [u8; 4] = [173, 148, 140, 0];
506+
507+/// RFC 6386 `Pcat4` (trailing 0 is the DCTextra sentinel).
508+pub const PCAT4: [u8; 5] = [176, 155, 140, 135, 0];
509+
510+/// RFC 6386 `Pcat5` (trailing 0 is the DCTextra sentinel).
511+pub const PCAT5: [u8; 6] = [180, 157, 141, 134, 130, 0];
512+
513+/// RFC 6386 `Pcat6` (trailing 0 is the DCTextra sentinel).
514+pub const PCAT6: [u8; 12] = [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0];
515+
516+/// RFC 6386 `k_default_mv_probs`.
517+pub const DEFAULT_MV_PROBS: [[u8; 19]; 2] = [
518+ [
519+ 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254,
520+ ],
521+ [
522+ 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254,
523+ 254,
524+ ],
525+];
526+
527+/// RFC 6386 `k_mv_entropy_update_probs`.
528+pub const MV_UPDATE_PROBS: [[u8; 19]; 2] = [
529+ [
530+ 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254,
531+ 254,
532+ ],
533+ [
534+ 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254,
535+ 254,
536+ ],
537+];
crates/ec-vp8/src/tokens.rsadded+314 -0
@@ -0,0 +1,314 @@
1+//! DCT coefficient (token) decoding — RFC 6386 §13.
2+//!
3+//! Per 4x4 block: tokens are tree-decoded at
4+//! `probs[type][band[position]][ctx]` where `ctx` (0..2) is the zero-
5+//! neighbour count — sum of the above/left block contexts for the first
6+//! coded coefficient, then derived from the magnitude of the previous
7+//! coefficient within the block (§13.3). Coefficients are written in
8+//! natural (de-zigzagged) order and dequantized on the fly (the first
9+//! coded position takes the DC factor, all others the AC factor — the
10+//! same arithmetic dixie applies inline and libvpx applies in
11+//! `vp8_dequantize_b`).
12+//!
13+//! After an EOB the block ends; after a `DCT_0` token the tree decode of
14+//! the next coefficient skips the EOB branch (§13.2). A block whose
15+//! coefficients fill all 16 positions cannot take an EOB (the decoder
16+//! stops at 16 exactly like the reference decoder, down to the sentinel
17+//! band entry).
18+
19+use crate::bool::BoolDecoder;
20+use crate::tables::{PCAT3, PCAT4, PCAT5, PCAT6};
21+
22+/// De-zigzag: coefficient scan position -> natural order index
23+/// (RFC 6386 §13, dixie/libvpx `zigzag`).
24+const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
25+
26+/// Band per coefficient position, with the reference decoder's sentinel
27+/// entry at 16 (band 0 on the malformed no-EOB path — libvpx `kBands`).
28+const BANDS: [u8; 17] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0];
29+
30+/// Extra-bit probability tables per category (cat3..cat6, RFC 6386
31+/// §13.2; the cat1/cat2 probabilities 159/165+145 are inlined in the
32+/// tree decode exactly as the reference does). Trailing 0 is the
33+/// DCTextra sentinel.
34+const CAT_EXTRA: [&[u8]; 4] = [&PCAT3, &PCAT4, &PCAT5, &PCAT6];
35+
36+/// Dequantization factors for one macroblock (already scaled: Y2 AC has
37+/// the ×155/100 min-8 rule applied, Y2 DC ×2, UV DC capped at 132).
38+#[derive(Debug, Clone, Copy)]
39+pub(crate) struct Dq {
40+ pub y1_dc: i16,
41+ pub y1_ac: i16,
42+ pub uv_dc: i16,
43+ pub uv_ac: i16,
44+ pub y2_dc: i16,
45+ pub y2_ac: i16,
46+}
47+
48+/// The 25 blocks of one macroblock, dequantized, in natural coefficient
49+/// order. `eobs[b]` is the number of significant coefficients (position
50+/// of the last non-zero + 1); `eob_mask` mirrors dixie's: bit b set iff
51+/// block b ended with more than one significant coefficient, bit 31 set
52+/// iff ANY block had a non-zero coefficient.
53+pub(crate) struct MbCoeffs {
54+ pub y: [[i16; 16]; 16],
55+ pub u: [[i16; 16]; 4],
56+ pub v: [[i16; 16]; 4],
57+ pub y2: [i16; 16],
58+ pub has_y2: bool,
59+ pub eobs: [u8; 25],
60+ pub eob_mask: u32,
61+}
62+
63+impl MbCoeffs {
64+ pub(crate) fn empty(has_y2: bool) -> Self {
65+ Self {
66+ y: [[0; 16]; 16],
67+ u: [[0; 16]; 4],
68+ v: [[0; 16]; 4],
69+ y2: [0; 16],
70+ has_y2,
71+ eobs: [0; 25],
72+ eob_mask: 0,
73+ }
74+ }
75+
76+ /// Whether any block carries a non-zero coefficient (the loop
77+ /// filter's interior-edge condition, §15.1).
78+ pub fn has_nonzero(&self) -> bool {
79+ self.eob_mask & (1 << 31) != 0
80+ }
81+}
82+
83+/// Left/above context slot of each block (dixie `left_context_index` /
84+/// `above_context_index`).
85+const LEFT_INDEX: [usize; 25] = [
86+ 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,
87+];
88+const ABOVE_INDEX: [usize; 25] = [
89+ 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,
90+];
91+
92+/// Token entropy contexts (dixie/libvpx layout): indices 0-3 are the Y
93+/// subblock columns, 4-5 U, 6-7 V, 8 the Y2 block. `left` is the running
94+/// one-MB-wide column state; `above` is the per-MB-column state for the
95+/// current row (9 slots per MB column).
96+pub(crate) struct TokenContexts {
97+ pub above: Vec<u8>,
98+ pub left: [u8; 9],
99+}
100+
101+impl TokenContexts {
102+ /// `mb_cols` entries of 9 slots for the above state.
103+ pub fn new(mb_cols: usize) -> Self {
104+ Self {
105+ above: vec![0u8; mb_cols * 9],
106+ left: [0; 9],
107+ }
108+ }
109+
110+ /// Reset the above state at the start of a row (§13.3: non-existent
111+ /// neighbours are empty).
112+ pub fn reset_above_row(&mut self) {
113+ self.above.iter_mut().for_each(|s| *s = 0);
114+ }
115+
116+ /// Reset the left state at the start of a row (the caller MUST call
117+ /// this once per MB row before decoding its tokens).
118+ pub fn reset_left(&mut self) {
119+ self.left = [0; 9];
120+ }
121+
122+ /// Skip-MB context reset (dixie `reset_mb_context`): everything to 0
123+ /// except the Y2 slots, which survive iff this MB has no Y2 block.
124+ pub fn reset_mb(&mut self, mb_col: usize, has_y2: bool) {
125+ let a = &mut self.above[mb_col * 9..mb_col * 9 + 9];
126+ a[..8].fill(0);
127+ self.left[..8].fill(0);
128+ if has_y2 {
129+ a[8] = 0;
130+ self.left[8] = 0;
131+ }
132+ }
133+
134+ fn ctx_pair(&self, mb_col: usize, block: usize) -> (u8, u8) {
135+ let a = &self.above[mb_col * 9..mb_col * 9 + 9];
136+ (self.left[LEFT_INDEX[block]], a[ABOVE_INDEX[block]])
137+ }
138+
139+ fn set_ctx(&mut self, mb_col: usize, block: usize, v: u8) {
140+ self.left[LEFT_INDEX[block]] = v;
141+ self.above[mb_col * 9 + ABOVE_INDEX[block]] = v;
142+ }
143+}
144+
145+/// Decode one 4x4 block's tokens (libvpx `GetCoeffs` / RFC §13.2-13.3
146+/// verbatim). `probs_t` is `[band][ctx][node]` for the block's plane
147+/// type; `n0` the first coded position (1 for Y blocks after a Y2).
148+/// Returns the number of significant coefficients. Coefficients are
149+/// written dequantized into `out` (natural order).
150+fn get_coeffs(
151+ bc: &mut BoolDecoder<'_>,
152+ probs_t: &[[[u8; 11]; 3]; 8],
153+ ctx: usize,
154+ n0: usize,
155+ dc_factor: i16,
156+ ac_factor: i16,
157+ out: &mut [i16; 16],
158+) -> usize {
159+ let trace = std::env::var_os("EC_VP8_TRACE").is_some();
160+ // One token decision: decode the bool, then — under EC_VP8_TRACE —
161+ // print the consulted (n, band, ctx, prob) and the decoded bit so the
162+ // stream can be diffed read-for-read against scripts/vp8ref_model.py.
163+ macro_rules! g {
164+ ($n:expr, $band:expr, $c:expr, $prob:expr) => {{
165+ let bit = bc.read_bool($prob);
166+ if trace {
167+ eprintln!(
168+ "G n={} band={} ctx={} prob={} bit={}",
169+ $n, $band, $c, $prob, u8::from(bit)
170+ );
171+ }
172+ bit
173+ }};
174+ }
175+ let mut n = n0;
176+ let mut band = BANDS[n0];
177+ let mut c = ctx;
178+ let mut p = &probs_t[band as usize][c];
179+ if !g!(n, band, c, p[0]) {
180+ return 0; // immediate EOB
181+ }
182+ loop {
183+ n += 1;
184+ let mut v: i32;
185+ if !g!(n, band, c, p[1]) {
186+ // DCT_0: the next decision skips the EOB branch (§13.2) and
187+ // libvpx forces the context to 0 after a zero token.
188+ c = 0;
189+ band = BANDS[n];
190+ p = &probs_t[band as usize][0];
191+ } else {
192+ if !g!(n, band, c, p[2]) {
193+ c = 1;
194+ band = BANDS[n];
195+ p = &probs_t[band as usize][1];
196+ v = 1;
197+ } else {
198+ if !g!(n, band, c, p[3]) {
199+ if !g!(n, band, c, p[4]) {
200+ v = 2;
201+ } else {
202+ v = 3 + i32::from(g!(n, band, c, p[5]));
203+ }
204+ } else {
205+ if !g!(n, band, c, p[6]) {
206+ if !g!(n, band, c, p[7]) {
207+ v = 5 + i32::from(g!(n, band, c, 159u8));
208+ } else {
209+ v = 7 + 2 * i32::from(g!(n, band, c, 165u8));
210+ v += i32::from(g!(n, band, c, 145u8));
211+ }
212+ } else {
213+ let bit1 = usize::from(g!(n, band, c, p[8]));
214+ let bit0 = usize::from(g!(n, band, c, p[9 + bit1]));
215+ let cat = 2 * bit1 + bit0;
216+ v = 0;
217+ for &prob in CAT_EXTRA[cat].iter() {
218+ if prob == 0 {
219+ break;
220+ }
221+ v += v + i32::from(g!(n, band, c, prob));
222+ }
223+ v += 3 + (8 << cat);
224+ }
225+ }
226+ c = 2;
227+ band = BANDS[n];
228+ p = &probs_t[band as usize][2];
229+ }
230+
231+ // Sign flag, then dequantize (first coded position is DC).
232+ // Shared by the ONE and magnitude paths, exactly like the
233+ // reference walk (libvpx detokenize.c GetCoeffs).
234+ let neg = g!(n, band, c, 128u8);
235+ let mag = if neg { -v } else { v };
236+ out[ZIGZAG[n - 1]] = if n - 1 == 0 {
237+ (mag * i32::from(dc_factor)) as i16
238+ } else {
239+ (mag * i32::from(ac_factor)) as i16
240+ };
241+ if n < 16 && !g!(n, band, c, p[0]) {
242+ return n; // EOB
243+ }
244+ }
245+ if n == 16 {
246+ return 16; // malformed without EOB: stop like the reference
247+ }
248+ }
249+}
250+
251+/// Decode all 25 blocks of one macroblock (dixie `decode_mb_tokens`):
252+/// Y2 first when present, then the 16 Y, then U, then V. A skipped MB
253+/// must not be run through here — call [`skip_mb_tokens`] instead.
254+pub(crate) fn decode_mb_tokens(
255+ bc: &mut BoolDecoder<'_>,
256+ probs: &[[[[u8; 11]; 3]; 8]; 4],
257+ dq: &Dq,
258+ has_y2: bool,
259+ ctxs: &mut TokenContexts,
260+ mb_col: usize,
261+) -> MbCoeffs {
262+ let mut out = MbCoeffs::empty(has_y2);
263+ let mut eob_mask = 0u32;
264+
265+ // Decode one block and fold its contexts/mask in.
266+ macro_rules! block {
267+ ($idx:expr, $ptype:expr, $dc:expr, $ac:expr, $slot:expr) => {{
268+ let n0 = usize::from($ptype == 0);
269+ let (l, a) = ctxs.ctx_pair(mb_col, $idx);
270+ let ctx = (usize::from(l) + usize::from(a)).min(2);
271+ if std::env::var_os("EC_VP8_TRACE").is_some() {
272+ eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a);
273+ }
274+ let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot);
275+ if std::env::var_os("EC_VP8_TRACE").is_some() {
276+ eprintln!("TBE {} eob={}", $idx, eob);
277+ }
278+ out.eobs[$idx] = eob as u8;
279+ let t = u8::from(eob > 0);
280+ ctxs.set_ctx(mb_col, $idx, t);
281+ eob_mask |= (u32::from(eob > 1)) << $idx;
282+ eob_mask |= u32::from(t != 0) << 31;
283+ }};
284+ }
285+
286+ if has_y2 {
287+ block!(24, 1, dq.y2_dc, dq.y2_ac, &mut out.y2);
288+ for b in 0..16 {
289+ block!(b, 0, dq.y1_dc, dq.y1_ac, &mut out.y[b]);
290+ }
291+ } else {
292+ for b in 0..16 {
293+ block!(b, 3, dq.y1_dc, dq.y1_ac, &mut out.y[b]);
294+ }
295+ }
296+ for b in 0..4 {
297+ block!(16 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.u[b]);
298+ }
299+ for b in 0..4 {
300+ block!(20 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.v[b]);
301+ }
302+
303+ out.eob_mask = eob_mask;
304+ out
305+}
306+
307+/// The context reset a skipped MB applies (dixie `reset_mb_context`):
308+/// the returned [`MbCoeffs`] is all-zero and the contexts look like a
309+/// fully-empty MB — except the Y2 slots survive when the skipped MB has
310+/// no Y2 block.
311+pub(crate) fn skip_mb_tokens(ctxs: &mut TokenContexts, mb_col: usize, has_y2: bool) -> MbCoeffs {
312+ ctxs.reset_mb(mb_col, has_y2);
313+ MbCoeffs::empty(has_y2)
314+}
crates/ec-vp8/src/transform.rsadded+640 -0
@@ -0,0 +1,640 @@
1+//! Inverse transforms (inverse DCT, inverse Walsh-Hadamard) and dequant
2+//! factor computation for VP8 (RFC 6386 §14).
3+//!
4+//! Every function here is a bit-exact transcription of the normative
5+//! reference implementation in libvpx (`vp8/common/idctllm.c` and
6+//! `vp8/common/quant_common.c`), which is also what RFC 6386 §§14.3–14.5
7+//! print as pseudocode. Bit-level fidelity of the rounding is a hard
8+//! requirement: arithmetic right shifts (`>>` on `i32` in Rust, as in C)
9+//! round toward negative infinity, and both implementations rely on that
10+//! floor behavior for negative operands.
11+//!
12+//! Fidelity details reproduced verbatim from the oracle:
13+//! - The 16-bit fixed-point constants `cospi8sqrt2minus1 = 20091` and
14+//! `sinpi8sqrt2 = 35468` (§14.4). The `>> 16` multiplies carry **no**
15+//! rounding constant; the `+4` before the final `>> 3` appears only in
16+//! the second DCT pass.
17+//! - `short output[16]` intermediates: libvpx stores the first-pass
18+//! results into a `short` array, truncating `i32` arithmetic to `i16`
19+//! between passes. We reproduce those truncation points with `as i16`
20+//! (wrapping two's-complement truncation, identical to the de facto C
21+//! behavior) so results stay oracle-exact even for adversarial inputs.
22+//! - The inverse WHT rounds with `(x + 3) >> 3` (§14.3); the DC-only
23+//! shortcut uses the same constant on `input[0]` alone.
24+//!
25+//! All functions are pure, allocation-free, and free of `unsafe`.
26+
27+#![deny(unsafe_code)]
28+
29+/// 16-bit fixed-point `sqrt(2) * cos(pi/8) - 1` (RFC 6386 §14.4). The
30+/// product `x * sqrt(2) * cos(pi/8)` is computed as `x + ((x * K) >> 16)`
31+/// because the constant exceeds 1.0 and would otherwise lose precision.
32+const COSPI8SQRT2MINUS1: i32 = 20091;
33+
34+/// 16-bit fixed-point `sqrt(2) * sin(pi/8)` (RFC 6386 §14.4).
35+const SINPI8SQRT2: i32 = 35468;
36+
37+/// DC quantizer lookup, `dc_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1),
38+/// transcribed mechanically from libvpx `vp8/common/quant_common.c`.
39+const DC_QLOOKUP: [i16; 128] = [
40+ 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,
41+ 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44,
42+ 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
43+ 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91,
44+ 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130,
45+ 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
46+];
47+
48+/// AC quantizer lookup, `ac_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1),
49+/// transcribed mechanically from libvpx `vp8/common/quant_common.c`.
50+const AC_QLOOKUP: [i16; 128] = [
51+ 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,
52+ 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+ 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94,
54+ 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140,
55+ 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205,
56+ 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
57+];
58+
59+/// Clamps a (possibly delta-adjusted) quantizer index to the valid
60+/// qindex range `[0, 127]` — dixie `clamp_q` / libvpx bounds in
61+/// `quant_common.c` (RFC 6386 §14.1).
62+#[inline]
63+fn clamp_q(q: i32) -> i32 {
64+ q.clamp(0, 127)
65+}
66+
67+/// `dc_qlookup[clamp(q + delta)]` — Y-after-second / per-plane DC factor
68+/// lookup with delta adjustment (RFC 6386 §14.1 `dc_q`).
69+#[inline]
70+fn dc_factor(q: i32, delta: i32) -> i16 {
71+ DC_QLOOKUP[clamp_q(q + delta) as usize]
72+}
73+
74+/// `ac_qlookup[clamp(q + delta)]` — AC factor lookup with delta
75+/// adjustment (RFC 6386 §14.1 `ac_q`).
76+#[inline]
77+fn ac_factor(q: i32, delta: i32) -> i16 {
78+ AC_QLOOKUP[clamp_q(q + delta) as usize]
79+}
80+
81+/// Inverse Walsh-Hadamard transform of the 16 dequantized Y2 DC
82+/// coefficients into the 16 Y-subblock DC residuals
83+/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_c`, oracle
84+/// `vp8_short_inv_walsh4x4_c` in `idctllm.c`).
85+///
86+/// `input` is the row-major 4x4 block of dequantized Y2 DCs; the returned
87+/// array holds the 16 Y-subblock DC values in the same row-major order
88+/// (the reference scatters `output[i]` to `mb_dqcoeff[i * 16]`, i.e. the
89+/// DC slot of the i-th Y subblock — the caller places them). Two passes
90+/// of the exact 4-point Hadamard butterfly, with `short` truncation of
91+/// the first-pass results and `(x + 3) >> 3` rounding in the second.
92+#[inline]
93+pub fn iwht4x4(input: &[i16; 16]) -> [i16; 16] {
94+ let mut tmp = [0i16; 16];
95+
96+ // First pass: transform columns; results are stored transposed into
97+ // rows of `tmp` (ip walks input[i], input[4+i], input[8+i],
98+ // input[12+i]). libvpx stores into `short`: truncate to i16.
99+ for i in 0..4 {
100+ let a1 = input[i] as i32 + input[12 + i] as i32;
101+ let b1 = input[4 + i] as i32 + input[8 + i] as i32;
102+ let c1 = input[4 + i] as i32 - input[8 + i] as i32;
103+ let d1 = input[i] as i32 - input[12 + i] as i32;
104+
105+ tmp[i] = (a1 + b1) as i16;
106+ tmp[4 + i] = (c1 + d1) as i16;
107+ tmp[8 + i] = (a1 - b1) as i16;
108+ tmp[12 + i] = (d1 - c1) as i16;
109+ }
110+
111+ let mut output = [0i16; 16];
112+
113+ // Second pass: transform rows in place, rounding with (x + 3) >> 3.
114+ for r in 0..4 {
115+ let i = 4 * r;
116+ let a1 = tmp[i] as i32 + tmp[i + 3] as i32;
117+ let b1 = tmp[i + 1] as i32 + tmp[i + 2] as i32;
118+ let c1 = tmp[i + 1] as i32 - tmp[i + 2] as i32;
119+ let d1 = tmp[i] as i32 - tmp[i + 3] as i32;
120+
121+ let a2 = a1 + b1;
122+ let b2 = c1 + d1;
123+ let c2 = a1 - b1;
124+ let d2 = d1 - c1;
125+
126+ output[i] = ((a2 + 3) >> 3) as i16;
127+ output[i + 1] = ((b2 + 3) >> 3) as i16;
128+ output[i + 2] = ((c2 + 3) >> 3) as i16;
129+ output[i + 3] = ((d2 + 3) >> 3) as i16;
130+ }
131+
132+ output
133+}
134+
135+/// One-nonzero-DC shortcut of the inverse WHT
136+/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_1_c`, oracle
137+/// `vp8_short_inv_walsh4x4_1_c` in `idctllm.c`).
138+///
139+/// When only `input[0]` is non-zero, every Y-subblock DC equals
140+/// `(input[0] + 3) >> 3`. Bit-identical to `iwht4x4` for such inputs.
141+#[inline]
142+pub fn iwht4x4_dc(input: &[i16; 16]) -> [i16; 16] {
143+ let a1 = ((input[0] as i32 + 3) >> 3) as i16;
144+ [a1; 16]
145+}
146+
147+/// Full inverse DCT of one dequantized 4x4 coefficient block
148+/// (RFC 6386 §14.4; oracle `short_idct4x4llm_c` in `idctllm.c`).
149+///
150+/// `coeffs` is a row-major 4x4 block of **already dequantized**
151+/// coefficients (dequantization happens before the transform, RFC 6386
152+/// §14.5). Two passes of the 4-point inverse DCT with the §14.4
153+/// fixed-point constants; the `>> 16` multiplies carry no rounding
154+/// constant and the `(x + 4) >> 3` rounding is applied only in the
155+/// second pass. First-pass results are truncated to `i16` exactly where
156+/// the oracle stores into its `short output[16]` scratch.
157+///
158+/// Returns the row-major 4x4 residual. Not clamped, not added to the
159+/// prediction — see [`idct4x4_add`] for the combined form.
160+#[inline]
161+pub fn idct4x4(coeffs: &[i16; 16]) -> [i16; 16] {
162+ let mut tmp = [0i16; 16];
163+
164+ // First pass: transform columns; results land transposed in rows of
165+ // `tmp` (ip walks coeffs[i], coeffs[4+i], coeffs[8+i], coeffs[12+i]).
166+ for i in 0..4 {
167+ let a1 = coeffs[i] as i32 + coeffs[8 + i] as i32;
168+ let b1 = coeffs[i] as i32 - coeffs[8 + i] as i32;
169+
170+ let temp1 = (coeffs[4 + i] as i32 * SINPI8SQRT2) >> 16;
171+ let temp2 = coeffs[12 + i] as i32 + ((coeffs[12 + i] as i32 * COSPI8SQRT2MINUS1) >> 16);
172+ let c1 = temp1 - temp2;
173+
174+ let temp1 = coeffs[4 + i] as i32 + ((coeffs[4 + i] as i32 * COSPI8SQRT2MINUS1) >> 16);
175+ let temp2 = (coeffs[12 + i] as i32 * SINPI8SQRT2) >> 16;
176+ let d1 = temp1 + temp2;
177+
178+ // libvpx stores into `short`: truncate to i16.
179+ tmp[i] = (a1 + d1) as i16;
180+ tmp[12 + i] = (a1 - d1) as i16;
181+ tmp[4 + i] = (b1 + c1) as i16;
182+ tmp[8 + i] = (b1 - c1) as i16;
183+ }
184+
185+ let mut output = [0i16; 16];
186+
187+ // Second pass: transform rows, rounding with (x + 4) >> 3.
188+ for r in 0..4 {
189+ let i = 4 * r;
190+ let ip0 = tmp[i] as i32;
191+ let ip1 = tmp[i + 1] as i32;
192+ let ip2 = tmp[i + 2] as i32;
193+ let ip3 = tmp[i + 3] as i32;
194+
195+ let a1 = ip0 + ip2;
196+ let b1 = ip0 - ip2;
197+
198+ let temp1 = (ip1 * SINPI8SQRT2) >> 16;
199+ let temp2 = ip3 + ((ip3 * COSPI8SQRT2MINUS1) >> 16);
200+ let c1 = temp1 - temp2;
201+
202+ let temp1 = ip1 + ((ip1 * COSPI8SQRT2MINUS1) >> 16);
203+ let temp2 = (ip3 * SINPI8SQRT2) >> 16;
204+ let d1 = temp1 + temp2;
205+
206+ output[i] = ((a1 + d1 + 4) >> 3) as i16;
207+ output[i + 3] = ((a1 - d1 + 4) >> 3) as i16;
208+ output[i + 1] = ((b1 + c1 + 4) >> 3) as i16;
209+ output[i + 2] = ((b1 - c1 + 4) >> 3) as i16;
210+ }
211+
212+ output
213+}
214+
215+/// DC-only inverse DCT shortcut (RFC 6386 §14.4
216+/// `vp8_dc_only_idct_add_c` math; oracle `idctllm.c`): when position 0 is
217+/// the sole non-zero coefficient, every residual pixel is `(dc + 4) >> 3`.
218+///
219+/// Bit-identical to `idct4x4` on such inputs. Not clamped; the caller
220+/// adds and clamps (or uses [`idct4x4_add`]).
221+#[inline]
222+pub fn idct4x4_dc(dc: i16) -> [i16; 16] {
223+ let a1 = ((dc as i32 + 4) >> 3) as i16;
224+ [a1; 16]
225+}
226+
227+/// Combined per-block reconstruction kernel (RFC 6386 §14.4/§14.5; oracle
228+/// `short_idct4x4llm_c` final loop in `idctllm.c`): inverse-transforms
229+/// `coeffs` and writes `clamp(predict + residual)` into `recon`.
230+///
231+/// `coeffs` must already be dequantized (dequantization is applied before
232+/// the transform; for intra Y macroblocks the DC positions already hold
233+/// the [`iwht4x4`] output). `predict` and `recon` are row-major 4x4
234+/// blocks of exactly 16 bytes each. Residuals are fully computed before
235+/// any output byte is written.
236+#[inline]
237+pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) {
238+ let residual = idct4x4(coeffs);
239+ for i in 0..16 {
240+ let a = residual[i] as i32 + predict[i] as i32;
241+ recon[i] = a.clamp(0, 255) as u8;
242+ }
243+}
244+
245+/// Dequantization factors for one macroblock, indexed by plane and
246+/// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`).
247+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248+pub struct Dequant {
249+ /// Y plane, DC coefficient (after inverse WHT for intra Y2 rows).
250+ pub y1_dc: i16,
251+ /// Y plane, AC coefficients.
252+ pub y1_ac: i16,
253+ /// Y2 plane (second-order) DC coefficient: `dc_qlookup[...] * 2`.
254+ pub y2_dc: i16,
255+ /// Y2 plane AC coefficient: `ac_qlookup[...] * 155 / 100`, floored at 8.
256+ pub y2_ac: i16,
257+ /// Chroma DC coefficient, capped at 132 after lookup.
258+ pub uv_dc: i16,
259+ /// Chroma AC coefficient.
260+ pub uv_ac: i16,
261+}
262+
263+/// Computes the six dequantization factors for quantizer index `q` with
264+/// the per-frame delta updates (RFC 6386 §9.6 header fields applied per
265+/// §14.1; dixie `dequant_init`, oracle `vp8cx_init_quantizer` in
266+/// libvpx `decodframe.c` / `quant_common.c`).
267+///
268+/// `q` is the per-macroblock segment-adjusted base qindex (already
269+/// absolute or offset by the segment level per the segment header); the
270+/// delta arguments are the frame-header updates. Each lookup clamps its
271+/// `q + delta` sum to `[0, 127]`. Semantics transcribed exactly:
272+/// - `y1_dc = dc_qlookup[clamp(q + y1_dc_delta)]`,
273+/// `y1_ac = ac_qlookup[clamp(q)]` (no delta exists for Y AC),
274+/// - `y2_dc = dc_qlookup[clamp(q + y2_dc_delta)] * 2`,
275+/// - `y2_ac = ac_qlookup[clamp(q + y2_ac_delta)] * 155 / 100` (integer
276+/// division), floored at 8,
277+/// - `uv_dc = min(dc_qlookup[clamp(q + uv_dc_delta)], 132)` (cap applied
278+/// after the lookup),
279+/// - `uv_ac = ac_qlookup[clamp(q + uv_ac_delta)]`.
280+#[must_use]
281+pub fn dequant(
282+ q: i32,
283+ y1_dc_delta: i32,
284+ y2_dc_delta: i32,
285+ y2_ac_delta: i32,
286+ uv_dc_delta: i32,
287+ uv_ac_delta: i32,
288+) -> Dequant {
289+ Dequant {
290+ y1_dc: dc_factor(q, y1_dc_delta),
291+ y1_ac: ac_factor(q, 0),
292+ y2_dc: dc_factor(q, y2_dc_delta) * 2,
293+ y2_ac: {
294+ let v = (ac_factor(q, y2_ac_delta) as i32 * 155) / 100;
295+ (if v < 8 { 8 } else { v }) as i16
296+ },
297+ uv_dc: {
298+ let v = dc_factor(q, uv_dc_delta);
299+ if v > 132 { 132 } else { v }
300+ },
301+ uv_ac: ac_factor(q, uv_ac_delta),
302+ }
303+}
304+
305+#[cfg(test)]
306+mod tests {
307+ use super::*;
308+
309+ /// Hand-derived: impulse `input[0] = 8`, all else 0. First pass, the
310+ /// only touched column (0) reads (8,0,0,0): a1 = 8+0 = 8, b1 = 0,
311+ /// c1 = 0, d1 = 8, giving intermediate column 0 = [8,8,8,8]. Second
312+ /// pass, every row reads (8,0,0,0): a2 = b2 = c2 = d2 = 8, and
313+ /// (8 + 3) >> 3 = 1. Expected: all 16 outputs are 1.
314+ #[test]
315+ fn iwht_unit_impulse_yields_all_ones() {
316+ let mut input = [0i16; 16];
317+ input[0] = 8;
318+ assert_eq!(iwht4x4(&input), [1i16; 16]);
319+ }
320+
321+ /// Hand-derived: impulse `input[5] = 8` (row 1, col 1). First pass,
322+ /// column 1 reads (0,8,0,0): a1 = 0, b1 = 8, c1 = 8, d1 = 0, giving
323+ /// intermediate column 1 = [8, 8, -8, -8]. Second pass, rows 0-1 read
324+ /// (0,8,0,0) → outputs (1, 1, -1, -1); rows 2-3 read (0,-8,0,0) →
325+ /// (-1, -1, 1, 1) — the Hadamard basis pattern for position (1,1).
326+ #[test]
327+ fn iwht_impulse_at_row1_col1_yields_hadamard_pattern() {
328+ let mut input = [0i16; 16];
329+ input[5] = 8;
330+ assert_eq!(
331+ iwht4x4(&input),
332+ [
333+ 1, 1, -1, -1, //
334+ 1, 1, -1, -1, //
335+ -1, -1, 1, 1, //
336+ -1, -1, 1, 1,
337+ ]
338+ );
339+ }
340+
341+ /// Mixed-coefficient oracle: expected values computed with a Python
342+ /// model of the exact libvpx integer algorithm (see the model in
343+ /// `idct_mixed_block_matches_oracle` below — the WHT variant is the
344+ /// same structure with §14.3 butterflies and `(x + 3) >> 3`).
345+ #[test]
346+ fn iwht_mixed_block_matches_oracle() {
347+ let input = [
348+ 40, -13, 0, 7, 222, 5, -40, 1, 0, 0, 17, -9, 300, -250, 88, 3,
349+ ];
350+ assert_eq!(
351+ iwht4x4(&input),
352+ [
353+ 46, 30, 95, 110, //
354+ 9, 42, -15, -55, //
355+ -3, -35, 37, 60, //
356+ -36, -27, -86, -92,
357+ ]
358+ );
359+ }
360+
361+ /// The `_dc` shortcut must agree with the full transform whenever
362+ /// only `input[0]` is non-zero — across the whole practical range,
363+ /// including negatives and both i16 extremes (arithmetic shifts are
364+ /// floor rounding for negatives in both C and Rust).
365+ #[test]
366+ fn iwht_dc_shortcut_matches_full_transform() {
367+ for v in [
368+ 0,
369+ 1,
370+ -1,
371+ 3,
372+ -3,
373+ 8,
374+ -8,
375+ 100,
376+ -100,
377+ 1234,
378+ -4321,
379+ i16::MAX,
380+ i16::MIN,
381+ ] {
382+ let input = {
383+ let mut i = [0i16; 16];
384+ i[0] = v;
385+ i
386+ };
387+ assert_eq!(iwht4x4(&input), iwht4x4_dc(&input), "mismatch at dc={v}");
388+ }
389+ }
390+
391+ /// §14.4 DC-only math: input [40, 0, ...] gives every pixel
392+ /// (40 + 4) >> 3 = 5.
393+ #[test]
394+ fn idct_dc_only_40_yields_five() {
395+ let coeffs = {
396+ let mut c = [0i16; 16];
397+ c[0] = 40;
398+ c
399+ };
400+ assert_eq!(idct4x4(&coeffs), [5i16; 16]);
401+ assert_eq!(idct4x4_dc(40), [5i16; 16]);
402+ }
403+
404+ /// Mixed-coefficient oracle. The Python model below is a line-for-line
405+ /// transcription of libvpx `short_idct4x4llm_c` (same integer math,
406+ /// `short` truncation between passes via `s16`); running it on
407+ /// `coeffs` prints the expected block embedded in the assertion.
408+ ///
409+ /// ```python
410+ /// COS, SIN = 20091, 35468
411+ /// def s16(x):
412+ /// x &= 0xFFFF
413+ /// return x - 0x10000 if x >= 0x8000 else x
414+ /// def idct(inp):
415+ /// out = [0] * 16
416+ /// for i in range(4): # pass 1: columns, transposed into rows
417+ /// a1 = inp[i] + inp[8+i]; b1 = inp[i] - inp[8+i]
418+ /// c1 = ((inp[4+i]*SIN) >> 16) - (inp[12+i] + ((inp[12+i]*COS) >> 16))
419+ /// d1 = (inp[4+i] + ((inp[4+i]*COS) >> 16)) + ((inp[12+i]*SIN) >> 16)
420+ /// out[i] = s16(a1 + d1); out[12+i] = s16(a1 - d1)
421+ /// out[4+i] = s16(b1 + c1); out[8+i] = s16(b1 - c1)
422+ /// res = [0] * 16
423+ /// for i in range(4): # pass 2: rows, rounding (x + 4) >> 3
424+ /// ip = out[4*i:4*i+4]
425+ /// a1 = ip[0] + ip[2]; b1 = ip[0] - ip[2]
426+ /// c1 = ((ip[1]*SIN) >> 16) - (ip[3] + ((ip[3]*COS) >> 16))
427+ /// d1 = (ip[1] + ((ip[1]*COS) >> 16)) + ((ip[3]*SIN) >> 16)
428+ /// res[4*i+0] = s16((a1 + d1 + 4) >> 3)
429+ /// res[4*i+3] = s16((a1 - d1 + 4) >> 3)
430+ /// res[4*i+1] = s16((b1 + c1 + 4) >> 3)
431+ /// res[4*i+2] = s16((b1 - c1 + 4) >> 3)
432+ /// return res
433+ /// ```
434+ #[test]
435+ fn idct_mixed_block_matches_oracle() {
436+ let coeffs = [
437+ 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55,
438+ ];
439+ assert_eq!(
440+ idct4x4(&coeffs),
441+ [
442+ 305, 108, 139, 72, //
443+ -508, -228, -88, 303, //
444+ 372, 85, -443, -640, //
445+ -48, -41, 345, 441,
446+ ]
447+ );
448+ }
449+
450+ /// The DC-only shortcut must equal the full transform for any value
451+ /// at coefficient position 0 (with the rest zero), including the i16
452+ /// extremes where the intermediate still fits.
453+ #[test]
454+ fn idct_dc_shortcut_matches_full_transform() {
455+ for v in [
456+ 0,
457+ 1,
458+ -1,
459+ 8,
460+ -8,
461+ 40,
462+ -40,
463+ 100,
464+ -100,
465+ 4088,
466+ i16::MAX,
467+ i16::MIN,
468+ ] {
469+ let coeffs = {
470+ let mut c = [0i16; 16];
471+ c[0] = v;
472+ c
473+ };
474+ assert_eq!(idct4x4(&coeffs), idct4x4_dc(v), "mismatch at dc={v}");
475+ }
476+ }
477+
478+ /// §14.5: `idct4x4_add` is `clamp255(predict + idct4x4(coeffs))`
479+ /// pixelwise. With a flat prediction of 100, every output byte must
480+ /// be the saturated sum; extreme residuals clamp to 0 and 255.
481+ #[test]
482+ fn idct_add_equals_clamped_predict_plus_residual() {
483+ let coeffs = [
484+ 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55,
485+ ];
486+ let residual = idct4x4(&coeffs);
487+ let predict = [100u8; 16];
488+ let mut recon = [0u8; 16];
489+ idct4x4_add(&coeffs, &predict, &mut recon);
490+ for i in 0..16 {
491+ let expected = (residual[i] as i32 + 100).clamp(0, 255) as u8;
492+ assert_eq!(recon[i], expected, "pixel {i}");
493+ }
494+
495+ // Saturation: DC 4088 → residual (4088 + 4) >> 3 = 511; 100 + 511
496+ // clamps to 255. Negative DC -32768 → residual (-32764) >> 3 =
497+ // -4096; clamps to 0.
498+ let mut hi = [0i16; 16];
499+ hi[0] = 4088;
500+ let mut lo = [0i16; 16];
501+ lo[0] = i16::MIN;
502+ let mut recon = [0u8; 16];
503+ idct4x4_add(&hi, &predict, &mut recon);
504+ assert_eq!(recon, [255u8; 16]);
505+ idct4x4_add(&lo, &predict, &mut recon);
506+ assert_eq!(recon, [0u8; 16]);
507+ }
508+
509+ /// `idct4x4_add` over an existing recon block that already holds the
510+ /// prediction (the common libvpx dst/pred shape). The `&[u8]` /
511+ /// `&mut [u8]` signature statically excludes predict/recon aliasing.
512+ #[test]
513+ fn idct_add_updates_existing_recon_buffer() {
514+ let coeffs = {
515+ let mut c = [0i16; 16];
516+ c[0] = 40;
517+ c
518+ };
519+ let predict = [100u8; 16];
520+ let mut recon = [100u8; 16];
521+ idct4x4_add(&coeffs, &predict, &mut recon);
522+ assert_eq!(recon, [105u8; 16]);
523+ }
524+
525+ /// §14.1 tables, transcribed from libvpx `quant_common.c`: exact
526+ /// length plus boundary and known-trap entries (the duplicated 10 at
527+ /// dc[6..7], the >89 acceleration at dc[95..96] and dc[111..112], and
528+ /// the ac[54..55] and ac[84..85] jumps).
529+ #[test]
530+ fn quant_lookup_tables_match_libvpx() {
531+ assert_eq!(DC_QLOOKUP.len(), 128);
532+ assert_eq!(AC_QLOOKUP.len(), 128);
533+ assert_eq!(&DC_QLOOKUP[..3], &[4, 5, 6]);
534+ assert_eq!(DC_QLOOKUP[127], 157);
535+ assert_eq!(AC_QLOOKUP[0], 4);
536+ assert_eq!(AC_QLOOKUP[127], 284);
537+ assert_eq!(&DC_QLOOKUP[6..=8], &[10, 10, 11]);
538+ assert_eq!(&DC_QLOOKUP[95..=97], &[89, 91, 93]);
539+ assert_eq!(&DC_QLOOKUP[111..=112], &[118, 122]);
540+ assert_eq!(&AC_QLOOKUP[53..=55], &[57, 58, 60]);
541+ assert_eq!(&AC_QLOOKUP[83..=85], &[116, 119, 122]);
542+ }
543+
544+ /// §14.1 boundary qindices: q=0 gives the minimum factors (with the
545+ /// Y2 AC floor of 8 already active), q=127 gives the maxima including
546+ /// the chroma DC cap at 132.
547+ #[test]
548+ fn dequant_at_qindex_boundaries() {
549+ assert_eq!(
550+ dequant(0, 0, 0, 0, 0, 0),
551+ Dequant {
552+ y1_dc: 4,
553+ y1_ac: 4,
554+ y2_dc: 8,
555+ y2_ac: 8,
556+ uv_dc: 4,
557+ uv_ac: 4
558+ }
559+ );
560+ assert_eq!(
561+ dequant(127, 0, 0, 0, 0, 0),
562+ Dequant {
563+ y1_dc: 157,
564+ y1_ac: 284,
565+ y2_dc: 314,
566+ y2_ac: 440, // 284 * 155 / 100
567+ uv_dc: 132, // 157 capped at 132
568+ uv_ac: 284,
569+ }
570+ );
571+ }
572+
573+ /// Delta-adjusted qindices clamp to [0, 127] before each lookup, for
574+ /// every delta channel (RFC 6386 §14.1 dixie `clamp_q`).
575+ #[test]
576+ fn dequant_delta_indices_clamp_to_qindex_range() {
577+ let lo = dequant(0, -1000, -1000, -1000, -1000, -1000);
578+ assert_eq!(lo.y1_dc, 4);
579+ assert_eq!(lo.y2_dc, 8); // 4 * 2
580+ assert_eq!(lo.y2_ac, 8); // floor
581+ assert_eq!(lo.uv_dc, 4);
582+ assert_eq!(lo.uv_ac, 4);
583+
584+ let hi = dequant(127, 1000, 1000, 1000, 1000, 1000);
585+ assert_eq!(hi.y1_dc, 157);
586+ assert_eq!(hi.y2_dc, 314);
587+ assert_eq!(hi.y2_ac, 440);
588+ assert_eq!(hi.uv_dc, 132);
589+ assert_eq!(hi.uv_ac, 284);
590+
591+ // A base q of 0 with positive deltas reaches mid-table: q=60 has
592+ // dc_qlookup[60] = 55, ac_qlookup[60] = 70.
593+ let mid = dequant(0, 60, 60, 60, 60, 60);
594+ assert_eq!(mid.y1_dc, 55);
595+ assert_eq!(mid.y1_ac, 4); // Y AC has no delta channel
596+ assert_eq!(mid.y2_dc, 110);
597+ assert_eq!(mid.y2_ac, 70 * 155 / 100); // 108
598+ assert_eq!(mid.uv_dc, 55);
599+ assert_eq!(mid.uv_ac, 70);
600+ }
601+
602+ /// The Y2 AC floor: `x * 155 / 100 < 8` becomes 8. At q=0..4
603+ /// (ac = 4..8) the scaled values are 6, 7, 9, 10, 12 — only the first
604+ /// two floor up.
605+ #[test]
606+ fn dequant_y2_ac_floor_at_eight() {
607+ for q in 0..=4i32 {
608+ let ac = AC_QLOOKUP[q as usize] as i32;
609+ let scaled = ac * 155 / 100;
610+ assert_eq!(
611+ dequant(q, 0, 0, 0, 0, 0).y2_ac as i32,
612+ scaled.max(8),
613+ "q={q}"
614+ );
615+ }
616+ assert_eq!(dequant(0, 0, 0, 0, 0, 0).y2_ac, 8); // 4*155/100 = 6 → 8
617+ assert_eq!(dequant(1, 0, 0, 0, 0, 0).y2_ac, 8); // 5*155/100 = 7 → 8
618+ assert_eq!(dequant(2, 0, 0, 0, 0, 0).y2_ac, 9); // 6*155/100 = 9
619+ }
620+
621+ /// libvpx computes the Y2 AC factor as `(x * 101581) >> 16` and its
622+ /// comment asserts bitwise equality with `x * 155 / 100` for all
623+ /// table entries; our transcription of dixie uses `* 155 / 100`, so
624+ /// sweep the whole qindex range and prove the two agree through the
625+ /// public API (with a matching delta for the Y2 AC channel).
626+ #[test]
627+ fn dequant_y2_ac_matches_libvpx_fixed_point_over_all_q() {
628+ for q in 0..=127i32 {
629+ for delta in [0, -q - 1, 127 - q] {
630+ let x = AC_QLOOKUP[clamp_q(q + delta) as usize] as i32;
631+ let expected = (((x * 101581) >> 16).max(8)) as i16;
632+ assert_eq!(
633+ dequant(q, 0, 0, delta, 0, 0).y2_ac,
634+ expected,
635+ "q={q}, delta={delta}"
636+ );
637+ }
638+ }
639+ }
640+}
crates/ec-vp8/tests/header_parse.rsadded+138 -0
@@ -0,0 +1,138 @@
1+//! M1 witness: the header parser handles real libvpx-produced key frames
2+//! (and a VP8-in-WebP still) with no desync and the right dimensions.
3+
4+mod ivf;
5+
6+use ec_vp8::PersistedState;
7+use ec_vp8::frame::{FrameTag, FrameType, mb_geometry, parse_keyframe_dims};
8+use ec_vp8::header::FrameHeader;
9+
10+const FIXTURES: &[(&str, u16, u16)] = &[
11+ ("kf-160x96-q20.ivf", 160, 96),
12+ ("kf-160x96-q40.ivf", 160, 96),
13+ ("kf-76x52-q30.ivf", 76, 52),
14+ ("kf-32x16-q35.ivf", 32, 16),
15+ ("kf-172x144-q25.ivf", 172, 144),
16+ ("kf-96x80-q63.ivf", 96, 80),
17+ ("mparts-160x96.ivf", 160, 96),
18+];
19+
20+#[test]
21+fn parses_real_key_frame_headers() {
22+ let Some(dir) = ivf::fixture_dir() else {
23+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
24+ };
25+ for (name, width, height) in FIXTURES {
26+ let bytes = std::fs::read(dir.join(name)).unwrap();
27+ let (fourcc, w, h, frames) = ivf::parse_ivf(&bytes);
28+ assert_eq!(fourcc, "VP80", "{name}");
29+ assert_eq!((w, h), (*width, *height), "{name} IVF dimensions");
30+ assert!(!frames.is_empty(), "{name} has no frames");
31+
32+ let first = &frames[0].data;
33+ let tag = FrameTag::parse(first).unwrap();
34+ assert_eq!(tag.frame_type, FrameType::Key, "{name} first frame");
35+ assert!(tag.show_frame, "{name} first frame must be shown");
36+ assert_eq!(tag.version, 0, "{name}: default profile");
37+ let kf = parse_keyframe_dims(first).unwrap();
38+ assert_eq!((kf.width, kf.height), (*width, *height));
39+ assert_eq!((kf.h_scale, kf.v_scale), (0, 0), "{name} unscaled");
40+
41+ let mut state = PersistedState::default();
42+ let (header, _) = FrameHeader::parse(first, &mut state).unwrap();
43+ assert_eq!(header.token_data_offset - 10, tag.first_part_size as usize);
44+ assert!(header.dims.is_some());
45+ assert_eq!(header.color_space, 0, "{name}: YUV colour space");
46+ assert_eq!(
47+ header.partition_sizes.len(),
48+ 1usize << header.log2_partitions,
49+ "{name} partition count vs log2 field"
50+ );
51+ let n_parts = header.partition_sizes.len();
52+ assert_eq!(
53+ header.token_data_offset
54+ + 3 * (n_parts - 1)
55+ + header.partition_sizes.iter().sum::<u32>() as usize,
56+ first.len(),
57+ "{name}: partition sizes must tile the frame exactly"
58+ );
59+ // The header partition must decode without reading past its end.
60+ assert!(
61+ header.quant.yac_qi <= 127,
62+ "{name}: qindex sanity {}",
63+ header.quant.yac_qi
64+ );
65+ let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height);
66+ assert_eq!(
67+ (mb_cols, mb_rows),
68+ (
69+ (usize::from(*width) + 15) / 16,
70+ (usize::from(*height) + 15) / 16
71+ )
72+ );
73+ }
74+}
75+
76+#[test]
77+fn parses_multi_partition_header() {
78+ let Some(dir) = ivf::fixture_dir() else {
79+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
80+ };
81+ let bytes = std::fs::read(dir.join("mparts-160x96.ivf")).unwrap();
82+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
83+ let mut state = PersistedState::default();
84+ let (header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap();
85+ // vpxenc was asked for --token-parts=3 => 8 token partitions.
86+ assert_eq!(header.log2_partitions, 3, "8 token partitions expected");
87+ assert_eq!(header.partition_sizes.len(), 8);
88+ assert!(header.partition_sizes.iter().all(|&s| s > 0));
89+}
90+
91+#[test]
92+fn parses_vp8_in_webp_still() {
93+ let Some(dir) = ivf::fixture_dir() else {
94+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
95+ };
96+ let Ok(bytes) = std::fs::read(dir.join("still.webp")) else {
97+ panic!("still.webp missing (libwebp encoder unavailable at generation time)");
98+ };
99+ let vp8 = ivf::webp_vp8_chunk(&bytes);
100+ let tag = FrameTag::parse(&vp8).unwrap();
101+ assert_eq!(tag.frame_type, FrameType::Key);
102+ let kf = parse_keyframe_dims(&vp8).unwrap();
103+ assert_eq!((kf.width, kf.height), (96, 80));
104+ let mut state = PersistedState::default();
105+ let (header, _) = FrameHeader::parse(&vp8, &mut state).unwrap();
106+ assert!(header.dims.is_some());
107+}
108+
109+#[test]
110+fn gop_key_frame_parses_and_coexists_with_inter() {
111+ let Some(dir) = ivf::fixture_dir() else {
112+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
113+ };
114+ let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap();
115+ let (_, _, _, frames) = ivf::parse_ivf(&bytes);
116+ assert!(frames.len() >= 30);
117+
118+ let mut state = PersistedState::default();
119+ let (kf_header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap();
120+ assert_eq!(kf_header.frame_type(), FrameType::Key);
121+ assert!(kf_header.refresh.refresh_last && kf_header.refresh.refresh_gf);
122+
123+ // First inter frame: header fields come from the same first partition,
124+ // and the persisted entropy state has absorbed the key frame's updates.
125+ let mut inter_seen = false;
126+ for f in &frames[1..] {
127+ let tag = FrameTag::parse(&f.data).unwrap();
128+ if tag.frame_type == FrameType::Key {
129+ continue;
130+ }
131+ let (header, _) = FrameHeader::parse(&f.data, &mut state).unwrap();
132+ assert_eq!(header.frame_type(), FrameType::Inter);
133+ assert!(header.dims.is_none(), "inter frames carry no dimensions");
134+ inter_seen = true;
135+ break;
136+ }
137+ assert!(inter_seen, "gop fixture has no inter frame");
138+}
crates/ec-vp8/tests/ivf.rsadded+83 -0
@@ -0,0 +1,83 @@
1+//! Minimal IVF demuxing for the ec-vp8 test fixtures (RFC's companion
2+//! container; only what the witnesses need).
3+
4+/// One IVF frame: (pts, payload).
5+pub struct IvfFrame {
6+ /// Presentation timestamp from the IVF frame header.
7+ #[allow(dead_code)]
8+ pub pts: u64,
9+ /// The compressed VP8 frame payload.
10+ #[allow(dead_code)] // pts-only consumers exist in the stream witnesses
11+ pub data: Vec<u8>,
12+}
13+
14+/// The frame tag's `show_frame` bit (RFC 6386 §9.1): hidden frames
15+/// (`false`) update the reference buffers but are never displayed.
16+#[allow(dead_code)] // not every witness binary needs the census
17+pub fn show_frame(data: &[u8]) -> bool {
18+ (data[0] >> 4) & 1 == 1
19+}
20+
21+/// Parse an IVF file into (fourcc, width, height, frames).
22+pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
23+ assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file");
24+ let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
25+ let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap();
26+ let width = u16::from_le_bytes([bytes[12], bytes[13]]);
27+ let height = u16::from_le_bytes([bytes[14], bytes[15]]);
28+ let mut pos = hdr_len;
29+ let mut frames = Vec::new();
30+ while pos + 12 <= bytes.len() {
31+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
32+ as usize;
33+ let pts = u64::from_le_bytes([
34+ bytes[pos + 4],
35+ bytes[pos + 5],
36+ bytes[pos + 6],
37+ bytes[pos + 7],
38+ bytes[pos + 8],
39+ bytes[pos + 9],
40+ bytes[pos + 10],
41+ bytes[pos + 11],
42+ ]);
43+ pos += 12;
44+ if pos + sz > bytes.len() {
45+ break;
46+ }
47+ frames.push(IvfFrame {
48+ pts,
49+ data: bytes[pos..pos + sz].to_vec(),
50+ });
51+ pos += sz;
52+ }
53+ (fourcc, width, height, frames)
54+}
55+
56+/// Extract the VP8 payload from a lossy WebP file (RIFF/WEBP with a VP8
57+/// chunk) — the same VP8 key-frame bytes in a different container.
58+#[allow(dead_code)] // only the keyframe_exact binary exercises WebP
59+pub fn webp_vp8_chunk(bytes: &[u8]) -> Vec<u8> {
60+ assert_eq!(&bytes[0..4], b"RIFF");
61+ assert_eq!(&bytes[8..12], b"WEBP");
62+ let mut pos = 12;
63+ while pos + 8 <= bytes.len() {
64+ let tag = &bytes[pos..pos + 4];
65+ let sz = u32::from_le_bytes([
66+ bytes[pos + 4],
67+ bytes[pos + 5],
68+ bytes[pos + 6],
69+ bytes[pos + 7],
70+ ]) as usize;
71+ if tag == b"VP8 " {
72+ return bytes[pos + 8..pos + 8 + sz].to_vec();
73+ }
74+ pos += 8 + sz + (sz & 1); // chunks are word-aligned
75+ }
76+ panic!("no VP8 chunk in webp");
77+}
78+
79+/// Root of the workspace checkout this test runs in (crates/ec-vp8/../..).
80+pub fn fixture_dir() -> Option<std::path::PathBuf> {
81+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vp8");
82+ if dir.is_dir() { Some(dir) } else { None }
83+}
crates/ec-vp8/tests/keyframe_exact.rsadded+156 -0
@@ -0,0 +1,156 @@
1+//! M2 witness: key-frame decode is sample-exact against ffmpeg/libvpx
2+//! (`ffmpeg -v error -i in.ivf -f rawvideo -pix_fmt yuv420p -`).
3+
4+mod ivf;
5+
6+use ec_vp8::decode::Decoder;
7+
8+/// ffmpeg's decoded rawvideo byte stream for the same file.
9+fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec<u8> {
10+ let out = std::process::Command::new("ffmpeg")
11+ .args(["-v", "error", "-i"])
12+ .arg(path)
13+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
14+ .output()
15+ .expect("ffmpeg must be on PATH for the witnesses");
16+ assert!(out.status.success(), "ffmpeg failed on {path:?}");
17+ out.stdout
18+}
19+
20+fn raw<'a>(pos: &mut usize, data: &'a [u8], len: usize) -> &'a [u8] {
21+ let s = &data[*pos..*pos + len];
22+ *pos += len;
23+ s
24+}
25+
26+/// Decode every frame of an IVF with our decoder and compare each SHOWN
27+/// frame's planes against ffmpeg's byte stream (ffmpeg skips hidden
28+/// `show_frame == 0` frames exactly like a player).
29+fn compare(name: &str, skip_if_missing: bool) {
30+ let Some(dir) = ivf::fixture_dir() else {
31+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
32+ };
33+ let path = dir.join(name);
34+ if skip_if_missing && !path.exists() {
35+ panic!("{name} missing (regenerate fixtures)");
36+ }
37+ let bytes = std::fs::read(&path).unwrap();
38+ let (_, w, h, frames) = ivf::parse_ivf(&bytes);
39+ let all = ffmpeg_raw_yuv(&path);
40+ let frame_len = usize::from(w) * usize::from(h) * 3 / 2;
41+ let shown: Vec<&ivf::IvfFrame> =
42+ frames.iter().filter(|f| ivf::show_frame(&f.data)).collect();
43+ assert_eq!(
44+ all.len(),
45+ shown.len() * frame_len,
46+ "{name}: ffmpeg output {}/{} not {} whole shown frames",
47+ all.len(),
48+ frame_len,
49+ shown.len()
50+ );
51+
52+ let mut dec = Decoder::new();
53+ let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2);
54+ let mut shown_idx = 0;
55+ for (i, f) in frames.iter().enumerate() {
56+ match dec.decode(&f.data).expect("decode succeeds") {
57+ Some(pic) => {
58+ assert!(ivf::show_frame(&f.data), "{name} frame {i}: picture for hidden frame");
59+ assert_eq!(pic.width, w);
60+ assert_eq!(pic.height, h);
61+ let mut pos = shown_idx * frame_len;
62+ shown_idx += 1;
63+ let exp_y = raw(&mut pos, &all, usize::from(w) * usize::from(h));
64+ let exp_u = raw(&mut pos, &all, cw * ch);
65+ let exp_v = raw(&mut pos, &all, cw * ch);
66+ assert_eq!(pic.y, exp_y, "{name} frame {i}: luma mismatch");
67+ assert_eq!(pic.u, exp_u, "{name} frame {i}: U mismatch");
68+ assert_eq!(pic.v, exp_v, "{name} frame {i}: V mismatch");
69+ }
70+ None => assert!(
71+ !ivf::show_frame(&f.data),
72+ "{name} frame {i}: shown frame produced no picture"
73+ ),
74+ }
75+ }
76+ assert_eq!(shown_idx, shown.len(), "{name}: shown picture count");
77+}
78+
79+#[test]
80+fn keyframes_match_ffmpeg() {
81+ for (name, _, _) in [
82+ ("kf-160x96-q20.ivf", 160, 96),
83+ ("kf-160x96-q40.ivf", 160, 96),
84+ ("kf-76x52-q30.ivf", 76, 52),
85+ ("kf-32x16-q35.ivf", 32, 16),
86+ ("kf-172x144-q25.ivf", 172, 144),
87+ ("kf-96x80-q63.ivf", 96, 80),
88+ ] {
89+ compare(name, false);
90+ }
91+}
92+
93+#[test]
94+fn multi_partition_keyframe_matches_ffmpeg() {
95+ compare("mparts-160x96.ivf", false);
96+}
97+
98+/// M3 witness: full inter-frame streams — simple-filter GOP, multi-token-
99+/// partition, hidden-altref and the OBS screen-content clip — decode
100+/// byte-exact against ffmpeg, every frame. The altref vector must
101+/// actually CONTAIN hidden frames (census the tags; a shown-only stream
102+/// would silently stop exercising the hidden-frame contract).
103+#[test]
104+fn interframe_streams_match_ffmpeg() {
105+ for name in [
106+ "gop-160x96.ivf",
107+ "clip-obs-320x192.ivf",
108+ "altref-160x96.ivf",
109+ ] {
110+ if name == "altref-160x96.ivf" {
111+ let dir = ivf::fixture_dir().expect("fixtures dir");
112+ let bytes = std::fs::read(dir.join(name)).unwrap();
113+ let hidden = census_hidden(&bytes);
114+ assert!(
115+ hidden >= 6,
116+ "{name}: only {hidden} hidden frames — regenerate with \
117+ scripts/gen_vp8_fixtures.sh (--auto-alt-ref=1 --passes=2)"
118+ );
119+ }
120+ compare(name, false);
121+ }
122+}
123+
124+/// Number of hidden (`show_frame == 0`) frames in an IVF stream.
125+fn census_hidden(bytes: &[u8]) -> usize {
126+ let (_, _, _, frames) = ivf::parse_ivf(bytes);
127+ frames.iter().filter(|f| !ivf::show_frame(&f.data)).count()
128+}
129+
130+#[test]
131+fn vp8_in_webp_still_matches_ffmpeg() {
132+ let Some(dir) = ivf::fixture_dir() else {
133+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
134+ };
135+ let bytes = std::fs::read(dir.join("still.webp")).unwrap();
136+ let vp8 = ivf::webp_vp8_chunk(&bytes);
137+ let reference = std::process::Command::new("ffmpeg")
138+ .args(["-v", "error", "-i"])
139+ .arg(dir.join("still.webp"))
140+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
141+ .output()
142+ .unwrap();
143+ assert!(reference.status.success());
144+ let mut dec = Decoder::new();
145+ let pic = dec.decode(&vp8).expect("decode").expect("shown");
146+ assert_eq!(
147+ pic.y.len() + pic.u.len() + pic.v.len(),
148+ reference.stdout.len()
149+ );
150+ let mut exp = &reference.stdout[..];
151+ assert_eq!(pic.y, &exp[..pic.y.len()]);
152+ exp = &exp[pic.y.len()..];
153+ assert_eq!(pic.u, &exp[..pic.u.len()]);
154+ exp = &exp[pic.u.len()..];
155+ assert_eq!(pic.v, exp);
156+}
crates/ec-vp8/tests/stream_exact.rsadded+141 -0
@@ -0,0 +1,141 @@
1+//! M4 witness: the whole-stream public API (`ec_vp8::stream`) decodes
2+//! every fixture byte-exact against ffmpeg and refuses malformed
3+//! containers with errors, not panics.
4+
5+mod ivf;
6+
7+use ec_vp8::decode::Decoder;
8+use ec_vp8::stream::decode_stream;
9+
10+/// Every IVF fixture in the witness set (the WebP still is covered by
11+/// `keyframe_exact::vp8_in_webp_still_matches_ffmpeg`).
12+const FIXTURES: &[&str] = &[
13+ "kf-16x16-black-q0.ivf",
14+ "kf-32x16-q35.ivf",
15+ "kf-76x52-q30.ivf",
16+ "kf-96x80-q63.ivf",
17+ "kf-160x96-q20.ivf",
18+ "kf-160x96-q40.ivf",
19+ "kf-172x144-q25.ivf",
20+ "gop-96x80-v1.ivf",
21+ "gop-160x96.ivf",
22+ "mparts-160x96.ivf",
23+ "altref-160x96.ivf",
24+ "clip-obs-320x192.ivf",
25+];
26+
27+#[test]
28+fn decode_stream_matches_ffmpeg_on_every_fixture() {
29+ let Some(dir) = ivf::fixture_dir() else {
30+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
31+ };
32+ for name in FIXTURES {
33+ let path = dir.join(name);
34+ let bytes = std::fs::read(&path).unwrap();
35+ let (_, w, h, frames) = ivf::parse_ivf(&bytes);
36+ let all = ffmpeg_raw_yuv(&path);
37+ let frame_len = usize::from(w) * usize::from(h) * 3 / 2;
38+ let shown = frames.iter().filter(|f| ivf::show_frame(&f.data)).count();
39+ assert_eq!(all.len(), shown * frame_len, "{name}: ffmpeg output size");
40+ assert!(!frames[0].data.is_empty(), "{name}: empty first frame");
41+
42+ let pictures =
43+ decode_stream(&bytes).unwrap_or_else(|e| panic!("{name}: decode failed: {e}"));
44+ assert_eq!(pictures.len(), shown, "{name}: picture count (shown only)");
45+ for (i, pic) in pictures.iter().enumerate() {
46+ let expect = &all[i * frame_len..(i + 1) * frame_len];
47+ let (cw, ch) = (usize::from(w + 1) / 2, usize::from(h + 1) / 2);
48+ assert_eq!(pic.y, &expect[..usize::from(w) * usize::from(h)], "{name} frame {i}: Y");
49+ assert_eq!(pic.u, &expect[usize::from(w) * usize::from(h)..][..cw * ch], "{name} frame {i}: U");
50+ assert_eq!(pic.v, &expect[usize::from(w) * usize::from(h) + cw * ch..], "{name} frame {i}: V");
51+ }
52+ }
53+}
54+
55+/// The hidden-frame contract, end to end on a REAL auto-alt-ref stream:
56+/// `Decoder::decode` returns `Ok(None)` for a hidden frame while its
57+/// reference content stays live — the frames that follow (which the
58+/// encoder predicted across the hidden altref) stay byte-exact against
59+/// ffmpeg.
60+#[test]
61+fn hidden_frames_update_references_and_produce_no_picture() {
62+ let Some(dir) = ivf::fixture_dir() else {
63+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
64+ };
65+ let path = dir.join("altref-160x96.ivf");
66+ let bytes = std::fs::read(&path).unwrap();
67+ let (_, w, h, frames) = ivf::parse_ivf(&bytes);
68+ let hidden_at: Vec<usize> = frames
69+ .iter()
70+ .enumerate()
71+ .filter(|(_, f)| !ivf::show_frame(&f.data))
72+ .map(|(i, _)| i)
73+ .collect();
74+ assert!(
75+ hidden_at.len() >= 6,
76+ "altref-160x96.ivf lost its hidden frames ({}) — regenerate",
77+ hidden_at.len()
78+ );
79+
80+ // ffmpeg's display stream, shown-frame-indexed.
81+ let all = ffmpeg_raw_yuv(&path);
82+ let frame_len = usize::from(w) * usize::from(h) * 3 / 2;
83+ let mut dec = Decoder::new();
84+ let mut shown_seen = 0;
85+ for (i, f) in frames.iter().enumerate() {
86+ let pic = dec.decode(&f.data).expect("hidden frame decodes");
87+ if ivf::show_frame(&f.data) {
88+ let expect = &all[shown_seen * frame_len..(shown_seen + 1) * frame_len];
89+ let y = &pic.as_ref().expect("shown frame has picture").y;
90+ assert_eq!(y, &expect[..usize::from(w) * usize::from(h)], "frame {i}: Y");
91+ // The frame right after the FIRST hidden altref must already
92+ // be byte-exact: it predicts across the hidden reference.
93+ if i == hidden_at[0] + 1 {
94+ assert!(
95+ y[..32] == expect[..32] && y == &expect[..y.len()],
96+ "frame after hidden altref diverges"
97+ );
98+ }
99+ shown_seen += 1;
100+ } else {
101+ assert!(pic.is_none(), "hidden frame {i} produced a picture");
102+ }
103+ }
104+ assert_eq!(shown_seen * frame_len, all.len());
105+}
106+
107+/// ffmpeg's decoded rawvideo byte stream for an IVF file.
108+fn ffmpeg_raw_yuv(path: &std::path::Path) -> Vec<u8> {
109+ let out = std::process::Command::new("ffmpeg")
110+ .args(["-v", "error", "-i"])
111+ .arg(path)
112+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
113+ .output()
114+ .expect("ffmpeg must be on PATH for the witnesses");
115+ assert!(out.status.success(), "ffmpeg failed on {path:?}");
116+ out.stdout
117+}
118+
119+#[test]
120+fn decode_stream_is_error_not_panic_on_bad_containers() {
121+ let Some(dir) = ivf::fixture_dir() else {
122+ panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh");
123+ };
124+ let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap();
125+
126+ // Missing magic.
127+ let mut bad = bytes.clone();
128+ bad[0..4].copy_from_slice(b"JUNK");
129+ assert!(decode_stream(&bad).is_err(), "non-DKIF accepted");
130+
131+ // Wrong fourcc (a WebP-lossless VP8L tag is not a VP8 video stream).
132+ let mut bad = bytes.clone();
133+ bad[8..12].copy_from_slice(b"VP8L");
134+ assert!(decode_stream(&bad).is_err(), "non-VP80 fourcc accepted");
135+
136+ // A frame header claiming more payload than the stream carries.
137+ let mut bad = bytes.clone();
138+ bad[32..36].copy_from_slice(&u32::MAX.to_le_bytes());
139+ assert!(decode_stream(&bad).is_err(), "truncated frame accepted");
140+}
141+
lanes/vp8.report.mdadded+107 -0
@@ -0,0 +1,107 @@
1+# lane-vp8 — native VP8 decoder (ec-vp8), RFC 6386
2+
3+Base: `a8f2186a` (main), worktree `edith_codecs-vp8`, branch `lane-vp8`.
4+Never merged, never pushed. Pins untouched (no ec-av1 changes at all).
5+
6+## Milestone table
7+
8+| Milestone | State | Evidence |
9+|---|---|---|
10+| 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 |
11+| 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) |
12+| 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 |
13+| 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<Vec<Picture>>` + `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 |
14+
15+## What shipped (M1 `57b5a53a`, M2 WIP `20f7d742`)
16+
17+- `bool.rs`: RFC §7.3 decoder verbatim (bool/literal/signed/maybe-signed/
18+ prob7/tree + EOB-skipping token form), zero-extend init for tiny
19+ partitions, overread counter as desync detector; test-only RFC encoder.
20+- `frame.rs`/`header.rs`: 3-byte LE tag, key-frame start code/dims,
21+ complete partition-1 header in dixie field order (colour space,
22+ segmentation w/ cross-frame state, LF type/level/sharpness/deltas,
23+ token partition size table, quant indices, reference refresh/copies/
24+ sign-bias, coef-prob updates, mb_no_skip_coeff, inter prob_intra/last/gf
25+ + ymode/uv/MV updates). `PersistedState` carries entropy/segmentation/
26+ LF deltas across frames, resets at key frames.
27+- `tables.rs`: GENERATED from the RFC text by `scripts/extract_vp8_tables.py`
28+ (element counts asserted; page-header stripping; Pcat sentinels kept):
29+ default+update coefficient probs, kf_bmode_prob, coeff_bands, dequant
30+ lookups, Pcat1-6, default+update MV probs.
31+- `tokens.rs`: §13 GetCoeffs port — bands incl. sentinel entry, 3-context
32+ model (above/left per-plane, Y2 last-MB-with-Y2 semantics), EOB skipped
33+ after zero, dequant-on-write (DC at first coded position), Y2-first
34+ block order, dixie skip-MB reset (Y2 slots survive iff no Y2 block).
35+- `modes.rs`: all trees/tables; NOTE SPLITMV partition leaves use the RFC
36+ enum values (top_bottom=0, left_right=1, quarters=2, MV_16=3).
37+- `transform.rs` (subagent): idct4x4/iwht4x4 + shortcuts + dequant;
38+ 400,000-vector bit-exact fuzz vs verbatim libvpx idctllm.c; dequant
39+ differentially fuzzed vs libvpx C over 528 q x 15 deltas x 5 channels.
40+- `intra.rs` (subagent): all 16x16/8x8/4x4 predictors; 20,000-stream
41+ machine diff vs libvpx intrapred.c — 28.8M/28.8M samples equal; svg2p
42+ RFC typo handled (avg2p).
43+- `loopfilter.rs` (subagent): normal+simple kernels and frame driver in
44+ dixie order (V-MB, V-sub, H-MB, H-sub; level 0 skips; combined
45+ blim/mblim for simple), dixie-table-exact limits, frame-type-exact hev
46+ via `filter_frame_ex(..., is_keyframe)`; 10 tests incl. Python-oracle
47+ full-frame driver order.
48+- `decode.rs`: per-row pipeline (modes -> tokens -> reconstruct),
49+ bordered planes (127 top incl. corner / 129 left), above-right
50+ synthesis (shared extras for right-edge subblocks, replicate on
51+ rightmost MB, 127 on top row), B_PRED interleaved predict+residual
52+ (subblocks chain through reconstructed pixels), Y2 WHT DC override,
53+ per-MB LF level with dixie DOUBLE-clamp, LF post-pass (order-equivalent
54+ to dixie's row-delayed filtering for non-threaded decode; frame-level
55+ level==0 gate).
56+- Fixtures: `scripts/gen_vp8_fixtures.sh` + local libvpx build recipe
57+ (`~/.cache/vp8/libvpx-src`, gives vpxenc for --token-parts; ffmpeg 8's
58+ wrapper has no token-part option). CQ quirk: `-crf` inside the
59+ qmin/qmax band is mandatory.
60+
61+## Witnesses
62+
63+- M1: `cargo test -p ec-vp8 --test header_parse` — 4 tests on real
64+ libvpx/vpxenc bitstreams: dims, start code, partition tiling
65+ (`token_data_offset + 3*(n-1) + sum(sizes) == frame len`), 8
66+ partitions, inter header coexists with persisted entropy, VP8-in-WebP
67+ chunk parses. ALL PASS.
68+- M2 (this session): FULL-FRAME decision-exactness — `EC_VP8_TRACE=1`
69+ example `dbg_first` vs `scripts/vp8ref_model.py`: 19131 token
70+ decisions, identical `(n, band, ctx, prob, bit)` on every read, 0
71+ diffs (`kf-160x96-q20.ivf`). Pixel exactness: frame 0 of all 7 kf
72+ fixtures + mparts dumped via `examples/dump_frame` and `cmp`-ed
73+ against `ffmpeg -frames:v 1` — ALL EXACT. `cargo test -p ec-vp8`:
74+ unit (49) + header_parse (4) + webp witness green; the remaining 2
75+ `keyframe_exact` cases decode every frame of each fixture and go
76+ green with M3 inter frames.
77+
78+## M2 blocker — RESOLVED
79+
80+Root cause: `get_coeffs`' ONE-token path (`tokens.rs`). After the
81+`p[2]` decision selects value 1, the reference walk (libvpx
82+`detokenize.c` GetCoeffs, RFC §13.2) falls through to the SHARED
83+sign-read / coefficient-write / EOB-after-nonzero sequence — the ONE
84+and magnitude paths converge right after the tree decision. The Rust
85+port had the sign/write/EOB block nested inside the magnitude branch
86+only, so a ONE token skipped the sign read and the EOB check and
87+re-entered the walk at the ZERO node: same read count (positions
88+stayed in lockstep, hence "same (pos,bit_count), different table
89+entry"), different decoded stream from the first ONE token in a busy
90+block — invisible on the lossless single-MB black fixture (no ONE
91+tokens), fatal from ~28 reads into kf-160x96-q20's first block.
92+
93+Two reference-model bugs also fixed while instrumenting
94+(`scripts/vp8ref_model.py`): per-decision `G n/band/ctx/prob/bit`
95+lines replacing the DEC counter, and token-partition bool decoders
96+are now PERSISTENT across MB rows that share a partition (was:
97+re-created per row, which double-counted the walk on single-partition
98+streams). Trace protocol: diff `grep '^G '` of both sides; the first
99+differing line names decision, node and whether prob or bit diverges.
100+
101+
102+## Repro
103+
104+```
105+CARGO_TARGET_DIR=~/.cache/cargo-target-vp8 cargo test -p ec-vp8
106+scripts/gen_vp8_fixtures.sh # fixtures/vp8/*.ivf (gitignored)
107+```
scripts/extract_vp8_tables.pyadded+102 -0
@@ -0,0 +1,102 @@
1+#!/usr/bin/env python3
2+"""Extract the fixed probability/quant tables from the local RFC 6386 text
3+into a Rust module (crates/ec-vp8/src/tables.rs).
4+
5+The tables are transcribed VERBATIM from the RFC text; the script asserts
6+each table's element count so a parsing slip cannot produce a silently
7+wrong table. Run from the worktree root:
8+
9+ python3 scripts/extract_vp8_tables.py [rfc.txt] [out.rs]
10+"""
11+
12+import re
13+import sys
14+
15+RFC = sys.argv[1] if len(sys.argv) > 1 else "/home/user/.cache/vp8/rfc6386.txt"
16+OUT = sys.argv[2] if len(sys.argv) > 2 else "crates/ec-vp8/src/tables.rs"
17+
18+text = open(RFC, encoding="utf-8").read()
19+# Strip RFC page furniture (running headers/footers land mid-table).
20+text = "\n".join(
21+ l for l in text.splitlines()
22+ if not re.search(r"RFC 6386\s+VP8 Data Format.*2011$", l)
23+ and not re.search(r"Bankoski, et al\..*\[Page \d+\]$", l)
24+)
25+text = text.replace("\f", "")
26+
27+INT_RE = re.compile(r"-?\d+")
28+
29+
30+def collect(name: str, expect: int) -> list[int]:
31+ """Find `name`'s C array DEFINITION -- '=' reachable from the name
32+ through nothing but brackets, identifiers, spaces and hyphens (the
33+ section-13.4 pseudocode mentions `coeff_update_probs [i] [j] [k] [t]))`
34+ and must not match) -- and collect every integer between '=' and the
35+ terminating '};'."""
36+ for m in re.finditer(rf"\b{re.escape(name)}\b[\[\]\w\s-]*?=", text):
37+ body = text[m.end() : m.end() + 60000]
38+ end = body.find("};")
39+ assert end != -1, f"{name}: no terminator"
40+ vals = [int(v) for v in INT_RE.findall(body[:end])]
41+ if len(vals) != expect:
42+ raise SystemExit(
43+ f"{name}: expected {expect} ints, got {len(vals)}: {vals[:10]}..."
44+ )
45+ return vals
46+ raise SystemExit(f"{name}: definition not found")
47+
48+
49+# (rust name, RFC name, expected ints incl. Pcat sentinels, dims, type)
50+TABLES = [
51+ ("COEFF_UPDATE_PROBS", "coeff_update_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"),
52+ ("DEFAULT_COEFF_PROBS", "default_coeff_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"),
53+ ("KF_BMODE_PROB", "kf_bmode_prob", 10 * 10 * 9, (10, 10, 9), "u8"),
54+ ("COEFF_BANDS", "coeff_bands", 16, (16,), "u8"),
55+ ("DC_QLOOKUP", "dc_qlookup", 128, (128,), "i16"),
56+ ("AC_QLOOKUP", "ac_qlookup", 128, (128,), "i16"),
57+ ("PCAT1", "Pcat1", 2, (2,), "u8"),
58+ ("PCAT2", "Pcat2", 3, (3,), "u8"),
59+ ("PCAT3", "Pcat3", 4, (4,), "u8"),
60+ ("PCAT4", "Pcat4", 5, (5,), "u8"),
61+ ("PCAT5", "Pcat5", 6, (6,), "u8"),
62+ ("PCAT6", "Pcat6", 12, (12,), "u8"),
63+ ("DEFAULT_MV_PROBS", "k_default_mv_probs", 2 * 19, (2, 19), "u8"),
64+ ("MV_UPDATE_PROBS", "k_mv_entropy_update_probs", 2 * 19, (2, 19), "u8"),
65+]
66+
67+
68+def rust_ty(ty: str, dims: tuple[int, ...]) -> str:
69+ t = ty
70+ for d in reversed(dims):
71+ t = f"[{t}; {d}]"
72+ return t
73+
74+
75+def nest(vals: list[int], dims: tuple[int, ...]) -> str:
76+ if len(dims) == 1:
77+ return "[" + ", ".join(str(v) for v in vals) + "]"
78+ step = len(vals) // dims[0]
79+ parts = [
80+ nest(vals[i * step : (i + 1) * step], dims[1:]) for i in range(dims[0])
81+ ]
82+ if len(dims) == 2:
83+ return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]"
84+ return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]"
85+
86+
87+out = [
88+ "//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and",
89+ "//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from",
90+ "//! the RFC text; do not edit by hand. The extractor asserts every",
91+ "//! table's element count, so a slip cannot drop or add values.",
92+ "#![allow(clippy::all)]",
93+ "",
94+]
95+for rust_name, rfc_name, expect, dims, ty in TABLES:
96+ vals = collect(rfc_name, expect)
97+ note = " (trailing 0 is the DCTextra sentinel)" if rfc_name.startswith("Pcat") else ""
98+ out.append(f"/// RFC 6386 `{rfc_name}`{note}.")
99+ out.append(f"pub const {rust_name}: {rust_ty(ty, dims)} = {nest(vals, dims)};\n")
100+
101+open(OUT, "w", encoding="utf-8").write("\n".join(out))
102+print(f"wrote {OUT}")
scripts/gen_vp8_fixtures.shadded+123 -0
@@ -0,0 +1,123 @@
1+#!/usr/bin/env bash
2+# Generate the ec-vp8 test fixtures (gitignored, like the rest of the
3+# workspace's fixtures/). Every vector is libvpx-encoded via ffmpeg; the
4+# decoder's witnesses compare its raw YUV output against ffmpeg's.
5+#
6+# Usage: scripts/gen_vp8_fixtures.sh [worktree-root]
7+set -euo pipefail
8+ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
9+OUT="$ROOT/fixtures/vp8"
10+mkdir -p "$OUT"
11+
12+enc() { # name size frames q extra-source-args...
13+ local name=$1 size=$2 frames=$3 q=$4
14+ shift 4
15+ ffmpeg -hide_banner -loglevel error -y \
16+ -f lavfi -i "$@" \
17+ -frames:v "$frames" -c:v libvpx -qmin "$q" -qmax "$q" -crf "$q" \
18+ -auto-alt-ref 0 -cpu-used 1 -g "$frames" \
19+ "$OUT/$name.ivf"
20+ echo "wrote $OUT/$name.ivf"
21+}
22+
23+# Key-frame vectors (M2): several sizes incl. non-multiple-of-16, several q.
24+enc kf-160x96-q20 160x96 4 20 testsrc2=size=160x96:rate=30
25+enc kf-160x96-q40 160x96 4 40 testsrc2=size=160x96:rate=30
26+enc kf-76x52-q30 76x52 4 30 testsrc2=size=76x52:rate=30
27+enc kf-32x16-q35 32x16 4 35 testsrc2=size=32x16:rate=30
28+enc kf-172x144-q25 172x144 4 25 testsrc2=size=172x144:rate=30
29+enc kf-96x80-q63 96x80 4 63 testsrc2=size=96x80:rate=30
30+
31+# Multi-frame GOP (M3): keyframe + interframes, golden/altref in play.
32+ffmpeg -hide_banner -loglevel error -y \
33+ -f lavfi -i testsrc2=size=160x96:rate=30 \
34+ -frames:v 60 -c:v libvpx -qmin 30 -qmax 45 -crf 38 \
35+ -auto-alt-ref 0 -g 15 -keyint_min 15 -cpu-used 1 -lag-in-frames 0 \
36+ "$OUT/gop-160x96.ivf"
37+echo "wrote $OUT/gop-160x96.ivf"
38+
39+# Larger short GOP with the simple loop filter via profile (version 1)?
40+# libvpx picks profile 0 normally; the version field is exercised through
41+# -profile:v 1 (simple filter, bilinear reconstruction).
42+ffmpeg -hide_banner -loglevel error -y \
43+ -f lavfi -i testsrc2=size=96x80:rate=30 \
44+ -frames:v 12 -c:v libvpx -qmin 30 -qmax 30 -crf 30 -auto-alt-ref 0 -g 6 \
45+ -profile:v 1 -cpu-used 1 -lag-in-frames 0 \
46+ "$OUT/gop-96x80-v1.ivf" 2>/dev/null || \
47+ echo "SKIP gop-96x80-v1 (profile 1 unsupported by this libvpx build)"
48+
49+# Multi-partition token partitions (M3): ffmpeg's libvpx wrapper has no
50+# token-part option, so this one vector comes from a locally built vpxenc
51+# (checked out at ~/.cache/vp8/libvpx-src; `./configure && make -j`).
52+VPXENC="$HOME/.cache/vp8/libvpx-src/vpxenc"
53+if [ -x "$VPXENC" ]; then
54+ ffmpeg -hide_banner -loglevel error -y \
55+ -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 30 \
56+ -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-mparts.raw
57+ { printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n'
58+ python3 - <<'PYEOF'
59+raw = open("/tmp/ecvp8-mparts.raw", "rb").read()
60+frame = 160 * 96 * 3 // 2
61+for i in range(len(raw) // frame):
62+ open("/dev/stdout", "wb").write(b"FRAME\n" + raw[i*frame:(i+1)*frame])
63+PYEOF
64+ } | "$VPXENC" --codec=vp8 -w 160 -h 96 --token-parts=3 --limit=30 \
65+ --ivf --cpu-used=1 --end-usage=q --cq-level=32 --min-q=30 --max-q=45 \
66+ --kf-max-dist=10 -o "$OUT/mparts-160x96.ivf" - 2>/dev/null
67+ echo "wrote $OUT/mparts-160x96.ivf"
68+else
69+ echo "SKIP mparts (build libvpx at ~/.cache/vp8/libvpx-src for vpxenc)"
70+fi
71+
72+# VP8-in-WebP still (same key-frame payload in a RIFF container).
73+ffmpeg -hide_banner -loglevel error -y \
74+ -f lavfi -i testsrc2=size=96x80:rate=30 -frames:v 1 \
75+ "$OUT/still.png"
76+if ffmpeg -hide_banner -loglevel error -y -i "$OUT/still.png" -q:v 60 "$OUT/still.webp" 2>/dev/null; then
77+ echo "wrote $OUT/still.webp"
78+else
79+ echo "SKIP still.webp (libwebp support missing)"
80+ rm -f "$OUT/still.png"
81+fi
82+
83+# Note on the three vectors below (review flag): every fixture in the set
84+# must come from THIS script — no ad-hoc leftovers.
85+#
86+# kf-16x16-black-q0: 1-MB all-black frame at q0 (the M2 "no ONE tokens"
87+# degenerate vector: exercises the zero-coefficient and overread paths).
88+enc kf-16x16-black-q0 16x16 1 0 color=black:size=16x16:rate=30
89+
90+# clip-obs-320x192: screen-content-shaped 320x192 clip. The original was
91+# an OBS window capture; the recorded reproducible stand-in is testsrc2
92+# at the same size (same decoder paths: 20x12 MB grid, small-MV motion).
93+enc clip-obs-320x192 320x192 169 28 testsrc2=size=320x192:rate=30
94+
95+# altref-160x96: vpxenc --auto-alt-ref=1 in TWO passes (one-pass CQ/VBR
96+# never inserts hidden altrefs for this content) with --lag-in-frames, so
97+# libvpx emits HIDDEN alternate-reference frames (frame tag show_frame=0,
98+# currently 6 of 90 at decode indices 1,17,33,49,65,81). The witnesses
99+# census the tags and refuse a shown-only stream: the hidden-frame
100+# contract (no output, reference buffers still update, later frames
101+# reference the hidden altref) must be exercised.
102+ffmpeg -hide_banner -loglevel error -y \
103+ -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 90 \
104+ -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-altref.raw
105+# Two passes need a seekable input (stdin cannot rewind for pass 2), so
106+# the y4m goes through a temp FILE, not a pipe.
107+{ printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n'
108+ cat /tmp/ecvp8-altref.raw | python3 -c '
109+import sys
110+raw = sys.stdin.buffer.read()
111+frame = 160 * 96 * 3 // 2
112+for i in range(len(raw) // frame):
113+ sys.stdout.buffer.write(b"FRAME\n" + raw[i*frame:(i+1)*frame])
114+' > /tmp/ecvp8-altref.y4m
115+}
116+"$VPXENC" --codec=vp8 -w 160 -h 96 --limit=90 --ivf --cpu-used=1 \
117+ --end-usage=vbr --target-bitrate=400 --kf-max-dist=15 \
118+ --auto-alt-ref=1 --lag-in-frames=15 --passes=2 --fpf=/tmp/ecvp8-altref.fpf \
119+ --quiet -o "$OUT/altref-160x96.ivf" /tmp/ecvp8-altref.y4m
120+rm -f /tmp/ecvp8-altref.raw /tmp/ecvp8-altref.y4m /tmp/ecvp8-altref.fpf
121+echo "wrote $OUT/altref-160x96.ivf"
122+
123+ls -la "$OUT"
scripts/raw_to_y4m.pyadded+15 -0
@@ -0,0 +1,15 @@
1+#!/usr/bin/env python3
2+"""Wrap raw planar yuv420p frames into a minimal y4m (for vpxenc).
3+
4+ ffmpeg ... -f rawvideo - | raw_to_y4m.py W H FPS out.y4m
5+"""
6+import sys
7+
8+w, h, fps, out = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
9+frame = int(w) * int(h) * 3 // 2
10+raw = sys.stdin.buffer.read()
11+with open(out, "wb") as f:
12+ f.write(f"YUV4MPEG2 W{w} H{h} F{fps}:1 Ip A1:1 C420jpeg\n".encode())
13+ for i in range(len(raw) // frame):
14+ f.write(b"FRAME\n")
15+ f.write(raw[i * frame : (i + 1) * frame])
scripts/vp8ref_model.pyadded+646 -0
@@ -0,0 +1,646 @@
1+#!/usr/bin/env python3
2+"""Dixie-faithful multi-frame VP8 decode model (header + mode records +
3+tokens, no pixels) with per-read `B` and per-token-decision `G` tracing
4+that mirror the Rust decoder's EC_VP8_TRACE output byte-for-byte.
5+
6+Usage: python3 vp8ref_model.py frame.ivf [max-frames]
7+"""
8+import re
9+import sys
10+
11+TABLES_RS = "crates/ec-vp8/src/tables.rs"
12+
13+
14+class BD:
15+ def __init__(self, data):
16+ self.data = data
17+ self.pos = 2 if len(data) >= 2 else len(data)
18+ v = 0
19+ if len(data) >= 1:
20+ v = data[0] << 8
21+ if len(data) >= 2:
22+ v |= data[1]
23+ self.value = v
24+ self.range = 255
25+ self.bit_count = 0
26+
27+ def bool(self, prob):
28+ split = 1 + (((self.range - 1) * prob) >> 8)
29+ big = split << 8
30+ if self.value >= big:
31+ self.range -= split
32+ self.value -= big
33+ bit = 1
34+ else:
35+ self.range = split
36+ bit = 0
37+ while self.range < 128:
38+ self.value <<= 1
39+ self.range <<= 1
40+ self.bit_count += 1
41+ if self.bit_count == 8:
42+ self.bit_count = 0
43+ if self.pos < len(self.data):
44+ self.value |= self.data[self.pos]
45+ self.pos += 1
46+ print(f"B {self.pos} {self.bit_count} {prob} {bit}")
47+ return bit
48+
49+ def lit(self, n):
50+ v = 0
51+ for _ in range(n):
52+ v = (v << 1) + self.bool(128)
53+ return v
54+
55+ def maybe_int(self, n):
56+ if not self.bool(128):
57+ return 0
58+ v = self.lit(n)
59+ return -v if self.bool(128) else v
60+
61+ def tree(self, tree, probs):
62+ i = 0
63+ while True:
64+ b = self.bool(probs[i >> 1])
65+ i = tree[i + b]
66+ if i <= 0:
67+ return -i
68+
69+
70+def table(name):
71+ src = open(TABLES_RS).read()
72+ m = re.search(rf"pub const {name}: [^=]+= ", src)
73+ body = src[m.end(): src.index("];", m.end())]
74+ return [int(x) for x in re.findall(r"-?\d+", body)]
75+
76+
77+# ---------------------------------------------------------------------------
78+# Inter-parse constants (RFC 6386; cross-checked against libvpx modecont.c /
79+# findnearmv.h / blockd.h — see managed skill ec-vp8-lane-recipe).
80+MODE_CONTEXTS = [
81+ [7, 1, 1, 143],
82+ [14, 18, 14, 107],
83+ [135, 64, 57, 68],
84+ [60, 56, 128, 65],
85+ [159, 134, 128, 34],
86+ [234, 188, 128, 28],
87+]
88+SUB_MV_REF_PROBS = [
89+ [147, 136, 18],
90+ [106, 145, 1],
91+ [179, 121, 1],
92+ [223, 1, 34],
93+ [208, 1, 1],
94+]
95+MV_PARTITION_TREE = [-3, 2, -2, 4, 0, -1]
96+MV_PARTITION_PROBS = [110, 111, 150]
97+SUB_MV_REF_TREE = [0, 2, -1, 4, -2, -3]
98+SMALL_MV_TREE = [2, 8, 4, 6, 0, -1, -2, -3, 10, 12, -4, -5, -6, -7]
99+MBSPLIT_OFFSET = [
100+ [0, 8], [0, 2], [0, 2, 8, 10], list(range(16)),
101+]
102+MBSPLIT_FILL_COUNT = [8, 8, 4, 1]
103+MBSPLIT_FILL_OFFSET = [
104+ list(range(16)),
105+ [0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15],
106+ [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15],
107+ list(range(16)),
108+]
109+
110+
111+def main():
112+ CUP = table("COEFF_UPDATE_PROBS")
113+ KF_BMODE = table("KF_BMODE_PROB")
114+ DEF_COEF = table("DEFAULT_COEFF_PROBS")
115+ DEF_MV = table("DEFAULT_MV_PROBS")
116+ MV_UP = table("MV_UPDATE_PROBS")
117+ BANDS = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0]
118+ ZIGZAG = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]
119+ CAT_EXTRA = [
120+ [173, 148, 140],
121+ [176, 155, 140, 135],
122+ [180, 157, 141, 134, 130],
123+ [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129],
124+ ]
125+ KF_YMODE_TREE = [-4, 2, 4, 6, 0, -1, -2, -3]
126+ BMODE_TREE = [0, 2, -1, 4, -2, 6, 8, 12, -3, 10, -5, -6, -4, 14, -7, 16, -8, -9]
127+ UV_MODE_TREE = [0, 2, -1, 4, -2, -3]
128+ YMODE_TREE = [0, 2, 4, 6, -1, -2, -3, -4]
129+ YMODE_MAP = {0: 0, 1: 2, 2: 3, 3: 1}
130+ INTER_BMODE = [120, 90, 79, 133, 87, 85, 80, 111, 151] # libvpx vp8_bmode_prob
131+ 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]
132+ 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]
133+
134+ raw = open(sys.argv[1], "rb").read()
135+ max_frames = int(sys.argv[2]) if len(sys.argv) > 2 else 2
136+ frames = []
137+ pos = 32
138+ while pos + 12 <= len(raw):
139+ sz = int.from_bytes(raw[pos : pos + 4], "little")
140+ frames.append(raw[pos + 12 : pos + 12 + sz])
141+ pos += 12 + sz
142+
143+ w = h = 0
144+ cols = rows = 0
145+ ctx = {
146+ "coef": DEF_COEF[:],
147+ "mv": DEF_MV[:],
148+ "ymode": [112, 86, 140, 37],
149+ "uv": [162, 101, 204],
150+ }
151+ probs = None
152+ seg_map = [0] * 65536
153+
154+ for fi, frame in enumerate(frames[:max_frames]):
155+ tag = int.from_bytes(frame[0:3], "little")
156+ kf = (frame[0] & 1) == 0
157+ part0_sz = tag >> 5
158+ # Uncompressed data chunk: key frames carry start code + dims
159+ # (partition 0 at byte 10); inter frames start partition 0 at
160+ # byte 3 (RFC 6386 §9.1).
161+ hdr0 = 10 if kf else 3
162+ d = BD(frame[hdr0 : hdr0 + part0_sz])
163+
164+ if kf:
165+ w = int.from_bytes(frame[6:8], "little") & 0x3FFF
166+ h = int.from_bytes(frame[8:10], "little") & 0x3FFF
167+ cols, rows = (w + 15) // 16, (h + 15) // 16
168+ d.lit(2) # colour space + clamping
169+ ctx["coef"] = DEF_COEF[:]
170+
171+ # segmentation
172+ seg_enabled = d.bool(128)
173+ seg_update_map = False
174+ seg_tree_probs = [255, 255, 255]
175+ if seg_enabled:
176+ seg_update_map = d.bool(128)
177+ if d.bool(128):
178+ d.bool(128)
179+ for _ in range(4):
180+ d.maybe_int(7)
181+ for _ in range(4):
182+ d.maybe_int(6)
183+ if seg_update_map:
184+ seg_tree_probs = [d.lit(8) for _ in range(3)]
185+ # loop filter header
186+ d.lit(1)
187+ d.lit(6)
188+ d.lit(3)
189+ if d.bool(128):
190+ if d.bool(128):
191+ for _ in range(4):
192+ d.maybe_int(6)
193+ for _ in range(4):
194+ d.maybe_int(6)
195+ # token partitions
196+ log2 = d.lit(2)
197+ nparts = 1 << log2
198+ off = hdr0 + part0_sz
199+ sizes = []
200+ for i in range(nparts):
201+ if i < nparts - 1:
202+ sizes.append(int.from_bytes(frame[off : off + 3], "little"))
203+ off += 3
204+ else:
205+ sizes.append(len(frame) - off)
206+ parts = []
207+ po = off
208+ for i in range(nparts):
209+ parts.append(frame[po : po + sizes[i]])
210+ po += sizes[i]
211+ # quant
212+ d.lit(7)
213+ for _ in range(5):
214+ d.maybe_int(4)
215+
216+ # refresh header
217+ if kf:
218+ refresh_entropy = d.bool(128)
219+ sb = [False, False]
220+ else:
221+ refresh_gf = d.bool(128)
222+ if not refresh_gf:
223+ d.lit(2)
224+ refresh_arf = d.bool(128)
225+ if not refresh_arf:
226+ d.lit(2)
227+ sb = [False, d.bool(128), d.bool(128)]
228+ refresh_entropy = d.bool(128)
229+ d.bool(128) # refresh_last
230+ snapshot = (ctx["coef"][:], ctx["mv"][:], ctx["ymode"][:], ctx["uv"][:])
231+
232+ # coefficient probability updates
233+ idx = 0
234+ for _i in range(4):
235+ for _j in range(8):
236+ for _k in range(3):
237+ for _l in range(11):
238+ if d.bool(CUP[idx]):
239+ ctx["coef"][idx] = d.lit(8)
240+ idx += 1
241+ # mb_no_skip_coeff
242+ skip_enabled = d.bool(128)
243+ prob_skip = d.lit(8) if skip_enabled else 128
244+
245+ probs = ctx["coef"]
246+ prob_intra = prob_last = prob_gf = 128
247+ if not kf:
248+ prob_intra = d.lit(8)
249+ prob_last = d.lit(8)
250+ prob_gf = d.lit(8)
251+ yflag = d.bool(128)
252+ print(f"HDR pi={prob_intra} pl={prob_last} pg={prob_gf} yflag={1 if yflag else 0}")
253+ if yflag:
254+ ctx["ymode"] = [d.lit(8) for _ in range(4)]
255+ uflag = d.bool(128)
256+ print(f"HDR uflag={1 if uflag else 0}")
257+ if uflag:
258+ ctx["uv"] = [d.lit(8) for _ in range(3)]
259+ for c in range(2):
260+ for j in range(19):
261+ if d.bool(MV_UP[c * 19 + j]):
262+ x = d.lit(7)
263+ ctx["mv"][c * 19 + j] = (x << 1) if x else 1
264+
265+ if not kf:
266+ print("YUV ymode =", ctx["ymode"], "uv =", ctx["uv"])
267+ print("MVT c0 =", ctx["mv"][0:19])
268+ print("MVT c1 =", ctx["mv"][19:38])
269+
270+ # per-MB state (row/col 0 = border)
271+ mbmode = [[0] * (cols + 1) for _ in range(rows + 1)]
272+ bmode = [[[0] * 16 for _ in range(cols + 1)] for _ in range(rows + 1)]
273+ skips = [[False] * (cols + 1) for _ in range(rows + 1)]
274+ hasy2 = [[True] * (cols + 1) for _ in range(rows + 1)]
275+ mbref = [[0] * (cols + 1) for _ in range(rows + 1)]
276+ mbmv = [[(0, 0)] * (cols + 1) for _ in range(rows + 1)]
277+ mbsplit = [[False] * (cols + 1) for _ in range(rows + 1)]
278+ mbbmi = [[[(0, 0)] * 16 for _ in range(cols + 1)] for _ in range(rows + 1)]
279+ mbmvclamp = [[False] * (cols + 1) for _ in range(rows + 1)]
280+ above_ctx = [[0] * 9 for _ in range(cols)]
281+
282+ def clamp_mv2(mv, edges):
283+ l, r, t, b = edges
284+ if mv[1] < l - 128:
285+ mv = (l - 128, mv[1])
286+ elif mv[1] > r + 128:
287+ mv = (r + 128, mv[1])
288+ if mv[0] < t - 128:
289+ mv = (t - 128, mv[1])
290+ elif mv[0] > b + 128:
291+ mv = (b + 128, mv[1])
292+ return mv
293+
294+ def oob(mv, edges):
295+ l, r, t, b = edges
296+ return mv[1] < l or mv[1] > r or mv[0] < t or mv[0] > b
297+
298+ def read_mv_component(p):
299+ if d.bool(p[0]):
300+ x = 0
301+ for i in range(3):
302+ x += d.bool(p[9 + i]) << i
303+ for i in (9, 8, 7, 6, 5, 4):
304+ x += d.bool(p[9 + i]) << i
305+ if (x & 0xFFF0) == 0 or d.bool(p[9 + 3]):
306+ x += 8
307+ else:
308+ x = d.tree(SMALL_MV_TREE, p[2:9])
309+ if x and d.bool(p[1]):
310+ x = -x
311+ return x
312+
313+ def read_mv():
314+ r = read_mv_component(ctx["mv"][0:19]) * 2
315+ c = read_mv_component(ctx["mv"][19:38]) * 2
316+ return (r, c)
317+
318+ def find_near(above, left, aboveleft, to_bias):
319+ mvs = [(0, 0), (0, 0), (0, 0), (0, 0)]
320+ cnt = [0, 0, 0, 0]
321+ ix = 0
322+ cx = 0
323+
324+ def bias(mv, from_b):
325+ if from_b != to_bias:
326+ return (-mv[0], -mv[1])
327+ return mv
328+
329+ if not above["intra"]:
330+ if above["mv"] != (0, 0):
331+ ix += 1
332+ mvs[ix] = bias(above["mv"], above["sb"])
333+ cx += 1
334+ cnt[cx] += 2
335+ for mb, wgt in ((left, 2), (aboveleft, 1)):
336+ if not mb["intra"]:
337+ if mb["mv"] != (0, 0):
338+ this = bias(mb["mv"], mb["sb"])
339+ if this != mvs[ix]:
340+ ix += 1
341+ mvs[ix] = this
342+ cx += 1
343+ cnt[cx] += wgt
344+ else:
345+ cnt[0] += wgt
346+ # libvpx decodemv.c:366 — when the above-left pushed a THIRD
347+ # distinct candidate it counted into cnt[CNT_SPLITMV] (cntx
348+ # reached slot 3), and if that candidate equals the nearest,
349+ # NEAREST absorbs it. Alive, not dead.
350+ if cnt[3] != 0 and mvs[ix] == mvs[1]:
351+ cnt[1] += 1
352+ cnt[3] = (above["split"] * 2) + (left["split"] * 2) + aboveleft["split"]
353+ if cnt[2] > cnt[1]:
354+ cnt[1], cnt[2] = cnt[2], cnt[1]
355+ mvs[1], mvs[2] = mvs[2], mvs[1]
356+ return mvs, cnt
357+
358+ def parse_inter_modes(r, c):
359+ mb_edge = (
360+ -(((c - 1) * 16) << 3),
361+ (((cols - 1 - (c - 1)) * 16) << 3),
362+ -(((r - 1) * 16) << 3),
363+ (((rows - 1 - (r - 1)) * 16) << 3),
364+ )
365+ to_bias = sb[mbref[r][c] - 1]
366+
367+ def neigh(rr, cc):
368+ if rr == 0 or cc == 0 or mbref[rr][cc] == 0:
369+ return {"intra": True, "zero": False, "mv": (0, 0), "split": False, "sb": False}
370+ return {
371+ "intra": False,
372+ "zero": mbmv[rr][cc] == (0, 0),
373+ "mv": mbmv[rr][cc],
374+ "split": mbsplit[rr][cc],
375+ "sb": sb[mbref[rr][cc] - 1],
376+ }
377+
378+ near_mvs, cnt = find_near(
379+ neigh(r - 1, c), neigh(r, c - 1), neigh(r - 1, c - 1), to_bias
380+ )
381+ print(f"CNT r={r-1} c={c-1} cnt={cnt} mvs={near_mvs}")
382+ MC = MODE_CONTEXTS
383+ if not d.bool(MC[cnt[0]][0]):
384+ mbmode[r][c] = -1 # ZEROMV marker
385+ mbmv[r][c] = (0, 0)
386+ mbref_marker = 1
387+ return
388+ if not d.bool(MC[cnt[1]][1]):
389+ mbmode[r][c] = -2 # NEAREST
390+ mv = clamp_mv2(near_mvs[1], mb_edge)
391+ mbmv[r][c] = mv
392+ mbref_marker = 1
393+ return
394+ if not d.bool(MC[cnt[2]][2]):
395+ mbmode[r][c] = -3 # NEAR
396+ mv = clamp_mv2(near_mvs[2], mb_edge)
397+ mbmv[r][c] = mv
398+ mbref_marker = 1
399+ return
400+ ni = 1 if cnt[1] >= cnt[0] else 0
401+ near_mvs[ni] = clamp_mv2(near_mvs[ni], mb_edge)
402+ best = near_mvs[ni]
403+ if not d.bool(MC[cnt[3]][3]):
404+ mbmode[r][c] = -4 # NEW
405+ mv = read_mv()
406+ mv = (mv[0] + best[0], mv[1] + best[1])
407+ mbmvclamp[r][c] = oob(mv, mb_edge)
408+ mbmv[r][c] = mv
409+ mbref_marker = 1
410+ return
411+ # SPLITMV
412+ s = d.tree(MV_PARTITION_TREE, MV_PARTITION_PROBS)
413+ num_p = [2, 2, 4, 16][s]
414+ bmi = [(0, 0)] * 16
415+ mbbmi[r][c] = bmi
416+ for j in range(num_p):
417+ k = MBSPLIT_OFFSET[s][j]
418+ if k % 4 == 0:
419+ lm = r, c - 1
420+ leftmv = (
421+ mbbmi[lm[0]][lm[1]][k + 3]
422+ if mbsplit[lm[0]][lm[1]]
423+ else mbmv[lm[0]][lm[1]]
424+ )
425+ else:
426+ leftmv = bmi[k - 1]
427+ if k < 4:
428+ am = r - 1, c
429+ abovemv = (
430+ mbbmi[am[0]][am[1]][k + 12]
431+ if mbsplit[am[0]][am[1]]
432+ else mbmv[am[0]][am[1]]
433+ )
434+ else:
435+ abovemv = bmi[k - 4]
436+ lez = leftmv == (0, 0)
437+ aez = abovemv == (0, 0)
438+ lea = leftmv == abovemv
439+ ctxi = 4 if (lez and aez) else (3 if lea else (1 if lez else (2 if aez else 0)))
440+ pr = d.tree(SUB_MV_REF_TREE, SUB_MV_REF_PROBS[ctxi])
441+ if pr == 0:
442+ blockmv = leftmv
443+ elif pr == 1:
444+ blockmv = abovemv
445+ elif pr == 2:
446+ blockmv = (0, 0)
447+ else:
448+ mv = read_mv()
449+ blockmv = (mv[0] + best[0], mv[1] + best[1])
450+ print(
451+ 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]})"
452+ )
453+ mbmvclamp[r][c] = mbmvclamp[r][c] or oob(blockmv, mb_edge)
454+ cntf = MBSPLIT_FILL_COUNT[s]
455+ for o in MBSPLIT_FILL_OFFSET[s][j * cntf : (j + 1) * cntf]:
456+ bmi[o] = blockmv
457+ mbbmi[r][c] = bmi
458+ mbsplit[r][c] = True
459+ mbmode[r][c] = 4
460+ hasy2[r][c] = False
461+ mbmv[r][c] = bmi[15]
462+ return
463+
464+ # ---- mode records + tokens ----------------------------------------
465+ # Key frames interleave per row (like the Rust decode_keyframe);
466+ # inter frames read ALL mode records first, then token rows
467+ # (like decode_interframe). B-line order must match Rust exactly.
468+ d2s = [None] * nparts
469+
470+ def row_modes(r):
471+ for c in range(1, cols + 1):
472+ if seg_enabled and seg_update_map:
473+ seg_map[(r - 1) * cols + (c - 1)] = d.tree(
474+ [2, 4, 0, -1, -2, -3], seg_tree_probs
475+ )
476+ if skip_enabled:
477+ skips[r][c] = bool(d.bool(prob_skip))
478+ if kf:
479+ ym = d.tree(KF_YMODE_TREE, [145, 156, 163, 128])
480+ mbmode[r][c] = ym
481+ hasy2[r][c] = ym != 4
482+ if ym == 4:
483+ for j in range(16):
484+ if j < 4:
485+ am = mbmode[r - 1][c]
486+ a = bmode[r - 1][c][j + 12] if am == 4 else YMODE_MAP[am]
487+ else:
488+ a = bmode[r][c][j - 4]
489+ if j % 4 == 0:
490+ lm = mbmode[r][c - 1]
491+ l = bmode[r][c - 1][j + 3] if lm == 4 else YMODE_MAP[lm]
492+ else:
493+ l = bmode[r][c][j - 1]
494+ bmode[r][c][j] = d.tree(
495+ BMODE_TREE, KF_BMODE[(a * 10 + l) * 9 : (a * 10 + l) * 9 + 9]
496+ )
497+ d.tree(UV_MODE_TREE, [142, 114, 183])
498+ else:
499+ # ---- inter mode record (§16) ----
500+ if not d.bool(prob_intra):
501+ mbref[r][c] = 0
502+ ym = d.tree(YMODE_TREE, ctx["ymode"])
503+ mbmode[r][c] = ym
504+ if ym == 4:
505+ # Interframe B_PRED subblocks: CONSTANT
506+ # probs, no above/left context (libvpx
507+ # decodemv.c:467 reads fc.bmode_prob =
508+ # vp8_bmode_prob).
509+ for j in range(16):
510+ bmode[r][c][j] = d.tree(BMODE_TREE, INTER_BMODE)
511+ d.tree(UV_MODE_TREE, ctx["uv"])
512+ else:
513+ if not d.bool(prob_last):
514+ mbref[r][c] = 1
515+ elif not d.bool(prob_gf):
516+ mbref[r][c] = 2
517+ else:
518+ mbref[r][c] = 3
519+ try:
520+ parse_inter_modes(r, c)
521+ except Exception as e:
522+ import traceback; traceback.print_exc()
523+ print(f"EXC at r={r} c={c}: {e}")
524+ raise SystemExit(1)
525+ mvref_print = 4 if mbsplit[r][c] else {-1: 0, -2: 1, -3: 2, -4: 3}.get(
526+ mbmode[r][c], 0
527+ )
528+ print(
529+ f"IMB r={r-1} c={c-1} ref={mbref[r][c]} mvref={mvref_print} "
530+ f"mv=({mbmv[r][c][0]},{mbmv[r][c][1]}) clamp={mbmvclamp[r][c]}"
531+ )
532+ if 0 < mbref[r][c] and mbmode[r][c] < 0:
533+ hasy2[r][c] = True
534+
535+ def row_tokens(r):
536+ pi = (r - 1) % nparts
537+ if d2s[pi] is None:
538+ d2s[pi] = BD(parts[pi])
539+ d2 = d2s[pi]
540+ left_ctx = [0] * 9
541+
542+ def get_coeffs(ptype, n0, ctx0, out):
543+ base = ptype * 264
544+ n = n0
545+ band = BANDS[n0]
546+ c = ctx0
547+ p = base + band * 33 + c * 11
548+
549+ def g(prob_):
550+ bit = d2.bool(prob_)
551+ print(f"G n={n} band={band} ctx={c} prob={prob_} bit={1 if bit else 0}")
552+ return bit
553+
554+ if not g(probs[p]):
555+ return 0
556+ while True:
557+ n += 1
558+ if not g(probs[p + 1]):
559+ c = 0
560+ band = BANDS[n]
561+ p = base + band * 33
562+ else:
563+ if not g(probs[p + 2]):
564+ c = 1
565+ band = BANDS[n]
566+ p = base + band * 33 + 11
567+ v = 1
568+ else:
569+ if not g(probs[p + 3]):
570+ if not g(probs[p + 4]):
571+ v = 2
572+ else:
573+ v = 3 + (1 if g(probs[p + 5]) else 0)
574+ else:
575+ if not g(probs[p + 6]):
576+ if not g(probs[p + 7]):
577+ v = 5 + (1 if g(159) else 0)
578+ else:
579+ v = 7 + 2 * (1 if g(165) else 0)
580+ v += 1 if g(145) else 0
581+ else:
582+ bit1 = 1 if g(probs[p + 8]) else 0
583+ bit0 = 1 if g(probs[p + 9 + bit1]) else 0
584+ cat = 2 * bit1 + bit0
585+ v = 0
586+ for prob in CAT_EXTRA[cat]:
587+ v += v + (1 if g(prob) else 0)
588+ v += 3 + (8 << cat)
589+ c = 2
590+ band = BANDS[n]
591+ p = base + band * 33 + 22
592+ out[ZIGZAG[n - 1]] = -v if g(128) else v
593+ if n < 16 and not g(probs[p]):
594+ return n
595+ if n == 16:
596+ return 16
597+
598+ for c in range(1, cols + 1):
599+ left_ctx = [0] * 9 if c == 1 else left_ctx
600+
601+ def one(blkidx, ptype, n0):
602+ o = [0] * 16
603+ ctxv = min(2, left_ctx[LEFT[blkidx]] + above_ctx[c - 1][ABOVE[blkidx]])
604+ print(f"TB {blkidx} ctx={ctxv} l={left_ctx[LEFT[blkidx]]} a={above_ctx[c - 1][ABOVE[blkidx]]}")
605+ print(f"T {r-1} {c-1} {blkidx} {ptype} {ctxv}")
606+ eob = get_coeffs(ptype, n0, ctxv, o)
607+ print(f"TBE {blkidx} eob={eob}")
608+ t = 1 if eob > 0 else 0
609+ left_ctx[LEFT[blkidx]] = t
610+ above_ctx[c - 1][ABOVE[blkidx]] = t
611+
612+ if skips[r][c]:
613+ for i in range(8):
614+ above_ctx[c - 1][i] = 0
615+ left_ctx[i] = 0
616+ if hasy2[r][c]:
617+ above_ctx[c - 1][8] = 0
618+ left_ctx[8] = 0
619+ continue
620+ if hasy2[r][c]:
621+ one(24, 1, 0)
622+ for b in range(16):
623+ one(b, 0, 1)
624+ else:
625+ for b in range(16):
626+ one(b, 3, 0)
627+ for b in range(4):
628+ one(16 + b, 2, 0)
629+ for b in range(4):
630+ one(20 + b, 2, 0)
631+
632+ if kf:
633+ for r in range(1, rows + 1):
634+ row_modes(r)
635+ row_tokens(r)
636+ else:
637+ for r in range(1, rows + 1):
638+ row_modes(r)
639+ for r in range(1, rows + 1):
640+ row_tokens(r)
641+
642+ if not refresh_entropy:
643+ ctx["coef"], ctx["mv"], ctx["ymode"], ctx["uv"] = snapshot
644+
645+
646+main()