From 718eababa6a07bb264c9d68e2b11483b18e86730 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 05:37:25 +0300 Subject: [PATCH] fix(av1): motion_field_projection returns 0 for a key/intra start frame, so a forward key frame no longer spends a ref_stamp slot; av1_copy_frame_mvs clear ported --- crates/ec-av1/src/decode.rs | 13 ++- crates/ec-av1/src/motion_field.rs | 79 ++++++++++++++-- crates/ec-av1/src/stream.rs | 147 ++++++++++++++++++++++++++++++ 3 files changed, 229 insertions(+), 10 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 1239ae48..be9afd3a 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1748,7 +1748,7 @@ pub(crate) fn build_motion_field( ref_order_hints: [u32; 7], ) -> crate::motion_field::MotionField { let mut field = - crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints); + crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false); // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block @@ -1771,7 +1771,14 @@ pub(crate) fn build_motion_field( let Some(info) = grid.get(row, col) else { continue; }; + // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and + // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`), + // so an intra block -- or an inter block whose every slot is on the + // other side / over the limit -- wipes what an earlier block wrote + // into the same 8x8 cell (only reachable from sub-8x8 leaves, which + // share a cell). if !info.is_inter { + field.set(row, col, None); continue; } // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST @@ -1797,9 +1804,7 @@ pub(crate) fn build_motion_field( } saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf }); } - if let Some(saved) = saved { - field.set(row, col, saved); - } + field.set(row, col, saved); } } field diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index 7768f7ac..330a5e97 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -31,13 +31,23 @@ pub struct MotionField { cells: Vec>, pub order_hint: u32, pub ref_order_hints: [u32; 7], + /// libaom `motion_field_projection`'s own first test: a start frame whose + /// `frame_type` is `KEY_FRAME`/`INTRA_ONLY_FRAME` is never projected at + /// all (`return 0`), so it also never spends a `ref_stamp` slot. + pub is_intra: bool, } impl MotionField { /// A field sized for an `mi_cols` by `mi_rows` frame, all cells /// initially unset (spec 7.9's own reset to `-1`/invalid before any /// block writes into it). - pub fn new(mi_cols: usize, mi_rows: usize, order_hint: u32, ref_order_hints: [u32; 7]) -> Self { + pub fn new( + mi_cols: usize, + mi_rows: usize, + order_hint: u32, + ref_order_hints: [u32; 7], + is_intra: bool, + ) -> Self { let cols = mi_cols.div_ceil(2); let rows = mi_rows.div_ceil(2); Self { @@ -46,6 +56,7 @@ impl MotionField { cells: vec![None; cols * rows], order_hint, ref_order_hints, + is_intra, } } @@ -53,10 +64,14 @@ impl MotionField { /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution /// write. - pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: SavedMv) { + /// `saved == None` is `av1_copy_frame_mvs`'s own leading clear + /// (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which every block + /// of an inter frame performs -- an intra (or nothing-to-store) block + /// sharing an 8x8 cell with an earlier inter one wipes that cell. + pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: Option) { let (r, c) = (mi_row / 2, mi_col / 2); if r < self.rows && c < self.cols { - self.cells[r * self.cols + c] = Some(saved); + self.cells[r * self.cols + c] = saved; } } @@ -217,6 +232,14 @@ fn motion_field_projection( dir: u8, tpl_cells: &mut [Option<((i32, i32), i32)>], ) -> bool { + // libaom's own first two `return 0`s, in order: a key/intra-only start + // frame is never projected (and so never spends a `ref_stamp` slot -- + // returning `true` here made a forward key frame, `--enable-fwd-kf=1`, + // consume the slot ALTREF/LAST2 should have had), then the frame-size + // test. + if start.is_intra { + return false; + } let mvs_rows = mi_rows.div_ceil(2); let mvs_cols = mi_cols.div_ceil(2); if start.rows != mvs_rows || start.cols != mvs_cols { @@ -264,6 +287,24 @@ fn motion_field_projection( true } +thread_local! { + /// Frames whose `av1_setup_motion_field` saw at least one forward + /// references holding a key/intra-only frame -- the `ref_stamp` path + /// [`motion_field_projection`]'s intra early return governs. + static REFSTAMP_INTRA_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The subset of those frames with TWO or more such references. + static REFSTAMP_INTRA2_FRAMES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Reads the counter above (gate +/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`). +pub fn refstamp_intra_frames() -> (usize, usize) { + ( + REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get), + REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get), + ) +} + /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when @@ -287,6 +328,11 @@ pub fn setup_motion_field( let cols = mi_cols.div_ceil(2); let rows = mi_rows.div_ceil(2); let mut cells = vec![None; cols * rows]; + // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;` + // leaves every `tpl_mvs` cell INVALID. + if order_hint_bits == 0 { + return TplField { cols, rows, cells }; + } let slot_of = |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref(); @@ -294,6 +340,27 @@ pub fn setup_motion_field( let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 + // Gate counter (lane-refstamp): frames whose forward references include at + // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the + // early return above fixes. + let intra_forward_refs = [ + BWDREF_FRAME, + crate::mvstack::ALTREF2_FRAME, + ALTREF_FRAME, + ] + .into_iter() + .filter(|&rf| { + get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0 + && slot_of(rf).is_some_and(|m| m.is_intra) + }) + .count(); + if intra_forward_refs >= 1 { + REFSTAMP_INTRA_FRAMES.with(|c| c.set(c.get() + 1)); + } + if intra_forward_refs >= 2 { + REFSTAMP_INTRA2_FRAMES.with(|c| c.set(c.get() + 1)); + } + if let Some(last) = slot_of(LAST_FRAME) { let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize]; let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME); @@ -464,14 +531,14 @@ mod tests { // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV // against its own LAST_FRAME (order_hint 1). The current frame // (order_hint 4) names that same slot as *its* LAST_FRAME. - let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0]); + let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0], false); mf.set( 0, 0, - SavedMv { + Some(SavedMv { mv: (-64, 0), ref_frame: LAST_FRAME, - }, + }), ); let slots: [Option; 8] = std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None }); diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index f7aab93d..5e5baf7a 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -616,6 +616,9 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.mi_rows as usize, header.order_hint, ref_order_hints, + // `frame_type` for the DPB slot: a key (or intra-only) frame is + // never a projection source, and never spends a `ref_stamp`. + true, ); (picture, end_cdfs, motion_field) } else { @@ -4881,6 +4884,150 @@ mod tests { } } + /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the + /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only + /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF) + /// holds a key frame while temporal MV projection runs. libaom's + /// `motion_field_projection` returns 0 for such a start frame, so it costs + /// no `ref_stamp`; ours used to project the (empty) field and report + /// success, spending the slot ALTREF/LAST2 should have had and losing + /// their temporal candidates. + /// + /// Both bit depths; EVERY decoded frame (including the hidden alt-refs) + /// compared to the oracle in decode order; a refusal is counted, never + /// SKIPped. Two hard counters make the gate non-vacuous: frames that + /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks + /// that folded a temporal MV candidate into their stack. + #[test] + fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_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, 24usize); + for bit_depth in [8u32, 10u32] { + let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) = + (0u32, 0u32, 0usize, 0usize); + let mut stamp2_proved = 0usize; + for attempt in 0..2u32 { + let duration = frame_count as f64 / 25.0; + // Natural-ish motion: structure translating along X at 3 px per + // frame plus a slow vertical drift, the source family the + // temporal-MV gate already decodes fully. + let source = format!( + "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\ + geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p" + ); + let pix_fmt = if bit_depth == 10 { "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(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 }); + let args: Vec<&str> = vec![ + "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0", + "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg, + "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0", + "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0", + "--enable-rect-partitions=1", "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", "--min-partition-size=16", + "--max-partition-size=32", + // Per-arm/feature overrides go LAST (aomenc keeps the LAST + // occurrence of a repeated --enable-* flag). + "--enable-order-hint=1", "--enable-ref-frame-mvs=1", + "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000", + "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=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 before_tmv = decode::tmv_hits(); + let before_stamp = crate::motion_field::refstamp_intra_frames(); + if let Err(e) = decode_stream(&stream) { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \ + attempt {attempt}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}"); + continue; + } + let tmv = decode::tmv_hits() - before_tmv; + let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0; + let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1; + // Every frame, hidden ones included, compared in DECODE order. + let (total, hidden) = decode_all_frames_vs_oracle( + &stream, + &format!("{NAME}-{bit_depth}bit-attempt{attempt}"), + ); + eprintln!( + "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \ + ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \ + forward ref={stamp} (two or more: {stamp2})" + ); + compared += 1; + tmv_proved += tmv; + stamp_proved += stamp; + stamp2_proved += stamp2; + } + assert!( + compared > 0, + "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \ + proved nothing" + ); + assert!( + tmv_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \ + into a block's stack -- gate proved nothing" + ); + assert!( + stamp_proved > 0, + "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \ + holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \ + path this gate exists for never ran" + ); + } + } + #[test] // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter // residual path IS implemented and reached, but no aomenc recipe swept