From dd7b5a6ce9d12bd105b03b33d403cceca78fba32 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 17:04:43 +0300 Subject: [PATCH] =?UTF-8?q?ec-vp8:=20fix=20M2=20token=20walk=20=E2=80=94?= =?UTF-8?q?=20ONE=20path=20missed=20sign/EOB;=20frame-0=20byte-exact=20on?= =?UTF-8?q?=20all=20kf=20fixtures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit get_coeffs' ONE-token path (p[2] branch) had the sign read, coefficient write, and EOB-after-nonzero check nested inside the magnitude branch only. The reference walk (libvpx detokenize.c GetCoeffs / RFC 6386 section 13.2) shares that tail between the ONE and magnitude paths. A ONE token therefore skipped the sign read and EOB check and re-entered the walk at the ZERO node — read counts stayed in lockstep (so stream positions matched) while the decoded stream diverged from the first ONE token, which is why the lossless single-MB fixture passed and busy fixtures split ~28 reads into block 0. Evidence: - EC_VP8_TRACE G-lines (n, band, ctx, prob, bit) vs scripts/vp8ref_model.py on kf-160x96-q20.ivf: 19131 decisions, 0 diffs (model also fixed: persistent per-partition decoders, G tracing with consulted prob + decoded bit). - examples/dump_frame frame 0 vs 'ffmpeg -frames:v 1': byte-exact on all 7 kf fixtures + mparts-160x96 kf0. - cargo test -p ec-vp8: unit 49 + header_parse 4 + webp green; keyframe_exact 1/3 (the 2 red cases decode every frame of each fixture and complete when M3 inter frames land). --- crates/ec-vp8/examples/dump_frame.rs | 58 ++++++++++++++++ crates/ec-vp8/src/tokens.rs | 98 +++++++++++++--------------- lanes/vp8.report.md | 63 +++++++++--------- scripts/vp8ref_model.py | 77 ++++++++++++---------- 4 files changed, 175 insertions(+), 121 deletions(-) create mode 100644 crates/ec-vp8/examples/dump_frame.rs diff --git a/crates/ec-vp8/examples/dump_frame.rs b/crates/ec-vp8/examples/dump_frame.rs new file mode 100644 index 00000000..31bca7de --- /dev/null +++ b/crates/ec-vp8/examples/dump_frame.rs @@ -0,0 +1,58 @@ +//! Dump decoded frame N of an IVF as raw yuv420p (ffmpeg-comparable: +//! `ffmpeg -i in.ivf -f rawvideo -pix_fmt yuv420p -` streams the same +//! layout, frame after frame). Usage: `dump_frame +//! `. Decoding stops at the first frame the crate cannot yet +//! decode (e.g. inter frames before M3), reporting it on stderr. + +use ec_vp8::decode::Decoder; + +fn main() { + let args: Vec = std::env::args().collect(); + assert_eq!(args.len(), 4, "usage: dump_frame "); + let want: usize = args[2].parse().expect("frame index"); + let bytes = std::fs::read(&args[1]).unwrap(); + + // IVF: 32-byte file header, then (4-byte LE size, 8-byte pts, data). + let mut frames = Vec::new(); + let mut pos = 32; + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; + frames.push(&bytes[pos + 12..pos + 12 + sz]); + pos += 12 + sz; + } + + let mut dec = Decoder::new(); + for (i, f) in frames.iter().enumerate() { + match dec.decode(f) { + Ok(Some(pic)) if i == want => { + let mut out = Vec::with_capacity( + pic.y.len() + pic.u.len() + pic.v.len(), + ); + for row in 0..usize::from(pic.height) { + let s = row * pic.stride; + out.extend_from_slice(&pic.y[s..s + usize::from(pic.width)]); + } + let (cw, ch) = ( + usize::from(pic.width + 1) / 2, + usize::from(pic.height + 1) / 2, + ); + for plane in [&pic.u, &pic.v] { + for row in 0..ch { + let s = row * pic.uv_stride; + out.extend_from_slice(&plane[s..s + cw]); + } + } + std::fs::write(&args[3], out).unwrap(); + return; + } + Ok(Some(_)) => {} + Ok(None) => {} + Err(e) => { + eprintln!("frame {i}: {e}"); + std::process::exit(1); + } + } + } + eprintln!("no frame {want} decoded"); + std::process::exit(1); +} diff --git a/crates/ec-vp8/src/tokens.rs b/crates/ec-vp8/src/tokens.rs index a4178ae7..b5a0607c 100644 --- a/crates/ec-vp8/src/tokens.rs +++ b/crates/ec-vp8/src/tokens.rs @@ -147,7 +147,6 @@ impl TokenContexts { /// type; `n0` the first coded position (1 for Y blocks after a Y2). /// Returns the number of significant coefficients. Coefficients are /// written dequantized into `out` (natural order). -#[allow(unused_assignments)] // v is always read on every path that matters fn get_coeffs( bc: &mut BoolDecoder<'_>, probs_t: &[[[u8; 11]; 3]; 8], @@ -158,74 +157,68 @@ fn get_coeffs( out: &mut [i16; 16], ) -> usize { let trace = std::env::var_os("EC_VP8_TRACE").is_some(); - macro_rules! ann { - ($n:expr, $band:expr, $ctx:expr, $node:expr) => { + // One token decision: decode the bool, then — under EC_VP8_TRACE — + // print the consulted (n, band, ctx, prob) and the decoded bit so the + // stream can be diffed read-for-read against scripts/vp8ref_model.py. + macro_rules! g { + ($n:expr, $band:expr, $c:expr, $prob:expr) => {{ + let bit = bc.read_bool($prob); if trace { - eprintln!("G n={} band={} ctx={} prob={}", $n, $band, $ctx, $node); + eprintln!( + "G n={} band={} ctx={} prob={} bit={}", + $n, $band, $c, $prob, u8::from(bit) + ); } - }; + bit + }}; } let mut n = n0; let mut band = BANDS[n0]; let mut c = ctx; let mut p = &probs_t[band as usize][c]; - ann!(n, band, c, 0); - if !bc.read_bool(p[0]) { + if !g!(n, band, c, p[0]) { return 0; // immediate EOB } loop { n += 1; let mut v: i32; - ann!(n, band, c, 1); - if !bc.read_bool(p[1]) { - // DCT_0: the next decision skips the EOB branch (§13.2). + if !g!(n, band, c, p[1]) { + // DCT_0: the next decision skips the EOB branch (§13.2) and + // libvpx forces the context to 0 after a zero token. c = 0; band = BANDS[n]; p = &probs_t[band as usize][0]; } else { - ann!(n, band, c, 2); - if !bc.read_bool(p[2]) { + if !g!(n, band, c, p[2]) { c = 1; band = BANDS[n]; p = &probs_t[band as usize][1]; v = 1; } else { - ann!(n, band, c, 3); - if !bc.read_bool(p[3]) { - ann!(n, band, c, 4); - if !bc.read_bool(p[4]) { + if !g!(n, band, c, p[3]) { + if !g!(n, band, c, p[4]) { v = 2; } else { - ann!(n, band, c, 5); - v = 3 + i32::from(bc.read_bool(p[5])); + v = 3 + i32::from(g!(n, band, c, p[5])); } - let _ = v; } else { - ann!(n, band, c, 6); - if !bc.read_bool(p[6]) { - ann!(n, band, c, 7); - if !bc.read_bool(p[7]) { - ann!(n, band, c, 91); - v = 5 + i32::from(bc.read_bool(159)); + if !g!(n, band, c, p[6]) { + if !g!(n, band, c, p[7]) { + v = 5 + i32::from(g!(n, band, c, 159u8)); } else { - ann!(n, band, c, 161); - v = 7 + 2 * i32::from(bc.read_bool(165)); - ann!(n, band, c, 162); - v += i32::from(bc.read_bool(145)); + v = 7 + 2 * i32::from(g!(n, band, c, 165u8)); + v += i32::from(g!(n, band, c, 145u8)); } } else { - ann!(n, band, c, 8); - let bit1 = usize::from(bc.read_bool(p[8])); - ann!(n, band, c, 9); - let bit0 = usize::from(bc.read_bool(p[9 + bit1])); + let bit1 = usize::from(g!(n, band, c, p[8])); + let bit0 = usize::from(g!(n, band, c, p[9 + bit1])); let cat = 2 * bit1 + bit0; v = 0; - for (i, &prob) in CAT_EXTRA[cat].iter().enumerate() { + for &prob in CAT_EXTRA[cat].iter() { if prob == 0 { break; } - ann!(n, band, c, 30 + i); - v += v + i32::from(bc.read_bool(prob)); + v += v + i32::from(g!(n, band, c, prob)); } v += 3 + (8 << cat); } @@ -233,26 +226,25 @@ fn get_coeffs( c = 2; band = BANDS[n]; p = &probs_t[band as usize][2]; - - // Sign flag, then dequantize (first coded position is DC). - ann!(n, band, c, 128); - let mag = if bc.read_bool(128) { -v } else { v }; - out[ZIGZAG[n - 1]] = if n - 1 == 0 { - (mag * i32::from(dc_factor)) as i16 - } else { - (mag * i32::from(ac_factor)) as i16 - }; - if n < 16 { - ann!(n, band, c, 0); - } - if n == 16 || !bc.read_bool(p[0]) { - return n; - } } - if n == 16 { - return 16; // malformed without EOB: stop like the reference + + // Sign flag, then dequantize (first coded position is DC). + // Shared by the ONE and magnitude paths, exactly like the + // reference walk (libvpx detokenize.c GetCoeffs). + let neg = g!(n, band, c, 128u8); + let mag = if neg { -v } else { v }; + out[ZIGZAG[n - 1]] = if n - 1 == 0 { + (mag * i32::from(dc_factor)) as i16 + } else { + (mag * i32::from(ac_factor)) as i16 + }; + if n < 16 && !g!(n, band, c, p[0]) { + return n; // EOB } } + if n == 16 { + return 16; // malformed without EOB: stop like the reference + } } } diff --git a/lanes/vp8.report.md b/lanes/vp8.report.md index d00e98de..e4e07888 100644 --- a/lanes/vp8.report.md +++ b/lanes/vp8.report.md @@ -8,7 +8,7 @@ Never merged, never pushed. Pins untouched (no ec-av1 changes at all). | Milestone | State | Evidence | |---|---|---| | M1 bool decoder + frame tag + full first-partition header | **done/verified** | commit `57b5a53a`; 12 unit tests green; real vpxenc/ffmpeg streams (6 sizes/q, 8-token-partition, WebP still) parse with exact partition tiling, correct dims (incl. 76x52 non-MB-aligned), 0 desyncs | -| M2 key-frame-only decode, sample-exact vs ffmpeg | **implemented, NOT verified — 2 of 3 root-cause bugs FIXED, 1 remaining, precisely localized** | commits `20f7d742`, `072f842f`; single-MB 16x16 black fixture decodes BYTE-EXACT vs ffmpeg; multi-MB witnesses still RED (decision 2563, see below) | +| M2 key-frame-only decode, sample-exact vs ffmpeg | **root cause FIXED, verified at frame level** — decision-exact vs the reference model for the whole frame (19131 reads, 0 diffs) and frame-0 byte-exact vs ffmpeg on ALL 8 kf/mparts fixtures; the `keyframe_exact` suite goes 3/3 when inter frames land (each fixture carries 1 KF + inter frames), see M3 | commits `20f7d742`, `072f842f`, M2-fix commit (this one) | | M3 inter frames | **not attempted** (fixtures + spec recon done) | `clip-obs-320x192.ivf` (169 fr, 4 KFs), `altref-160x96.ivf`, `mparts-160x96.ivf` (8 partitions), `gop-160x96.ivf`; §16-18 read; inter trees/tables in `modes.rs` | | M4 public API + docs | **not attempted** | `Decoder::decode(&[u8]) -> Result>` exists; ec-av1-style `decode_stream` not yet | @@ -65,42 +65,39 @@ Never merged, never pushed. Pins untouched (no ec-av1 changes at all). (`token_data_offset + 3*(n-1) + sum(sizes) == frame len`), 8 partitions, inter header coexists with persisted entropy, VP8-in-WebP chunk parses. ALL PASS. -- M2: `cargo test -p ec-vp8 --test keyframe_exact` — ffmpeg byte-compare - (`ffmpeg -v error -i F -f rawvideo -pix_fmt yuv420p -`) on 6 kf fixtures - + mparts + WebP still. **FAILING — 0/3** (see below). +- M2 (this session): FULL-FRAME decision-exactness — `EC_VP8_TRACE=1` + example `dbg_first` vs `scripts/vp8ref_model.py`: 19131 token + decisions, identical `(n, band, ctx, prob, bit)` on every read, 0 + diffs (`kf-160x96-q20.ivf`). Pixel exactness: frame 0 of all 7 kf + fixtures + mparts dumped via `examples/dump_frame` and `cmp`-ed + against `ffmpeg -frames:v 1` — ALL EXACT. `cargo test -p ec-vp8`: + unit (49) + header_parse (4) + webp witness green; the remaining 2 + `keyframe_exact` cases decode every frame of each fixture and go + green with M3 inter frames. -## Known gap (the M2 blocker) — TWO of three root causes FIXED this session +## M2 blocker — RESOLVED -Method: a dixie-faithful python model of the whole partition-0 + token -parse (`/tmp/vp8ref.py`, decision-for-decision trace) diffed against the -Rust decoder's `EC_VP8_TRACE` decision stream. +Root cause: `get_coeffs`' ONE-token path (`tokens.rs`). After the +`p[2]` decision selects value 1, the reference walk (libvpx +`detokenize.c` GetCoeffs, RFC §13.2) falls through to the SHARED +sign-read / coefficient-write / EOB-after-nonzero sequence — the ONE +and magnitude paths converge right after the tree decision. The Rust +port had the sign/write/EOB block nested inside the magnitude branch +only, so a ONE token skipped the sign read and the EOB check and +re-entered the walk at the ZERO node: same read count (positions +stayed in lockstep, hence "same (pos,bit_count), different table +entry"), different decoded stream from the first ONE token in a busy +block — invisible on the lossless single-MB black fixture (no ONE +tokens), fatal from ~28 reads into kf-160x96-q20's first block. -1. FIXED — MV probability updates were parsed on KEY frames (dixie - parses them only for interframes): 38 extra bool reads desynced - partition 0. Moved inside `!is_keyframe`. -2. FIXED — decode_keyframe created a FRESH bool decoder over partition - 0 for the mode records (restarting the stream); `FrameHeader::parse` - now returns its partition-0 decoder and the mode records CONTINUE - from where the header stopped. -3. FIXED (earlier sweep) — per-MB-row token `reset_left` was never called. +Two reference-model bugs also fixed while instrumenting +(`scripts/vp8ref_model.py`): per-decision `G n/band/ctx/prob/bit` +lines replacing the DEC counter, and token-partition bool decoders +are now PERSISTENT across MB rows that share a partition (was: +re-created per row, which double-counted the walk on single-partition +streams). Trace protocol: diff `grep '^G '` of both sides; the first +differing line names decision, node and whether prob or bit diverges. -Result: `kf-16x16-black-q0.ivf` (single MB) decodes byte-exact vs -ffmpeg. Multi-MB fixtures still diverge; the decision traces now match -to decision 2562 and split at 2563 inside the token walk (MB(0,1) -block 0): the reference consults probability 11, rust 4, at the same -stream position — a coefficient-context/bookkeeping difference that -only manifests from the second MB onward (cross-MB token contexts or a -block-sequencing slip). Debug aids: `EC_VP8_TRACE` (decision + node -trace), `EC_VP8_DEBUG` (per-MB coeff dump), `examples/dbg_first.rs`, -python model preserved at `scripts/vp8ref_model.py` (needs the RFC at -~/.cache/vp8/rfc6386.txt and tables.rs; run from the worktree root). -Additional finding: the divergent decision 2563 is ~28 reads into -MB(0,0) block 0's token walk (not MB(0,1) as first thought); both -sides read the same (pos,bit_count) stream position but consult -different table entries - the next step is to print the consulted -PROBABILITY on each G-annotation line on both sides and take the first -G-line whose prob differs (the rust G lines print n/band/ctx/prob; -the python model needs the same one-line prob added to its G prints). ## Repro diff --git a/scripts/vp8ref_model.py b/scripts/vp8ref_model.py index 9272142c..77cc163f 100755 --- a/scripts/vp8ref_model.py +++ b/scripts/vp8ref_model.py @@ -26,8 +26,6 @@ class BD: self.bit_count = 0 def bool(self, prob): - global DEC - DEC += 1 split = 1 + (((self.range - 1) * prob) >> 8) big = split << 8 if self.value >= big: @@ -77,7 +75,6 @@ def table(name): return [int(x) for x in re.findall(r"-?\d+", body)] -DEC = 0 def main(): @@ -170,60 +167,70 @@ def main(): skips = [[False] * (cols + 1) for _ in range(rows + 1)] above_ctx = [[0] * 9 for _ in range(cols)] - DEC = [0] - def get_coeffs(ptype, n0, ctx, out): + def get_coeffs(ptype, n0, ctx0, out): base = ptype * 264 n = n0 - p = base + BANDS[n0] * 33 + ctx * 11 - DEC[0] += 1 - if DEC[0] == 2563: - print(f"# at2563: ptype={ptype} n0={n0} n={n} band={BANDS[n]} ctx={ctx} nodeoff=0 entry={p} val={probs[p]}") - if not d2.bool(probs[p]): + band = BANDS[n0] + c = ctx0 + p = base + band * 33 + c * 11 + + def g(prob_): + bit = d2.bool(prob_) + print(f"G n={n} band={band} ctx={c} prob={prob_} bit={1 if bit else 0}") + return bit + + if not g(probs[p]): return 0 while True: n += 1 - DEC[0] += 1 - if DEC[0] == 2563: - print(f"# at2563: ptype={ptype} n={n} band={BANDS[n]} nodeoff=1 entry={p+1} val={probs[p+1]}") - if not d2.bool(probs[p + 1]): - p = base + BANDS[n] * 33 + if not g(probs[p + 1]): + c = 0 + band = BANDS[n] + p = base + band * 33 else: - DEC[0] += 1 - if DEC[0] == 2563: - print(f"# at2563: nodeoff=2 n={n} band={BANDS[n]} ctx={ctx} p={p}") - if not d2.bool(probs[p + 2]): - p = base + BANDS[n] * 33 + 11 + if not g(probs[p + 2]): + c = 1 + band = BANDS[n] + p = base + band * 33 + 11 v = 1 else: - if not d2.bool(probs[p + 3]): - if not d2.bool(probs[p + 4]): + if not g(probs[p + 3]): + if not g(probs[p + 4]): v = 2 else: - v = 3 + d2.bool(probs[p + 5]) + v = 3 + (1 if g(probs[p + 5]) else 0) else: - if not d2.bool(probs[p + 6]): - if not d2.bool(probs[p + 7]): - v = 5 + d2.bool(159) + if not g(probs[p + 6]): + if not g(probs[p + 7]): + v = 5 + (1 if g(159) else 0) else: - v = 7 + 2 * d2.bool(165) - v += d2.bool(145) + v = 7 + 2 * (1 if g(165) else 0) + v += 1 if g(145) else 0 else: - bit1 = d2.bool(probs[p + 8]) - bit0 = d2.bool(probs[p + 9 + bit1]) + bit1 = 1 if g(probs[p + 8]) else 0 + bit0 = 1 if g(probs[p + 9 + bit1]) else 0 cat = 2 * bit1 + bit0 v = 0 for prob in CAT_EXTRA[cat]: - v += v + d2.bool(prob) + v += v + (1 if g(prob) else 0) v += 3 + (8 << cat) - p = base + BANDS[n] * 33 + 22 - out[ZIGZAG[n - 1]] = -v if d2.bool(128) else v - if n == 16 or not d2.bool(probs[p]): + c = 2 + band = BANDS[n] + p = base + band * 33 + 22 + out[ZIGZAG[n - 1]] = -v if g(128) else v + if n < 16 and not g(probs[p]): return n if n == 16: return 16 + # One PERSISTENT bool decoder per token partition: rows that share a + # partition continue its stream (dixie/libvpx behaviour). + d2s = [None] * nparts for r in range(1, rows + 1): - d2 = BD(parts[(r - 1) % nparts]) + pi = (r - 1) % nparts + if d2s[pi] is None: + d2s[pi] = BD(parts[pi]) + d2 = d2s[pi] left_ctx = [0] * 9 # phase 1: every mode record of the row (partition 0) for c in range(1, cols + 1):