diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 35731748..7a5888d7 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -719,6 +719,21 @@ pub(crate) fn sb_rect_hits() -> usize { SB_RECT_HITS.with(|c| c.get()) } +// lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane +// dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the +// running-vs-stale-snapshot bug this round fixed is exercised by a gate, not +// just inert-compiled. Zero forever on a passing gate means that gate's +// stream never carries `delta_q_present=1` through a rect64 block. +thread_local! { + static RECT64_QIDX_DRIFT_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT64_QIDX_DRIFT_HITS`]. +pub(crate) fn rect64_qidx_drift_hits() -> usize { + RECT64_QIDX_DRIFT_HITS.with(|c| c.get()) +} + // lane-partab r1: how many 32x32 quadrants decoded an AB partition // (PARTITION_HORZ_A / VERT_A / VERT_B -- two 16x16 squares plus one // 16x32/32x16 strip). Like [`RECT_PARTITION_HITS`], this is the @@ -3527,6 +3542,17 @@ fn decode_block_rect64( for row in 0..32 { luma_levels[row * bw..][..32].copy_from_slice(&luma_corner[row * 32..][..32]); } + { + let cur = CURRENT_Q_IDX.with(|c| c.get()); + if cur != i32::from(base_q_idx) { + RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); + } + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}" + ); + } + } let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, @@ -3588,6 +3614,17 @@ fn decode_block_rect64( let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=1 row={mi_r} col={mi_c} rng={rng}"); } + { + let cur = CURRENT_Q_IDX.with(|c| c.get()); + if cur != i32::from(base_q_idx) { + RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); + } + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE rect64_dequant plane=1 base_q_idx={base_q_idx} current_q_idx={cur}" + ); + } + } let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, @@ -3631,6 +3668,17 @@ fn decode_block_rect64( let (rng, _) = dec.debug_state(); eprintln!("EC_COEFF_VAL plane=2 row={mi_r} col={mi_c} rng={rng}"); } + { + let cur = CURRENT_Q_IDX.with(|c| c.get()); + if cur != i32::from(base_q_idx) { + RECT64_QIDX_DRIFT_HITS.with(|c| c.set(c.get() + 1)); + } + if std::env::var_os("EC_AV1_TRACE").is_some() { + eprintln!( + "TRACE rect64_dequant plane=2 base_q_idx={base_q_idx} current_q_idx={cur}" + ); + } + } let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 485e4b1f..850fa207 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -8831,6 +8831,169 @@ mod tests { ); } + /// lane-rect64q r1: same recipe as + /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`] + /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is + /// `DELTA_Q_OBJECTIVE` (`av1_cx_iface.c:271`), so dropping that one flag + /// is enough to make `delta_q_present=1` the norm and drive + /// [`crate::decode::decode_block_rect64`]'s running `CURRENT_Q_IDX` away + /// from the frame-constant `base_q_idx` inside a real rect64 SB -- + /// exactly the bug this round's dequant fix targets. Hard-asserts + /// `rect64_qidx_drift_hits() > 0`: without that, this gate could pass + /// vacuously the same way the `--deltaq-mode=0` sibling always did. + /// + /// lane-rect64q r1: measured, does NOT fire -- 15/40 attempts matched + /// but `rect64_qidx_drift_hits()` stayed 0 every time. Real aomenc's RD + /// never chose a nonzero delta-q on this tiny synthetic gradients frame + /// even with `deltaq-mode` left at its default; `#[ignore]`d rather than + /// deleted so the recipe and the negative result both survive for the + /// next attempt (see `lanes/rect64q-r1.report.md`). + #[test] + #[ignore = "drift never observed this round -- see lanes/rect64q-r1.report.md"] + fn a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact() + { + const NAME: &str = + "a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 1usize); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let n_attempts: u32 = std::env::var("EC_SBPART_DQ_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(40); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + let source = + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=32", + "--max-partition-size=64", + "--enable-restoration=0", + "--enable-palette=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--enable-tx-size-search=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} frame {i} luma vs ffmpeg (seed {seed})"); + assert_eq!(got.u, want.u, "{NAME} frame {i} U vs ffmpeg (seed {seed})"); + assert_eq!(got.v, want.v, "{NAME} frame {i} V vs ffmpeg (seed {seed})"); + } + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every attempt refused; the gate never decoded a stream" + ); + assert!( + crate::decode::rect64_qidx_drift_hits() > 0, + "{NAME}: zero rect64 dequant calls ever observed CURRENT_Q_IDX != base_q_idx \ + ({matched} matches, {named_refusals} refusals out of {n_attempts}) -- delta_q \ + was never actually exercised through decode_block_rect64 this run" + ); + eprintln!( + "{NAME}: {named_refusals} named refusals, {matched} pixel-exact matches out of \ + {n_attempts}, sb_rect_hits={}, rect64_qidx_drift_hits={}", + crate::decode::sb_rect_hits(), + crate::decode::rect64_qidx_drift_hits() + ); + } + /// lane-sbpart r4: replays a pinned mismatch byte-for-byte off disk (no /// aomenc/ffmpeg re-encode), same pattern as `pinned_golden3/4_stream_ /// decodes_pixel_exact` -- fast red/green loop for the bisect, and lets diff --git a/lanes/rect64q-r1.report.md b/lanes/rect64q-r1.report.md new file mode 100644 index 00000000..d74ce86d --- /dev/null +++ b/lanes/rect64q-r1.report.md @@ -0,0 +1,145 @@ +# lane-rect64q r1 report + +## What was already there / applied + +Hunter's fix (three `decode_block_rect64` dequant call sites use +`CURRENT_Q_IDX.with(|c| c.get())` instead of the stale `base_q_idx` +parameter) was already applied uncommitted in this worktree. Committed +first, as instructed: `1d2c3bb`. + +## Instrumentation (charter step 1) + +Added `RECT64_QIDX_DRIFT_HITS` thread-local counter (`decode.rs:719-733`) +and, at each of the three dequant sites inside `decode_block_rect64` +(luma, U, V — `decode.rs` ~3560, 3623, 3684), a check comparing +`CURRENT_Q_IDX` against `base_q_idx`, incrementing the counter on any +mismatch and printing `TRACE rect64_dequant plane=

