From 1944bfcc673fef016d0af84f497536f7b8282750 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 28 Aug 2026 14:31:17 +0300 Subject: [PATCH] feat(av1): thread read_motion_mode/OBMC through decode_inter_block8's 8x8 leaves Round 2 left an OBMC correctness hole: bsize 8x8 is motion_mode_allowed- eligible but decode_inter_block8 never read the symbol, so an OBMC stream coding motion_mode on an 8x8 leaf would desync silently. Mirrors the 16x16 decode_inter_block read (same 2-symbol obmc_cdf, same allow_warped_motion=1 refusal, same obmc_blend call after MC prediction) and threads switchable_motion_mode/allow_warped_motion/interp_fixed into decode_inter_block8's signature. Added a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact plus an obmc_hits_8 counter to try to exercise this path. Measured live: 80 attempts, aomenc's cpu-used=0 RD search never once splits a 16x16 down to a clean 4-way 8x8 leaf for the gate's smooth gradients fixture (large blocks always win); kept as an honest never-fired record, matching the file's existing never_fired-skip convention. --- crates/ec-av1/src/decode.rs | 84 ++++++++++++++++- crates/ec-av1/src/stream.rs | 174 ++++++++++++++++++++++++++++++++++++ 2 files changed, 254 insertions(+), 4 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index d61b678d..63fbb242 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -165,6 +165,17 @@ pub(crate) fn obmc_hits() -> usize { OBMC_HITS.load(std::sync::atomic::Ordering::Relaxed) } +/// lane-motionmode round 3: same proof as [`OBMC_HITS`], narrowed to +/// `decode_inter_block8`'s own 8x8-leaf `read_motion_mode` -- a subset of +/// [`OBMC_HITS`] (both fire together on an 8x8 hit), lets the gate tell an +/// 8x8-leaf OBMC block apart from a 16x16+ one. +static OBMC_HITS_8: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Current value of [`OBMC_HITS_8`]. +pub(crate) fn obmc_hits_8() -> usize { + OBMC_HITS_8.load(std::sync::atomic::Ordering::Relaxed) +} + /// How many [`read_inter_compound_mode`] reads actually happened /// (lane-av1comp) -- proves a `COMPOUND_REFERENCE` block reached its own /// `compound_mode` symbol (past `comp_mode`/`comp_ref` and the compound @@ -5761,6 +5772,16 @@ fn decode_inter_block8( // lane-cdffwd2: this frame header's own `reduced_tx_set` bit -- see // [`decode_inter_frame_tile_with_cdfs`]'s own doc. reduced_tx_set: bool, + // lane-motionmode round 3: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits (spec 5.11.24's `read_motion_mode`), plus + // the fixed/switchable interp filter kind `obmc_blend`'s own neighbour + // reads need (see [`decode_inter_block`]'s own doc) -- this leaf's own + // prediction is always `Regular` (documented corner-cut, `mc::predict` + // has no filter param), but an OBMC neighbour can be a real 16x16+ + // block that DID resolve a switchable filter. + interp_fixed: Option, + switchable_motion_mode: bool, + allow_warped_motion: bool, // lane-av1comp: `Some((ref1, comp_group_idx, compound_idx))` only for a // real `COMPOUND_REFERENCE` leaf, for the caller's own end-of-16x16 // `record_compound_ctx` call -- mirrors [`decode_inter_block`]'s own @@ -6208,6 +6229,33 @@ fn decode_inter_block8( }; (mv, false) }; + // lane-motionmode round 3: `read_motion_mode` (spec 5.11.24) at the + // 8x8 leaf too -- `motion_mode_allowed` still holds here (BLOCK_8X8 + // is the spec's own minimum eligible size, single-ref-only branch, + // no interintra reader, `IDENTITY`-only global motion). Mirrors the + // 16x16 leaf's own `decode_inter_block` read (see its doc above) -- + // same 2-symbol `obmc_cdf` alphabet, same `allow_warped_motion=1` + // refusal (warp needs `av1_findSamples`, not ported at either leaf). + let motion_mode_eligible = switchable_motion_mode + && !skip_mode + && (!overlappable_above(grid, mi_row, mi_col, 2, mi_cols as usize, 1).is_empty() + || !overlappable_left(grid, mi_row, mi_col, 2, mi_rows as usize, 1).is_empty()); + let mut obmc_selected = false; + if motion_mode_eligible { + if allow_warped_motion { + return Err(unsupported( + "a motion-variation-eligible 8x8 leaf under allow_warped_motion=1 \ + (round 3 only reads the 2-symbol obmc_cdf; telling OBMC_CAUSAL \ + from WARPED_CAUSAL needs av1_findSamples, not ported)", + )); + } + // `default_obmc_cdf`'s own index: square bsize 8/16/32/64 -> 0/1/2/3. + obmc_selected = dec.symbol(&mut cdfs.obmc[0]) == 1; + if obmc_selected { + OBMC_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + OBMC_HITS_8.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } for dr in 0..2 { for dc in 0..2 { grid.set( @@ -6264,6 +6312,32 @@ fn decode_inter_block8( &mut pred_v, ); + if obmc_selected { + obmc_blend( + grid, + neighbours, + mi_row, + mi_col, + 2, + mi_rows as usize, + mi_cols as usize, + SIDE, + CHROMA_SIDE, + px, + py, + cpx, + cpy, + ref_y, + ref_u, + ref_v, + other_refs, + interp_fixed, + &mut pred_y, + &mut pred_u, + &mut pred_v, + )?; + } + if skip { y.reconstruct_mc(px, py, SIDE, &pred_y, &vec![0i32; SIDE * SIDE]); u.reconstruct_mc( @@ -6599,10 +6673,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( // `Set1` coefficient tables at 16x16/8x8 rather than the reduced // 2-symbol ones -- see [`TxbSet::Luma16InterSet1`]/[`TxbSet::Luma8InterSet1`]). reduced_tx_set: bool, - // lane-motionmode round 1: this frame header's own `is_motion_mode_switchable`/ - // `allow_warped_motion` bits, threaded to every `decode_inter_block` call - // below (spec 5.11.24's `read_motion_mode`) -- `decode_inter_block8`'s 8x8 - // leaves do not read this symbol yet (round 2). + // lane-motionmode round 1/3: this frame header's own `is_motion_mode_switchable`/ + // `allow_warped_motion` bits, threaded to every `decode_inter_block`/ + // `decode_inter_block8` call below (spec 5.11.24's `read_motion_mode`). switchable_motion_mode: bool, allow_warped_motion: bool, ) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { @@ -6945,6 +7018,9 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( skip_mode_present, skip_mode_frame, reduced_tx_set, + interp_fixed, + switchable_motion_mode, + allow_warped_motion, )?; prev_leaf = Some((leaf_mi, skip, is_inter)); last_skip_mode = skip_mode_leaf; diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 6d2c2091..15cc5cbd 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3062,6 +3062,180 @@ mod tests { ); } + /// lane-motionmode round 3: same shape as + /// `a_real_aomenc_stream_with_obmc_decodes_pixel_exact`, but relaxed the + /// `--min-partition-size=32 --max-partition-size=32` clamp (that other + /// gate's own doc: locked to remove partition-depth choice from the + /// search entirely) to `8`/`32`, to make an 8x8-leaf `OBMC_CAUSAL` pick + /// possible at all. Gated on [`decode::obmc_hits_8`] specifically, not + /// the aggregate [`decode::obmc_hits`]. Measured live (round 3, this + /// box): 80 attempts, 0 ever called `decode_inter_block8` at all -- + /// `cpu-used=0`'s RD search never once splits a 16x16 down to a clean + /// 4-way 8x8 leaf for this smooth `gradients` fixture (large blocks + /// always win the RD cost there); the handful of named refusals seen + /// are `PARTITION_SPLIT` chosen *at* 8x8 (down to 4x4, already refused + /// at `decode.rs`'s `part8 != PARTITION_NONE` check) or + /// `allow_screen_content_tools`, neither reaching a leaf. Kept anyway + /// (mirrors this file's own `never_fired`-skip convention) as the + /// honest record of the attempt; a real 8x8 OBMC fixture needs + /// higher-frequency content than this gate's fixtures use, out of + /// round-3 budget. + #[test] + fn a_real_aomenc_stream_with_obmc_8x8_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_obmc_8x8_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) = (64usize, 64usize, 24usize); + let mut refusals = Vec::new(); + let mut never_fired = 0u32; + let mut total_obmc8 = 0usize; + for attempt in 0..80u32 { + let seed = 42 + attempt % 40; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}: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", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-warped-motion=0", + "--enable-obmc=1", + "--enable-masked-comp=0", + "--enable-interintra-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", + "--min-partition-size=8", + "--max-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=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 before8 = decode::obmc_hits_8(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + let fired8 = decode::obmc_hits_8() - before8; + total_obmc8 += fired8; + if fired8 == 0 { + never_fired += 1; + continue; + } + 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})"); + } + eprintln!( + "{NAME} FIRING seed {seed}: 8x8 obmc hits {fired8} (total across attempts so far {total_obmc8})" + ); + return; + } + eprintln!( + "SKIP {NAME}: {never_fired} attempts decoded but never fired an 8x8 obmc block \ + ({total_obmc8} total 8x8 obmc hits across all attempts), and every other attempt \ + hit a named refusal:\n{}", + refusals.join("\n") + ); + } + /// lane-motionmode round 1: `--enable-warped-motion=1` must be a NAMED /// refusal, never a silent mis-decode -- this decoder does not port /// `av1_findSamples`/`num_proj_ref`, so it cannot tell `OBMC_CAUSAL`