From d9a9866f50ac29ead3ce1b26025d7fa0e0e23d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 16:36:52 +0300 Subject: [PATCH] ec-vp8: two partition-0 desync bugs fixed (M2 debugging state) BUG 1 (found by decision-trace diff vs a python dixie model): the MV probability update loop ran on KEY frames - dixie/libvpx parse it only for interframes. On key frames the 38 extra bool reads desynced the whole partition-0 parse. Moved inside the !is_keyframe branch. BUG 2: decode_keyframe created a FRESH bool decoder over partition 0 for the per-MB mode records - re-reading the partition from its start. FrameHeader::parse now returns its partition-0 decoder so the mode records CONTINUE from where the header stopped (dixie decode_frame shares one decoder). Result: single-MB 16x16 black q0 fixture now decodes BYTE-EXACT vs ffmpeg (chroma and luma). Multi-MB fixtures still diverge: decision traces (python dixie model scripts side /tmp/vp8ref.py vs EC_VP8_TRACE) match to decision 2562 and split at 2563 inside the token walk of MB(0,1) block 0 (ref consults prob 11, rust prob 4 at the same stream position) - a coefficient-context/bookkeeping difference in the multi-MB token pass that is now precisely localized for the next session. Debug tooling retained: EC_VP8_TRACE decision trace, EC_VP8_DEBUG per-MB coeff dump, examples/dbg_first.rs. --- crates/ec-vp8/examples/dbg_first.rs | 38 ++++------------------------- crates/ec-vp8/src/decode.rs | 22 ++++++++++++----- crates/ec-vp8/src/header.rs | 28 ++++++++++++++------- crates/ec-vp8/src/modes.rs | 14 +++++++++++ crates/ec-vp8/tests/header_parse.rs | 4 +-- 5 files changed, 56 insertions(+), 50 deletions(-) diff --git a/crates/ec-vp8/examples/dbg_first.rs b/crates/ec-vp8/examples/dbg_first.rs index 45048f1d..36e27020 100644 --- a/crates/ec-vp8/examples/dbg_first.rs +++ b/crates/ec-vp8/examples/dbg_first.rs @@ -1,46 +1,18 @@ -// Decode one frame: print header/dequant summary + pixel stats. +// Decode frame 0 of an IVF with decision tracing (EC_VP8_TRACE=1). use ec_vp8::decode::Decoder; -use ec_vp8::transform; -use ec_vp8::{PersistedState, frame, header::FrameHeader}; fn main() { let path = std::env::args().nth(1).expect("ivf path"); let bytes = std::fs::read(path).unwrap(); let sz = u32::from_le_bytes([bytes[32], bytes[33], bytes[34], bytes[35]]) as usize; let frame = &bytes[44..44 + sz]; - let mut st = PersistedState::default(); - let (h, _) = FrameHeader::parse(frame, &mut st).unwrap(); - println!( - "q={} y2dc_d={} y2ac_d={} skip={} lvl={}", - h.quant.yac_qi, - h.quant.y2dc_delta, - h.quant.y2ac_delta, - h.coeff_skip_enabled, - h.filter_level - ); - let dq = transform::dequant( - i32::from(h.quant.yac_qi), - h.quant.ydc_delta, - h.quant.y2dc_delta, - h.quant.y2ac_delta, - h.quant.uvdc_delta, - h.quant.uvac_delta, - ); - println!( - "y1dc={} y1ac={} y2dc={} y2ac={}", - dq.y1_dc, dq.y1_ac, dq.y2_dc, dq.y2_ac - ); let mut dec = Decoder::new(); match dec.decode(frame) { Ok(Some(pic)) => println!( - "{}x{} y[0..8]={:?} min={} max={}", - pic.width, - pic.height, - &pic.y[..8], - pic.y.iter().min().unwrap(), - pic.y.iter().max().unwrap() + "OUT {}x{} y[0..8]={:?}", + pic.width, pic.height, &pic.y[..8] ), - Ok(None) => println!("hidden"), - Err(e) => println!("ERR {e}"), + Ok(None) => println!("OUT hidden"), + Err(e) => println!("OUT ERR {e}"), } } diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs index be914741..c6b098fd 100644 --- a/crates/ec-vp8/src/decode.rs +++ b/crates/ec-vp8/src/decode.rs @@ -119,7 +119,9 @@ pub struct Picture { pub u: Vec, /// V (Cr) plane, half resolution. pub v: Vec, + /// Frame width in pixels. pub width: u16, + /// Frame height in pixels. pub height: u16, /// Luma row pitch of the returned planes. pub stride: usize, @@ -167,9 +169,9 @@ impl Decoder { /// Decode one frame; returns the picture when it is for display /// (`show_frame`). Hidden frames still update the decode state. pub fn decode(&mut self, frame: &[u8]) -> Result> { - let (header, _part0) = FrameHeader::parse(frame, &mut self.state)?; + let (header, hdr_dec) = FrameHeader::parse(frame, &mut self.state)?; match header.tag.frame_type { - FrameType::Key => self.decode_keyframe(frame, header), + FrameType::Key => self.decode_keyframe(frame, header, hdr_dec), FrameType::Inter => Err(Error::unsupported( "VP8 inter frame", "inter-frame decoding is the next milestone of this crate", @@ -209,7 +211,12 @@ impl Decoder { &mut self.mb_info[row * w + col] } - fn decode_keyframe(&mut self, frame: &[u8], header: FrameHeader) -> Result> { + fn decode_keyframe( + &mut self, + frame: &[u8], + header: FrameHeader, + mut hdr_dec: BoolDecoder<'_>, + ) -> Result> { let kf = header.dims.expect("key frame header carries dimensions"); self.ensure_buffers(kf); @@ -255,9 +262,6 @@ impl Decoder { ); } - let hdr_start = crate::frame::FRAME_TAG_SZ + crate::frame::KEYFRAME_HEADER_SZ; - let mut hdr_dec = BoolDecoder::new(&frame[hdr_start..header.token_data_offset])?; - self.token_ctxs.reset_above_row(); for row in 1..=self.mb_rows { @@ -280,6 +284,9 @@ impl Decoder { // `r` (0-based) reads partition `r % n` like the reference. let part = (row - 1) % partitions.len(); for col in 1..=self.mb_cols { + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("M {} {}", row - 1, col - 1); + } let mb = self.mbi(row, col).clone(); let has_y2 = mb.has_y2(); let seg_i = usize::from(header.segmentation.enabled) * usize::from(mb.segment_id); @@ -292,6 +299,9 @@ impl Decoder { y2_dc: dq.y2_dc, y2_ac: dq.y2_ac, }; + if std::env::var_os("EC_VP8_TRACE").is_some() { + eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2); + } let probs = self.state.coeff_probs; let coeffs = if mb.skip { tokens::skip_mb_tokens(&mut self.token_ctxs, col - 1, has_y2) diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs index 097d6200..8d5930dc 100644 --- a/crates/ec-vp8/src/header.rs +++ b/crates/ec-vp8/src/header.rs @@ -192,7 +192,7 @@ impl FrameHeader { pub fn parse<'a>( data: &'a [u8], state: &mut PersistedState, - ) -> Result<(FrameHeader, &'a [u8])> { + ) -> Result<(FrameHeader, BoolDecoder<'a>)> { let tag = FrameTag::parse(data)?; let key = tag.frame_type == FrameType::Key; let mut off = crate::frame::FRAME_TAG_SZ; @@ -372,10 +372,16 @@ impl FrameHeader { // --- 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. + let trace = std::env::var_os("EC_VP8_TRACE").is_some(); + let mut idx = 0; for i in 0..4 { for j in 0..8 { for k in 0..3 { for l in 0..11 { + if trace { + eprintln!("IDX {idx} flag={}", crate::tables::COEFF_UPDATE_PROBS[i][j][k][l]); + } + idx += 1; 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; } @@ -412,17 +418,18 @@ impl FrameHeader { state.uv_mode_probs[i] = d.read_literal(8) as u8; } } + // MV probability updates: P(7) form, x ? x << 1 : 1 (§17.2). + for c in 0..2 { + for j in 0..MV_PROB_CNT { + if d.read_bool(MV_UPDATE_PROBS[c][j]) { + state.mv_probs[c][j] = d.read_prob7(); + } + } + } probs } else { (112, 86, 140) // placeholders; only read on inter frames }; - 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(); - } - } - } // The reference decoder zero-fills past the end of a partition; // tiny partitions (e.g. one-MB key frames) can legitimately @@ -458,6 +465,9 @@ impl FrameHeader { token_data_offset: part0_end, partition_sizes, }; - Ok((header, &data[off..part0_end])) + let _ = off; + // The partition-0 decoder is returned mid-stream: the per-MB + // mode records continue from exactly where the header stopped. + Ok((header, d)) } } diff --git a/crates/ec-vp8/src/modes.rs b/crates/ec-vp8/src/modes.rs index a0a2a4b0..b799e265 100644 --- a/crates/ec-vp8/src/modes.rs +++ b/crates/ec-vp8/src/modes.rs @@ -181,17 +181,27 @@ pub enum MvRef { } /// mv_ref coding tree (RFC 6386 §16.2): leaves are [`MvRef`] integers. +/// mv_ref coding tree (RFC 6386 §16.2); leaves are [`MvRef`] integers. pub const MV_REF_TREE: [i8; 8] = [0, 2, -1, 4, -2, 6, -3, -4]; /// Motion-vector component: row then column, each with the 19-probability /// table (§17.1). +/// Probability-table offsets of one MV component (RFC 6386 §17.1). pub const MVP_IS_SHORT: usize = 0; +/// Sign probability offset (§17.1). pub const MVP_SIGN: usize = 1; +/// Short-value tree offset (§17.1). +/// Short-value tree offset (§17.1). pub const MVP_SHORT: usize = 2; +/// Long-value bit probabilities offset (§17.1). +/// Long-value bit probabilities offset (§17.1). pub const MVP_BITS: usize = MVP_SHORT + 7; +/// Total probabilities per MV component (§17.1). +/// Total probabilities per MV component (§17.1). pub const MVP_COUNT: usize = MVP_BITS + 10; /// Small-value coding tree for MV components (§17.1 `small_mvtree`). +/// Small-value coding tree for MV components (§17.1). pub const SMALL_MV_TREE: [i8; 14] = [ 2, 8, // "0" / "1" subtrees 4, 6, // "00" / "01" @@ -206,6 +216,7 @@ pub const SMALL_MV_TREE: [i8; 14] = [ /// RFC's `MVpartition` integers: 0 = top/bottom, 1 = left/right, /// 2 = quarters, 3 = MV_16. pub const MV_PARTITION_TREE: [i8; 6] = [-3, 2, -2, 4, 0, -1]; +/// SPLITMV partition tree fixed probabilities (§16.4). pub const MV_PARTITION_PROBS: [u8; 3] = [110, 111, 150]; /// The four SPLITMV partitionings as subblock groups (§16.4), indexed @@ -240,6 +251,8 @@ pub enum SubMvRef { New4x4 = 3, } +/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers. +/// Sub-MV coding tree (RFC 6386 §16.4); leaves are [`SubMvRef`] integers. pub const SUB_MV_REF_TREE: [i8; 6] = [0, 2, -1, 4, -2, -3]; /// Context-conditioned sub-MV probabilities (§16.4 `sub_mv_ref_prob`). @@ -253,6 +266,7 @@ pub const SUB_MV_REF_PROBS: [[u8; 3]; 5] = [ /// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, /// 3 = left==above, 2 = above zero, 1 = left zero, 0 = normal. +/// Sub-MV tree context (§16.4 `vp8_mvCont`): 4 = left==above==zero, pub fn mv_cont(l: (i16, i16), a: (i16, i16)) -> usize { let lez = l == (0, 0); let aez = a == (0, 0); diff --git a/crates/ec-vp8/tests/header_parse.rs b/crates/ec-vp8/tests/header_parse.rs index ffd8fb31..37cc3aca 100644 --- a/crates/ec-vp8/tests/header_parse.rs +++ b/crates/ec-vp8/tests/header_parse.rs @@ -39,8 +39,8 @@ fn parses_real_key_frame_headers() { 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); + let (header, _) = FrameHeader::parse(first, &mut state).unwrap(); + assert_eq!(header.token_data_offset - 10, tag.first_part_size as usize); assert!(header.dims.is_some()); assert_eq!(header.color_space, 0, "{name}: YUV colour space"); assert_eq!(