base_q_idx= +current_q_idx=` under the existing `EC_AV1_TRACE` gate. + +**Measured on the only existing gate that reaches `decode_block_rect64`** +(`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`, +40 attempts, `--deltaq-mode=0`): 105 dequant calls traced, every single one +`base_q_idx=180 current_q_idx=180`. `rect64_qidx_drift_hits()` stayed 0. +This gate forces `delta_q_present=0` by its own recipe (`--deltaq-mode=0`), +so this result is exactly as expected — it proves the instrumentation +works, not that the fix is inert in general. + +EVIDENCE: `EC_AV1_TRACE=1 EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib +a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact +-- --nocapture --test-threads=1` | `/tmp/rect64q-trace1.log` | 105/105 +`TRACE rect64_dequant` lines all `180 180`, `sb_rect_hits=36`. + +## Gate attempt 2: drop `--deltaq-mode=0` (charter step 2) + +Wrote +`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_and_delta_q_decodes_pixel_exact` +(`stream.rs`, right after the sibling gate): identical recipe minus the +one flag, since real aomenc's non-realtime default is `DELTA_Q_OBJECTIVE` +(hunter's own finding, `av1_cx_iface.c:271`). Hard-asserts +`rect64_qidx_drift_hits() > 0`. + +**Result: does not fire.** 40 attempts, 15 matched, 25 named refusals +(same refusal shapes as the sibling gate — AB-at-64, 32x32 AB, Golomb +tail, screen-content strip), but `rect64_qidx_drift_hits()` stayed 0 +across all 15 matched attempts. Real aomenc's objective delta-q RD never +chose a nonzero delta on this tiny (192x128, 1 frame, cq=45) synthetic +gradients content, even with the flag left at its default. Marked +`#[ignore]` with the negative result recorded in its own doc comment +rather than deleted, so the recipe survives for whoever picks this up +next; it does NOT run in the default `--lib` suite, so it does not block +green. + +I did **not** port lane-palette2's gate. Two reasons found live, in order: +1. My worktree's `read_intra_mode_rect` (used by both `decode_block_rect` + and `decode_block_rect64`) still carries the blanket refusal *"a + HORZ/VERT intra strip in a screen-content frame"* for any + `allow_screen_content_tools` frame — I do not have lane-palette2's + rect-generalised palette wiring (`palette_bsize_ctx_wh` is defined at + `decode.rs:2553` but never called). Porting palette2's gate as-is would + mostly just hit this refusal (confirmed live: seed 59 in my own + modified gate's run hit exactly this string). +2. The coordinator's mid-task message pointed at a cheaper, *already-real* + repro (below) before I sank more budget into that path. + +## The coordinator's SB(0,1) lead — investigated, does not reproduce here + +lane-part32 (`64ccb9f`, read-only) reported seed 42, same +`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact` +recipe, SB(0,1)'s VERT-64 left arm, `row=0 col=91`, DC_PRED, +`all_zero=1`, "got=80 want=81". + +Regenerated that exact stream by hand (same `gradients_source` seed-42 +hash, same aomenc args) and decoded it in **this** worktree with +`EC_SBPART_DUMP64=1`: + +``` +DUMP64 mi_r=0 mi_c=16 px=64 py=0 bw=32 bh=64 mode=0 skip=false eob_nonzero=false + row0=[81,81,...,81] (32 values, all 81) +``` + +Independently decoded the same `.obu` with real ffmpeg +(`ffmpeg -i seed42.obu -f rawvideo -pix_fmt yuv420p`) and read row 0, +cols 60-99 of luma: all `81`. **My worktree and ffmpeg agree at col 91 +(value 81) — no mismatch.** This is also exactly the outcome the +coordinator's own reasoning predicts: `eob_nonzero=false` means zero +residual, so a dequant qindex bug (drift or not) cannot move this +specific block's pixels either way — consistent with `rect64_qidx_drift_hits()` +staying 0 on this exact stream too (checked: `deltaq-mode=0` in this +recipe, no drift possible by construction). + +I cannot explain the discrepancy with part32's reported "got=80" from the +evidence available in this round (my byte-for-byte reproduction matches +ffmpeg, not their reported mismatch) — possibly a difference in tree +state between their fork point and mine, or an artifact of the exact +attempt-loop state (`lock_gate_counters`/thread-local counters carried +across earlier attempts in the same test process) rather than this one +block in isolation. Did not chase further given budget; this is now open +for whoever picks up either lane next, with the reproduction recipe above +(exact aomenc/ffmpeg commands in scratchpad) ready to hand. + +**lane-palette2's defect status: still open, not touched this round.** +**lane-part32's SB(0,1) defect: investigated, does NOT reproduce +byte-for-byte in this worktree against real ffmpeg; open.** + +## Dead parameter (charter step 3) + +**Not removed.** My own instrumentation (comparing `CURRENT_Q_IDX` against +`base_q_idx` to increment the drift counter) now legitimately *uses* +`base_q_idx` inside `decode_block_rect64` — it is no longer a parsed-and- +discarded value, so `cargo check` no longer warns about it there +(confirmed: the only two remaining `unused variable: base_q_idx` warnings +are at `decode.rs:3053` (`decode_block_rect`) and `decode.rs:7259` +(`read_inter_plane`), both pre-existing and out of this charter's scope — +`decode_block_rect64` itself is clean). This is a deviation from the +charter's literal step 3 instruction ("remove the parameter"): the +premise (dead parameter) stopped being true once the drift-proof +instrumentation was added, since that instrumentation is exactly the +"permanently non-inert" proof charter step 2 asked for and it needs +`base_q_idx` as its ground truth. Flagging this explicitly rather than +silently keeping the param. + +## Suite / check + +- `cargo check -p ec-av1 --lib`: clean, no new warnings beyond pre-existing + 108 doc/lint warnings. +- `cargo test -p ec-av1 --lib` (default set, `#[ignore]`d test excluded): + running full run at report time — appending numbers below once done. + +## HEAD + +Will update after final commit. + +## Open (disposition) + +- `rect64_qidx_drift_hits()` has never been observed nonzero anywhere in + this repo. The dequant fix (`1d2c3bb`) is **still unproven live** — + correct by code inspection and by matching every sibling path + (`decode_block`, `decode_block_rect`), but no gate in this repo (old or + new) has yet exercised a rect64 block with `delta_q_present=1` AND a + nonzero coded residual. `deferred: a firing gate for this fix — + needs either bigger/noisier real content (more SB rows so aomenc's + objective delta-q actually varies q) or a hand-crafted/pinned stream — + next lane round.` +- lane-part32's SB(0,1) "got=80 want=81" report does not reproduce here; + `deferred: reconcile the two worktrees' byte streams for seed 42 — next + round, needs comparing actual stream bytes, not just recipe text.`