forge
Explore
Log in

Don't you dare go Hollow

ec-vp8 M1: bool arithmetic decoder, frame tag + full first-partition header parsing, RFC-transcribed tables

Browse files at this commit

5233d888088eb5041b010868c65e031ab5b91755Ahmet Kaan GümüşParent: 3a3d412
- bool.rs: RFC 6386 section 7.3 decoder (read_bool/literal/signed_literal/
  maybe_signed/prob7/tree incl. the EOB-skipping token-tree form), plus a
  test-only reference bool encoder; round-trip tests at probability
  extremes, long LCG streams, literals to 19 bits, tree paths.
- frame.rs: 3-byte LE frame tag, key-frame start code + dimensions/scaling,
  MB geometry.
- header.rs: complete partition-1 header in dixie field order — colour
  space/clamping, segmentation (with cross-frame state), loop filter
  type/level/sharpness/deltas, token partition size table, quant indices,
  reference refresh/copies/sign-bias, coefficient probability updates,
  mb_no_skip_coeff, inter prob_intra/last/gf + ymode/uv/MV probability
  updates. PersistedState carries entropy/segmentation/filter deltas
  across frames and resets at key frames.
- tables.rs: GENERATED verbatim from the RFC text by
  scripts/extract_vp8_tables.py (element counts asserted): default + update
  coefficient probs, kf_bmode_prob, coeff_bands, dequant lookups, Pcat1-6
  (sentinel kept), default + update MV probs.
- scripts/gen_vp8_fixtures.sh: libvpx-encoded IVF witnesses (6 sizes/q,
  60-frame GOP, 8-token-partition vector via local vpxenc, WebP still).
