diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index c055f0df..112d7015 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -1684,7 +1684,6 @@ impl Decoder { let maxw = (n4w as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; let maxh = (n4h as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; let nblocks = 1usize << tx_size; - let eob_pos = usize::from(coef.eob > 0); let shift_a = if maxw > 0 && nblocks + tx_col > maxw { (nblocks - (maxw - tx_col)) * 8 } else { @@ -1695,35 +1694,16 @@ impl Decoder { } else { 0 }; - match tx_size { - TX_4X4 => { - ectx[plane].above[ax] = eob_pos as u8; - ectx[plane].left[ay] = eob_pos as u8; - } - TX_8X8 => { - let va = ((eob_pos as u16) * 0x0101) >> shift_a; - ectx[plane].above[ax] = va as u8; - ectx[plane].above[ax + 1] = (va >> 8) as u8; - let vl = ((eob_pos as u16) * 0x0101) >> shift_l; - ectx[plane].left[ay] = vl as u8; - ectx[plane].left[ay + 1] = (vl >> 8) as u8; - } - TX_16X16 => { - for k in 0..4 { - let va = ((eob_pos as u32) * 0x01010101) >> shift_a; - ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; - let vl = ((eob_pos as u32) * 0x01010101) >> shift_l; - ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; - } - } - _ => { - for k in 0..8 { - let va = ((eob_pos as u64) * 0x0101010101010101) >> shift_a; - ectx[plane].above[ax + k] = (va >> (8 * k)) as u8; - let vl = ((eob_pos as u64) * 0x0101010101010101) >> shift_l; - ectx[plane].left[ay + k] = (vl >> (8 * k)) as u8; - } - } + write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l); + if crate::tokdbg_enabled() { + eprintln!( + "TDW row={mi_row} col={mi_col} plane={plane} brow={tx_row} bcol={tx_col} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?} intra=1", + coef.eob, + shift_a, + shift_l, + &ectx[plane].above[ax..ax + nblocks], + &ectx[plane].left[ay..ay + nblocks], + ); } // 4. Residual add. @@ -1853,6 +1833,48 @@ fn reset_skip_context( ectx[plane].left[(offy + i) % lrows] = 0; } } + if crate::tokdbg_enabled() { + eprintln!( + "TDK row={row} col={col} n4w={n4w:?} n4h={n4h:?} la={:?} lc={:?}", + &ectx[0].left[..], + &ectx[1].left[..], + ); + } +} + +/// The entropy-context write-back of one transform block +/// (`vp9_decode_block_tokens`, `vp9_detokenize.c:273-323`): the block's +/// `eob` spreads over its `1 << tx_size` 4x4 slots, and `shift_a`/`shift_l` +/// (the `get_ctx_shift` frame-edge rule) zero the slots past the frame edge. +/// +/// libvpx applies the shift to a value whose WIDTH IS THE WINDOW'S — a +/// `(uint16_t)` for `TX_8X8`, `(uint32_t)` for `TX_16X16`, `(uint64_t)` for +/// `TX_32X32` — so the shift zeroes the window's TAIL. Shifting a 64-bit +/// spread instead only zeroes bytes past the window and leaves the in-window +/// tail set: the last-SB-row chroma blocks then hand a stale 1 to the next +/// row's context read (the frame-72 desync). +fn write_tx_context( + ectx: &mut [PlaneContexts; 3], + plane: usize, + tx_size: usize, + ax: usize, + ay: usize, + eob: bool, + shift_a: usize, + shift_l: usize, +) { + const ONES: u64 = 0x0101_0101_0101_0101; + let nblocks = 1usize << tx_size; + let eob_pos = u64::from(eob); + // Narrow to the window first (libvpx's cast), then apply the edge shift; + // the clamp keeps a fully-outside window (libvpx: undefined shift) total. + let narrow = 64 - 8 * nblocks; + let spread_a = ((eob_pos * ONES) >> narrow) >> shift_a.min(8 * nblocks); + let spread_l = ((eob_pos * ONES) >> narrow) >> shift_l.min(8 * nblocks); + for k in 0..nblocks { + ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8; + ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8; + } } /// `mode_lf_lut` (`vp9/common/vp9_loopfilter.c:223`): @@ -1943,7 +1965,6 @@ fn decode_inter_tx_tokens( let n4h_s = bh * 2 >> s; let maxw = (n4w_s as i32 + (mb_to_right.min(0) >> (5 + s))).max(0) as usize; let maxh = (n4h_s as i32 + (mb_to_bottom.min(0) >> (5 + s))).max(0) as usize; - let eob_pos = u64::from(coef.eob > 0); let shift_a = if maxw > 0 && nblocks + bcol > maxw { (nblocks - (maxw - bcol)) * 8 } else { @@ -1954,11 +1975,16 @@ fn decode_inter_tx_tokens( } else { 0 }; - let spread_a = (eob_pos * 0x0101_0101_0101_0101) >> shift_a; - let spread_l = (eob_pos * 0x0101_0101_0101_0101) >> shift_l; - for k in 0..nblocks { - ectx[plane].above[ax + k] = (spread_a >> (8 * k)) as u8; - ectx[plane].left[ay + k] = (spread_l >> (8 * k)) as u8; + write_tx_context(ectx, plane, tx_size, ax, ay, coef.eob > 0, shift_a, shift_l); + if crate::tokdbg_enabled() { + eprintln!( + "TDW row={row} col={col} plane={plane} brow={brow} bcol={bcol} tx={tx_size} eob={} sa={} sl={} aw={:?} lw={:?}", + coef.eob, + shift_a, + shift_l, + &ectx[plane].above[ax..ax + nblocks], + &ectx[plane].left[ay..ay + nblocks], + ); } coef } diff --git a/crates/ec-vp9/tests/inter_pixels_exact.rs b/crates/ec-vp9/tests/inter_pixels_exact.rs index 3ac4ea64..5d2f6ea0 100644 --- a/crates/ec-vp9/tests/inter_pixels_exact.rs +++ b/crates/ec-vp9/tests/inter_pixels_exact.rs @@ -129,3 +129,30 @@ fn inter_gop_with_tile_columns_matches_ffmpeg() { ensure_fixture(&path, 1); assert!(compare(&path) >= 2); } + +/// Real-content regression for the last-partial-SB-row context bug: this +/// 120-frame 1080p stream used to abort at input frame 72 with +/// `tile bool decoder desync`, because a chroma transform block whose +/// write-back window runs past the frame bottom edge kept the window's +/// TAIL slot set (`write_tx_context`), and the next row of blocks read it +/// as an entropy context. Every shown frame must match ffmpeg. +/// +/// Media-gated: the corpus fixture is not versioned, so the witness skips +/// when `fixtures/bitstreams/vp9-1080p-60-8bit.ivf` is absent. +#[test] +fn corpus_1080p_60fps_matches_ffmpeg_past_frame_72() { + let Some(dir) = ivf::fixture_dir() else { + println!("SKIP: fixtures/bitstreams absent (media-gated witness)"); + return; + }; + let path = dir.join("vp9-1080p-60-8bit.ivf"); + if !path.exists() { + println!("SKIP: {} absent (media-gated witness)", path.display()); + return; + } + let shown = compare(&path); + assert!( + shown >= 73, + "the witness must decode past input frame 72 (got {shown} shown frames)" + ); +} diff --git a/lanes/vp9f72.report.md b/lanes/vp9f72.report.md new file mode 100644 index 00000000..a382a8a3 --- /dev/null +++ b/lanes/vp9f72.report.md @@ -0,0 +1,256 @@ +# Lane vp9f72: the frame-72 tile desync — entropy-context write-back width + +Branch `lane-vp9-f72`, base `main e910d25b`. Crate scope: `crates/ec-vp9` only. +Worktree `/home/user/Documents/Code/Rust/edith_codecs-vp9f72`, private +`CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72`. + +Deliverable: `vp9-1080p-60-8bit.ivf` (1920x1080, 120 frames) decodes **all 120 +frames byte-identically** to the local libvpx 1.15 oracle, and the rest of the +corpus is unchanged; every other corpus stream stays byte-identical. + +## Baseline (milestone 0) + + $ cd /home/user/Documents/Code/Rust/edith_codecs-vp9f72 + $ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72 cargo test -p ec-vp9 + -> 20 test binaries, 31 passed, 0 failed, 0 ignored + $ cargo check -p ec-vp9 # warnings + -> 5 warnings (modes.rs `partition_probs`/`x_mis`/`y_mis`, `read_partition`, + tables `TM_PRED`) -- identical count on the base worktree + +## Symptom and reproduction + + $ $HOME/.cache/vp9pix/sweep.sh vp9-1080p-60-8bit 1920 1080 # against the vp9pix worktree + # on THIS lane's tree (see `$HOME/.cache/vp9f72/sweep_f72.sh`, same shape): + -> 72 shown frames, `PIXERR input=72: corrupt bitstream: vp9: tile bool decoder desync` + +Frames 0..71 are byte-identical; frame 72 aborts. Reproduced on this lane's +build before any edit (72/120 shown, error at input 72). + +## Root cause + +**The entropy-context write-back of a transform block applied the frame-edge +shift to a 64-bit spread, so it zeroed bytes BEYOND the window instead of the +window's tail.** + +libvpx `vp9_detokenize.c:273-323` (`vp9_decode_block_tokens`) writes: + + case TX_8X8: + get_ctx_shift(xd, &ctx_shift_a, &ctx_shift_l, x, y, 1 << TX_8X8); + ... + *(uint16_t *)a = ((eob > 0) * 0x0101) >> ctx_shift_a; + *(uint16_t *)l = ((eob > 0) * 0x0101) >> ctx_shift_l; + +The shift is applied to a value **whose width is the written window's** (u16 +for `TX_8X8`, u32 for `TX_16X16`, u64 for `TX_32X32`), so `>> 8` on a two-byte +window yields `0x0001` — bytes `[1, 0]`. Our port shifted the full 64-bit +spread (`0x0101..01 >> 8` = `0x0001_0101_0101_0101`) and then took byte `k`, +which leaves bytes `[1, 1]`: the window's last slot keeps its old value. + +`get_ctx_shift` only fires when the block runs past an edge +(`xd->max_blocks_wide/high != 0`, i.e. `mb_to_*_edge < 0`), which needs an mi +extent that is not a multiple of the block size — for 1080 (mi_rows 135) that +is exactly the **last, partial superblock row**. So frames 0..~71 behave and +the defect shows up wherever a bottom-row chroma block's stale tail slot is +later read as an entropy context. + +Mechanism as an equation (the written window for `nblocks` slots): + +| | written bytes | +|---|---| +| libvpx | `mask(nblocks) >> shift` | +| our port (bug) | `(mask(8) >> shift)` truncated to `nblocks` bytes | + +`mask(n) = (eob>0) * 0x0101..01` over `n` bytes. The two agree only for +`shift == 0` (every other corpus stream, every non-edge block) — hence a +corpus-only defect. + +### The two-site oracle that pinned it + +A **fresh** instrumented libvpx 1.15.0 was built for this lane (the parse-time +`/tmp/vp9loss` build was gone; `$HOME/.cache/vp9pix/drv_pix` is a static +pixel-only driver and could not print contexts). Build + instruments: + + $HOME/.cache/vp9f72/libvpx-1.15.0 # configure --disable-unit-tests --disable-vp8 + # --disable-vp9-encoder --disable-examples --disable-tools --enable-pic + vp9/decoder/vp9_decodeframe.c : g_dbg_row/g_dbg_col/g_dbg_bsize set in decode_block; + `SKIPCTX` print at the end of dec_reset_skip_context + vp9/decoder/vp9_detokenize.c : `TXBW` print of (row, col, plane, x, y, tx, a[], l[]) before the switch; + `TXBWC` print of (ctx, eob, shift_a, shift_l, written a[]/l[]) after it + $HOME/.cache/vp9f72/drv_txbw # drv.c linked against that build + +Per-frame arming without rebuilding the driver: `$HOME/.cache/vp9f72/armtrace.c` +is an `LD_PRELOAD` that counts IVF header/size reads (`fread`) and sets/unsets +the instrument env vars at the requested frame (`TRACEFROM=72 TRACETO=73 +ARMVARS="TXBW=1 SKIPCTX=1 MODEDUMP=1"`). Both sides' events are then compared +block by block. + +**First divergent event (pre-fix), tile 3, decode-order index 2076:** + + O (132,180) plane 1 bcol=2 brow=2 tx=1 eob=3 sl=8 lw=[1, 0] + M (132,180) plane 1 bcol=2 brow=2 tx=1 eob=3 sl=8 lw=[1, 1] + +Same shift (`sl=8`), different written window — the bug above, exactly. + +**First divergence that reads it** (same tile, block `(132,200)`): + + O (132,200) p=1 bcol=0 brow=2 tx=1 a=[0, 0] l=[0, 0] ctx=0 + M (132,200) p=1 bcol=0 brow=2 tx=1 a=[0, 0] l=[0, 1] cin=1 + +and in the bool trace the first differing read is the first coefficient bool +of that transform block: oracle prob **217** (band 0, ctx 0), ours prob **98** +(band 0, ctx 1) — the "same ordinal, different question" signature of a wrong +entropy context, 3 bools after the tile's marker read. + +## Fix + +One rule, one place: `write_tx_context` (`crates/ec-vp9/src/decode.rs`) now +mirrors libvpx's per-tx-size casts — narrow the spread to the window width +FIRST, then apply the edge shift: + + let narrow = 64 - 8 * nblocks; // libvpx's cast + let spread_a = ((eob_pos * ONES) >> narrow) >> shift_a.min(8 * nblocks); + let spread_l = ((eob_pos * ONES) >> narrow) >> shift_l.min(8 * nblocks); + +The `.min(8 * nblocks)` clamp is the only liberty taken: libvpx shifts a wider +type by more than its own width there (undefined in C, 0 on x86); the clamp +makes the same intent total in Rust. It is unreachable from the walk (a block +entirely past the edge is never visited). + +Both call sites use it: the inter token path (`decode_inter_tx_tokens`) and +the intra-in-inter path (`predict_and_reconstruct`). The latter already had +per-width casts and was correct — sharing the helper keeps the class fixed in +one place instead of two. + +## Evidence + +### 1. State-event equality with libvpx on frame 72 (post-fix) + +Every transform-block context write (value, edge shift and the written +a[]/l[] window) and every skip-context reset, in decode order, per tile: + +| tile | writes ours | writes oracle | equals | skip resets ours | oracle | +|---|---|---|---|---|---| +| 0 | 705 | 705 | yes | 246 | 246 | +| 1 | 1449 | 1449 | yes | 246 | 246 | +| 2 | 2824 | 2824 | yes | 300 | 300 | +| 3 | 3511 | 3511 | yes | 308 | 308 | + +Pre-fix, the write streams diverged by exactly one window per edge block +(tile 3 index 2076) and the reset streams matched until the desync. + +### 2. Pixel byte-exactness (the acceptance gate) + + $ $HOME/.cache/vp9f72/sweep_f72.sh # oracle drv_pix + our dump + pixcmp.py + +| fixture | frames | identical | +|---|---|---| +| `vp9-1080p-60-8bit.ivf` (1920x1080) | 120 | **120/120** (was 72) | +| `vp9-1080p-23.976-8bit.ivf` | 48 | 48/48 | +| `vp9-2160p-23.976-8bit.ivf` (3840x2160) | 48 | 48/48 | +| `vp9-superframe-altref.ivf` (320x240) | 60 | 60/60 | +| `vp9-tiles-1280.ivf` (1280x720) | 30 | 30/30 | +| `/tmp/inter.ivf` (1080p, 2 tile cols) | 3 | 3/3 | +| `/tmp/inter1.ivf` (1080p, 1 tile col) | 3 | 3/3 | +| generated 1918x1080 60-frame-long GOP (even, non-multiple-of-8 width) | 120 | 120/120 | + +The 10-bit corpus members are refused by name as before +(`PIXERR input=0: unsupported: vp9 profile 2`). + +### 3. Fail-pre-fix / pass-post-fix + +New media-gated witness `corpus_1080p_60fps_matches_ffmpeg_past_frame_72` +(`tests/inter_pixels_exact.rs`, reuses the file's `compare()` against +ffmpeg's rawvideo): + + # lane tree (fixed): + $ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72 cargo test -p ec-vp9 --test inter_pixels_exact + -> 3 passed (incl. corpus_1080p_60fps_matches_ffmpeg_past_frame_72) + + # base worktree at e910d25b + the same test file (throwaway, removed): + $ ... cargo test -p ec-vp9 --test inter_pixels_exact corpus_1080p + -> panicked at inter_pixels_exact.rs:82: frame decodes: + Corrupt { context: "vp9: tile bool decoder desync" } + test result: FAILED. 0 passed; 1 failed + +Skipped (with a `SKIP:` line) when `fixtures/bitstreams/vp9-1080p-60-8bit.ivf` +is absent — the corpus fixtures are not versioned. + +### 4. Gates + + $ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72 cargo test -p ec-vp9 + -> 20 test binaries, 31 passed, 0 failed, 0 ignored + $ cargo check -p ec-vp9 | grep -c ^warning + -> 6 (5 warnings + the summary line) -- equal to the base worktree + $ rustfmt --edition 2021 --check crates/ec-vp9/src/decode.rs + -> 6 diffs, exactly the pre-existing count on the base tree (import + ordering + the repo's compact-argument style); my additions are clean + $ rustfmt --edition 2021 --check crates/ec-vp9/tests/inter_pixels_exact.rs + -> only ivf.rs (shared `mod ivf`) pre-existing diffs + +Named refusals unchanged (verified with the vp9pix scratch fixtures): + + refusal_odd.ivf -> "vp9 inter odd frame dimensions (321x241 ...)" + refusal_sizechange.ivf -> "vp9 inter reference size change (...)" + vp9-1080p-23.976-10bit -> "vp9 profile 2 ..." + +## Deferred / limitations (explicit) + +- **The horizontal half of the class has no witness.** `shift_a` follows the + same rule and uses the same helper, but `mb_to_right_edge < 0` needs an mi + extent that is not a multiple of the block size in the COLUMN direction + (mi_cols odd), which no corpus stream here reaches — a 1918x1080 stream + (`mi_cols` 240, even) decodes 120/120 identically on BOTH the base and the + fixed trees, so it is not a witness. `deferred()`: the vertical half is what real content hits. +- **Cross-lane scope**: the odd-*coded*-extent path belongs to `lane-vp9-odd` + (merged on main as `e8152b9b`, which does not touch the write-back). My fix + is orthogonal — verified inert: `odd.ivf` decodes byte-identically on the + base and this lane (460800 bytes, `cmp` equal). The odd-dims refusal is left + in place. +- Diagnostics kept (gated by the existing scratch hook `EC_VP9_TOKDGB`): + `TDB` (transform-block context read, pre-existing), `TDW` (write value + + shift + written window, both token paths) and `TDK` (skip-context reset). + They are the instruments that isolated this defect; a next context lane can + re-derive any of the tables above from them. + +## Repro (all commands a verifier can re-run) + + # 1. gate + cd /home/user/Documents/Code/Rust/edith_codecs-vp9f72 + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72 cargo test -p ec-vp9 + + # 2. the acceptance sweep (120/120) + $HOME/.cache/vp9f72/sweep_f72.sh vp9-1080p-60-8bit 1920 1080 + + # 3. oracle state-event equality for frame 72 + cd $HOME/.cache/vp9f72/libvpx-1.15.0 && make -j6 + gcc -O1 -g -o $HOME/.cache/vp9f72/drv_txbw $HOME/.cache/vp9pix/drv.c -I. -Ibuild/make -L. -lvpx -lm -lpthread + gcc -O1 -shared -fPIC -o $HOME/.cache/vp9f72/armtrace.so $HOME/.cache/vp9f72/armtrace.c -ldl + TRACEFROM=72 TRACETO=73 ARMVARS="TXBW=1 SKIPCTX=1" \ + LD_PRELOAD=$HOME/.cache/vp9f72/armtrace.so $HOME/.cache/vp9f72/drv_txbw \ + /vp9-1080p-60-8bit.ivf 2>or.txt + cd /home/user/Documents/Code/Rust/edith_codecs-vp9f72 + CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9f72 INTER_IVF=/vp9-1080p-60-8bit.ivf \ + EC_VP9_PIXDUMP=/dev/null EC_VP9_TOKDGB=1 \ + cargo test -p ec-vp9 --test scratch_pixdump -- --nocapture 2>&1 \ + | awk '/PIXFRAME input=71 /{on=1;next} /PIXFRAME input=72 /{exit} on' > ours.txt + # then diff the TDW/TDK event streams per tile (scripts under $HOME/.cache/vp9f72) + +## VERDICT + +- GATE 1: `cargo test -p ec-vp9` — 20 binaries, 31 passed, 0 failed, 0 ignored: **PASS** +- GATE 2: `sweep_f72.sh vp9-1080p-60-8bit 1920 1080` — **120/120 byte-identical**: **PASS** +- GATE 3: corpus re-sweep (48/48, 48/48, 60/60, 30/30, 3/3, 3/3, 1918-wide 120/120): **PASS** +- GATE 4: state-event equality with libvpx (writes + skip resets, per tile): **PASS** +- GATE 5: fail-pre-fix / pass-post-fix witness, media-gated per house style: **PASS** +- GATE 6: warning parity (5) and scoped rustfmt parity with the base tree: **PASS** +- GATE 7: this report; deferred items named above: **PASS** + +## git log + + cargo test / git log for this lane: + * THIS COMMIT -- "vp9: inter context write-back zeroes the window's tail, + not bytes past it" -- the only commit on lane-vp9-f72 above the base + * e910d25b vp9pix: merge-side follow-ups -- ff merge verified, dependent + sweep empty, gates re-run on main (base) + $ git log --oneline lane-vp9-f72 ^e910d25b # -> exactly one line