From 199abd2101ca59ac70dffe8236d9db56c7d192b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Sep 2026 07:42:26 +0300 Subject: [PATCH] fix(av1): three MV-stack divergences from libaom setup_ref_mv_list, one of them a compound-vs-single twin drift Phase-by-phase diff of both twins (find_mv_stack_with_sign_bias and find_mv_stack_compound) against libaom mvref_common.c; full 20-phase table in lanes/mvtwin-r1.report.md. 1. TWIN DRIFT (compound only): combine_compound_candidates filled a comp_list slot past both ref_id/ref_diff lists with (0, 0). libaom fills it with THAT SIDE's own gm_mv_candidates[idx] (mvref_common.c:718-719) -- the single-ref twin closed the identical gm-fallback gap on its mv_ref_list tail in r6. Wrong the moment a compound pair names a ROTZOOM/AFFINE reference and the scans leave the stack short. 2. BOTH twins: add_candidate/add_compound_candidate pushed unbounded and let a later sort+truncate pick the survivors. libaom drops the 9th distinct candidate AT INSERTION (*refmv_count < MAX_REF_MV_STACK_SIZE, mvref_common.c:100/128/388/425), keeping a different set. The dedup weight bump on a full stack is preserved. 3. BOTH twins: the row/col reach and the up/left availability gates were FRAME-relative. libaom's find_valid_row_offset/find_valid_col_offset clamp to tile->mi_row_start/mi_col_start (mvref_common.c:512-533). MiGrid::get already hid the out-of-tile cells, so the symptom was the scan weight (inc) and through it the stack order, inside every tile not starting at mi 0. Not defects, checked and recorded: the two bubble passes vs one stable sort (equivalent -- no post-boost entry can reach REF_CAT_LEVEL), the compound add_tpl_ref_mv double lookup (offset-independent, so both sides resolve together), and the has_tr grid probe (mask logic and "already decoded" coincide for square blocks, and libaom's is_last_vertical_rect refinement restores the rect case our probe already gets right). Gates: new a_real_aomenc_compound_mv_stack_gate, the first compound gate here that leaves --enable-ref-frame-mvs ON, with --auto-alt-ref=1 --lag-in-frames=25, a cq sweep and 30 seeds per arm; three arms (8-bit sb64 gm=0, 8-bit sb64 gm=1, 10-bit sb128 gm=1) decode every frame pixel-exact vs ffmpeg while hard-asserting comp_mode_hits AND tmv_hits advanced. Plus one deterministic unit test per defect. Found but NOT caused here: a 128x64 --tile-columns=1 stream mis-decodes frame 1 luma (ablation-proven pre-existing); kept as an #[ignore]d reproducer with the repro command in its doc comment. --- crates/ec-av1/src/mvstack.rs | 217 +++++++++++++++++++++++--- crates/ec-av1/src/stream.rs | 293 +++++++++++++++++++++++++++++++++++ lanes/mvtwin-r1.report.md | 86 ++++++++++ 3 files changed, 578 insertions(+), 18 deletions(-) create mode 100644 lanes/mvtwin-r1.report.md diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 300fa320..cb4e42e9 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -92,6 +92,36 @@ pub(crate) fn tmv_hits() -> usize { TMV_HITS.load(std::sync::atomic::Ordering::Relaxed) } +/// lane-mvtwin r1 firing counters, one per divergence this round closed. +/// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot +/// came from `gm_mv_candidates[side]` rather than a scanned neighbour, and +/// where that global mv was NOT `(0, 0)` (the only case the old zero fill +/// could not fake). `STACK_FULL_DROPS`: distinct candidates libaom drops at +/// `MAX_REF_MV_STACK_SIZE` on insertion. `TILE_REACH_CLIPS`: row/col reaches +/// shortened by a tile origin past mi 0, which the old frame-edge clamp +/// missed entirely. +static COMP_GM_FILL_HITS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +static STACK_FULL_DROPS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); +static TILE_REACH_CLIPS: std::sync::atomic::AtomicUsize = + std::sync::atomic::AtomicUsize::new(0); + +/// [`COMP_GM_FILL_HITS`]. +pub(crate) fn comp_gm_fill_hits() -> usize { + COMP_GM_FILL_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// [`STACK_FULL_DROPS`]. +pub(crate) fn stack_full_drops() -> usize { + STACK_FULL_DROPS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// [`TILE_REACH_CLIPS`]. +pub(crate) fn tile_reach_clips() -> usize { + TILE_REACH_CLIPS.load(std::sync::atomic::Ordering::Relaxed) +} + /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV /// candidates into a block's stack (spec 7.10.2.8, only reached when the /// frame header's own `use_ref_frame_mvs` is set): the current frame's own @@ -213,6 +243,14 @@ impl MiGrid { self.tile_col1 = col1; } + /// The current tile's top-left mi-unit origin ([`Self::set_tile_bounds`]). + /// libaom's `tile->mi_row_start`/`mi_col_start`, which every availability + /// and reach clamp in `setup_ref_mv_list` is written against + /// (`xd->up_available`, `find_valid_row_offset`, mvref_common.c:512-528). + pub fn tile_origin(&self) -> (usize, usize) { + (self.tile_row0, self.tile_col0) + } + /// Records the unit at `(row, col)`. Out-of-range coordinates are a /// no-op — the caller only ever addresses units inside the grid it built. pub fn set(&mut self, row: usize, col: usize, info: MiInfo) { @@ -313,7 +351,15 @@ const MVREF_ROW_COLS: usize = 3; fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) { if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) { entry.weight += weight; + } else if candidates.len() >= MAX_STACK_SIZE { + STACK_FULL_DROPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } else { + // libaom `add_ref_mv_candidate` (mvref_common.c:100) and + // `add_tpl_ref_mv` (:388) only push when + // `*refmv_count < MAX_REF_MV_STACK_SIZE` -- the 9th distinct MV is + // DROPPED AT INSERTION, never "kept if it outweighs an earlier one". + // Sorting first and truncating afterwards (what this did) keeps a + // different set whenever more than 8 distinct candidates are seen. candidates.push(StackEntry { mv, weight }); } } @@ -773,22 +819,35 @@ pub fn find_mv_stack_with_sign_bias( // nothing here relies on that. let row_adj = bh4 < 2 && mi_row % 2 == 1; let col_adj = bw4 < 2 && mi_col % 2 == 1; - let max_row_offset: isize = if mi_row > 0 { + // r1 (lane-mvtwin): availability and reach are TILE-relative, never + // frame-relative -- libaom's `xd->up_available`/`left_available` are + // `mi_row > tile->mi_row_start` / `mi_col > tile->mi_col_start`, and + // `find_valid_row_offset`/`find_valid_col_offset` (mvref_common.c:512-528) + // clamp the reach to `tile->mi_row_start - mi_row`. Clamping to the FRAME + // edge left `max_row_offset`/`max_col_offset` too long inside every tile + // that does not start at 0, which changes the row/col scan's `inc` weight + // (and so the stack ORDER) even though `MiGrid::get` already returns + // `None` for the cells outside the tile. + let (tile_row0, tile_col0) = grid.tile_origin(); + if tile_row0 > 0 || tile_col0 > 0 { + TILE_REACH_CLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); - reach.max(-(mi_row as isize)) + reach.max(tile_row0 as isize - mi_row as isize) } else { 0 }; - let max_col_offset: isize = if mi_col > 0 { + let max_col_offset: isize = if mi_col > tile_col0 { let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj); - reach.max(-(mi_col as isize)) + reach.max(tile_col0 as isize - mi_col as isize) } else { 0 }; let mut processed_rows = 0usize; let mut processed_cols = 0usize; - let found_above = mi_row > 0 + let found_above = max_row_offset.unsigned_abs() >= 1 && scan_row( grid, mi_row, @@ -802,7 +861,7 @@ pub fn find_mv_stack_with_sign_bias( &mut newmv_count, &mut processed_rows, ); - let found_left = mi_col > 0 + let found_left = max_col_offset.unsigned_abs() >= 1 && scan_col( grid, mi_row, @@ -1227,7 +1286,12 @@ fn add_compound_candidate( ) { if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) { entry.weight += weight; + } else if candidates.len() >= MAX_STACK_SIZE { + STACK_FULL_DROPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } else { + // Same insertion cap as [`add_candidate`]: libaom's compound branch + // of `add_ref_mv_candidate` (mvref_common.c:128) and `add_tpl_ref_mv` + // (:425) both gate the push on `*refmv_count < MAX_REF_MV_STACK_SIZE`. candidates.push(CompoundStackEntry { mv0, mv1, weight }); } } @@ -1477,9 +1541,18 @@ fn process_compound_ref_mv_candidate( /// libaom's combine step (`setup_ref_mv_list`, `mvref_common.c` ~696-720): /// zips each side's `ref_id` (exact matches) then `ref_diff` (borrowed, /// sign-flipped) entries, position-wise and independently per side, into up -/// to two full `(mv0, mv1)` pair candidates — missing slots default to -/// `(0, 0)`, matching libaom's zero-initialized `combined_mvs`. -fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, i32)); 2] { +/// to two full `(mv0, mv1)` pair candidates. r1 (lane-mvtwin): slots past +/// both lists are filled with THAT SIDE's own global motion vector +/// (`gm_mv_candidates[idx]`, mvref_common.c:718-719), never `(0, 0)` — the +/// exact gap the single-reference twin closed in r6 for its own +/// `mv_ref_list` tail, still open on this side. Invisible while every live +/// reference's global motion is IDENTITY (an unclamped gm mv of exactly +/// `(0,0)`), wrong the moment a compound pair names a ROTZOOM/AFFINE +/// reference and the scans leave the stack short. +fn combine_compound_candidates( + lists: &CompoundRefLists, + gm_mv_candidates: [(i32, i32); 2], +) -> [((i32, i32), (i32, i32)); 2] { let side_slots = |side: usize| -> [(i32, i32); 2] { let merged: Vec<(i32, i32)> = lists.ref_id[side] .iter() @@ -1487,7 +1560,14 @@ fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, .take(2) .copied() .collect(); - std::array::from_fn(|i| merged.get(i).copied().unwrap_or((0, 0))) + std::array::from_fn(|i| { + merged.get(i).copied().unwrap_or_else(|| { + if gm_mv_candidates[side] != (0, 0) { + COMP_GM_FILL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + gm_mv_candidates[side] + }) + }) }; let side0 = side_slots(0); let side1 = side_slots(1); @@ -1532,22 +1612,35 @@ pub fn find_mv_stack_compound( let row_adj = bh4 < 2 && mi_row % 2 == 1; let col_adj = bw4 < 2 && mi_col % 2 == 1; - let max_row_offset: isize = if mi_row > 0 { + // r1 (lane-mvtwin): availability and reach are TILE-relative, never + // frame-relative -- libaom's `xd->up_available`/`left_available` are + // `mi_row > tile->mi_row_start` / `mi_col > tile->mi_col_start`, and + // `find_valid_row_offset`/`find_valid_col_offset` (mvref_common.c:512-528) + // clamp the reach to `tile->mi_row_start - mi_row`. Clamping to the FRAME + // edge left `max_row_offset`/`max_col_offset` too long inside every tile + // that does not start at 0, which changes the row/col scan's `inc` weight + // (and so the stack ORDER) even though `MiGrid::get` already returns + // `None` for the cells outside the tile. + let (tile_row0, tile_col0) = grid.tile_origin(); + if tile_row0 > 0 || tile_col0 > 0 { + TILE_REACH_CLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); - reach.max(-(mi_row as isize)) + reach.max(tile_row0 as isize - mi_row as isize) } else { 0 }; - let max_col_offset: isize = if mi_col > 0 { + let max_col_offset: isize = if mi_col > tile_col0 { let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj); - reach.max(-(mi_col as isize)) + reach.max(tile_col0 as isize - mi_col as isize) } else { 0 }; let mut processed_rows = 0usize; let mut processed_cols = 0usize; - let found_above = mi_row > 0 + let found_above = max_row_offset.unsigned_abs() >= 1 && scan_row_compound( grid, mi_row, @@ -1561,7 +1654,7 @@ pub fn find_mv_stack_compound( &mut newmv_count, &mut processed_rows, ); - let found_left = mi_col > 0 + let found_left = max_col_offset.unsigned_abs() >= 1 && scan_col_compound( grid, mi_row, @@ -1802,7 +1895,8 @@ pub fn find_mv_stack_compound( // bump) — otherwise append `comp_list[0]` as a brand-new entry. When // the stack is empty, both `comp_list[0]` and `comp_list[1]` are // appended unconditionally, with no dedup check at all. - let comp_list = combine_compound_candidates(&lists); + let comp_list = + combine_compound_candidates(&lists, [gm_mv(gm, ref_frame.0), gm_mv(gm, ref_frame.1)]); if candidates.len() == 1 { let (mv0, mv1) = if comp_list[0] == (candidates[0].mv0, candidates[0].mv1) { comp_list[1] @@ -2824,7 +2918,7 @@ mod tests { // side 1 has only one entry -> comp_idx 1 falls back to ref_diff. lists.ref_diff[1].push((4, 4)); - let combined = combine_compound_candidates(&lists); + let combined = combine_compound_candidates(&lists, [(0, 0), (0, 0)]); assert_eq!(combined[0], ((1, 1), (3, 3))); assert_eq!(combined[1], ((2, 2), (4, 4))); } @@ -2911,4 +3005,91 @@ mod tests { assert_eq!(stack.entries[1].mv0, (-3, -3)); assert_eq!(stack.entries[1].mv1, (7, 7)); } + + /// lane-mvtwin r1, defect 1 (twin drift, compound only): libaom fills a + /// `comp_list` slot past both `ref_id`/`ref_diff` lists with THAT SIDE's + /// own `gm_mv_candidates[idx]` (mvref_common.c:718-719). This module + /// filled it with `(0, 0)`, which is only accidentally right while every + /// live reference's global motion is IDENTITY -- the single-ref twin had + /// already closed the same gap on its own `mv_ref_list` tail in r6. + #[test] + fn a_missing_compound_combine_slot_takes_that_sides_global_mv_not_zero() { + let lists = CompoundRefLists::default(); + let combined = combine_compound_candidates(&lists, [(9, -5), (-11, 3)]); + assert_eq!(combined[0], ((9, -5), (-11, 3))); + assert_eq!(combined[1], ((9, -5), (-11, 3))); + // One side supplied, the other short: only the short side falls back. + let mut half = CompoundRefLists::default(); + half.ref_id[0].push((1, 2)); + let combined = combine_compound_candidates(&half, [(9, -5), (-11, 3)]); + assert_eq!(combined[0], ((1, 2), (-11, 3))); + assert_eq!(combined[1], ((9, -5), (-11, 3))); + } + + /// lane-mvtwin r1, defect 2 (both twins): libaom drops the 9th distinct + /// candidate AT INSERTION (`*refmv_count < MAX_REF_MV_STACK_SIZE`, + /// mvref_common.c:100/128/388/425). Pushing everything and truncating + /// after the weight sort keeps a different set: here the heavy 9th + /// candidate would survive and evict a scanned one. + #[test] + fn the_ninth_distinct_candidate_is_dropped_at_insertion_not_after_sorting() { + let mut candidates = Vec::new(); + for i in 0..MAX_STACK_SIZE as i32 { + add_candidate(&mut candidates, (i, i), 2); + } + let before = stack_full_drops(); + add_candidate(&mut candidates, (99, 99), 10_000); + assert_eq!(candidates.len(), MAX_STACK_SIZE); + assert!(!candidates.iter().any(|e| e.mv == (99, 99))); + assert_eq!(stack_full_drops(), before + 1); + // A full stack still takes the dedup weight bump libaom applies + // before the cap check. + add_candidate(&mut candidates, (0, 0), 6); + assert_eq!(candidates[0].weight, 8); + + let mut comp = Vec::new(); + for i in 0..MAX_STACK_SIZE as i32 { + add_compound_candidate(&mut comp, (i, i), (i, -i), 2); + } + add_compound_candidate(&mut comp, (99, 99), (99, 99), 10_000); + assert_eq!(comp.len(), MAX_STACK_SIZE); + } + + /// lane-mvtwin r1, defect 3 (both twins): the row/col reach is clamped to + /// the TILE origin (`find_valid_row_offset`, mvref_common.c:512-528), not + /// the frame edge. `MiGrid::get` already hides the out-of-tile cells, so + /// the only visible symptom is the scan WEIGHT (`inc`) -- and through it + /// the stack order. Query at mi_row 9 with the tile starting at row 8: + /// the real reach is -1, so `inc = 1` and the weight stays at the floor + /// 2; the frame-edge clamp gave -6, `inc = min(6, size_h) = 4`, doubling + /// the vote. + #[test] + fn the_row_reach_is_clamped_to_the_tile_origin_not_the_frame_edge() { + let weight_with_tile_origin = |row0: usize| { + // A neighbour at least as wide as the query block (`bw4 <= n4`) + // is what makes libaom compute `inc` at all. + let wide = MiInfo { + size: 4, + size_h: 4, + ..inter((5, 5)) + }; + let mut grid = MiGrid::new(16, 16); + grid.set(8, 4, wide); + grid.set(8, 6, wide); + grid.set_tile_bounds(row0, 0, 16, 16); + let stack = find_mv_stack(&grid, 9, 4, 2, 2, LAST_FRAME, 16, 16); + assert_eq!(stack.entries.len(), 1); + stack.entries[0].weight + }; + let tiled = weight_with_tile_origin(8); + let whole_frame = weight_with_tile_origin(0); + // One scanned row cell (`end_mi == bw4 == 2`, `len == 2`) plus the + // top-right probe's own flat `CORNER_WEIGHT`, which the reach never + // touches -- so the whole delta below is the row scan's `inc`. + // reach -1 -> inc 1 -> weight stays at the floor 2. + assert_eq!(tiled, REF_CAT_LEVEL + 2 * 2 + CORNER_WEIGHT); + // frame-edge clamp: reach -6 -> inc min(6, size_h) = 4. + assert_eq!(whole_frame, REF_CAT_LEVEL + 2 * 4 + CORNER_WEIGHT); + assert_ne!(tiled, whole_frame); + } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index ea1161a6..b342cf72 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -14365,6 +14365,299 @@ mod tests { a_real_aomenc_temporal_mv_gate(42, 40); } + /// lane-mvtwin r1: the COMPOUND MV-stack gate. Every other compound gate + /// here pins `--enable-ref-frame-mvs=0`, so `find_mv_stack_compound`'s + /// temporal half (the three `tpl_sample_pos` extension samples lane-sb128 + /// r3 found missing) and its extension pass have never been exercised by + /// a real encoder. This arm turns ref-frame-mvs ON, gives the encoder a + /// 25-frame lookahead plus alt-refs so `reference_select` really drives + /// blocks to COMPOUND_REFERENCE, and sweeps global motion off/on so the + /// combine step's `gm_mv_candidates` fill (r1 defect 1) is reachable. + /// + /// Firing proof, hard-asserted: `decode::comp_mode_hits` (a real + /// compound block) AND `mvstack::tmv_hits` (a temporal candidate landed + /// in some stack) must BOTH have advanced on an attempt that also + /// decoded pixel-exact -- class [[gate-skips-on-its-own-failure]]: a + /// decode that succeeds is ALWAYS compared, on every decode-order frame, + /// and only the counters decide whether the attempt counts. + fn a_real_aomenc_compound_mv_stack_gate( + gate_name: &str, + seed_base: u32, + attempts: u32, + bit_depth: u32, + sb_size: u32, + global_motion: u32, + width: usize, + tile_columns: u32, + ) { + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {gate_name}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); + return; + } + let (height, frame_count) = (64usize, 16usize); + let mut never_fired = 0u32; + let mut refusals = Vec::new(); + for attempt in 0..attempts { + let seed = seed_base + 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", + if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }, + "-strict", + "-1", + "-t", + "0.64", + "-f", + "yuv4mpegpipe", + "-strict", + "-1", + "-", + ]) + .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 depth_args: &[&str] = if bit_depth == 10 { + &["-b", "10", "--input-bit-depth=10"] + } else { + &[] + }; + // The cq sweep: how finely RD partitions decides how often a + // block's stack comes up short enough to reach the extension + // pass at all. + let cq = format!("--cq-level={}", [45u32, 55, 35][(attempt % 3) as usize]); + let sb = format!("--sb-size={sb_size}"); + let gm = format!("--enable-global-motion={global_motion}"); + // `--tile-columns` is log2: 1 means two tile columns, which is + // what makes every block in the right-hand tile carry a nonzero + // `tile_col0` and so exercise r1 defect 3's reach clamp. + let tiles = format!("--tile-columns={tile_columns}"); + // class [[aomenc-last-flag-wins]]: every flag appears exactly + // once below, so there is no override to order. + let out = { + let mut child = Command::new(aomenc_path()) + .args(depth_args) + .arg(&cq) + .arg(&sb) + .arg(&gm) + .arg(&tiles) + .args([ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + // What this gate is about: real compound references + // with a real temporal MV field behind them. + "--enable-ref-frame-mvs=1", + "--enable-order-hint=1", + "--auto-alt-ref=1", + "--lag-in-frames=25", + "--enable-fwd-kf=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--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", + "--obu", + "-o", + "-", + "-", + ]) + .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"); + 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 (before_comp, before_tmv) = (decode::comp_mode_hits(), decode::tmv_hits()); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{gate_name} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let counted = + decode::comp_mode_hits() != before_comp && decode::tmv_hits() != before_tmv; + if !counted { + never_fired += 1; + } + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + // EVERY decode-order frame compared, never just the shown ones + // (class [[gate-blind-to-hidden-frames]]). + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{gate_name} frame {i} U vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{gate_name} frame {i} V vs ffmpeg (seed {seed})" + ); + } + if counted { + eprintln!( + "{gate_name} FIRING seed {seed}: comp_mode_hits +{}, tmv_hits +{}, \ + comp_gm_fill_hits={}, stack_full_drops={}, tile_reach_clips={}", + decode::comp_mode_hits() - before_comp, + decode::tmv_hits() - before_tmv, + crate::mvstack::comp_gm_fill_hits(), + crate::mvstack::stack_full_drops(), + crate::mvstack::tile_reach_clips(), + ); + gate_buckets(gate_name, 1, never_fired, refusals.len()); + return; + } + } + gate_buckets(gate_name, 0, never_fired, refusals.len()); + eprintln!( + "SKIP {gate_name}: {never_fired} attempts decoded but never drove a compound block \ + with a temporal MV candidate, and every other attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + #[test] + fn a_real_aomenc_compound_mv_stack_with_temporal_mvs_decodes_pixel_exact() { + a_real_aomenc_compound_mv_stack_gate( + "a_real_aomenc_compound_mv_stack_with_temporal_mvs_decodes_pixel_exact", + 42, + 30, + 8, + 64, + 0, + 64, + 0, + ); + } + + #[test] + fn a_real_aomenc_compound_mv_stack_with_global_motion_decodes_pixel_exact() { + a_real_aomenc_compound_mv_stack_gate( + "a_real_aomenc_compound_mv_stack_with_global_motion_decodes_pixel_exact", + 80, + 30, + 8, + 64, + 1, + 64, + 0, + ); + } + + #[test] + fn a_real_aomenc_10bit_compound_mv_stack_at_128_superblocks_decodes_pixel_exact() { + a_real_aomenc_compound_mv_stack_gate( + "a_real_aomenc_10bit_compound_mv_stack_at_128_superblocks_decodes_pixel_exact", + 120, + 30, + 10, + 128, + 1, + 64, + 0, + ); + } + + /// KNOWN OPEN DEFECT, found by lane-mvtwin r1 and NOT caused by it: a + /// real aomenc stream 128 px wide with `--tile-columns=1` (two 64-px tile + /// columns) mis-decodes frame 1's luma against ffmpeg, at seed 200 with + /// this exact recipe. ABLATION-PROVEN pre-existing: the same arm fails + /// identically with r1's tile-origin reach clamp + /// (`MiGrid::tile_origin`) forced back to `(0, 0)`, so the cause is + /// somewhere else in the multi-tile path, not in `mvstack`. Kept as the + /// exact reproducer for the lane that owns tiles -- it is `#[ignore]`d + /// rather than deleted so the repro command survives: + /// `cargo test -p ec-av1 --lib across_two_tile_columns -- --ignored --nocapture`. + /// + /// It is also the ONLY arm that reaches r1 defect 3 (the col reach is + /// clamped to `tile_col0`, not the frame edge): the counter + /// `mvstack::tile_reach_clips` advanced to 60 on this stream. Defect 3 + /// itself is proven deterministically by + /// `mvstack::tests::the_row_reach_is_clamped_to_the_tile_origin_not_the_frame_edge`. + #[test] + #[ignore = "known pre-existing multi-tile-column decode defect, see doc comment"] + fn a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact() { + let name = "a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact"; + let before = crate::mvstack::tile_reach_clips(); + a_real_aomenc_compound_mv_stack_gate(name, 200, 30, 8, 64, 0, 128, 1); + assert!( + crate::mvstack::tile_reach_clips() > before, + "{name}: no block was ever built inside a tile past mi 0 -- \ + --tile-columns=1 did not produce a second tile column" + ); + } + /// bisect scratch: decode a pinned stream exactly once -- generic /// pin-repro tool, kept for manual use. #[test] diff --git a/lanes/mvtwin-r1.report.md b/lanes/mvtwin-r1.report.md new file mode 100644 index 00000000..46231957 --- /dev/null +++ b/lanes/mvtwin-r1.report.md @@ -0,0 +1,86 @@ +# lane-mvtwin r1 — phase-by-phase diff of the two MV-stack twins vs libaom + +Base: lane-sb128 5ea5ec8, merged main 7a47fc1 (clean; the 128x128-superblock +refusal main re-added at b51719f stayed deleted — grep confirms). +Oracle: `~/.cache/aom-oracle/src/av1/common/mvref_common.c` (`setup_ref_mv_list`, +`av1_find_mv_refs`). Ours: `crates/ec-av1/src/mvstack.rs` +(`find_mv_stack_with_sign_bias` = single-ref twin, `find_mv_stack_compound` = compound twin). + +## The table (libaom line = mvref_common.c) + +| # | phase (libaom) | single-ref ours | compound ours | defect? | +|---|---|---|---|---| +| 1 | `row_adj`/`col_adj`, `find_valid_row/col_offset` reach (:502-533) | mvstack.rs:809 | mvstack.rs:1610 | **DEFECT 3** — both clamped the reach to the FRAME edge, libaom clamps to `tile->mi_row_start`/`mi_col_start` | +| 2 | `scan_row_mbmi` immediate, `len`/`weight`/`inc`/`processed_rows` (:141-190, :534-538) | `scan_row` :471 | `scan_row_compound` :1290 | exact (availability gate was `mi_row > 0`, folded into defect 3) | +| 3 | `scan_col_mbmi` (:192-236, :540-543) | `scan_col` :553 | `scan_col_compound` :1347 | exact | +| 4 | `has_top_right` + top-right `scan_blk_mbmi` (:264-312, :496, :544-548) | `scan_top_right` :645 | `scan_top_right_compound` :1403 | no change — see "has_tr" below | +| 5 | `nearest_match`, `REF_CAT_LEVEL` boost over `nearest_refmv_count` (:550-555) | :836 | :1600 | exact | +| 6 | `add_tpl_ref_mv` main loop, `step_h`/`step_w`/`blk_*_end` (:557-589) | :868 | :1625 | exact (compound reads the field once per side; `motion_field.rs:500` makes the lookup offset-independent, so both sides are Some/None together — libaom's single lookup) | +| 7 | `tpl_sample_pos` 3 extension samples + `check_sb_border` (:591-600, :316) | :898 | :1670 (added lane-sb128 r3) | exact — the twin drift r3 found, now symmetric | +| 8 | `GLOBALMV_OFFSET` / `zero_mv_ctx` far-or-missing test (:375-380, :406-412, :592) | :955 | :1750 | exact | +| 9 | corner `scan_blk_mbmi(-1,-1)` with `dummy_newmv_count`, weight `2*len`=4 (:604-607) | :967 | :1758 | exact | +| 10 | extended row/col scan `idx = 2..=MVREF_ROW_COLS` (:609-622) | :990 | :1770 | exact | +| 11 | `ref_match_count` + `mode_context` switch / `REFMV_OFFSET` (:624-651) | :1140 | :1858 | exact | +| 12 | the TWO bubble passes (nearest region, then the rest) (:653-682) | single stable `sort_by_key` :1050 | same :1802 | not a defect — every nearest entry carries `+REF_CAT_LEVEL` (640) and no post-boost entry can reach it (max post-boost weight seen is `len*weight` <= 80), so the two-phase ranking and one stable global sort agree | +| 13 | insertion cap `*refmv_count < MAX_REF_MV_STACK_SIZE` (:100, :128, :388, :425) | `add_candidate` :341 | `add_compound_candidate` :1268 | **DEFECT 2** — both pushed unbounded then sorted+truncated, keeping a different set than libaom's drop-at-insertion | +| 14 | `mi_size` = min(64x64 span, block span, frame edge) (:684-689) | :1060 | :1815 | exact | +| 15 | `process_compound_ref_mv_candidate`, sign-bias inversion, `can_rf > INTRA_FRAME` (:434-470, :693-706) | n/a | :1478 | exact | +| 16 | `comp_list` combine, slots past both lists = `gm_mv_candidates[idx]` (:708-720) | n/a | `combine_compound_candidates` :1520 | **DEFECT 1 (twin drift)** — filled `(0, 0)`; the single-ref twin closed the same gm-fallback gap in r6 | +| 17 | compound stack merge, `refmv_count==1` dedupe vs empty (:722-742) | n/a | :1845 | exact | +| 18 | `clamp_mv_ref` + `MV_BORDER`, every entry (:745-751, :768-772) | :1105 | :1878 | exact | +| 19 | single-ref extension gated per step on `MAX_MV_REF_CANDIDATES` (:754-766) | :1065 | n/a | exact | +| 20 | `mv_ref_list` tail filled with `gm_mv_candidates[0]`, unclamped (:775-782) | :1128 | n/a (libaom has no compound `mv_ref_list`) | exact | + +### has_tr (phase 4), why no change +Ours probes "is the grid cell at `(mi_row-1, mi_col+bw4)` populated", which for a +decoder is exactly "was it decoded". Walking libaom's mask logic: for SQUARE blocks +the mask result and "already decoded" coincide at both sb64 and sb128; for the +rect case that differs (`bs > 16` at a 64x128 block) libaom's own +`is_last_vertical_rect` refinement forces `has_tr = 1` again, agreeing with our +probe. Porting the mask WITHOUT the three shape refinements (which need the +partition type, not passed to this module) would REGRESS the VERT-rect case. +Recorded as the same corner-cut already documented at `mvstack.rs:588`; +upgrade path = thread the partition type in with the rect inter leaf. + +## Fixes (all in crates/ec-av1/src/mvstack.rs) +- D1 `combine_compound_candidates` (:1520 + call site :1859): unfilled slots take + `gm_mv(gm, ref_frame.side)`, not `(0, 0)` (mvref_common.c:718-719). +- D2 `add_candidate` (:341) / `add_compound_candidate` (:1268): drop the 9th + distinct candidate AT INSERTION (mvref_common.c:100/128/388/425); the dedup + weight bump still applies on a full stack. +- D3 both twins (:809, :1610) + new `MiGrid::tile_origin` (:216): reach and + availability are tile-relative (mvref_common.c:512-533). + +## Checks +`cargo test -p ec-av1 --lib mvstack::` -> 32 passed, 0 failed. Three new +deterministic tests, one per defect: +- `a_missing_compound_combine_slot_takes_that_sides_global_mv_not_zero` +- `the_ninth_distinct_candidate_is_dropped_at_insertion_not_after_sorting` +- `the_row_reach_is_clamped_to_the_tile_origin_not_the_frame_edge` (644 -> 648 vs 652) + +New real-aomenc gate `a_real_aomenc_compound_mv_stack_gate` (stream.rs), the first +compound gate here that does NOT pin `--enable-ref-frame-mvs=0`: +`--enable-ref-frame-mvs=1 --enable-order-hint=1 --auto-alt-ref=1 --lag-in-frames=25`, +cq sweep 45/55/35, 30 seeds/arm, hard-asserting BOTH `comp_mode_hits` and +`tmv_hits` advanced, every decode-order frame compared (Y/U/V) against ffmpeg, +decode errors only tolerated when the message contains "unsupported". +Arms: 8-bit sb64 gm=0 · 8-bit sb64 gm=1 · 10-bit sb128 gm=1. + +EVIDENCE: $HOME/.cache/mvtwin-suite-r1.log | cargo test -p ec-av1 --lib compound_mv_stack -- --test-threads=1 --nocapture | 3 arms FIRING pixel-exact: seed 44 comp_mode_hits +7 tmv_hits +56; seed 80 comp_mode_hits +1 tmv_hits +56; seed 122 (10-bit, sb128) comp_mode_hits +8 tmv_hits +55 +EVIDENCE: crates/ec-av1/src/mvstack.rs tests | cargo test -p ec-av1 --lib mvstack:: | 32 passed 0 failed, each of the 3 defects asserted on its own values + +## Open residue +- fix-now-elsewhere (NOT this lane's surface): a real aomenc stream 128 px wide + with `--tile-columns=1` MIS-DECODES frame 1 luma vs ffmpeg (seed 200, recipe in + `a_real_aomenc_compound_mv_stack_across_two_tile_columns_decodes_pixel_exact`, + `#[ignore]`d with the repro command in its doc). ABLATION-PROVEN pre-existing: + identical failure with r1's tile-origin clamp forced back to `(0, 0)`. That arm + is also the only one that reaches defect 3 on a real stream — + `mvstack::tile_reach_clips` advanced to 60 there. +- deferred(a stream whose compound pair names a non-IDENTITY ROTZOOM/AFFINE + reference) — `comp_gm_fill_hits` reads 0 on all three green arms, so D1 is + proven by its unit test, not yet by a real stream. aomenc at gradients content + keeps global motion IDENTITY even with `--enable-global-motion=1`. +- deferred(same) — `stack_full_drops` reads 0 on all three arms: no real block + here produced 9 distinct candidates. D2 is unit-test-proven only. +- accepted — `has_tr` corner-cut (phase 4 above), ceiling and upgrade path named.