- Witness: real vpxenc/ffmpeg-produced streams parse with exact tiling of
  partition sizes, correct dims (incl. 76x52 non-MB-aligned), 8 partitions;
  VP8-in-WebP still decodes its header. 12 tests green, zero warnings.
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/src/bool.rsadded+422 -0
@@ -0,0 +1,422 @@
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::{Error, 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.
36+ pub fn new(data: &'a [u8]) -> Result<Self> {
37+ if data.len() < 2 {
38+ return Err(Error::corrupt(
39+ "VP8 partition shorter than the two-byte bool decoder init",
40+ ));
41+ }
42+ let value = (u32::from(data[0]) << 8) | u32::from(data[1]);
43+ Ok(Self {
44+ data,
45+ pos: 2,
46+ range: 255,
47+ value,
48+ bit_count: 0,
49+ overreads: 0,
50+ })
51+ }
52+
53+ /// Bytes consumed past the end of the partition, read as zero. Any
54+ /// non-zero value on a complete, valid partition is a desync symptom.
55+ pub fn overreads(&self) -> u32 {
56+ self.overreads
57+ }
58+
59+ /// Offset of the next unread input byte, for desync diagnostics.
60+ pub fn byte_offset(&self) -> usize {
61+ self.pos
62+ }
63+
64+ fn next_byte(&mut self) -> u32 {
65+ match self.data.get(self.pos) {
66+ Some(&b) => {
67+ self.pos += 1;
68+ u32::from(b)
69+ }
70+ None => {
71+ self.overreads += 1;
72+ 0
73+ }
74+ }
75+ }
76+
77+ /// Decode one bool whose zero-probability is `prob`/256
78+ /// (RFC `read_bool`).
79+ pub fn read_bool(&mut self, prob: u8) -> bool {
80+ let prob = u32::from(prob);
81+ let split = 1 + (((self.range - 1) * prob) >> 8);
82+ let bigsplit = split << 8;
83+ let bit = if self.value >= bigsplit {
84+ self.range -= split;
85+ self.value -= bigsplit;
86+ true
87+ } else {
88+ self.range = split;
89+ false
90+ };
91+ while self.range < 128 {
92+ self.value <<= 1;
93+ self.range <<= 1;
94+ self.bit_count += 1;
95+ if self.bit_count == 8 {
96+ self.bit_count = 0;
97+ self.value |= self.next_byte();
98+ }
99+ }
100+ bit
101+ }
102+
103+ /// Unsigned `n`-bit literal, bits high- to low-order, each at
104+ /// probability 128 (RFC `read_literal`).
105+ pub fn read_literal(&mut self, n: u32) -> u32 {
106+ let mut v = 0;
107+ for _ in 0..n {
108+ v = (v << 1) + u32::from(self.read_bool(128));
109+ }
110+ v
111+ }
112+
113+ /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude
114+ /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0.
115+ pub fn read_signed_literal(&mut self, n: u32) -> i32 {
116+ if n == 0 {
117+ return 0;
118+ }
119+ let mut v: i32 = if self.read_bool(128) { -1 } else { 0 };
120+ for _ in 0..n - 1 {
121+ v = (v << 1) + i32::from(self.read_bool(128));
122+ }
123+ v
124+ }
125+ /// Presence-gated signed integer in the frame-header shape (RFC §9.3,
126+ /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an
127+ /// `n`-bit magnitude followed by a sign flag (1 = negative). This is
128+ /// every segment/quantizer/loop-filter delta in the frame header.
129+ pub fn read_maybe_signed(&mut self, n: u32) -> i32 {
130+ if !self.read_bool(128) {
131+ return 0;
132+ }
133+ let v = self.read_literal(n) as i32;
134+ if self.read_bool(128) { -v } else { v }
135+ }
136+
137+ /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1
138+ /// : 1` (RFC §8, MV probability updates use exactly this shape).
139+ pub fn read_prob7(&mut self) -> u8 {
140+ let x = self.read_literal(7);
141+ if x == 0 { 1 } else { (x << 1) as u8 }
142+ }
143+
144+ /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the
145+ /// left/right branch entries (positive = interior node index, negative
146+ /// `-leaf`), `probs[i]` is the probability of interior node `i` (the
147+ /// tree position halved).
148+ pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
149+ let mut i: i32 = 0;
150+ loop {
151+ let b = self.read_bool(probs[(i >> 1) as usize]);
152+ i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
153+ if i <= 0 {
154+ return (-i) as u8;
155+ }
156+ }
157+ }
158+
159+ /// Decode a tree-coded value, skipping the root's `dct_eob` branch —
160+ /// used for every token after a `DCT_0`, since EOB cannot follow a
161+ /// zero token (RFC §13.2). `tree` must be the full coefficient tree;
162+ /// decoding starts at interior node 1.
163+ pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
164+ // The coefficient tree's layout puts the EOB leaf at the root's
165+ // left branch; descending the right branch first is exactly
166+ // "start at the root with a read 1".
167+ let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch
168+ while {
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+ i > 0
172+ } {}
173+ (-i) as u8
174+ }
175+}
176+
177+/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests
178+/// drive [`BoolDecoder`] against known bitstreams instead of trusting the
179+/// decoder to decode its own idea of the format.
180+#[cfg(test)]
181+pub(crate) struct BoolEncoder {
182+ out: Vec<u8>,
183+ range: u32,
184+ bottom: u32,
185+ bit_count: i32,
186+}
187+
188+#[cfg(test)]
189+impl BoolEncoder {
190+ pub(crate) fn new() -> Self {
191+ Self {
192+ out: Vec::new(),
193+ range: 255,
194+ bottom: 0,
195+ bit_count: 24,
196+ }
197+ }
198+
199+ pub(crate) fn write_bool(&mut self, val: bool, prob: u8) {
200+ let prob = u32::from(prob);
201+ let split = 1 + (((self.range - 1) * prob) >> 8);
202+ if val {
203+ self.bottom += split;
204+ self.range -= split;
205+ } else {
206+ self.range = split;
207+ }
208+ while self.range < 128 {
209+ self.range <<= 1;
210+ if self.bottom & (1 << 31) != 0 {
211+ Self::add_one_to_output(&mut self.out);
212+ }
213+ self.bottom <<= 1;
214+ self.bit_count -= 1;
215+ if self.bit_count == 0 {
216+ self.out.push((self.bottom >> 24) as u8);
217+ self.bottom &= (1 << 24) - 1;
218+ self.bit_count = 8;
219+ }
220+ }
221+ }
222+
223+ pub(crate) fn write_literal(&mut self, v: u32, n: u32) {
224+ for i in (0..n).rev() {
225+ self.write_bool((v >> i) & 1 != 0, 128);
226+ }
227+ }
228+
229+ fn add_one_to_output(out: &mut [u8]) {
230+ for b in out.iter_mut().rev() {
231+ if *b == 255 {
232+ *b = 0;
233+ } else {
234+ *b += 1;
235+ return;
236+ }
237+ }
238+ // Carry out of the beginning cannot happen: x < 1 always (RFC).
239+ unreachable!("bool encoder carry propagated past the first byte");
240+ }
241+
242+ /// RFC `flush_bool_encoder`.
243+ pub(crate) fn flush(mut self) -> Vec<u8> {
244+ let c = self.bit_count;
245+ let mut v = self.bottom;
246+ if v & (1 << (32 - c)) != 0 {
247+ Self::add_one_to_output(&mut self.out);
248+ }
249+ v <<= c & 7;
250+ let mut c = c >> 3;
251+ while c > 0 {
252+ v <<= 8;
253+ c -= 1;
254+ }
255+ for _ in 0..4 {
256+ self.out.push((v >> 24) as u8);
257+ v <<= 8;
258+ }
259+ self.out
260+ }
261+}
262+
263+#[cfg(test)]
264+mod tests {
265+ use super::*;
266+
267+ fn roundtrip_bools(pattern: &[(&[bool], u8)]) {
268+ let mut e = BoolEncoder::new();
269+ for (vals, p) in pattern {
270+ for &v in *vals {
271+ e.write_bool(v, *p);
272+ }
273+ }
274+ let data = e.flush();
275+ let mut d = BoolDecoder::new(&data).unwrap();
276+ for (vals, p) in pattern {
277+ for &v in *vals {
278+ assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p);
279+ }
280+ }
281+ assert_eq!(d.overreads(), 0);
282+ }
283+
284+ #[test]
285+ fn roundtrips_bools_at_every_extreme() {
286+ // p = 1 (all zeros essentially free) through p = 255, with 1s at
287+ // the most improbable settings to force carry propagation.
288+ roundtrip_bools(&[
289+ (&[false; 64], 1),
290+ (&[true], 1),
291+ (&[false, true, false, true], 128),
292+ (&[true; 3], 255),
293+ (&[false; 32], 255),
294+ (&[true; 16], 1),
295+ ]);
296+ }
297+
298+ #[test]
299+ fn roundtrips_long_random_streams() {
300+ // Deterministic LCG so failures reproduce.
301+ let mut state: u64 = 0x9E3779B97F4A7C15;
302+ let mut next = move || {
303+ state ^= state << 13;
304+ state ^= state >> 7;
305+ state ^= state << 17;
306+ state
307+ };
308+ let probs = [1u8, 2, 32, 128, 200, 254, 255];
309+ let mut e = BoolEncoder::new();
310+ let mut expected = Vec::new();
311+ for &p in &probs {
312+ for _ in 0..200 {
313+ let v = next() & 1 == 1;
314+ e.write_bool(v, p);
315+ expected.push((v, p));
316+ }
317+ }
318+ let data = e.flush();
319+ let mut d = BoolDecoder::new(&data).unwrap();
320+ for (v, p) in expected {
321+ assert_eq!(d.read_bool(p), v);
322+ }
323+ assert_eq!(d.overreads(), 0);
324+ }
325+
326+ #[test]
327+ fn roundtrips_literals() {
328+ let mut e = BoolEncoder::new();
329+ for n in 1..=19u32 {
330+ let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
331+ e.write_literal(ones, n);
332+ e.write_literal(0, n);
333+ e.write_literal(0x15 & ones, n); // 0b10101 truncated
334+ }
335+ let data = e.flush();
336+ let mut d = BoolDecoder::new(&data).unwrap();
337+ for n in 1..=19u32 {
338+ let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
339+ assert_eq!(d.read_literal(n), ones);
340+ assert_eq!(d.read_literal(n), 0);
341+ assert_eq!(d.read_literal(n), 0x15 & ones);
342+ }
343+ assert_eq!(d.overreads(), 0);
344+ }
345+
346+ #[test]
347+ fn roundtrips_signed_literals() {
348+ let mut e = BoolEncoder::new();
349+ // sign flag then 4 magnitude bits: the two's-complement value in
350+ // -16..=15 (RFC read_signed_literal shifts the sign-extended -1).
351+ for mag in 0..=15u32 {
352+ e.write_bool(true, 128);
353+ e.write_literal(mag, 4);
354+ e.write_bool(false, 128);
355+ e.write_literal(mag, 4);
356+ }
357+ let data = e.flush();
358+ let mut d = BoolDecoder::new(&data).unwrap();
359+ for mag in 0..=15i32 {
360+ assert_eq!(d.read_signed_literal(5), mag - 16);
361+ assert_eq!(d.read_signed_literal(5), mag);
362+ }
363+ assert_eq!(d.overreads(), 0);
364+ }
365+
366+ #[test]
367+ fn roundtrips_prob7() {
368+ let mut e = BoolEncoder::new();
369+ for x in 0..=127u32 {
370+ e.write_literal(x, 7);
371+ }
372+ let data = e.flush();
373+ let mut d = BoolDecoder::new(&data).unwrap();
374+ for x in 0..=127u32 {
375+ assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 });
376+ }
377+ }
378+
379+ #[test]
380+ fn roundtrips_tree_values() {
381+ // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2:
382+ // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}.
383+ let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3];
384+ let probs = [145u8, 156, 163, 128];
385+ // (bit path, leaf value) pairs of the kf ymode tree (§11.2):
386+ // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110",
387+ // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics.
388+ let leaves: [(&[bool], u8); 5] = [
389+ (&[false], 4),
390+ (&[true, false, false], 0),
391+ (&[true, false, true], 1),
392+ (&[true, true, false], 2),
393+ (&[true, true, true], 3),
394+ ];
395+ for (path, val) in leaves {
396+ let mut e = BoolEncoder::new();
397+ for (i, &b) in path.iter().enumerate() {
398+ e.write_bool(b, probs[i]);
399+ }
400+ let data = e.flush();
401+ let mut d = BoolDecoder::new(&data).unwrap();
402+ assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}");
403+ }
404+ }
405+
406+ #[test]
407+ fn short_partition_is_corrupt() {
408+ assert!(BoolDecoder::new(&[]).is_err());
409+ assert!(BoolDecoder::new(&[7]).is_err());
410+ }
411+
412+ #[test]
413+ fn overreads_are_counted_not_panicked() {
414+ // Two bytes of init, then nothing: any read shifts in zeros.
415+ let data = [0u8, 0];
416+ let mut d = BoolDecoder::new(&data).unwrap();
417+ for _ in 0..100 {
418+ d.read_bool(128);
419+ }
420+ assert!(d.overreads() > 0);
421+ }
422+}
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+458 -0
@@ -0,0 +1,458 @@
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+ ymode_probs: [145, 156, 163, 128],
53+ uv_mode_probs: [142, 114, 183],
54+ segmentation: SegmentationState::default(),
55+ ref_lf_delta: [0; 4],
56+ mode_lf_delta: [0; 4],
57+ }
58+ }
59+}
60+
61+/// Segment feature state (RFC 6386 §10). `quant_idx`/`lf_level` hold the
62+/// raw transmitted values; they are absolute in absolute mode and deltas
63+/// in delta mode.
64+#[derive(Debug, Clone, Default)]
65+pub struct SegmentationState {
66+ /// Segment features active for the current frame.
67+ pub enabled: bool,
68+ /// The per-MB segment map is re-coded this frame.
69+ pub update_map: bool,
70+ /// Segment feature values are re-coded this frame.
71+ pub update_data: bool,
72+ /// 0 = absolute values, 1 = deltas against the frame baseline.
73+ /// 0 = absolute values, 1 = deltas against the frame baseline.
74+ pub abs_delta: bool,
75+ /// Per-segment quantizer value or delta (§10).
76+ pub quant_idx: [i32; 4],
77+ /// Per-segment loop-filter level or delta (§10).
78+ pub lf_level: [i32; 4],
79+ /// Segment-map decoding tree probabilities (default 255).
80+ /// Segment-map tree probabilities (default 255; §9.3 item 5).
81+ pub tree_probs: [u8; 3],
82+}
83+
84+/// Frame-level fields parsed from the uncompressed chunk and the first
85+/// data partition. Everything the per-macroblock decode needs.
86+#[derive(Debug, Clone)]
87+pub struct FrameHeader {
88+ /// Parsed 3-byte frame tag.
89+ pub tag: FrameTag,
90+ /// Key-frame dimensions (key frames only).
91+ pub dims: Option<crate::frame::KeyFrameDims>,
92+ /// Key-frame-only colour-space bit (0 = YUV; 1 is reserved).
93+ pub color_space: u8,
94+ /// Key-frame-only clamping bit (1 = reconstructed pixels guaranteed
95+ /// 0..255, clamping optional).
96+ pub clamping_type: u8,
97+ /// Segment feature snapshot this frame decodes under.
98+ pub segmentation: SegmentationState,
99+ /// Loop filter type/level/sharpness (§9.4).
100+ /// 0 = normal loop filter, 1 = simple (§9.4).
101+ pub filter_type: u8,
102+ /// Baseline loop filter strength 0-63 (0 disables filtering).
103+ pub filter_level: u8,
104+ /// Loop filter sharpness 0-7 (§9.4, §15.2).
105+ pub sharpness_level: u8,
106+ /// Per-MB loop-filter delta adjustment enabled for this frame.
107+ pub lf_delta_enabled: bool,
108+ /// This frame updated the (persisted) delta values.
109+ pub lf_delta_update: bool,
110+ /// log2 of the token partition count (1, 2, 4 or 8 partitions).
111+ pub log2_partitions: u8,
112+ /// Quantization indices (§9.6): base Y-AC index plus per-plane deltas.
113+ pub quant: QuantIndices,
114+ /// Probability an interframe MB is intra-coded (§9.10 `prob_intra`).
115+ pub prob_intra: u8,
116+ /// Probability an inter MB uses the last-frame reference.
117+ pub prob_last: u8,
118+ /// Probability an inter MB uses the golden rather than altref ref.
119+ pub prob_gf: u8,
120+ /// Whether this frame updated the interframe Y-mode probabilities.
121+ pub ymode_probs_updated: bool,
122+ /// Whether this frame updated the chroma-mode probabilities.
123+ pub uv_mode_probs_updated: bool,
124+ /// Reference-frame refresh/copies/sign-biases (§9.7-§9.8).
125+ pub refresh: RefreshHeader,
126+ /// mb_no_skip_coeff (§9.10/§9.11): per-MB "no non-zero coefficients"
127+ /// flag is coded at all.
128+ pub coeff_skip_enabled: bool,
129+ /// Probability for the per-MB skip flag (meaningful when enabled).
130+ pub prob_skip_false: u8,
131+ /// Offset of the first token partition from the start of `data`
132+ /// (i.e. uncompressed chunk + first partition).
133+ pub token_data_offset: usize,
134+ /// Token partition sizes in bytes; last entry is the remainder.
135+ pub partition_sizes: Vec<u32>,
136+}
137+
138+/// Six dequantization indices (§9.6): the always-coded Y-AC index plus
139+/// signed deltas for the other five factors.
140+#[derive(Debug, Clone, Copy, Default)]
141+pub struct QuantIndices {
142+ /// Base quantizer index for Y AC (7 bits).
143+ pub yac_qi: u8,
144+ /// Signed delta applied to the Y-DC dequant index (§9.6).
145+ pub ydc_delta: i32,
146+ /// Signed delta applied to the Y2-DC dequant index (§9.6).
147+ pub y2dc_delta: i32,
148+ /// Signed delta applied to the Y2-AC dequant index (§9.6).
149+ pub y2ac_delta: i32,
150+ /// Signed delta applied to the chroma-DC dequant index (§9.6).
151+ pub uvdc_delta: i32,
152+ /// Signed delta applied to the chroma-AC dequant index (§9.6).
153+ pub uvac_delta: i32,
154+}
155+
156+/// Reference-frame refresh state for one frame (§9.7-§9.8). Key frames
157+/// refresh every reference and read only `refresh_entropy`.
158+#[derive(Debug, Clone, Copy)]
159+pub struct RefreshHeader {
160+ /// The golden buffer is refreshed with the current frame.
161+ pub refresh_gf: bool,
162+ /// The altref buffer is refreshed with the current frame.
163+ pub refresh_arf: bool,
164+ /// 0 = none, 1 = copy last, 2 = copy altref (to golden).
165+ pub copy_gf: u8,
166+ /// 0 = none, 1 = copy last, 2 = copy golden (to altref).
167+ pub copy_arf: u8,
168+ /// Sign bias applied to MVs referencing the golden frame (§9.7).
169+ pub sign_bias_golden: bool,
170+ /// Sign bias applied to MVs referencing the altref frame (§9.7).
171+ pub sign_bias_altref: bool,
172+ /// Whether this frame's entropy updates persist to the next frame.
173+ pub refresh_entropy: bool,
174+ /// The last-frame buffer is refreshed with the current frame.
175+ pub refresh_last: bool,
176+}
177+
178+impl FrameHeader {
179+ /// The frame's type (key or inter), from the frame tag.
180+ pub fn frame_type(&self) -> FrameType {
181+ self.tag.frame_type
182+ }
183+
184+ /// Parse one frame's uncompressed chunk + first partition from
185+ /// `data`, folding entropy/segmentation/filter-delta updates into
186+ /// `state`. Returns the header and the partition-1 slice.
187+ ///
188+ /// `token_data_offset` + every `partition_sizes[i]` together describe
189+ /// the bytes after partition 1.
190+ pub fn parse<'a>(
191+ data: &'a [u8],
192+ state: &mut PersistedState,
193+ ) -> Result<(FrameHeader, &'a [u8])> {
194+ let tag = FrameTag::parse(data)?;
195+ let key = tag.frame_type == FrameType::Key;
196+ let mut off = crate::frame::FRAME_TAG_SZ;
197+
198+ let mut dims = None;
199+ if key {
200+ let kf = parse_keyframe_dims(data)?;
201+ dims = Some(kf);
202+ off += KEYFRAME_HEADER_SZ;
203+ // A key frame resets every piece of persisted entropy and
204+ // segment/filter state (dixie `decode_frame`).
205+ *state = PersistedState::default();
206+ }
207+
208+ let part0_end = off + tag.first_part_size as usize;
209+ if data.len() < part0_end {
210+ return Err(Error::corrupt(format!(
211+ "VP8 first partition extends past end of frame \
212+ (need {part0_end} bytes, have {})",
213+ data.len()
214+ )));
215+ }
216+ let mut d = BoolDecoder::new(&data[off..part0_end])?;
217+
218+ // Colour space + clamping (key frames only): two literal bits;
219+ // the colour-space bit is reserved and must be 0 (dixie reads
220+ // both together and refuses any non-zero pair; we keep the
221+ // (legal) clamping bit decodable and refuse only the reserved
222+ // colour-space one).
223+ let (color_space, clamping_type) = if key {
224+ let cs = d.read_literal(1) as u8;
225+ let clamp = d.read_literal(1) as u8;
226+ if cs != 0 {
227+ return Err(Error::unsupported(
228+ "VP8 reserved colour-space bit",
229+ "bit 0 of the key-frame colour-space pair was set",
230+ ));
231+ }
232+ (cs, clamp)
233+ } else {
234+ (0, 0)
235+ };
236+
237+ // --- segmentation (§9.3, dixie decode_segmentation_header) ---
238+ let mut segmentation = if key {
239+ SegmentationState::default()
240+ } else {
241+ state.segmentation.clone()
242+ };
243+ segmentation.enabled = d.read_bool(128);
244+ if segmentation.enabled {
245+ segmentation.update_map = d.read_bool(128);
246+ segmentation.update_data = d.read_bool(128);
247+ if segmentation.update_data {
248+ segmentation.abs_delta = d.read_bool(128);
249+ for i in 0..4 {
250+ segmentation.quant_idx[i] = d.read_maybe_signed(7);
251+ }
252+ for i in 0..4 {
253+ segmentation.lf_level[i] = d.read_maybe_signed(6);
254+ }
255+ }
256+ if segmentation.update_map {
257+ for i in 0..3 {
258+ segmentation.tree_probs[i] = if d.read_bool(128) {
259+ d.read_literal(8) as u8
260+ } else {
261+ 255
262+ };
263+ }
264+ }
265+ } else {
266+ segmentation.update_map = false;
267+ segmentation.update_data = false;
268+ }
269+ state.segmentation = segmentation.clone();
270+
271+ // --- loop filter (§9.4, dixie decode_loopfilter_header) ---
272+ let mut ref_lf_delta = state.ref_lf_delta;
273+ let mut mode_lf_delta = state.mode_lf_delta;
274+ if key {
275+ ref_lf_delta = [0; 4];
276+ mode_lf_delta = [0; 4];
277+ }
278+ let filter_type = d.read_literal(1) as u8;
279+ let filter_level = d.read_literal(6) as u8;
280+ let sharpness_level = d.read_literal(3) as u8;
281+ let lf_delta_enabled = d.read_bool(128);
282+ let mut lf_delta_update = false;
283+ if lf_delta_enabled && d.read_bool(128) {
284+ lf_delta_update = true;
285+ for i in 0..4 {
286+ ref_lf_delta[i] = d.read_maybe_signed(6);
287+ }
288+ for i in 0..4 {
289+ mode_lf_delta[i] = d.read_maybe_signed(6);
290+ }
291+ }
292+ state.ref_lf_delta = ref_lf_delta;
293+ state.mode_lf_delta = mode_lf_delta;
294+
295+ // --- token partitions (§9.5) ---
296+ let log2_partitions = d.read_literal(2) as u8;
297+ let partitions = 1usize << log2_partitions;
298+ let sizes_area = 3 * (partitions - 1);
299+ if data.len() < part0_end + sizes_area {
300+ return Err(Error::corrupt(
301+ "VP8 token partition size table extends past end of frame",
302+ ));
303+ }
304+ let mut partition_sizes = Vec::with_capacity(partitions);
305+ let mut size_off = part0_end;
306+ let mut remaining = (data.len() - part0_end - sizes_area) as u32;
307+ for i in 0..partitions {
308+ if i < partitions - 1 {
309+ let sz = u32::from(data[size_off])
310+ | (u32::from(data[size_off + 1]) << 8)
311+ | (u32::from(data[size_off + 2]) << 16);
312+ size_off += 3;
313+ partition_sizes.push(sz);
314+ remaining = remaining
315+ .checked_sub(sz)
316+ .ok_or_else(|| Error::corrupt("VP8 token partitions exceed frame size"))?;
317+ } else {
318+ partition_sizes.push(remaining);
319+ }
320+ }
321+
322+ // --- quantization indices (§9.6) ---
323+ let mut quant = QuantIndices {
324+ yac_qi: d.read_literal(7) as u8,
325+ ..QuantIndices::default()
326+ };
327+ quant.ydc_delta = d.read_maybe_signed(4);
328+ quant.y2dc_delta = d.read_maybe_signed(4);
329+ quant.y2ac_delta = d.read_maybe_signed(4);
330+ quant.uvdc_delta = d.read_maybe_signed(4);
331+ quant.uvac_delta = d.read_maybe_signed(4);
332+
333+ // --- reference refresh (§9.7-§9.8) ---
334+ let refresh = if key {
335+ RefreshHeader {
336+ refresh_gf: true,
337+ refresh_arf: true,
338+ copy_gf: 0,
339+ copy_arf: 0,
340+ sign_bias_golden: false,
341+ sign_bias_altref: false,
342+ refresh_entropy: d.read_bool(128),
343+ refresh_last: true,
344+ }
345+ } else {
346+ let refresh_gf = d.read_bool(128);
347+ let refresh_arf = d.read_bool(128);
348+ let copy_gf = if refresh_gf {
349+ 0
350+ } else {
351+ d.read_literal(2) as u8
352+ };
353+ let copy_arf = if refresh_arf {
354+ 0
355+ } else {
356+ d.read_literal(2) as u8
357+ };
358+ RefreshHeader {
359+ refresh_gf,
360+ refresh_arf,
361+ copy_gf,
362+ copy_arf,
363+ sign_bias_golden: d.read_bool(128),
364+ sign_bias_altref: d.read_bool(128),
365+ refresh_entropy: d.read_bool(128),
366+ refresh_last: d.read_bool(128),
367+ }
368+ };
369+
370+ // --- entropy updates (§9.9; dixie decode_entropy_header) ---
371+ // Coefficient probability updates are read for every frame; on
372+ // key frames the tables were reset to defaults above.
373+ for i in 0..4 {
374+ for j in 0..8 {
375+ for k in 0..3 {
376+ for l in 0..11 {
377+ if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) {
378+ state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8;
379+ }
380+ }
381+ }
382+ }
383+ }
384+
385+ // mb_no_skip_coeff (§9.11 / inter §9.10).
386+ let coeff_skip_enabled = d.read_bool(128);
387+ let prob_skip_false = if coeff_skip_enabled {
388+ d.read_literal(8) as u8
389+ } else {
390+ 128
391+ };
392+ // Interframe-only probability updates.
393+ let mut ymode_probs_updated = false;
394+ let mut uv_mode_probs_updated = false;
395+ let (prob_intra, prob_last, prob_gf) = if !key {
396+ let probs = (
397+ d.read_literal(8) as u8,
398+ d.read_literal(8) as u8,
399+ d.read_literal(8) as u8,
400+ );
401+ ymode_probs_updated = d.read_bool(128);
402+ if ymode_probs_updated {
403+ for i in 0..4 {
404+ state.ymode_probs[i] = d.read_literal(8) as u8;
405+ }
406+ }
407+ uv_mode_probs_updated = d.read_bool(128);
408+ if uv_mode_probs_updated {
409+ for i in 0..3 {
410+ state.uv_mode_probs[i] = d.read_literal(8) as u8;
411+ }
412+ }
413+ probs
414+ } else {
415+ (145, 156, 163)
416+ };
417+ for c in 0..2 {
418+ for j in 0..MV_PROB_CNT {
419+ if d.read_bool(MV_UPDATE_PROBS[c][j]) {
420+ state.mv_probs[c][j] = d.read_prob7();
421+ }
422+ }
423+ }
424+
425+ if d.overreads() > 0 {
426+ return Err(Error::corrupt(format!(
427+ "VP8 first partition over-read by {} bytes (header desync)",
428+ d.overreads()
429+ )));
430+ }
431+
432+ let header = FrameHeader {
433+ tag,
434+ dims,
435+ color_space,
436+ clamping_type,
437+ segmentation,
438+ filter_type,
439+ filter_level,
440+ sharpness_level,
441+ lf_delta_enabled,
442+ lf_delta_update,
443+ log2_partitions,
444+ quant,
445+ refresh,
446+ prob_intra,
447+ prob_last,
448+ prob_gf,
449+ ymode_probs_updated,
450+ uv_mode_probs_updated,
451+ coeff_skip_enabled,
452+ prob_skip_false,
453+ token_data_offset: part0_end,
454+ partition_sizes,
455+ };
456+ Ok((header, &data[off..part0_end]))
457+ }
458+}
crates/ec-vp8/src/lib.rsadded+23 -0
@@ -0,0 +1,23 @@
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 frame;
19+pub mod header;
20+pub mod tables;
21+
22+pub use ec_core::{Error, Result};
23+pub use header::PersistedState;
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/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, part0) = FrameHeader::parse(first, &mut state).unwrap();
43+ assert_eq!(part0.len(), 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+74 -0
@@ -0,0 +1,74 @@
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+ pub data: Vec<u8>,
11+}
12+
13+/// Parse an IVF file into (fourcc, width, height, frames).
14+pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec<IvfFrame>) {
15+ assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file");
16+ let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize;
17+ let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap();
18+ let width = u16::from_le_bytes([bytes[12], bytes[13]]);
19+ let height = u16::from_le_bytes([bytes[14], bytes[15]]);
20+ let mut pos = hdr_len;
21+ let mut frames = Vec::new();
22+ while pos + 12 <= bytes.len() {
23+ let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
24+ as usize;
25+ let pts = u64::from_le_bytes([
26+ bytes[pos + 4],
27+ bytes[pos + 5],
28+ bytes[pos + 6],
29+ bytes[pos + 7],
30+ bytes[pos + 8],
31+ bytes[pos + 9],
32+ bytes[pos + 10],
33+ bytes[pos + 11],
34+ ]);
35+ pos += 12;
36+ if pos + sz > bytes.len() {
37+ break;
38+ }
39+ frames.push(IvfFrame {
40+ pts,
41+ data: bytes[pos..pos + sz].to_vec(),
42+ });
43+ pos += sz;
44+ }
45+ (fourcc, width, height, frames)
46+}
47+
48+/// Extract the VP8 payload from a lossy WebP file (RIFF/WEBP with a VP8
49+/// chunk) — the same VP8 key-frame bytes in a different container.
50+pub fn webp_vp8_chunk(bytes: &[u8]) -> Vec<u8> {
51+ assert_eq!(&bytes[0..4], b"RIFF");
52+ assert_eq!(&bytes[8..12], b"WEBP");
53+ let mut pos = 12;
54+ while pos + 8 <= bytes.len() {
55+ let tag = &bytes[pos..pos + 4];
56+ let sz = u32::from_le_bytes([
57+ bytes[pos + 4],
58+ bytes[pos + 5],
59+ bytes[pos + 6],
60+ bytes[pos + 7],
61+ ]) as usize;
62+ if tag == b"VP8 " {
63+ return bytes[pos + 8..pos + 8 + sz].to_vec();
64+ }
65+ pos += 8 + sz + (sz & 1); // chunks are word-aligned
66+ }
67+ panic!("no VP8 chunk in webp");
68+}
69+
70+/// Root of the workspace checkout this test runs in (crates/ec-vp8/../..).
71+pub fn fixture_dir() -> Option<std::path::PathBuf> {
72+ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vp8");
73+ if dir.is_dir() { Some(dir) } else { None }
74+}
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+83 -0
@@ -0,0 +1,83 @@
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+ls -la "$OUT"