diff --git a/Cargo.lock b/Cargo.lock index c535ff8f..1c075aa2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,6 +485,13 @@ dependencies = [ "ec-ogg", ] +[[package]] +name = "ec-vp8" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "ec-vp9-syntax" version = "0.1.0" diff --git a/crates/ec-vp8/Cargo.toml b/crates/ec-vp8/Cargo.toml new file mode 100644 index 00000000..a8b294dc --- /dev/null +++ b/crates/ec-vp8/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-vp8" +description = "Native VP8 decoder (RFC 6386) — key-frame and inter-frame decoding of the full format, replacing the runtime-dlopen'd libvpx seat." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-vp8/src/bool.rs b/crates/ec-vp8/src/bool.rs new file mode 100644 index 00000000..99e40613 --- /dev/null +++ b/crates/ec-vp8/src/bool.rs @@ -0,0 +1,422 @@ +//! The boolean arithmetic decoder (RFC 6386 §7). +//! +//! VP8 codes almost the entire frame as a sequence of bools, each written +//! at an 8-bit zero-probability `p` (meaning `p/256`). The decoder mirrors +//! the encoder's interval state with two numbers — `range` (128..=255) and +//! `value` (the encoded number x minus the interval's left endpoint) — and +//! renormalises one bit at a time, shifting a fresh input byte into +//! `value` for every 8 bits consumed. +//! +//! Every function here is the direct inverse of the RFC's reference +//! `bool_encoder`; the tests drive them against a test-only re-implementation +//! of that encoder and assert bit-exact round-trips. + +use ec_core::{Error, Result}; + +/// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3). +pub struct BoolDecoder<'a> { + data: &'a [u8], + /// Index of the next byte to shift into `value`. + pos: usize, + /// 128..=255; identical to the encoder's range. + range: u32, + /// Encoded number minus the current interval's left endpoint; the top + /// bits hold what has been read, bytes shift in at the bottom. + value: u32, + /// Bits shifted out of `value` since the last byte was shifted in. + bit_count: u32, + /// Bytes consumed past the end of the partition (read as 0, per the + /// spec's zero-extension of x). A healthy partition stays at 0. + overreads: u32, +} + +impl<'a> BoolDecoder<'a> { + /// Start decoding the partition `data` (RFC `init_bool_decoder`): the + /// first two bytes are read into `value`, big-endian. + pub fn new(data: &'a [u8]) -> Result { + if data.len() < 2 { + return Err(Error::corrupt( + "VP8 partition shorter than the two-byte bool decoder init", + )); + } + let value = (u32::from(data[0]) << 8) | u32::from(data[1]); + Ok(Self { + data, + pos: 2, + range: 255, + value, + bit_count: 0, + overreads: 0, + }) + } + + /// Bytes consumed past the end of the partition, read as zero. Any + /// non-zero value on a complete, valid partition is a desync symptom. + pub fn overreads(&self) -> u32 { + self.overreads + } + + /// Offset of the next unread input byte, for desync diagnostics. + pub fn byte_offset(&self) -> usize { + self.pos + } + + fn next_byte(&mut self) -> u32 { + match self.data.get(self.pos) { + Some(&b) => { + self.pos += 1; + u32::from(b) + } + None => { + self.overreads += 1; + 0 + } + } + } + + /// Decode one bool whose zero-probability is `prob`/256 + /// (RFC `read_bool`). + pub fn read_bool(&mut self, prob: u8) -> bool { + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + let bigsplit = split << 8; + let bit = if self.value >= bigsplit { + self.range -= split; + self.value -= bigsplit; + true + } else { + self.range = split; + false + }; + while self.range < 128 { + self.value <<= 1; + self.range <<= 1; + self.bit_count += 1; + if self.bit_count == 8 { + self.bit_count = 0; + self.value |= self.next_byte(); + } + } + bit + } + + /// Unsigned `n`-bit literal, bits high- to low-order, each at + /// probability 128 (RFC `read_literal`). + pub fn read_literal(&mut self, n: u32) -> u32 { + let mut v = 0; + for _ in 0..n { + v = (v << 1) + u32::from(self.read_bool(128)); + } + v + } + + /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude + /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0. + pub fn read_signed_literal(&mut self, n: u32) -> i32 { + if n == 0 { + return 0; + } + let mut v: i32 = if self.read_bool(128) { -1 } else { 0 }; + for _ in 0..n - 1 { + v = (v << 1) + i32::from(self.read_bool(128)); + } + v + } + /// Presence-gated signed integer in the frame-header shape (RFC §9.3, + /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an + /// `n`-bit magnitude followed by a sign flag (1 = negative). This is + /// every segment/quantizer/loop-filter delta in the frame header. + pub fn read_maybe_signed(&mut self, n: u32) -> i32 { + if !self.read_bool(128) { + return 0; + } + let v = self.read_literal(n) as i32; + if self.read_bool(128) { -v } else { v } + } + + /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1 + /// : 1` (RFC §8, MV probability updates use exactly this shape). + pub fn read_prob7(&mut self) -> u8 { + let x = self.read_literal(7); + if x == 0 { 1 } else { (x << 1) as u8 } + } + + /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the + /// left/right branch entries (positive = interior node index, negative + /// `-leaf`), `probs[i]` is the probability of interior node `i` (the + /// tree position halved). + pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 { + let mut i: i32 = 0; + loop { + let b = self.read_bool(probs[(i >> 1) as usize]); + i = i32::from(tree[(i + i32::from(b as i8)) as usize]); + if i <= 0 { + return (-i) as u8; + } + } + } + + /// Decode a tree-coded value, skipping the root's `dct_eob` branch — + /// used for every token after a `DCT_0`, since EOB cannot follow a + /// zero token (RFC §13.2). `tree` must be the full coefficient tree; + /// decoding starts at interior node 1. + pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 { + // The coefficient tree's layout puts the EOB leaf at the root's + // left branch; descending the right branch first is exactly + // "start at the root with a read 1". + let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch + while { + let b = self.read_bool(probs[(i >> 1) as usize]); + i = i32::from(tree[(i + i32::from(b as i8)) as usize]); + i > 0 + } {} + (-i) as u8 + } +} + +/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests +/// drive [`BoolDecoder`] against known bitstreams instead of trusting the +/// decoder to decode its own idea of the format. +#[cfg(test)] +pub(crate) struct BoolEncoder { + out: Vec, + range: u32, + bottom: u32, + bit_count: i32, +} + +#[cfg(test)] +impl BoolEncoder { + pub(crate) fn new() -> Self { + Self { + out: Vec::new(), + range: 255, + bottom: 0, + bit_count: 24, + } + } + + pub(crate) fn write_bool(&mut self, val: bool, prob: u8) { + let prob = u32::from(prob); + let split = 1 + (((self.range - 1) * prob) >> 8); + if val { + self.bottom += split; + self.range -= split; + } else { + self.range = split; + } + while self.range < 128 { + self.range <<= 1; + if self.bottom & (1 << 31) != 0 { + Self::add_one_to_output(&mut self.out); + } + self.bottom <<= 1; + self.bit_count -= 1; + if self.bit_count == 0 { + self.out.push((self.bottom >> 24) as u8); + self.bottom &= (1 << 24) - 1; + self.bit_count = 8; + } + } + } + + pub(crate) fn write_literal(&mut self, v: u32, n: u32) { + for i in (0..n).rev() { + self.write_bool((v >> i) & 1 != 0, 128); + } + } + + fn add_one_to_output(out: &mut [u8]) { + for b in out.iter_mut().rev() { + if *b == 255 { + *b = 0; + } else { + *b += 1; + return; + } + } + // Carry out of the beginning cannot happen: x < 1 always (RFC). + unreachable!("bool encoder carry propagated past the first byte"); + } + + /// RFC `flush_bool_encoder`. + pub(crate) fn flush(mut self) -> Vec { + let c = self.bit_count; + let mut v = self.bottom; + if v & (1 << (32 - c)) != 0 { + Self::add_one_to_output(&mut self.out); + } + v <<= c & 7; + let mut c = c >> 3; + while c > 0 { + v <<= 8; + c -= 1; + } + for _ in 0..4 { + self.out.push((v >> 24) as u8); + v <<= 8; + } + self.out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn roundtrip_bools(pattern: &[(&[bool], u8)]) { + let mut e = BoolEncoder::new(); + for (vals, p) in pattern { + for &v in *vals { + e.write_bool(v, *p); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (vals, p) in pattern { + for &v in *vals { + assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p); + } + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_bools_at_every_extreme() { + // p = 1 (all zeros essentially free) through p = 255, with 1s at + // the most improbable settings to force carry propagation. + roundtrip_bools(&[ + (&[false; 64], 1), + (&[true], 1), + (&[false, true, false, true], 128), + (&[true; 3], 255), + (&[false; 32], 255), + (&[true; 16], 1), + ]); + } + + #[test] + fn roundtrips_long_random_streams() { + // Deterministic LCG so failures reproduce. + let mut state: u64 = 0x9E3779B97F4A7C15; + let mut next = move || { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state + }; + let probs = [1u8, 2, 32, 128, 200, 254, 255]; + let mut e = BoolEncoder::new(); + let mut expected = Vec::new(); + for &p in &probs { + for _ in 0..200 { + let v = next() & 1 == 1; + e.write_bool(v, p); + expected.push((v, p)); + } + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for (v, p) in expected { + assert_eq!(d.read_bool(p), v); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_literals() { + let mut e = BoolEncoder::new(); + for n in 1..=19u32 { + let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 }; + e.write_literal(ones, n); + e.write_literal(0, n); + e.write_literal(0x15 & ones, n); // 0b10101 truncated + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for n in 1..=19u32 { + let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 }; + assert_eq!(d.read_literal(n), ones); + assert_eq!(d.read_literal(n), 0); + assert_eq!(d.read_literal(n), 0x15 & ones); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_signed_literals() { + let mut e = BoolEncoder::new(); + // sign flag then 4 magnitude bits: the two's-complement value in + // -16..=15 (RFC read_signed_literal shifts the sign-extended -1). + for mag in 0..=15u32 { + e.write_bool(true, 128); + e.write_literal(mag, 4); + e.write_bool(false, 128); + e.write_literal(mag, 4); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for mag in 0..=15i32 { + assert_eq!(d.read_signed_literal(5), mag - 16); + assert_eq!(d.read_signed_literal(5), mag); + } + assert_eq!(d.overreads(), 0); + } + + #[test] + fn roundtrips_prob7() { + let mut e = BoolEncoder::new(); + for x in 0..=127u32 { + e.write_literal(x, 7); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + for x in 0..=127u32 { + assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 }); + } + } + + #[test] + fn roundtrips_tree_values() { + // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2: + // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}. + let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3]; + let probs = [145u8, 156, 163, 128]; + // (bit path, leaf value) pairs of the kf ymode tree (§11.2): + // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110", + // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics. + let leaves: [(&[bool], u8); 5] = [ + (&[false], 4), + (&[true, false, false], 0), + (&[true, false, true], 1), + (&[true, true, false], 2), + (&[true, true, true], 3), + ]; + for (path, val) in leaves { + let mut e = BoolEncoder::new(); + for (i, &b) in path.iter().enumerate() { + e.write_bool(b, probs[i]); + } + let data = e.flush(); + let mut d = BoolDecoder::new(&data).unwrap(); + assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}"); + } + } + + #[test] + fn short_partition_is_corrupt() { + assert!(BoolDecoder::new(&[]).is_err()); + assert!(BoolDecoder::new(&[7]).is_err()); + } + + #[test] + fn overreads_are_counted_not_panicked() { + // Two bytes of init, then nothing: any read shifts in zeros. + let data = [0u8, 0]; + let mut d = BoolDecoder::new(&data).unwrap(); + for _ in 0..100 { + d.read_bool(128); + } + assert!(d.overreads() > 0); + } +} diff --git a/crates/ec-vp8/src/frame.rs b/crates/ec-vp8/src/frame.rs new file mode 100644 index 00000000..7344e491 --- /dev/null +++ b/crates/ec-vp8/src/frame.rs @@ -0,0 +1,102 @@ +//! Frame-level structures and the raw (uncompressed) frame tag +//! (RFC 6386 §9.1). + +use ec_core::{Error, Result}; + +/// Key frame or interframe — the 1-bit frame type from the frame tag. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FrameType { + /// Key frame (`frame_type` bit 0). + Key, + /// Interframe (`frame_type` bit 1); predicted from earlier frames. + Inter, +} + +/// The 3-byte frame tag every frame starts with (RFC 6386 §9.1 item 1-4): +/// 1 bit type, 3 bits version, 1 bit show_frame, 19 bits first-partition +/// size — all read out of one little-endian 24-bit word. +#[derive(Debug, Clone, Copy)] +pub struct FrameTag { + /// Key or inter frame. + pub frame_type: FrameType, + /// 3-bit version (reconstruction-filter / loop-filter profile; only + /// bits that matter historically — the header's own loop filter fields + /// govern decoding). + pub version: u8, + /// Whether the decoded frame is for display. + pub show_frame: bool, + /// Size in bytes of the first (header/mode) data partition. + pub first_part_size: u32, +} + +/// Bytes occupied by the 3-byte frame tag. +pub const FRAME_TAG_SZ: usize = 3; + +/// Bytes occupied by the key frame's start code + size fields (§9.1). +pub const KEYFRAME_HEADER_SZ: usize = 7; + +impl FrameTag { + /// Parse the tag from the first 3 bytes of a frame. + pub fn parse(data: &[u8]) -> Result { + if data.len() < FRAME_TAG_SZ { + return Err(Error::corrupt("VP8 frame shorter than its 3-byte tag")); + } + let tag = u32::from(data[0]) | (u32::from(data[1]) << 8) | (u32::from(data[2]) << 16); + Ok(FrameTag { + frame_type: if tag & 1 == 0 { + FrameType::Key + } else { + FrameType::Inter + }, + version: ((tag >> 1) & 7) as u8, + show_frame: (tag >> 4) & 1 == 1, + first_part_size: tag >> 5, + }) + } +} + +/// Key-frame dimensions and scaling flags (RFC 6386 §9.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct KeyFrameDims { + /// Encoded (pre-scaling) width in pixels, 14 bits. + pub width: u16, + /// Encoded height in pixels, 14 bits. + pub height: u16, + /// 2-bit horizontal scale (0 = none, 1 = 5/4, 2 = 5/3, 3 = 2). + pub h_scale: u8, + /// 2-bit vertical scale. + pub v_scale: u8, +} + +/// Parse the key-frame start code (`9d 01 2a`) and dimensions that follow +/// the frame tag. `data` starts at the frame tag. +pub fn parse_keyframe_dims(data: &[u8]) -> Result { + let dims_off = FRAME_TAG_SZ; + if data.len() < dims_off + KEYFRAME_HEADER_SZ { + return Err(Error::corrupt("VP8 key frame header truncated")); + } + let c = &data[dims_off..]; + if c[0] != 0x9d || c[1] != 0x01 || c[2] != 0x2a { + return Err(Error::corrupt(format!( + "VP8 key frame start code 9d 01 2a not found (got {:02x} {:02x} {:02x})", + c[0], c[1], c[2] + ))); + } + let w = u16::from_le_bytes([c[3], c[4]]); + let h = u16::from_le_bytes([c[5], c[6]]); + Ok(KeyFrameDims { + width: w & 0x3fff, + height: h & 0x3fff, + h_scale: (w >> 14) as u8, + v_scale: (h >> 14) as u8, + }) +} + +/// Number of 16×16 macroblock columns/rows covering `width × height` +/// pixels (the encoded frame is padded up to whole macroblocks). +pub fn mb_geometry(width: u16, height: u16) -> (usize, usize) { + ( + (usize::from(width) + 15) / 16, + (usize::from(height) + 15) / 16, + ) +} diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs new file mode 100644 index 00000000..6cf6d54b --- /dev/null +++ b/crates/ec-vp8/src/header.rs @@ -0,0 +1,458 @@ +//! Uncompressed chunk and first-partition header parsing +//! (RFC 6386 §9-§10, following the reference decoder's field order). +//! +//! Three pieces of state persist across frames until the next key frame +//! resets them: the entropy context (coefficient, MV and intra-mode +//! probabilities), the segmentation feature data and the per-macroblock +//! loop-filter deltas. They live in [`PersistedState`]; every frame's +//! [`FrameHeader::parse`] folds that frame's updates into it. + +use crate::bool::BoolDecoder; +use crate::frame::{FrameTag, FrameType, KEYFRAME_HEADER_SZ, parse_keyframe_dims}; +use crate::tables::{DEFAULT_COEFF_PROBS, DEFAULT_MV_PROBS, MV_UPDATE_PROBS}; +use ec_core::{Error, Result}; + +/// Probability-array length per MV component (dixie `MV_PROB_CNT`): +/// is_short, sign, 7 short-tree, 10 long-bits probabilities. +pub const MV_PROB_CNT: usize = 19; + +/// Everything that survives from frame to frame until a key frame. +#[derive(Debug, Clone)] +pub struct PersistedState { + /// Token-tree probabilities, `[block_type][band][ctx][node]` + /// (RFC 6386 §13.3). + /// Token-tree probabilities `[block_type][band][ctx][node]` (§13.3). + pub coeff_probs: [[[[u8; 11]; 3]; 8]; 4], + /// Per-MV-component probabilities `[component][prob]` (RFC §17.2). + /// Per-MV-component probabilities `[component][prob]` (§17.2). + pub mv_probs: [[u8; MV_PROB_CNT]; 2], + /// Interframe Y-mode tree probabilities (RFC §16.1). + /// Interframe Y-mode tree probabilities (§16.1). + pub ymode_probs: [u8; 4], + /// Interframe chroma-mode tree probabilities (RFC §16.1). + /// Interframe chroma-mode tree probabilities (§16.1). + pub uv_mode_probs: [u8; 3], + /// Segment feature state (RFC §10), zeroed at each key frame. + /// Segment feature state (§10), zeroed at each key frame. + pub segmentation: SegmentationState, + /// Per-MB loop-filter deltas (RFC §9.4), zeroed at each key frame. + /// Reference-frame-based loop-filter deltas (§9.4; intra, last, + /// golden, altref order). + pub ref_lf_delta: [i32; 4], + /// Mode-based loop-filter deltas (§9.4; B_PRED, ZEROMV, MV, + /// SPLITMV order). + pub mode_lf_delta: [i32; 4], +} + +impl Default for PersistedState { + fn default() -> Self { + Self { + coeff_probs: DEFAULT_COEFF_PROBS, + mv_probs: DEFAULT_MV_PROBS, + ymode_probs: [145, 156, 163, 128], + uv_mode_probs: [142, 114, 183], + segmentation: SegmentationState::default(), + ref_lf_delta: [0; 4], + mode_lf_delta: [0; 4], + } + } +} + +/// Segment feature state (RFC 6386 §10). `quant_idx`/`lf_level` hold the +/// raw transmitted values; they are absolute in absolute mode and deltas +/// in delta mode. +#[derive(Debug, Clone, Default)] +pub struct SegmentationState { + /// Segment features active for the current frame. + pub enabled: bool, + /// The per-MB segment map is re-coded this frame. + pub update_map: bool, + /// Segment feature values are re-coded this frame. + pub update_data: bool, + /// 0 = absolute values, 1 = deltas against the frame baseline. + /// 0 = absolute values, 1 = deltas against the frame baseline. + pub abs_delta: bool, + /// Per-segment quantizer value or delta (§10). + pub quant_idx: [i32; 4], + /// Per-segment loop-filter level or delta (§10). + pub lf_level: [i32; 4], + /// Segment-map decoding tree probabilities (default 255). + /// Segment-map tree probabilities (default 255; §9.3 item 5). + pub tree_probs: [u8; 3], +} + +/// Frame-level fields parsed from the uncompressed chunk and the first +/// data partition. Everything the per-macroblock decode needs. +#[derive(Debug, Clone)] +pub struct FrameHeader { + /// Parsed 3-byte frame tag. + pub tag: FrameTag, + /// Key-frame dimensions (key frames only). + pub dims: Option, + /// Key-frame-only colour-space bit (0 = YUV; 1 is reserved). + pub color_space: u8, + /// Key-frame-only clamping bit (1 = reconstructed pixels guaranteed + /// 0..255, clamping optional). + pub clamping_type: u8, + /// Segment feature snapshot this frame decodes under. + pub segmentation: SegmentationState, + /// Loop filter type/level/sharpness (§9.4). + /// 0 = normal loop filter, 1 = simple (§9.4). + pub filter_type: u8, + /// Baseline loop filter strength 0-63 (0 disables filtering). + pub filter_level: u8, + /// Loop filter sharpness 0-7 (§9.4, §15.2). + pub sharpness_level: u8, + /// Per-MB loop-filter delta adjustment enabled for this frame. + pub lf_delta_enabled: bool, + /// This frame updated the (persisted) delta values. + pub lf_delta_update: bool, + /// log2 of the token partition count (1, 2, 4 or 8 partitions). + pub log2_partitions: u8, + /// Quantization indices (§9.6): base Y-AC index plus per-plane deltas. + pub quant: QuantIndices, + /// Probability an interframe MB is intra-coded (§9.10 `prob_intra`). + pub prob_intra: u8, + /// Probability an inter MB uses the last-frame reference. + pub prob_last: u8, + /// Probability an inter MB uses the golden rather than altref ref. + pub prob_gf: u8, + /// Whether this frame updated the interframe Y-mode probabilities. + pub ymode_probs_updated: bool, + /// Whether this frame updated the chroma-mode probabilities. + pub uv_mode_probs_updated: bool, + /// Reference-frame refresh/copies/sign-biases (§9.7-§9.8). + pub refresh: RefreshHeader, + /// mb_no_skip_coeff (§9.10/§9.11): per-MB "no non-zero coefficients" + /// flag is coded at all. + pub coeff_skip_enabled: bool, + /// Probability for the per-MB skip flag (meaningful when enabled). + pub prob_skip_false: u8, + /// Offset of the first token partition from the start of `data` + /// (i.e. uncompressed chunk + first partition). + pub token_data_offset: usize, + /// Token partition sizes in bytes; last entry is the remainder. + pub partition_sizes: Vec, +} + +/// Six dequantization indices (§9.6): the always-coded Y-AC index plus +/// signed deltas for the other five factors. +#[derive(Debug, Clone, Copy, Default)] +pub struct QuantIndices { + /// Base quantizer index for Y AC (7 bits). + pub yac_qi: u8, + /// Signed delta applied to the Y-DC dequant index (§9.6). + pub ydc_delta: i32, + /// Signed delta applied to the Y2-DC dequant index (§9.6). + pub y2dc_delta: i32, + /// Signed delta applied to the Y2-AC dequant index (§9.6). + pub y2ac_delta: i32, + /// Signed delta applied to the chroma-DC dequant index (§9.6). + pub uvdc_delta: i32, + /// Signed delta applied to the chroma-AC dequant index (§9.6). + pub uvac_delta: i32, +} + +/// Reference-frame refresh state for one frame (§9.7-§9.8). Key frames +/// refresh every reference and read only `refresh_entropy`. +#[derive(Debug, Clone, Copy)] +pub struct RefreshHeader { + /// The golden buffer is refreshed with the current frame. + pub refresh_gf: bool, + /// The altref buffer is refreshed with the current frame. + pub refresh_arf: bool, + /// 0 = none, 1 = copy last, 2 = copy altref (to golden). + pub copy_gf: u8, + /// 0 = none, 1 = copy last, 2 = copy golden (to altref). + pub copy_arf: u8, + /// Sign bias applied to MVs referencing the golden frame (§9.7). + pub sign_bias_golden: bool, + /// Sign bias applied to MVs referencing the altref frame (§9.7). + pub sign_bias_altref: bool, + /// Whether this frame's entropy updates persist to the next frame. + pub refresh_entropy: bool, + /// The last-frame buffer is refreshed with the current frame. + pub refresh_last: bool, +} + +impl FrameHeader { + /// The frame's type (key or inter), from the frame tag. + pub fn frame_type(&self) -> FrameType { + self.tag.frame_type + } + + /// Parse one frame's uncompressed chunk + first partition from + /// `data`, folding entropy/segmentation/filter-delta updates into + /// `state`. Returns the header and the partition-1 slice. + /// + /// `token_data_offset` + every `partition_sizes[i]` together describe + /// the bytes after partition 1. + pub fn parse<'a>( + data: &'a [u8], + state: &mut PersistedState, + ) -> Result<(FrameHeader, &'a [u8])> { + let tag = FrameTag::parse(data)?; + let key = tag.frame_type == FrameType::Key; + let mut off = crate::frame::FRAME_TAG_SZ; + + let mut dims = None; + if key { + let kf = parse_keyframe_dims(data)?; + dims = Some(kf); + off += KEYFRAME_HEADER_SZ; + // A key frame resets every piece of persisted entropy and + // segment/filter state (dixie `decode_frame`). + *state = PersistedState::default(); + } + + let part0_end = off + tag.first_part_size as usize; + if data.len() < part0_end { + return Err(Error::corrupt(format!( + "VP8 first partition extends past end of frame \ + (need {part0_end} bytes, have {})", + data.len() + ))); + } + let mut d = BoolDecoder::new(&data[off..part0_end])?; + + // Colour space + clamping (key frames only): two literal bits; + // the colour-space bit is reserved and must be 0 (dixie reads + // both together and refuses any non-zero pair; we keep the + // (legal) clamping bit decodable and refuse only the reserved + // colour-space one). + let (color_space, clamping_type) = if key { + let cs = d.read_literal(1) as u8; + let clamp = d.read_literal(1) as u8; + if cs != 0 { + return Err(Error::unsupported( + "VP8 reserved colour-space bit", + "bit 0 of the key-frame colour-space pair was set", + )); + } + (cs, clamp) + } else { + (0, 0) + }; + + // --- segmentation (§9.3, dixie decode_segmentation_header) --- + let mut segmentation = if key { + SegmentationState::default() + } else { + state.segmentation.clone() + }; + segmentation.enabled = d.read_bool(128); + if segmentation.enabled { + segmentation.update_map = d.read_bool(128); + segmentation.update_data = d.read_bool(128); + if segmentation.update_data { + segmentation.abs_delta = d.read_bool(128); + for i in 0..4 { + segmentation.quant_idx[i] = d.read_maybe_signed(7); + } + for i in 0..4 { + segmentation.lf_level[i] = d.read_maybe_signed(6); + } + } + if segmentation.update_map { + for i in 0..3 { + segmentation.tree_probs[i] = if d.read_bool(128) { + d.read_literal(8) as u8 + } else { + 255 + }; + } + } + } else { + segmentation.update_map = false; + segmentation.update_data = false; + } + state.segmentation = segmentation.clone(); + + // --- loop filter (§9.4, dixie decode_loopfilter_header) --- + let mut ref_lf_delta = state.ref_lf_delta; + let mut mode_lf_delta = state.mode_lf_delta; + if key { + ref_lf_delta = [0; 4]; + mode_lf_delta = [0; 4]; + } + let filter_type = d.read_literal(1) as u8; + let filter_level = d.read_literal(6) as u8; + let sharpness_level = d.read_literal(3) as u8; + let lf_delta_enabled = d.read_bool(128); + let mut lf_delta_update = false; + if lf_delta_enabled && d.read_bool(128) { + lf_delta_update = true; + for i in 0..4 { + ref_lf_delta[i] = d.read_maybe_signed(6); + } + for i in 0..4 { + mode_lf_delta[i] = d.read_maybe_signed(6); + } + } + state.ref_lf_delta = ref_lf_delta; + state.mode_lf_delta = mode_lf_delta; + + // --- token partitions (§9.5) --- + let log2_partitions = d.read_literal(2) as u8; + let partitions = 1usize << log2_partitions; + let sizes_area = 3 * (partitions - 1); + if data.len() < part0_end + sizes_area { + return Err(Error::corrupt( + "VP8 token partition size table extends past end of frame", + )); + } + let mut partition_sizes = Vec::with_capacity(partitions); + let mut size_off = part0_end; + let mut remaining = (data.len() - part0_end - sizes_area) as u32; + for i in 0..partitions { + if i < partitions - 1 { + let sz = u32::from(data[size_off]) + | (u32::from(data[size_off + 1]) << 8) + | (u32::from(data[size_off + 2]) << 16); + size_off += 3; + partition_sizes.push(sz); + remaining = remaining + .checked_sub(sz) + .ok_or_else(|| Error::corrupt("VP8 token partitions exceed frame size"))?; + } else { + partition_sizes.push(remaining); + } + } + + // --- quantization indices (§9.6) --- + let mut quant = QuantIndices { + yac_qi: d.read_literal(7) as u8, + ..QuantIndices::default() + }; + quant.ydc_delta = d.read_maybe_signed(4); + quant.y2dc_delta = d.read_maybe_signed(4); + quant.y2ac_delta = d.read_maybe_signed(4); + quant.uvdc_delta = d.read_maybe_signed(4); + quant.uvac_delta = d.read_maybe_signed(4); + + // --- reference refresh (§9.7-§9.8) --- + let refresh = if key { + RefreshHeader { + refresh_gf: true, + refresh_arf: true, + copy_gf: 0, + copy_arf: 0, + sign_bias_golden: false, + sign_bias_altref: false, + refresh_entropy: d.read_bool(128), + refresh_last: true, + } + } else { + let refresh_gf = d.read_bool(128); + let refresh_arf = d.read_bool(128); + let copy_gf = if refresh_gf { + 0 + } else { + d.read_literal(2) as u8 + }; + let copy_arf = if refresh_arf { + 0 + } else { + d.read_literal(2) as u8 + }; + RefreshHeader { + refresh_gf, + refresh_arf, + copy_gf, + copy_arf, + sign_bias_golden: d.read_bool(128), + sign_bias_altref: d.read_bool(128), + refresh_entropy: d.read_bool(128), + refresh_last: d.read_bool(128), + } + }; + + // --- entropy updates (§9.9; dixie decode_entropy_header) --- + // Coefficient probability updates are read for every frame; on + // key frames the tables were reset to defaults above. + for i in 0..4 { + for j in 0..8 { + for k in 0..3 { + for l in 0..11 { + if d.read_bool(crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]) { + state.coeff_probs[i][j][k][l] = d.read_literal(8) as u8; + } + } + } + } + } + + // mb_no_skip_coeff (§9.11 / inter §9.10). + let coeff_skip_enabled = d.read_bool(128); + let prob_skip_false = if coeff_skip_enabled { + d.read_literal(8) as u8 + } else { + 128 + }; + // Interframe-only probability updates. + let mut ymode_probs_updated = false; + let mut uv_mode_probs_updated = false; + let (prob_intra, prob_last, prob_gf) = if !key { + let probs = ( + d.read_literal(8) as u8, + d.read_literal(8) as u8, + d.read_literal(8) as u8, + ); + ymode_probs_updated = d.read_bool(128); + if ymode_probs_updated { + for i in 0..4 { + state.ymode_probs[i] = d.read_literal(8) as u8; + } + } + uv_mode_probs_updated = d.read_bool(128); + if uv_mode_probs_updated { + for i in 0..3 { + state.uv_mode_probs[i] = d.read_literal(8) as u8; + } + } + probs + } else { + (145, 156, 163) + }; + for c in 0..2 { + for j in 0..MV_PROB_CNT { + if d.read_bool(MV_UPDATE_PROBS[c][j]) { + state.mv_probs[c][j] = d.read_prob7(); + } + } + } + + if d.overreads() > 0 { + return Err(Error::corrupt(format!( + "VP8 first partition over-read by {} bytes (header desync)", + d.overreads() + ))); + } + + let header = FrameHeader { + tag, + dims, + color_space, + clamping_type, + segmentation, + filter_type, + filter_level, + sharpness_level, + lf_delta_enabled, + lf_delta_update, + log2_partitions, + quant, + refresh, + prob_intra, + prob_last, + prob_gf, + ymode_probs_updated, + uv_mode_probs_updated, + coeff_skip_enabled, + prob_skip_false, + token_data_offset: part0_end, + partition_sizes, + }; + Ok((header, &data[off..part0_end])) + } +} diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs new file mode 100644 index 00000000..2d0b2295 --- /dev/null +++ b/crates/ec-vp8/src/lib.rs @@ -0,0 +1,23 @@ +//! Native VP8 (RFC 6386) decoder — the future replacement for edith's +//! runtime-dlopen'd libvpx seat. +//! +//! The crate is written from the specification ([RFC 6386]) alone; libvpx's +//! output is used only as a test oracle (sample-exactness witnesses), never +//! as code to port. Every module documents the spec section it implements. +//! +//! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386 +//! +//! # Unsafe +//! +//! This crate contains no `unsafe` code. + +#![deny(unsafe_code)] +#![warn(missing_docs)] + +pub mod bool; +pub mod frame; +pub mod header; +pub mod tables; + +pub use ec_core::{Error, Result}; +pub use header::PersistedState; diff --git a/crates/ec-vp8/src/tables.rs b/crates/ec-vp8/src/tables.rs new file mode 100644 index 00000000..1a50dfea --- /dev/null +++ b/crates/ec-vp8/src/tables.rs @@ -0,0 +1,537 @@ +//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and +//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from +//! the RFC text; do not edit by hand. The extractor asserts every +//! table's element count, so a slip cannot drop or add values. +#![allow(clippy::all)] + +/// RFC 6386 `coeff_update_probs`. +pub const COEFF_UPDATE_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255], + [250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255], + [234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255], + [234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255], + [251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255], + ], + [ + [255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], + [ + [ + [248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255], + [248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255], + [250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + [ + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + ], + ], +]; + +/// RFC 6386 `default_coeff_probs`. +pub const DEFAULT_COEFF_PROBS: [[[[u8; 11]; 3]; 8]; 4] = [ + [ + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128], + [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128], + [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128], + ], + [ + [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128], + [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128], + [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128], + ], + [ + [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128], + [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128], + [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128], + ], + [ + [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128], + [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128], + [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128], + ], + [ + [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128], + [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128], + [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128], + ], + [ + [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128], + [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128], + [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62], + [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1], + [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128], + ], + [ + [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128], + [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128], + [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128], + ], + [ + [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128], + [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128], + [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128], + ], + [ + [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128], + [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128], + [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128], + ], + [ + [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128], + [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128], + [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128], + ], + [ + [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128], + [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128], + [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128], + ], + [ + [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128], + [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128], + [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128], + ], + [ + [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128], + [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128], + [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128], + [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128], + ], + [ + [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128], + [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128], + [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128], + ], + [ + [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128], + [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128], + [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128], + ], + [ + [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128], + [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128], + [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128], + [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128], + [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128], + [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128], + [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + [ + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], + [ + [ + [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255], + [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128], + [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128], + ], + [ + [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128], + [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128], + [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128], + ], + [ + [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128], + [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128], + [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128], + ], + [ + [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128], + [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128], + [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128], + ], + [ + [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128], + [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128], + [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128], + ], + [ + [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128], + [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128], + [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128], + ], + [ + [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128], + [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128], + [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128], + ], + [ + [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128], + ], + ], +]; + +/// RFC 6386 `kf_bmode_prob`. +pub const KF_BMODE_PROB: [[[u8; 9]; 10]; 10] = [ + [ + [231, 120, 48, 89, 115, 113, 120, 152, 112], + [152, 179, 64, 126, 170, 118, 46, 70, 95], + [175, 69, 143, 80, 85, 82, 72, 155, 103], + [56, 58, 10, 171, 218, 189, 17, 13, 152], + [144, 71, 10, 38, 171, 213, 144, 34, 26], + [114, 26, 17, 163, 44, 195, 21, 10, 173], + [121, 24, 80, 195, 26, 62, 44, 64, 85], + [170, 46, 55, 19, 136, 160, 33, 206, 71], + [63, 20, 8, 114, 114, 208, 12, 9, 226], + [81, 40, 11, 96, 182, 84, 29, 16, 36], + ], + [ + [134, 183, 89, 137, 98, 101, 106, 165, 148], + [72, 187, 100, 130, 157, 111, 32, 75, 80], + [66, 102, 167, 99, 74, 62, 40, 234, 128], + [41, 53, 9, 178, 241, 141, 26, 8, 107], + [104, 79, 12, 27, 217, 255, 87, 17, 7], + [74, 43, 26, 146, 73, 166, 49, 23, 157], + [65, 38, 105, 160, 51, 52, 31, 115, 128], + [87, 68, 71, 44, 114, 51, 15, 186, 23], + [47, 41, 14, 110, 182, 183, 21, 17, 194], + [66, 45, 25, 102, 197, 189, 23, 18, 22], + ], + [ + [88, 88, 147, 150, 42, 46, 45, 196, 205], + [43, 97, 183, 117, 85, 38, 35, 179, 61], + [39, 53, 200, 87, 26, 21, 43, 232, 171], + [56, 34, 51, 104, 114, 102, 29, 93, 77], + [107, 54, 32, 26, 51, 1, 81, 43, 31], + [39, 28, 85, 171, 58, 165, 90, 98, 64], + [34, 22, 116, 206, 23, 34, 43, 166, 73], + [68, 25, 106, 22, 64, 171, 36, 225, 114], + [34, 19, 21, 102, 132, 188, 16, 76, 124], + [62, 18, 78, 95, 85, 57, 50, 48, 51], + ], + [ + [193, 101, 35, 159, 215, 111, 89, 46, 111], + [60, 148, 31, 172, 219, 228, 21, 18, 111], + [112, 113, 77, 85, 179, 255, 38, 120, 114], + [40, 42, 1, 196, 245, 209, 10, 25, 109], + [100, 80, 8, 43, 154, 1, 51, 26, 71], + [88, 43, 29, 140, 166, 213, 37, 43, 154], + [61, 63, 30, 155, 67, 45, 68, 1, 209], + [142, 78, 78, 16, 255, 128, 34, 197, 171], + [41, 40, 5, 102, 211, 183, 4, 1, 221], + [51, 50, 17, 168, 209, 192, 23, 25, 82], + ], + [ + [125, 98, 42, 88, 104, 85, 117, 175, 82], + [95, 84, 53, 89, 128, 100, 113, 101, 45], + [75, 79, 123, 47, 51, 128, 81, 171, 1], + [57, 17, 5, 71, 102, 57, 53, 41, 49], + [115, 21, 2, 10, 102, 255, 166, 23, 6], + [38, 33, 13, 121, 57, 73, 26, 1, 85], + [41, 10, 67, 138, 77, 110, 90, 47, 114], + [101, 29, 16, 10, 85, 128, 101, 196, 26], + [57, 18, 10, 102, 102, 213, 34, 20, 43], + [117, 20, 15, 36, 163, 128, 68, 1, 26], + ], + [ + [138, 31, 36, 171, 27, 166, 38, 44, 229], + [67, 87, 58, 169, 82, 115, 26, 59, 179], + [63, 59, 90, 180, 59, 166, 93, 73, 154], + [40, 40, 21, 116, 143, 209, 34, 39, 175], + [57, 46, 22, 24, 128, 1, 54, 17, 37], + [47, 15, 16, 183, 34, 223, 49, 45, 183], + [46, 17, 33, 183, 6, 98, 15, 32, 183], + [65, 32, 73, 115, 28, 128, 23, 128, 205], + [40, 3, 9, 115, 51, 192, 18, 6, 223], + [87, 37, 9, 115, 59, 77, 64, 21, 47], + ], + [ + [104, 55, 44, 218, 9, 54, 53, 130, 226], + [64, 90, 70, 205, 40, 41, 23, 26, 57], + [54, 57, 112, 184, 5, 41, 38, 166, 213], + [30, 34, 26, 133, 152, 116, 10, 32, 134], + [75, 32, 12, 51, 192, 255, 160, 43, 51], + [39, 19, 53, 221, 26, 114, 32, 73, 255], + [31, 9, 65, 234, 2, 15, 1, 118, 73], + [88, 31, 35, 67, 102, 85, 55, 186, 85], + [56, 21, 23, 111, 59, 205, 45, 37, 192], + [55, 38, 70, 124, 73, 102, 1, 34, 98], + ], + [ + [102, 61, 71, 37, 34, 53, 31, 243, 192], + [69, 60, 71, 38, 73, 119, 28, 222, 37], + [68, 45, 128, 34, 1, 47, 11, 245, 171], + [62, 17, 19, 70, 146, 85, 55, 62, 70], + [75, 15, 9, 9, 64, 255, 184, 119, 16], + [37, 43, 37, 154, 100, 163, 85, 160, 1], + [63, 9, 92, 136, 28, 64, 32, 201, 85], + [86, 6, 28, 5, 64, 255, 25, 248, 1], + [56, 8, 17, 132, 137, 255, 55, 116, 128], + [58, 15, 20, 82, 135, 57, 26, 121, 40], + ], + [ + [164, 50, 31, 137, 154, 133, 25, 35, 218], + [51, 103, 44, 131, 131, 123, 31, 6, 158], + [86, 40, 64, 135, 148, 224, 45, 183, 128], + [22, 26, 17, 131, 240, 154, 14, 1, 209], + [83, 12, 13, 54, 192, 255, 68, 47, 28], + [45, 16, 21, 91, 64, 222, 7, 1, 197], + [56, 21, 39, 155, 60, 138, 23, 102, 213], + [85, 26, 85, 85, 128, 128, 32, 146, 171], + [18, 11, 7, 63, 144, 171, 4, 4, 246], + [35, 27, 10, 146, 174, 171, 12, 26, 128], + ], + [ + [190, 80, 35, 99, 180, 80, 126, 54, 45], + [85, 126, 47, 87, 176, 51, 41, 20, 32], + [101, 75, 128, 139, 118, 146, 116, 128, 85], + [56, 41, 15, 176, 236, 85, 37, 9, 62], + [146, 36, 19, 30, 171, 255, 97, 27, 20], + [71, 30, 17, 119, 118, 255, 17, 18, 138], + [101, 38, 60, 138, 55, 70, 43, 26, 142], + [138, 45, 61, 62, 219, 1, 81, 188, 64], + [32, 41, 20, 117, 151, 142, 20, 21, 163], + [112, 19, 12, 61, 195, 128, 48, 4, 24], + ], +]; + +/// RFC 6386 `coeff_bands`. +pub const COEFF_BANDS: [u8; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7]; + +/// RFC 6386 `dc_qlookup`. +pub const DC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23, + 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, + 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, + 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, + 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130, + 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157, +]; + +/// RFC 6386 `ac_qlookup`. +pub const AC_QLOOKUP: [i16; 128] = [ + 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, + 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, + 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140, + 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205, + 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284, +]; + +/// RFC 6386 `Pcat1` (trailing 0 is the DCTextra sentinel). +pub const PCAT1: [u8; 2] = [159, 0]; + +/// RFC 6386 `Pcat2` (trailing 0 is the DCTextra sentinel). +pub const PCAT2: [u8; 3] = [165, 145, 0]; + +/// RFC 6386 `Pcat3` (trailing 0 is the DCTextra sentinel). +pub const PCAT3: [u8; 4] = [173, 148, 140, 0]; + +/// RFC 6386 `Pcat4` (trailing 0 is the DCTextra sentinel). +pub const PCAT4: [u8; 5] = [176, 155, 140, 135, 0]; + +/// RFC 6386 `Pcat5` (trailing 0 is the DCTextra sentinel). +pub const PCAT5: [u8; 6] = [180, 157, 141, 134, 130, 0]; + +/// RFC 6386 `Pcat6` (trailing 0 is the DCTextra sentinel). +pub const PCAT6: [u8; 12] = [254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0]; + +/// RFC 6386 `k_default_mv_probs`. +pub const DEFAULT_MV_PROBS: [[u8; 19]; 2] = [ + [ + 162, 128, 225, 146, 172, 147, 214, 39, 156, 128, 129, 132, 75, 145, 178, 206, 239, 254, 254, + ], + [ + 164, 128, 204, 170, 119, 235, 140, 230, 228, 128, 130, 130, 74, 148, 180, 203, 236, 254, + 254, + ], +]; + +/// RFC 6386 `k_mv_entropy_update_probs`. +pub const MV_UPDATE_PROBS: [[u8; 19]; 2] = [ + [ + 237, 246, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 250, 250, 252, 254, + 254, + ], + [ + 231, 243, 245, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 251, 251, 254, 254, + 254, + ], +]; diff --git a/crates/ec-vp8/tests/header_parse.rs b/crates/ec-vp8/tests/header_parse.rs new file mode 100644 index 00000000..ffd8fb31 --- /dev/null +++ b/crates/ec-vp8/tests/header_parse.rs @@ -0,0 +1,138 @@ +//! M1 witness: the header parser handles real libvpx-produced key frames +//! (and a VP8-in-WebP still) with no desync and the right dimensions. + +mod ivf; + +use ec_vp8::PersistedState; +use ec_vp8::frame::{FrameTag, FrameType, mb_geometry, parse_keyframe_dims}; +use ec_vp8::header::FrameHeader; + +const FIXTURES: &[(&str, u16, u16)] = &[ + ("kf-160x96-q20.ivf", 160, 96), + ("kf-160x96-q40.ivf", 160, 96), + ("kf-76x52-q30.ivf", 76, 52), + ("kf-32x16-q35.ivf", 32, 16), + ("kf-172x144-q25.ivf", 172, 144), + ("kf-96x80-q63.ivf", 96, 80), + ("mparts-160x96.ivf", 160, 96), +]; + +#[test] +fn parses_real_key_frame_headers() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + for (name, width, height) in FIXTURES { + let bytes = std::fs::read(dir.join(name)).unwrap(); + let (fourcc, w, h, frames) = ivf::parse_ivf(&bytes); + assert_eq!(fourcc, "VP80", "{name}"); + assert_eq!((w, h), (*width, *height), "{name} IVF dimensions"); + assert!(!frames.is_empty(), "{name} has no frames"); + + let first = &frames[0].data; + let tag = FrameTag::parse(first).unwrap(); + assert_eq!(tag.frame_type, FrameType::Key, "{name} first frame"); + assert!(tag.show_frame, "{name} first frame must be shown"); + assert_eq!(tag.version, 0, "{name}: default profile"); + let kf = parse_keyframe_dims(first).unwrap(); + assert_eq!((kf.width, kf.height), (*width, *height)); + assert_eq!((kf.h_scale, kf.v_scale), (0, 0), "{name} unscaled"); + + let mut state = PersistedState::default(); + let (header, part0) = FrameHeader::parse(first, &mut state).unwrap(); + assert_eq!(part0.len(), tag.first_part_size as usize); + assert!(header.dims.is_some()); + assert_eq!(header.color_space, 0, "{name}: YUV colour space"); + assert_eq!( + header.partition_sizes.len(), + 1usize << header.log2_partitions, + "{name} partition count vs log2 field" + ); + let n_parts = header.partition_sizes.len(); + assert_eq!( + header.token_data_offset + + 3 * (n_parts - 1) + + header.partition_sizes.iter().sum::() as usize, + first.len(), + "{name}: partition sizes must tile the frame exactly" + ); + // The header partition must decode without reading past its end. + assert!( + header.quant.yac_qi <= 127, + "{name}: qindex sanity {}", + header.quant.yac_qi + ); + let (mb_cols, mb_rows) = mb_geometry(kf.width, kf.height); + assert_eq!( + (mb_cols, mb_rows), + ( + (usize::from(*width) + 15) / 16, + (usize::from(*height) + 15) / 16 + ) + ); + } +} + +#[test] +fn parses_multi_partition_header() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("mparts-160x96.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut state = PersistedState::default(); + let (header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap(); + // vpxenc was asked for --token-parts=3 => 8 token partitions. + assert_eq!(header.log2_partitions, 3, "8 token partitions expected"); + assert_eq!(header.partition_sizes.len(), 8); + assert!(header.partition_sizes.iter().all(|&s| s > 0)); +} + +#[test] +fn parses_vp8_in_webp_still() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let Ok(bytes) = std::fs::read(dir.join("still.webp")) else { + panic!("still.webp missing (libwebp encoder unavailable at generation time)"); + }; + let vp8 = ivf::webp_vp8_chunk(&bytes); + let tag = FrameTag::parse(&vp8).unwrap(); + assert_eq!(tag.frame_type, FrameType::Key); + let kf = parse_keyframe_dims(&vp8).unwrap(); + assert_eq!((kf.width, kf.height), (96, 80)); + let mut state = PersistedState::default(); + let (header, _) = FrameHeader::parse(&vp8, &mut state).unwrap(); + assert!(header.dims.is_some()); +} + +#[test] +fn gop_key_frame_parses_and_coexists_with_inter() { + let Some(dir) = ivf::fixture_dir() else { + panic!("fixtures missing; run scripts/gen_vp8_fixtures.sh"); + }; + let bytes = std::fs::read(dir.join("gop-160x96.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + assert!(frames.len() >= 30); + + let mut state = PersistedState::default(); + let (kf_header, _) = FrameHeader::parse(&frames[0].data, &mut state).unwrap(); + assert_eq!(kf_header.frame_type(), FrameType::Key); + assert!(kf_header.refresh.refresh_last && kf_header.refresh.refresh_gf); + + // First inter frame: header fields come from the same first partition, + // and the persisted entropy state has absorbed the key frame's updates. + let mut inter_seen = false; + for f in &frames[1..] { + let tag = FrameTag::parse(&f.data).unwrap(); + if tag.frame_type == FrameType::Key { + continue; + } + let (header, _) = FrameHeader::parse(&f.data, &mut state).unwrap(); + assert_eq!(header.frame_type(), FrameType::Inter); + assert!(header.dims.is_none(), "inter frames carry no dimensions"); + inter_seen = true; + break; + } + assert!(inter_seen, "gop fixture has no inter frame"); +} diff --git a/crates/ec-vp8/tests/ivf.rs b/crates/ec-vp8/tests/ivf.rs new file mode 100644 index 00000000..324242d1 --- /dev/null +++ b/crates/ec-vp8/tests/ivf.rs @@ -0,0 +1,74 @@ +//! Minimal IVF demuxing for the ec-vp8 test fixtures (RFC's companion +//! container; only what the witnesses need). + +/// One IVF frame: (pts, payload). +pub struct IvfFrame { + /// Presentation timestamp from the IVF frame header. + #[allow(dead_code)] + pub pts: u64, + /// The compressed VP8 frame payload. + pub data: Vec, +} + +/// Parse an IVF file into (fourcc, width, height, frames). +pub fn parse_ivf(bytes: &[u8]) -> (&str, u16, u16, Vec) { + assert_eq!(&bytes[0..4], b"DKIF", "not an IVF file"); + let hdr_len = u16::from_le_bytes([bytes[6], bytes[7]]) as usize; + let fourcc = std::str::from_utf8(&bytes[8..12]).unwrap(); + let width = u16::from_le_bytes([bytes[12], bytes[13]]); + let height = u16::from_le_bytes([bytes[14], bytes[15]]); + let mut pos = hdr_len; + let mut frames = Vec::new(); + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]]) + as usize; + let pts = u64::from_le_bytes([ + bytes[pos + 4], + bytes[pos + 5], + bytes[pos + 6], + bytes[pos + 7], + bytes[pos + 8], + bytes[pos + 9], + bytes[pos + 10], + bytes[pos + 11], + ]); + pos += 12; + if pos + sz > bytes.len() { + break; + } + frames.push(IvfFrame { + pts, + data: bytes[pos..pos + sz].to_vec(), + }); + pos += sz; + } + (fourcc, width, height, frames) +} + +/// Extract the VP8 payload from a lossy WebP file (RIFF/WEBP with a VP8 +/// chunk) — the same VP8 key-frame bytes in a different container. +pub fn webp_vp8_chunk(bytes: &[u8]) -> Vec { + assert_eq!(&bytes[0..4], b"RIFF"); + assert_eq!(&bytes[8..12], b"WEBP"); + let mut pos = 12; + while pos + 8 <= bytes.len() { + let tag = &bytes[pos..pos + 4]; + let sz = u32::from_le_bytes([ + bytes[pos + 4], + bytes[pos + 5], + bytes[pos + 6], + bytes[pos + 7], + ]) as usize; + if tag == b"VP8 " { + return bytes[pos + 8..pos + 8 + sz].to_vec(); + } + pos += 8 + sz + (sz & 1); // chunks are word-aligned + } + panic!("no VP8 chunk in webp"); +} + +/// Root of the workspace checkout this test runs in (crates/ec-vp8/../..). +pub fn fixture_dir() -> Option { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/vp8"); + if dir.is_dir() { Some(dir) } else { None } +} diff --git a/scripts/extract_vp8_tables.py b/scripts/extract_vp8_tables.py new file mode 100755 index 00000000..61ca1950 --- /dev/null +++ b/scripts/extract_vp8_tables.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Extract the fixed probability/quant tables from the local RFC 6386 text +into a Rust module (crates/ec-vp8/src/tables.rs). + +The tables are transcribed VERBATIM from the RFC text; the script asserts +each table's element count so a parsing slip cannot produce a silently +wrong table. Run from the worktree root: + + python3 scripts/extract_vp8_tables.py [rfc.txt] [out.rs] +""" + +import re +import sys + +RFC = sys.argv[1] if len(sys.argv) > 1 else "/home/user/.cache/vp8/rfc6386.txt" +OUT = sys.argv[2] if len(sys.argv) > 2 else "crates/ec-vp8/src/tables.rs" + +text = open(RFC, encoding="utf-8").read() +# Strip RFC page furniture (running headers/footers land mid-table). +text = "\n".join( + l for l in text.splitlines() + if not re.search(r"RFC 6386\s+VP8 Data Format.*2011$", l) + and not re.search(r"Bankoski, et al\..*\[Page \d+\]$", l) +) +text = text.replace("\f", "") + +INT_RE = re.compile(r"-?\d+") + + +def collect(name: str, expect: int) -> list[int]: + """Find `name`'s C array DEFINITION -- '=' reachable from the name + through nothing but brackets, identifiers, spaces and hyphens (the + section-13.4 pseudocode mentions `coeff_update_probs [i] [j] [k] [t]))` + and must not match) -- and collect every integer between '=' and the + terminating '};'.""" + for m in re.finditer(rf"\b{re.escape(name)}\b[\[\]\w\s-]*?=", text): + body = text[m.end() : m.end() + 60000] + end = body.find("};") + assert end != -1, f"{name}: no terminator" + vals = [int(v) for v in INT_RE.findall(body[:end])] + if len(vals) != expect: + raise SystemExit( + f"{name}: expected {expect} ints, got {len(vals)}: {vals[:10]}..." + ) + return vals + raise SystemExit(f"{name}: definition not found") + + +# (rust name, RFC name, expected ints incl. Pcat sentinels, dims, type) +TABLES = [ + ("COEFF_UPDATE_PROBS", "coeff_update_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"), + ("DEFAULT_COEFF_PROBS", "default_coeff_probs", 4 * 8 * 3 * 11, (4, 8, 3, 11), "u8"), + ("KF_BMODE_PROB", "kf_bmode_prob", 10 * 10 * 9, (10, 10, 9), "u8"), + ("COEFF_BANDS", "coeff_bands", 16, (16,), "u8"), + ("DC_QLOOKUP", "dc_qlookup", 128, (128,), "i16"), + ("AC_QLOOKUP", "ac_qlookup", 128, (128,), "i16"), + ("PCAT1", "Pcat1", 2, (2,), "u8"), + ("PCAT2", "Pcat2", 3, (3,), "u8"), + ("PCAT3", "Pcat3", 4, (4,), "u8"), + ("PCAT4", "Pcat4", 5, (5,), "u8"), + ("PCAT5", "Pcat5", 6, (6,), "u8"), + ("PCAT6", "Pcat6", 12, (12,), "u8"), + ("DEFAULT_MV_PROBS", "k_default_mv_probs", 2 * 19, (2, 19), "u8"), + ("MV_UPDATE_PROBS", "k_mv_entropy_update_probs", 2 * 19, (2, 19), "u8"), +] + + +def rust_ty(ty: str, dims: tuple[int, ...]) -> str: + t = ty + for d in reversed(dims): + t = f"[{t}; {d}]" + return t + + +def nest(vals: list[int], dims: tuple[int, ...]) -> str: + if len(dims) == 1: + return "[" + ", ".join(str(v) for v in vals) + "]" + step = len(vals) // dims[0] + parts = [ + nest(vals[i * step : (i + 1) * step], dims[1:]) for i in range(dims[0]) + ] + if len(dims) == 2: + return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]" + return "[\n" + ",\n".join(" " + p for p in parts) + "\n ]" + + +out = [ + "//! Fixed tables transcribed from RFC 6386 (VP8 Data Format and", + "//! Decoding Guide). GENERATED by `scripts/extract_vp8_tables.py` from", + "//! the RFC text; do not edit by hand. The extractor asserts every", + "//! table's element count, so a slip cannot drop or add values.", + "#![allow(clippy::all)]", + "", +] +for rust_name, rfc_name, expect, dims, ty in TABLES: + vals = collect(rfc_name, expect) + note = " (trailing 0 is the DCTextra sentinel)" if rfc_name.startswith("Pcat") else "" + out.append(f"/// RFC 6386 `{rfc_name}`{note}.") + out.append(f"pub const {rust_name}: {rust_ty(ty, dims)} = {nest(vals, dims)};\n") + +open(OUT, "w", encoding="utf-8").write("\n".join(out)) +print(f"wrote {OUT}") diff --git a/scripts/gen_vp8_fixtures.sh b/scripts/gen_vp8_fixtures.sh new file mode 100755 index 00000000..eaee5bb5 --- /dev/null +++ b/scripts/gen_vp8_fixtures.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +# Generate the ec-vp8 test fixtures (gitignored, like the rest of the +# workspace's fixtures/). Every vector is libvpx-encoded via ffmpeg; the +# decoder's witnesses compare its raw YUV output against ffmpeg's. +# +# Usage: scripts/gen_vp8_fixtures.sh [worktree-root] +set -euo pipefail +ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}" +OUT="$ROOT/fixtures/vp8" +mkdir -p "$OUT" + +enc() { # name size frames q extra-source-args... + local name=$1 size=$2 frames=$3 q=$4 + shift 4 + ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i "$@" \ + -frames:v "$frames" -c:v libvpx -qmin "$q" -qmax "$q" -crf "$q" \ + -auto-alt-ref 0 -cpu-used 1 -g "$frames" \ + "$OUT/$name.ivf" + echo "wrote $OUT/$name.ivf" +} + +# Key-frame vectors (M2): several sizes incl. non-multiple-of-16, several q. +enc kf-160x96-q20 160x96 4 20 testsrc2=size=160x96:rate=30 +enc kf-160x96-q40 160x96 4 40 testsrc2=size=160x96:rate=30 +enc kf-76x52-q30 76x52 4 30 testsrc2=size=76x52:rate=30 +enc kf-32x16-q35 32x16 4 35 testsrc2=size=32x16:rate=30 +enc kf-172x144-q25 172x144 4 25 testsrc2=size=172x144:rate=30 +enc kf-96x80-q63 96x80 4 63 testsrc2=size=96x80:rate=30 + +# Multi-frame GOP (M3): keyframe + interframes, golden/altref in play. +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 \ + -frames:v 60 -c:v libvpx -qmin 30 -qmax 45 -crf 38 \ + -auto-alt-ref 0 -g 15 -keyint_min 15 -cpu-used 1 -lag-in-frames 0 \ + "$OUT/gop-160x96.ivf" +echo "wrote $OUT/gop-160x96.ivf" + +# Larger short GOP with the simple loop filter via profile (version 1)? +# libvpx picks profile 0 normally; the version field is exercised through +# -profile:v 1 (simple filter, bilinear reconstruction). +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=96x80:rate=30 \ + -frames:v 12 -c:v libvpx -qmin 30 -qmax 30 -crf 30 -auto-alt-ref 0 -g 6 \ + -profile:v 1 -cpu-used 1 -lag-in-frames 0 \ + "$OUT/gop-96x80-v1.ivf" 2>/dev/null || \ + echo "SKIP gop-96x80-v1 (profile 1 unsupported by this libvpx build)" + +# Multi-partition token partitions (M3): ffmpeg's libvpx wrapper has no +# token-part option, so this one vector comes from a locally built vpxenc +# (checked out at ~/.cache/vp8/libvpx-src; `./configure && make -j`). +VPXENC="$HOME/.cache/vp8/libvpx-src/vpxenc" +if [ -x "$VPXENC" ]; then + ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=160x96:rate=30 -frames:v 30 \ + -pix_fmt yuv420p -f rawvideo /tmp/ecvp8-mparts.raw + { printf 'YUV4MPEG2 W160 H96 F30:1 Ip A1:1 C420jpeg\n' + python3 - <<'PYEOF' +raw = open("/tmp/ecvp8-mparts.raw", "rb").read() +frame = 160 * 96 * 3 // 2 +for i in range(len(raw) // frame): + open("/dev/stdout", "wb").write(b"FRAME\n" + raw[i*frame:(i+1)*frame]) +PYEOF + } | "$VPXENC" --codec=vp8 -w 160 -h 96 --token-parts=3 --limit=30 \ + --ivf --cpu-used=1 --end-usage=q --cq-level=32 --min-q=30 --max-q=45 \ + --kf-max-dist=10 -o "$OUT/mparts-160x96.ivf" - 2>/dev/null + echo "wrote $OUT/mparts-160x96.ivf" +else + echo "SKIP mparts (build libvpx at ~/.cache/vp8/libvpx-src for vpxenc)" +fi + +# VP8-in-WebP still (same key-frame payload in a RIFF container). +ffmpeg -hide_banner -loglevel error -y \ + -f lavfi -i testsrc2=size=96x80:rate=30 -frames:v 1 \ + "$OUT/still.png" +if ffmpeg -hide_banner -loglevel error -y -i "$OUT/still.png" -q:v 60 "$OUT/still.webp" 2>/dev/null; then + echo "wrote $OUT/still.webp" +else + echo "SKIP still.webp (libwebp support missing)" + rm -f "$OUT/still.png" +fi + +ls -la "$OUT"