forge
Explore
Log in

Don't you dare go Hollow

Motion_field_projection returns 0 for a key/intra start frame, so a forward key frame no longer spends a ref_stamp slot

Browse files at this commit

718eababa6a07bb264c9d68e2b11483b18e86730Ahmet Kaan GümüşParent: 7c85bed
  • fix
    • 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
Show full message
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.rsmodified+9 -4
@@ -1748,7 +1748,7 @@ pub(crate) fn build_motion_field(
17481748 ref_order_hints: [u32; 7],
17491749 ) -> crate::motion_field::MotionField {
17501750 let mut field =
1751- crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
1751+ crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints, false);
17521752 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
17531753 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
17541754 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
@@ -1771,7 +1771,14 @@ pub(crate) fn build_motion_field(
17711771 let Some(info) = grid.get(row, col) else {
17721772 continue;
17731773 };
1774+ // `av1_copy_frame_mvs` runs for EVERY block of an inter frame and
1775+ // CLEARS the cells it covers first (`mv->ref_frame = NONE_FRAME`),
1776+ // so an intra block -- or an inter block whose every slot is on the
1777+ // other side / over the limit -- wipes what an earlier block wrote
1778+ // into the same 8x8 cell (only reachable from sub-8x8 leaves, which
1779+ // share a cell).
17741780 if !info.is_inter {
1781+ field.set(row, col, None);
17751782 continue;
17761783 }
17771784 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
@@ -1797,9 +1804,7 @@ pub(crate) fn build_motion_field(
17971804 }
17981805 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
17991806 }
1800- if let Some(saved) = saved {
1801- field.set(row, col, saved);
1802- }
1807+ field.set(row, col, saved);
18031808 }
18041809 }
18051810 field
crates/ec-av1/src/motion_field.rsmodified+73 -6
@@ -31,13 +31,23 @@ pub struct MotionField {
3131 cells: Vec<Option<SavedMv>>,
3232 pub order_hint: u32,
3333 pub ref_order_hints: [u32; 7],
34+ /// libaom `motion_field_projection`'s own first test: a start frame whose
35+ /// `frame_type` is `KEY_FRAME`/`INTRA_ONLY_FRAME` is never projected at
36+ /// all (`return 0`), so it also never spends a `ref_stamp` slot.
37+ pub is_intra: bool,
3438 }
3539
3640 impl MotionField {
3741 /// A field sized for an `mi_cols` by `mi_rows` frame, all cells
3842 /// initially unset (spec 7.9's own reset to `-1`/invalid before any
3943 /// block writes into it).
40- pub fn new(mi_cols: usize, mi_rows: usize, order_hint: u32, ref_order_hints: [u32; 7]) -> Self {
44+ pub fn new(
45+ mi_cols: usize,
46+ mi_rows: usize,
47+ order_hint: u32,
48+ ref_order_hints: [u32; 7],
49+ is_intra: bool,
50+ ) -> Self {
4151 let cols = mi_cols.div_ceil(2);
4252 let rows = mi_rows.div_ceil(2);
4353 Self {
@@ -46,6 +56,7 @@ impl MotionField {
4656 cells: vec![None; cols * rows],
4757 order_hint,
4858 ref_order_hints,
59+ is_intra,
4960 }
5061 }
5162
@@ -53,10 +64,14 @@ impl MotionField {
5364 /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single
5465 /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution
5566 /// write.
56- pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: SavedMv) {
67+ /// `saved == None` is `av1_copy_frame_mvs`'s own leading clear
68+ /// (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which every block
69+ /// of an inter frame performs -- an intra (or nothing-to-store) block
70+ /// sharing an 8x8 cell with an earlier inter one wipes that cell.
71+ pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: Option<SavedMv>) {
5772 let (r, c) = (mi_row / 2, mi_col / 2);
5873 if r < self.rows && c < self.cols {
59- self.cells[r * self.cols + c] = Some(saved);
74+ self.cells[r * self.cols + c] = saved;
6075 }
6176 }
6277
@@ -217,6 +232,14 @@ fn motion_field_projection(
217232 dir: u8,
218233 tpl_cells: &mut [Option<((i32, i32), i32)>],
219234 ) -> bool {
235+ // libaom's own first two `return 0`s, in order: a key/intra-only start
236+ // frame is never projected (and so never spends a `ref_stamp` slot --
237+ // returning `true` here made a forward key frame, `--enable-fwd-kf=1`,
238+ // consume the slot ALTREF/LAST2 should have had), then the frame-size
239+ // test.
240+ if start.is_intra {
241+ return false;
242+ }
220243 let mvs_rows = mi_rows.div_ceil(2);
221244 let mvs_cols = mi_cols.div_ceil(2);
222245 if start.rows != mvs_rows || start.cols != mvs_cols {
@@ -264,6 +287,24 @@ fn motion_field_projection(
264287 true
265288 }
266289
290+thread_local! {
291+ /// Frames whose `av1_setup_motion_field` saw at least one forward
292+ /// references holding a key/intra-only frame -- the `ref_stamp` path
293+ /// [`motion_field_projection`]'s intra early return governs.
294+ static REFSTAMP_INTRA_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
295+ /// The subset of those frames with TWO or more such references.
296+ static REFSTAMP_INTRA2_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
297+}
298+
299+/// Reads the counter above (gate
300+/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`).
301+pub fn refstamp_intra_frames() -> (usize, usize) {
302+ (
303+ REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get),
304+ REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get),
305+ )
306+}
307+
267308 /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to
268309 /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order
269310 /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when
@@ -287,6 +328,11 @@ pub fn setup_motion_field(
287328 let cols = mi_cols.div_ceil(2);
288329 let rows = mi_rows.div_ceil(2);
289330 let mut cells = vec![None; cols * rows];
331+ // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;`
332+ // leaves every `tpl_mvs` cell INVALID.
333+ if order_hint_bits == 0 {
334+ return TplField { cols, rows, cells };
335+ }
290336
291337 let slot_of =
292338 |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(
294340
295341 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
296342
343+ // Gate counter (lane-refstamp): frames whose forward references include at
344+ // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the
345+ // early return above fixes.
346+ let intra_forward_refs = [
347+ BWDREF_FRAME,
348+ crate::mvstack::ALTREF2_FRAME,
349+ ALTREF_FRAME,
350+ ]
351+ .into_iter()
352+ .filter(|&rf| {
353+ get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0
354+ && slot_of(rf).is_some_and(|m| m.is_intra)
355+ })
356+ .count();
357+ if intra_forward_refs >= 1 {
358+ REFSTAMP_INTRA_FRAMES.with(|c| c.set(c.get() + 1));
359+ }
360+ if intra_forward_refs >= 2 {
361+ REFSTAMP_INTRA2_FRAMES.with(|c| c.set(c.get() + 1));
362+ }
363+
297364 if let Some(last) = slot_of(LAST_FRAME) {
298365 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
299366 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
@@ -464,14 +531,14 @@ mod tests {
464531 // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV
465532 // against its own LAST_FRAME (order_hint 1). The current frame
466533 // (order_hint 4) names that same slot as *its* LAST_FRAME.
467- let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0]);
534+ let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0], false);
468535 mf.set(
469536 0,
470537 0,
471- SavedMv {
538+ Some(SavedMv {
472539 mv: (-64, 0),
473540 ref_frame: LAST_FRAME,
474- },
541+ }),
475542 );
476543 let slots: [Option<MotionField>; 8] =
477544 std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None });
crates/ec-av1/src/stream.rsmodified+147 -0
@@ -616,6 +616,9 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
616616 header.mi_rows as usize,
617617 header.order_hint,
618618 ref_order_hints,
619+ // `frame_type` for the DPB slot: a key (or intra-only) frame is
620+ // never a projection source, and never spends a `ref_stamp`.
621+ true,
619622 );
620623 (picture, end_cdfs, motion_field)
621624 } else {
@@ -4881,6 +4884,150 @@ mod tests {
48814884 }
48824885 }
48834886
4887+ /// lane-refstamp r1: `av1_setup_motion_field`'s `ref_stamp` budget in the
4888+ /// presence of FORWARD KEY FRAMES (`--enable-fwd-kf=1`), which is the only
4889+ /// configuration where a *forward* reference slot (BWDREF/ALTREF2/ALTREF)
4890+ /// holds a key frame while temporal MV projection runs. libaom's
4891+ /// `motion_field_projection` returns 0 for such a start frame, so it costs
4892+ /// no `ref_stamp`; ours used to project the (empty) field and report
4893+ /// success, spending the slot ALTREF/LAST2 should have had and losing
4894+ /// their temporal candidates.
4895+ ///
4896+ /// Both bit depths; EVERY decoded frame (including the hidden alt-refs)
4897+ /// compared to the oracle in decode order; a refusal is counted, never
4898+ /// SKIPped. Two hard counters make the gate non-vacuous: frames that
4899+ /// actually took the >=2-intra-forward-refs `ref_stamp` path, and blocks
4900+ /// that folded a temporal MV candidate into their stack.
4901+ #[test]
4902+ fn a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact() {
4903+ const NAME: &str = "a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact";
4904+ let _gate_lock = lock_gate_counters();
4905+ if !have_ffmpeg() {
4906+ eprintln!("SKIP {NAME}: no ffmpeg");
4907+ return;
4908+ }
4909+ if !have_aomenc() {
4910+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
4911+ return;
4912+ }
4913+ let (width, height, frame_count) = (192usize, 128usize, 24usize);
4914+ for bit_depth in [8u32, 10u32] {
4915+ let (mut named_refusals, mut compared, mut tmv_proved, mut stamp_proved) =
4916+ (0u32, 0u32, 0usize, 0usize);
4917+ let mut stamp2_proved = 0usize;
4918+ for attempt in 0..2u32 {
4919+ let duration = frame_count as f64 / 25.0;
4920+ // Natural-ish motion: structure translating along X at 3 px per
4921+ // frame plus a slow vertical drift, the source family the
4922+ // temporal-MV gate already decodes fully.
4923+ let source = format!(
4924+ "color=c=gray:s={width}x{height}:d={duration}:r=25,format=gray,\
4925+ geq=lum='128+58*sin((X+N*3)/6)+18*sin((Y+N*2)/23)',format=yuv420p"
4926+ );
4927+ let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" };
4928+ let y4m = Command::new("ffmpeg")
4929+ .args([
4930+ "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(),
4931+ "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-",
4932+ ])
4933+ .stdin(Stdio::null())
4934+ .stdout(Stdio::piped())
4935+ .stderr(Stdio::piped())
4936+ .output()
4937+ .expect("ffmpeg failed to run");
4938+ assert!(
4939+ y4m.status.success(),
4940+ "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}",
4941+ String::from_utf8_lossy(&y4m.stderr)
4942+ );
4943+ let depth_arg = format!("--bit-depth={bit_depth}");
4944+ let input_depth_arg = format!("--input-bit-depth={bit_depth}");
4945+ let cq_arg = format!("--cq-level={}", if attempt == 0 { 34 } else { 45 });
4946+ let args: Vec<&str> = vec![
4947+ "--codec=av1", "--passes=1", "--end-usage=q", &cq_arg, "--cpu-used=0",
4948+ "--threads=1", "--row-mt=0", "--sb-size=64", &depth_arg, &input_depth_arg,
4949+ "--enable-restoration=0", "--enable-palette=0", "--deltaq-mode=0",
4950+ "--enable-filter-intra=0", "--enable-cfl-intra=0", "--enable-intrabc=0",
4951+ "--enable-rect-partitions=1", "--enable-ab-partitions=0",
4952+ "--enable-1to4-partitions=0", "--min-partition-size=16",
4953+ "--max-partition-size=32",
4954+ // Per-arm/feature overrides go LAST (aomenc keeps the LAST
4955+ // occurrence of a repeated --enable-* flag).
4956+ "--enable-order-hint=1", "--enable-ref-frame-mvs=1",
4957+ "--enable-fwd-kf=1", "--fwd-kf-dist=8", "--kf-max-dist=1000",
4958+ "--lag-in-frames=16", "--auto-alt-ref=1", "--arnr-maxframes=0",
4959+ "--obu", "-o", "-", "-",
4960+ ];
4961+ let mut child = Command::new(aomenc_path())
4962+ .args(&args)
4963+ .stdin(Stdio::piped())
4964+ .stdout(Stdio::piped())
4965+ .stderr(Stdio::piped())
4966+ .spawn()
4967+ .expect("aomenc failed to start");
4968+ child
4969+ .stdin
4970+ .take()
4971+ .expect("aomenc stdin")
4972+ .write_all(&y4m.stdout)
4973+ .expect("writing y4m to aomenc");
4974+ let out = child.wait_with_output().expect("aomenc failed to run");
4975+ assert!(
4976+ out.status.success(),
4977+ "aomenc refused the fixture: {}",
4978+ String::from_utf8_lossy(&out.stderr)
4979+ );
4980+ let stream = out.stdout;
4981+ let before_tmv = decode::tmv_hits();
4982+ let before_stamp = crate::motion_field::refstamp_intra_frames();
4983+ if let Err(e) = decode_stream(&stream) {
4984+ let msg = e.to_string();
4985+ assert!(
4986+ msg.contains("unsupported"),
4987+ "{NAME} failed outright, not a named refusal ({bit_depth}-bit, \
4988+ attempt {attempt}): {msg}"
4989+ );
4990+ named_refusals += 1;
4991+ eprintln!("{bit_depth}-bit attempt {attempt} refusal: {msg}");
4992+ continue;
4993+ }
4994+ let tmv = decode::tmv_hits() - before_tmv;
4995+ let stamp = crate::motion_field::refstamp_intra_frames().0 - before_stamp.0;
4996+ let stamp2 = crate::motion_field::refstamp_intra_frames().1 - before_stamp.1;
4997+ // Every frame, hidden ones included, compared in DECODE order.
4998+ let (total, hidden) = decode_all_frames_vs_oracle(
4999+ &stream,
5000+ &format!("{NAME}-{bit_depth}bit-attempt{attempt}"),
5001+ );
5002+ eprintln!(
5003+ "{NAME} ({bit_depth}-bit attempt {attempt}): {total} frames decoded \
5004+ ({hidden} hidden), temporal candidates={tmv}, frames with a key/intra \
5005+ forward ref={stamp} (two or more: {stamp2})"
5006+ );
5007+ compared += 1;
5008+ tmv_proved += tmv;
5009+ stamp_proved += stamp;
5010+ stamp2_proved += stamp2;
5011+ }
5012+ assert!(
5013+ compared > 0,
5014+ "{NAME} ({bit_depth}-bit): every attempt refused ({named_refusals}) -- gate \
5015+ proved nothing"
5016+ );
5017+ assert!(
5018+ tmv_proved > 0,
5019+ "{NAME} ({bit_depth}-bit): no compared attempt folded a temporal MV candidate \
5020+ into a block's stack -- gate proved nothing"
5021+ );
5022+ assert!(
5023+ stamp_proved > 0,
5024+ "{NAME} ({bit_depth}-bit): no compared attempt ever had a forward reference \
5025+ holding a key/intra frame ({stamp2_proved} frames had two) -- the ref_stamp \
5026+ path this gate exists for never ran"
5027+ );
5028+ }
5029+ }
5030+
48845031 #[test]
48855032 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
48865033 // residual path IS implemented and reached, but no aomenc recipe swept