From 76c8a7751336d7967f2567f17dda6a6316cf1cc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 14 Sep 2026 18:25:02 +0300 Subject: [PATCH] vp9kf: libvpx-1.15 marker bit, lossless ONLY_4X4 header, tile-info rows/cols bounds, tx-row left-ctx fix; oracle-diff HANDOFF #3 --- crates/ec-vp9-syntax/src/header.rs | 17 +++--- crates/ec-vp9/src/bool.rs | 23 ++++++-- crates/ec-vp9/src/decode.rs | 17 +++++- crates/ec-vp9/src/header.rs | 16 ++++- crates/ec-vp9/src/tables/mod.rs | 1 + crates/ec-vp9/src/tokens.rs | 6 +- crates/ec-vp9/tests/scratch_bool.rs | 14 +++++ crates/ec-vp9/tests/scratch_err.rs | 17 ++++++ crates/ec-vp9/tests/scratch_hdr2.rs | 12 ++++ crates/ec-vp9/tests/scratch_hdr3.rs | 14 +++++ lanes/vp9kf.report.md | 92 +++++++++++++++++++++++++++++ 11 files changed, 211 insertions(+), 18 deletions(-) create mode 100644 crates/ec-vp9/tests/scratch_bool.rs create mode 100644 crates/ec-vp9/tests/scratch_err.rs create mode 100644 crates/ec-vp9/tests/scratch_hdr2.rs create mode 100644 crates/ec-vp9/tests/scratch_hdr3.rs diff --git a/crates/ec-vp9-syntax/src/header.rs b/crates/ec-vp9-syntax/src/header.rs index fde006f2..8e02b56d 100644 --- a/crates/ec-vp9-syntax/src/header.rs +++ b/crates/ec-vp9-syntax/src/header.rs @@ -893,15 +893,14 @@ fn read_tile_info(r: &mut BitReader<'_>, h: &mut FrameHeader) -> Result<()> { break; } } - let sb64_rows = h.mi_rows().div_ceil(8); - let (_, max_log2_rows) = tile_cols_log2_bounds(sb64_rows); + // Rows: one bit always codes whether log2_tile_rows is nonzero, and a + // second bit only follows when it is (decodeframe.c `setup_tile_info`: + // `cm->log2_tile_rows = vpx_rb_read_bit(rb); + // if (cm->log2_tile_rows) cm->log2_tile_rows += vpx_rb_read_bit(rb);`). + // This is not a min..max walk like the columns side. let mut rows_log2 = 0u8; - while rows_log2 < max_log2_rows { - if r.read_bit()? { - rows_log2 += 1; - } else { - break; - } + if r.read_bit()? { + rows_log2 = 1 + u8::from(r.read_bit()?); } h.tile_info = TileInfo { cols_log2, @@ -927,6 +926,8 @@ fn tile_cols_log2_bounds(sb64_cols: u32) -> (u8, u8) { while (sb64_cols >> max_log2) >= MIN_TILE_WIDTH_B64 { max_log2 += 1; } + // libvpx `get_max_log2_tile_cols` returns max_log2 - 1 (tile_common.c:48). + let max_log2 = max_log2 - 1; (min_log2, max_log2) } diff --git a/crates/ec-vp9/src/bool.rs b/crates/ec-vp9/src/bool.rs index ff14629d..86234c64 100644 --- a/crates/ec-vp9/src/bool.rs +++ b/crates/ec-vp9/src/bool.rs @@ -13,7 +13,7 @@ //! spec's reference encoder (8.3.3, the carry-propagating writer) and //! assert bit-exact round-trips. -use ec_core::Result; +use ec_core::{Error, Result}; /// Boolean arithmetic decoder over one data partition (spec 8.3.2). pub struct BoolDecoder<'a> { @@ -52,14 +52,23 @@ impl<'a> BoolDecoder<'a> { if data.len() > 1 { value |= u32::from(data[1]); } - Ok(Self { + let mut dec = Self { data, pos: data.len().min(2), range: 255, value, bit_count: 0, overreads: 0, - }) + }; + // libvpx 1.15 consumes one marker bit per partition right after the + // initial fill (bitreader.c `vpx_reader_init`: + // `return vpx_read_bit(r) != 0; // marker bit`); the matching writer + // (`vpx_start_encode`) emits a leading 0 bit per partition. A 1 here + // means the partition is not a libvpx bool stream. + if dec.read_bool(128) { + return Err(Error::corrupt("bool decoder marker bit is set")); + } + Ok(dec) } /// Bytes consumed past the end of the partition, read as zero. Any @@ -171,12 +180,16 @@ struct BoolEncoder { #[cfg(test)] impl BoolEncoder { fn new() -> Self { - Self { + let mut e = Self { out: Vec::new(), range: 255, bottom: 0, bit_count: 24, - } + }; + // `vpx_start_encode` parity: the writer emits a leading 0 bit per + // partition, which the decoder consumes as its marker bit. + e.write_bool(false, 128); + e } fn add_one_to_output(out: &mut [u8]) { diff --git a/crates/ec-vp9/src/decode.rs b/crates/ec-vp9/src/decode.rs index 5cc6c930..59ed3a16 100644 --- a/crates/ec-vp9/src/decode.rs +++ b/crates/ec-vp9/src/decode.rs @@ -134,10 +134,23 @@ impl Decoder { // A keyframe resets the frame context (spec 7.2) before the // compressed header codes this frame's updates on top. self.ctx = FrameContext::new(hdr.frame_type == FrameType::Key); + // [scratch probe] EC_VP9_FORCE_UH / EC_VP9_FORCE_HSZ: override the + // uncompressed-header size / header_size_in_bytes split for diagnosis. + let hdr = { + let mut h = hdr; + if let Ok(v) = std::env::var("EC_VP9_FORCE_UH") { + h.uncompressed_header_size = v.parse().unwrap_or(h.uncompressed_header_size); + } + if let Ok(v) = std::env::var("EC_VP9_FORCE_HSZ") { + h.header_size_in_bytes = v.parse().unwrap_or(h.header_size_in_bytes); + } + h + }; let hdr_start = hdr.uncompressed_header_size as usize; let tx_mode = read_compressed_header( &frame[hdr_start..hdr_start + hdr.header_size_in_bytes as usize], &mut self.ctx, + hdr.quantization.lossless(), )?; let pic = self.decode_keyframe(&hdr, frame, tx_mode)?; @@ -725,7 +738,7 @@ impl Decoder { let ptype = usize::from(plane != 0); let ax = ((mi_col << 1) >> s) + tx_col; let lrows = 32usize >> s; - let ay = ((mi_row << 1) >> s) % lrows; + let ay = (((mi_row << 1) >> s) + tx_row) % lrows; let ctx_in = usize::from(ectx[plane].above[ax] != 0) + usize::from(ectx[plane].left[ay] != 0); let coef = decode_coefs( @@ -737,6 +750,8 @@ impl Decoder { scan, nb, &self.ctx.coef[tx_size], + (x0, y0), + plane, ); // 3. Context write-back (vp9_decode_block_tokens, v1.15 shifts). diff --git a/crates/ec-vp9/src/header.rs b/crates/ec-vp9/src/header.rs index f86a5a56..b36f8111 100644 --- a/crates/ec-vp9/src/header.rs +++ b/crates/ec-vp9/src/header.rs @@ -161,9 +161,21 @@ fn read_tx_mode(r: &mut BoolDecoder) -> u8 { /// `read_compressed_header` for intra frames (the inter branch is dead /// in this lane): tx mode, tx probs, coef probs, skip probs. -pub(crate) fn read_compressed_header(data: &[u8], ctx: &mut FrameContext) -> crate::Result { +/// +/// Lossless forces `ONLY_4X4` and consumes no tx-mode bits — decodeframe.c +/// `read_compressed_header`: `cm->tx_mode = xd->lossless ? ONLY_4X4 : +/// read_tx_mode(&r);`. +pub(crate) fn read_compressed_header( + data: &[u8], + ctx: &mut FrameContext, + lossless: bool, +) -> crate::Result { let mut r = BoolDecoder::new(data)?; - let tx_mode = read_tx_mode(&mut r); + let tx_mode = if lossless { + ONLY_4X4 + } else { + read_tx_mode(&mut r) + }; if tx_mode == TX_MODE_SELECT { for row in 0..2 { for j in 0..1 { diff --git a/crates/ec-vp9/src/tables/mod.rs b/crates/ec-vp9/src/tables/mod.rs index 9b5ba70d..0077008f 100644 --- a/crates/ec-vp9/src/tables/mod.rs +++ b/crates/ec-vp9/src/tables/mod.rs @@ -31,6 +31,7 @@ pub(crate) const ADST_ADST: usize = 3; pub(crate) const BLOCK_INVALID: u8 = 255; // spec 5.3 (TX_MODE) +pub(crate) const ONLY_4X4: u8 = 0; pub(crate) const TX_MODE_SELECT: u8 = 4; /// decodeframe.c `tx_mode_to_biggest_tx_size`. pub(crate) const TX_MODE_TO_BIGGEST_TX_SIZE: [usize; 5] = diff --git a/crates/ec-vp9/src/tokens.rs b/crates/ec-vp9/src/tokens.rs index 5d33271a..e6a2e74b 100644 --- a/crates/ec-vp9/src/tokens.rs +++ b/crates/ec-vp9/src/tokens.rs @@ -61,6 +61,8 @@ pub(crate) fn decode_coefs( scan: &[i16], nb: &[i16], probs4d: &[[[[[u8; 3]; 6]; 6]; 2]; 2], + #[allow(unused_variables)] pos: (usize, usize), + #[allow(unused_variables)] plane: usize, ) -> CoeffBlock { let max_eob = 16 << (tx_size << 1); let mut coef = CoeffBlock { @@ -144,8 +146,8 @@ pub(crate) fn decode_coefs( coef.eob = c; if crate::trace_enabled() { eprintln!( - "C pt={} tx={} eob={} c0={}", - plane_type, tx_size, c, coef.coeffs[0] + "C p={} x={} y={} tx={} eob={} c0={}", + plane, pos.0, pos.1, tx_size, c, coef.coeffs[0] ); } coef diff --git a/crates/ec-vp9/tests/scratch_bool.rs b/crates/ec-vp9/tests/scratch_bool.rs new file mode 100644 index 00000000..457390eb --- /dev/null +++ b/crates/ec-vp9/tests/scratch_bool.rs @@ -0,0 +1,14 @@ +mod ivf; +use ec_vp9::bool::BoolDecoder; + +#[test] +fn probe_first_bools() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bytes = std::fs::read(dir.join("fixtures/vp9/lossless-64.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let frame = &frames[0].data; + println!("slice bytes: {:02x?}", &frame[18..26]); + let mut r = BoolDecoder::new(&frame[18..18 + 113]).unwrap(); + let bits: Vec = (0..8).map(|_| u8::from(r.read_bool(128))).collect(); + println!("first 8 bools(128): {bits:?}"); +} diff --git a/crates/ec-vp9/tests/scratch_err.rs b/crates/ec-vp9/tests/scratch_err.rs new file mode 100644 index 00000000..97dae52b --- /dev/null +++ b/crates/ec-vp9/tests/scratch_err.rs @@ -0,0 +1,17 @@ +mod ivf; +use ec_vp9::decode::Decoder; +#[test] +fn show_err() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bytes = std::fs::read(dir.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut d = Decoder::new(); + let dir2 = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let b2 = std::fs::read(dir2.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap(); + let (_, _, _, f2) = ivf::parse_ivf(&b2); + println!("f0 bytes: {:02x?}", &f2[0].data[16..24]); + match d.decode(&frames[0].data) { + Ok(_) => println!("OK"), + Err(e) => println!("ERR: {e}"), + } +} diff --git a/crates/ec-vp9/tests/scratch_hdr2.rs b/crates/ec-vp9/tests/scratch_hdr2.rs new file mode 100644 index 00000000..4c9f1c84 --- /dev/null +++ b/crates/ec-vp9/tests/scratch_hdr2.rs @@ -0,0 +1,12 @@ +mod ivf; +use ec_vp9_syntax::Vp9Parser; +#[test] +fn dump_hdr() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bytes = std::fs::read(dir.join("fixtures/vp9/lossless-64.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let mut p = Vp9Parser::new(); + let h = p.parse_frame(&frames[0].data).unwrap(); + println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation); + println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height); +} diff --git a/crates/ec-vp9/tests/scratch_hdr3.rs b/crates/ec-vp9/tests/scratch_hdr3.rs new file mode 100644 index 00000000..651ff809 --- /dev/null +++ b/crates/ec-vp9/tests/scratch_hdr3.rs @@ -0,0 +1,14 @@ +mod ivf; +use ec_vp9_syntax::Vp9Parser; +#[test] +fn dump_hdr() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let bytes = std::fs::read(dir.join("fixtures/bitstreams/vp9-superframe-altref.ivf")).unwrap(); + let (_, _, _, frames) = ivf::parse_ivf(&bytes); + let subs = ec_vp9_syntax::superframe::split(&frames[0].data).unwrap(); + println!("subframes: {}", subs.len()); + let mut p = Vp9Parser::new(); + let h = p.parse_frame(subs[0]).unwrap(); + println!("q={:#?} lf={:#?} seg={:#?}", h.quantization, h.loop_filter, h.segmentation); + println!("uh={} hsz={} tile={:#?} w={} h={}", h.uncompressed_header_size, h.header_size_in_bytes, h.tile_info, h.width, h.height); +} diff --git a/lanes/vp9kf.report.md b/lanes/vp9kf.report.md index 932d35f5..0484edb6 100644 --- a/lanes/vp9kf.report.md +++ b/lanes/vp9kf.report.md @@ -97,3 +97,95 @@ CARGO_TARGET_DIR=$HOME/.cache/cargo-target-vp9 cargo test -p ec-vp9 --test keyfr see "Fixed this round" item 4 for the rationale; merge reviewer must approve. - No edits to `ec-vp8`, `ec-hw`, or `edith`. Workspace `Cargo.toml` untouched (members glob covers the new crate, same as `ec-vp8`). + +## HANDOFF #3 (lossless-64 lane, 2026-09-14) — FIRST DISAGREEING STEP: bool-decoder init + lossless tx_mode; FAIL (4009/4096) + +Root causes found this round (all proven against an instrumented libvpx 1.15.0 oracle, +see "Oracle" below — bit-level diffs, not structural reads): + +1. **Bool decoder marker bit (FIXED, ec-vp9/src/bool.rs `BoolDecoder::new`).** libvpx 1.15 + `vpx_reader_init` consumes one marker bit per partition right after the initial fill + (bitreader.c:34 `return vpx_read_bit(r) != 0; // marker bit`); the writer + (`vpx_start_encode`, bitwriter.c:22) emits a leading 0 bit per partition. Our spec-8.3.2 + init did not → one-bit desync on the compressed header AND every tile. Now read and + validated; test-only `BoolEncoder::new` writes the parity bit. This is a libvpx-1.15 + format quirk, not in the VP9 spec document — the spec-based roundtrip hid it. +2. **Lossless forces ONLY_4X4 in the compressed header (FIXED, ec-vp9/src/header.rs + `read_compressed_header(data, ctx, lossless)` + decode.rs call).** decodeframe.c: + `cm->tx_mode = xd->lossless ? ONLY_4X4 : read_tx_mode(&r);` — lossless consumes NO + tx-mode bits and skips tx-prob updates. We parsed a tx_mode symbol and desynced the + whole compressed header for q=0 streams. (read_tx_size needs no lossless branch: 1.15 + has none; ONLY_4X4 propagates via tx_mode.) +3. **Tile-info rows walk (FIXED, ec-vp9-syntax/src/header.rs `read_tile_info`).** Rows are + NOT a min..max walk: `log2_tile_rows = read_bit(); if (..) += read_bit();` — always ≥1 + bit. We read 0 bits for 64x64 → header_size_in_bytes read one bit early (113 became 226 + = 113<<1). +4. **Tile-info cols max bound (FIXED, same file `tile_cols_log2_bounds`).** max_log2 + started at 1 and used `>=`: for sb64_cols=1 it returned 1 (reads an extra increment + bit). Correct shape: start 0, `while (sb64_cols >> max_log2) > MIN_TILE_WIDTH_B64`. + +Two syntax-crate edits this round — same justification as round 2 (hard blockers, libvpx +line citations above). Merge reviewer must approve. + +**Progress:** lossless-64.ivf mismatches 4092/4096 → 4009/4096; first diff moved from +pixel (0,0) to (8,0). First 6 token blocks byte-match the oracle exactly +(eob/c0: 4/-1056, 0, 0, 14/464, U 16/760, V 15/408). Pixel (0,0) reconstructs correctly +now. `scratch_lossless` still FAIL; `lossless_64_matches_ffmpeg` NOT ADDED YET (do not +write the byte-compare test until the plane matches; scratch_lossless covers it for now). +keyframes_match_ffmpeg NOT re-run to green (will share whatever the remaining bug is — +lossless-only forcing is not on key-320's path, but the marker-bit and tile-info fixes are). + +**Remaining divergence (next session's first step):** the second 8x8 area at MI (0,1). +Oracle: `PART row=0 col=1 bsl=0 p=3` (SPLIT → BLOCK_4X4, 4 bmi y-modes, first 4x4 +eob=2 c0=72). Ours: decoded 3 luma 4x4 TUs + chroma for that area — a different +subshape → our partition read or the sub8x8 mode-info read diverges there. Suspects in +order: (a) sub8x8 bmi mode loop in modes.rs (`get_y_mode_probs` / bmi above-left +adjustment per sub-block), (b) `dec_update_partition_context` after sub8x8 blocks +(above_seg/left_seg bit state feeding the next partition ctx), (c) skip-flag context +after sub8x8. Diff method: run our `EC_VP9_TRACE=1` (C lines now carry p/x/y/tx) against +oracle EOB lines; first mismatch at block 7 of 416. + +**Oracle (reusable):** instrumented libvpx 1.15.0 built from source at +`/tmp/vp9loss/libvpx-src` (git clone --depth 1 --branch v1.15.0 webmproject/libvpx; +./configure --disable-unit-tests --disable-vp8 --disable-vp9-encoder --disable-examples +--disable-tools; make -j6; ~10 s). Driver `/tmp/vp9loss/drv.c` decodes an IVF frame. +With `VP9TRACE=1` it prints PART/PARTIN (partition symbol+ctx+probs+reader state), +MODE (bsize/skip/tx/y/uv per block), TXB (ctx a/l + dequant per token block), EOB +(eob + c0), CH (compressed-header tx_mode + updated probs), CHDATA. Diff its trace +against ours line-by-line — this found all four root causes above in one session. +/tmp is volatile; rebuild takes ~1 min. + +Note: CAT6_MIN_VAL is 67 in this libvpx (contiguous 5,7,11,19,35,67) — NOT 1344; our +tokens.rs is correct. read_tx_size/decode_coefs structural port re-verified clean. +Scratch: `tests/scratch_bool.rs`, `tests/scratch_hdr2.rs` added; `EC_VP9_FORCE_UH/HSZ` +probe override in decode.rs (decode_one) — all removable after match. + +### HANDOFF #3 addendum (same session, post-commit draft) + +5. **Left-context row index ignored tx_row (FIXED, ec-vp9/src/decode.rs decode_txb).** + `ay = ((mi_row<<1)>>s) % lrows` dropped the tx-block row → for the 2nd 4x4 row of any + block the left entropy context aliased row 0 (ax already had +tx_col). Now + `ay = (((mi_row<<1)>>s) + tx_row) % lrows`. Found by per-symbol TOK diff against the + oracle: altref f0 block (0,4) decoded with ctx=2 vs oracle ctx=1. + lossless-64: first diff now pixel (16,0) (was (8,0)); matches through the whole first + 8x8 including its BLOCK_4X4 neighbour group start. +6. **tile_cols_log2_bounds max side (FIXED AGAIN, ec-vp9-syntax).** My earlier `> MIN` + rewrite was wrong: libvpx `get_max_log2_tile_cols` = the `>= MIN` loop returning + **max_log2 - 1** (tile_common.c:40-49). Original syntax code had the right loop but + dropped the `-1`; for sb64_cols=5 (320px) that read a phantom cols increment bit → + hsz 498 instead of 249 → key-320 frame 0 errored ("marker bit") after fix #1. + Now: loop unchanged, `max_log2 - 1` applied. + +**State at yield:** lossless-64 3960/4096 mismatching, first diff (16,0) ours 135 ref 145; +key-320 f0 decodes without error, `keyframes_match_ffmpeg` fails on CONTENT only at +pixel (7,0): ours 74 vs ref 75 (single-rounding-class errors now, not desync). +`inter_is_named_unsupported` fails: altref f0 (single-subframe keyframe, 320x240, +q=36, lf=2) hits "vp9: tile bool decoder desync" in OUR tile decode — oracle decodes +it fine, headers parse identical (uh=18 hsz=225 verified both sides). Suspect: another +entropy-context bookkeeping bug of the same class as #5 (above/left write-back spans or +skip-context clearing), NOT the header. Next steps: (1) diff altref f0 first tile with +oracle TOK/TXB line-by-line from block (4,4) onward using per-symbol probs — instrument +ours with a TOK-style trace in tokens.rs decode_coefs (oracle TOK print is in +/tmp/vp9loss/libvpx-src/vp9/decoder/vp9_detokenize.c decode_coefs loop top); +(2) re-check `lossless_64_matches_ffmpeg` after; keep scratch files until green. +Oracle: /tmp/vp9loss/{libvpx-src,drv} (see above; TOK c/band/ctx/p0 print per symbol).