diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 6a3f3cc7..f2c14a6c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1130,6 +1130,42 @@ thread_local! { const { std::cell::Cell::new(0) }; } +// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the +// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled +// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while +// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have +// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this +// decoder used to read with the wrong alphabet, so a gate that asserts this +// counter advanced proves the fixed path fired (class +// `gate-blind-to-feature`). +thread_local! { + static FIMV_ALPHABET_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`FIMV_ALPHABET_HITS`]. +pub fn fimv_alphabet_hits() -> usize { + FIMV_ALPHABET_HITS.with(|c| c.get()) +} + +// lane-fimv r1: how many frame headers this decoder has decoded with +/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate +// prove the encoder really produced the header state under test rather than +// assume it. +thread_local! { + static FIMV_FRAME_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of [`FIMV_FRAME_HITS`]. +pub fn fimv_frame_hits() -> usize { + FIMV_FRAME_HITS.with(|c| c.get()) +} + +/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose +/// `force_integer_mv` bit is set. +pub fn note_force_integer_mv_frame() { + FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1)); +} + /// Current value of [`OBMC_HITS`]. pub(crate) fn obmc_hits() -> usize { OBMC_HITS.with(|c| c.get()) @@ -14192,27 +14228,46 @@ fn decode_inter_block( // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf` // instead of the 2-symbol `obmc_cdf` exactly when // `num_proj_ref >= 1` under `allow_warped_motion`. - // lane-scaledref r2: libaom `motion_mode_allowed` - // (`blockd.h:1484`) requires - // `!av1_is_scaled(block_ref_scale_factors[0])` for - // WARPED_CAUSAL -- under a scaled reference (superres) the - // block reads the 2-symbol `obmc_cdf`, never the 3-symbol + // lane-scaledref r2 + lane-fimv r1: libaom + // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH + // `!av1_is_scaled(block_ref_scale_factors[0])` and + // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL -- + // under a scaled reference (superres) OR on a frame whose + // header set `force_integer_mv` (screen content) the block + // reads the 2-symbol `obmc_cdf`, never the 3-symbol // `motion_mode_cdf`. Reading the wrong alphabet here narrows // the arithmetic coder by the wrong amount and predicts the - // rest of the tile off a diverged state: it was silently - // wrong pixels (r1's `--enable-warped-motion=1` superres - // mismatch), not a desync error. + // rest of the tile off a diverged state: silently wrong + // pixels, not a desync error. `force_integer_mv` is the + // per-frame value (spec 5.9.2: coded per frame only when + // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from + // `FrameHeader::force_integer_mv`). + // libaom `av1_is_scaled` is `x_scale_fp != REF_NO_SCALE || + // y_scale_fp != REF_NO_SCALE`; the y half is unreachable here + // because a reference whose height differs from this frame's + // true size is refused before any tile decodes ("a reference + // picture whose height does not match this frame's own true + // size", ~14681). Whoever lifts that refusal adds the y term. let ref_is_scaled = mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE; - let warp_eligible = allow_warped_motion - && !ref_is_scaled - && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1; - if allow_warped_motion - && ref_is_scaled - && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1 - { + let proj_ok = num_proj_ref( + grid, + mi_row, + mi_col, + bw4, + bh4, + mi_cols as usize, + mi_rows as usize, + ref_frame, + ) >= 1; + let warp_eligible = + allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok; + if allow_warped_motion && proj_ok && ref_is_scaled { SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1)); } + if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv { + FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1)); + } if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]); match mode { @@ -15924,8 +15979,16 @@ fn decode_inter_block8( // leaf under a scaled reference is refused before this function // runs (see the block8 refusal below, ~12500) -- whoever lifts // that refusal must add `&& !ref_is_scaled` here too. - let warp_eligible = allow_warped_motion - && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1; + // lane-fimv r1: libaom `motion_mode_allowed` also requires + // `!xd->cur_frame_force_integer_mv`, so a screen-content frame + // that set `force_integer_mv` reads the 2-symbol `obmc_cdf` here + // (class wrong-alphabet-same-value). + let proj_ok = + num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, ref_frame) >= 1; + let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok; + if allow_warped_motion && proj_ok && force_integer_mv { + FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1)); + } if warp_eligible { let mode = dec.symbol(&mut cdfs.motion_mode[0]); match mode { diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 3efb8c86..ca48b25d 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -620,6 +620,11 @@ pub fn decode_stream(data: &[u8]) -> Result> { // refuses by name there if the slot is still empty -- widened // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every // one of the 7 single-reference slots. + // lane-fimv r1: record the header state the fimv gate asserts on + // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause). + if header.force_integer_mv { + decode::note_force_integer_mv_frame(); + } let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| { if ref_frame == 0 { None @@ -9230,6 +9235,234 @@ mod tests { assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran"); } + /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom + /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL` + /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set + /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol + /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the + /// 3-symbol alphabet there (silent tile desync, no refusal named it). + /// + /// The fixture is screen content that is mostly static with only + /// whole-pixel motion, which is exactly what aomenc's own + /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching + /// their collocated block) needs to set `cur_frame_force_integer_mv` + /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive: + /// `encoder.c:4171`). Two hard asserts, both class + /// `gate-blind-to-feature`: at least one decoded frame header carried + /// `force_integer_mv = 1`, and at least one block took the 2-symbol + /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would + /// have picked the 3-symbol one. A decode error or a pixel mismatch is a + /// FAILURE, never a skip. + #[track_caller] + fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) { + let _gate_lock = lock_gate_counters(); + assert!(have_ffmpeg(), "{name}: ffmpeg required"); + assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display()); + let (width, height, frame_count) = (64usize, 64usize, 20usize); + let fimv_frames_before = crate::decode::fimv_frame_hits(); + let alphabet_before = crate::decode::fimv_alphabet_hits(); + let mut matched = 0u32; + let mut named_refusals = 0u32; + let mut attempts = 0u32; + let mut refusals = Vec::new(); + for cq in [32u32, 45, 55] { + for step in [4u32, 8] { + attempts += 1; + // lane-fimv r1: per-attempt snapshots. The aggregate + // assertions below are satisfied by a single lucky cq/step + // cell; these prove EVERY attempt that decoded and + // pixel-compared really carried the header state and the + // forced alphabet under test (class gate-blind-to-feature). + let attempt_fimv_before = crate::decode::fimv_frame_hits(); + let attempt_alphabet_before = crate::decode::fimv_alphabet_hits(); + let duration = frame_count as f64 / 25.0; + // Flat screen-content tiles with hard edges, translating by a + // whole number of pixels per frame: static enough for + // `av1_is_integer_mv`, moving enough for a real inter block + // with overlappable neighbours. + let source = format!( + "color=c=black:s={width}x{height}:r=25,\ + drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\ + drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\ + drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill" + ); + let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", + &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1", + "-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 cq_arg = format!("--cq-level={cq}"); + let mut args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + &cq_arg, + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + // single reference only: the 10-bit compound MC defect + // (see `a_real_compound_global_warp_10bit_stream_...`) + // is unrelated to this lane and would mask it. + "--auto-alt-ref=0", + "--lag-in-frames=0", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + // the flag combination this gate exists for: warp allowed + // by the header, OBMC available, global motion off (so the + // GLOBALMV suppression is not what picks the alphabet). + "--tune-content=screen", + "--enable-warped-motion=1", + "--enable-obmc=1", + "--enable-global-motion=0", + "--enable-masked-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-dist-wtd-comp=0", + // partition/intra tools this decoder does not code yet -- + // the same exclusion list every inter gate here carries. + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + ]; + if ten_bit { + args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]); + } + args.extend_from_slice(&["--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 (cq {cq} step {step}): {msg}" + ); + named_refusals += 1; + refusals.push(format!("cq {cq} step {step}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let want = if ten_bit { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") + && frames + .iter() + .zip(&want) + .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v) + { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}"); + } + for (i, (got, want)) in frames.iter().zip(&want).enumerate() { + assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})"); + assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})"); + assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})"); + } + assert!( + crate::decode::fimv_frame_hits() > attempt_fimv_before, + "{name} (cq {cq} step {step}): decoded and compared all \ + frames but no frame header had force_integer_mv=1 -- \ + this attempt is vacuous" + ); + assert!( + crate::decode::fimv_alphabet_hits() > attempt_alphabet_before, + "{name} (cq {cq} step {step}): no block was forced onto the \ + 2-symbol obmc alphabet by force_integer_mv while \ + allow_warped_motion=1 and num_proj_ref>=1 -- this attempt \ + is vacuous" + ); + matched += 1; + } + } + let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before; + let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before; + eprintln!( + "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \ + force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}", + refusals.join("\n") + ); + assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran"); + assert!( + fimv_frames > 0, + "{name}: no decoded frame header had force_integer_mv=1 \ + ({matched} matches of {attempts}) -- gate vacuous" + ); + assert!( + alphabet > 0, + "{name}: no block read the 2-symbol obmc alphabet where \ + allow_warped_motion=1 and num_proj_ref>=1 would have picked the \ + 3-symbol motion_mode alphabet -- gate vacuous" + ); + } + + /// 8-bit arm of [`run_fimv_motion_mode_gate`]. + #[test] + fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() { + run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false); + } + + /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are + /// `yuv420p10le`. + #[test] + fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() { + run_fimv_motion_mode_gate( + "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact", + true, + ); + } + /// 8-bit arm of [`run_compound_global_warp_gate`]. #[test] fn a_real_compound_global_warp_stream_decodes_pixel_exact() { diff --git a/lanes/fimv-r1.report.md b/lanes/fimv-r1.report.md new file mode 100644 index 00000000..c111e4ad --- /dev/null +++ b/lanes/fimv-r1.report.md @@ -0,0 +1,74 @@ +# lane-fimv r1 report + +Branch `lane-fimv`, rebased onto main `df5d630`. Commits: + +- `0fea969` (rebased `7513e53`) `fix(av1): motion_mode alphabet ignored force_integer_mv (and scaled refs)` +- `fc8b30e` `test(av1): force_integer_mv motion-mode gate asserts non-vacuity per attempt` + +## Root cause (r1, first commit -- verified this round, not re-derived) + +libaom `motion_mode_allowed` (`blockd.h` ~1484) returns `WARPED_CAUSAL` only when +`!xd->cur_frame_force_integer_mv && !av1_is_scaled(...)`. Our `warp_eligible` +(`crates/ec-av1/src/decode.rs:12417`) had neither clause, so a screen-content frame whose +header set `force_integer_mv` read the 3-symbol `motion_mode_cdf` where libaom wrote the +2-symbol `obmc_cdf` -- a wrong-alphabet msac narrowing, silently wrong pixels with no +refusal naming it (class `wrong-alphabet-same-value`). Same clause in +`decode_inter_block8`'s 8x8-leaf read (`decode.rs:14071`). + +## What this round added + +- `crates/ec-av1/src/stream.rs:8180,8316` -- the gate's `force_integer_mv frames > 0` and + `forced-2-symbol blocks > 0` assertions were AGGREGATE over the 6 cq/step cells, so one + live cell could have hidden five vacuous ones (class `gate-blind-to-feature`). Both + counters are now snapshotted per attempt and asserted right after that attempt's pixel + compare. Both arms stay green => all 6/6 cells of each arm really carry the header state + and the forced alphabet. +- `crates/ec-av1/src/decode.rs:12398` -- charter asked for `ref_is_scaled` to become + `x || y` like `av1_is_scaled`. NOT DONE as code, deliberately: a reference whose height + differs from this frame's true size is refused before any tile decodes + ("a reference picture whose height does not match this frame's own true size", + `decode.rs:14681`), so the y term is unreachable dead code today. Recorded as a comment + at the site naming the refusal and handing the y term to whoever lifts it + (ladder rung 1: does not need to exist). + +## Gate + +`a_real_force_integer_mv_warp_stream_decodes_pixel_exact` (8-bit) and +`a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact` (10-bit), +`crates/ec-av1/src/stream.rs:8160`. Real `aomenc` (`~/.cache/aom-oracle/build/aomenc`), +`--tune-content=screen --enable-warped-motion=1 --enable-obmc=1 --enable-global-motion=0`, +64x64x20 translating screen-content tiles, 6 cells (`cq` 32/45/55 x `step` 4/8), every +decoded frame pixel-compared against ffmpeg. + +``` +EC_AV1_REQUIRE_AOMENC=1 CARGO_TARGET_DIR=$HOME/.cache/cargo-target-fimv \ + cargo test -p ec-av1 --lib -- force_integer_mv --nocapture --test-threads=1 +``` + +EVIDENCE: $HOME/.cache/fimv-suite.log | aomenc --tune-content=screen --enable-warped-motion=1 --enable-obmc=1 --enable-global-motion=0, 6 cq/step cells x 20 frames, each frame Y/U/V compared to ffmpeg | 8-bit 6/6 pixel-exact, 0 refusals, force_integer_mv frames=114, forced-2-symbol blocks=342; 10-bit identical 6/6 / 114 / 342 +EVIDENCE: $HOME/.cache/fimv-suite.log | sibling re-run `cargo test -p ec-av1 --lib -- warp obmc superres scaled` | 20 passed, 0 failed, 2 ignored (pre-existing: 10-bit compound MC defect; pinned-fixture test) + +## Refusals + +None lifted this lane -- the defect was a wrong CDF alphabet, not a refused capability. +`refusal_inventory` (3 tests) and `gate_coverage` (9 tests) stay green with no edit needed. + +## Suite totals + +`EC_AV1_REQUIRE_AOMENC=1 cargo test -p ec-av1 --lib -- --test-threads=3`, log +`$HOME/.cache/fimv-suite.log`: **300 passed, 1 failed, 27 ignored, 0 filtered out** (933s). The single failure is the pre-existing-on-main one below. + +`decode::tests::nz_map_ctx_offset_tables_match_the_rect_rule` fails, and is PRE-EXISTING ON +MAIN: reproduced at `df5d630` in a detached verify worktree with its own target dir -- +`32x64 nz_map offset at display (row 0, col 2) left: 6 right: 11` (`decode.rs:16315`). This +lane's diff never touches `nz_map` (`git diff df5d630..HEAD -- decode.rs | grep -c nz_map` += 0). + +## Residue + +- deferred(whoever lifts the reference-height refusal at `decode.rs:14681`): the + `av1_is_scaled` y_scale_fp term in `warp_eligible`. Unreachable today, documented at the + site. +- accepted (not this lane): `nz_map_ctx_offset_tables_match_the_rect_rule` red on main. +- accepted: `a_real_compound_global_warp_10bit_stream_decodes_pixel_exact` stays `#[ignore]` + (pre-existing 10-bit compound MC defect).