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+8 -3
@@ -1748,7 +1748,7 @@ pub(crate) fn build_motion_field(
1748 ref_order_hints: [u32; 7],1748 ref_order_hints: [u32; 7],
1749 ) -> crate::motion_field::MotionField {1749 ) -> crate::motion_field::MotionField {
1750 let mut field =1750 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);
1752 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference1752 // lane-interbis r1: libaom `av1_calculate_ref_frame_side` -- a reference
1753 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other1753 // whose OrderHint is AHEAD of (or equal to) this frame's is "on the other
1754 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block1754 // side", and `av1_copy_frame_mvs` skips it entirely, so a compound block
@@ -1771,7 +1771,14 @@ pub(crate) fn build_motion_field(
1771 let Some(info) = grid.get(row, col) else {1771 let Some(info) = grid.get(row, col) else {
1772 continue;1772 continue;
1773 };1773 };
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).
1774 if !info.is_inter {1780 if !info.is_inter {
1781+ field.set(row, col, None);
1775 continue;1782 continue;
1776 }1783 }
1777 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST1784 // `av1_copy_frame_mvs` walks BOTH reference slots and the LAST
@@ -1797,11 +1804,9 @@ pub(crate) fn build_motion_field(
1797 }1804 }
1798 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });1805 saved = Some(crate::motion_field::SavedMv { mv, ref_frame: rf });
1799 }1806 }
1800- if let Some(saved) = saved {
1801 field.set(row, col, saved);1807 field.set(row, col, saved);
1802 }1808 }
1803 }1809 }
1804- }
1805 field1810 field
1806 }1811 }
1807 1812
crates/ec-av1/src/motion_field.rsmodified+73 -6
@@ -31,13 +31,23 @@ pub struct MotionField {
31 cells: Vec<Option<SavedMv>>,31 cells: Vec<Option<SavedMv>>,
32 pub order_hint: u32,32 pub order_hint: u32,
33 pub ref_order_hints: [u32; 7],33 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,
34 }38 }
35 39
36 impl MotionField {40 impl MotionField {
37 /// A field sized for an `mi_cols` by `mi_rows` frame, all cells41 /// A field sized for an `mi_cols` by `mi_rows` frame, all cells
38 /// initially unset (spec 7.9's own reset to `-1`/invalid before any42 /// initially unset (spec 7.9's own reset to `-1`/invalid before any
39 /// block writes into it).43 /// 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 {
41 let cols = mi_cols.div_ceil(2);51 let cols = mi_cols.div_ceil(2);
42 let rows = mi_rows.div_ceil(2);52 let rows = mi_rows.div_ceil(2);
43 Self {53 Self {
@@ -46,6 +56,7 @@ impl MotionField {
46 cells: vec![None; cols * rows],56 cells: vec![None; cols * rows],
47 order_hint,57 order_hint,
48 ref_order_hints,58 ref_order_hints,
59+ is_intra,
49 }60 }
50 }61 }
51 62
@@ -53,10 +64,14 @@ impl MotionField {
53 /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single64 /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single
54 /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution65 /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution
55 /// write.66 /// 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>) {
57 let (r, c) = (mi_row / 2, mi_col / 2);72 let (r, c) = (mi_row / 2, mi_col / 2);
58 if r < self.rows && c < self.cols {73 if r < self.rows && c < self.cols {
59- self.cells[r * self.cols + c] = Some(saved);74+ self.cells[r * self.cols + c] = saved;
60 }75 }
61 }76 }
62 77
@@ -217,6 +232,14 @@ fn motion_field_projection(
217 dir: u8,232 dir: u8,
218 tpl_cells: &mut [Option<((i32, i32), i32)>],233 tpl_cells: &mut [Option<((i32, i32), i32)>],
219 ) -> bool {234 ) -> 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+ }
220 let mvs_rows = mi_rows.div_ceil(2);243 let mvs_rows = mi_rows.div_ceil(2);
221 let mvs_cols = mi_cols.div_ceil(2);244 let mvs_cols = mi_cols.div_ceil(2);
222 if start.rows != mvs_rows || start.cols != mvs_cols {245 if start.rows != mvs_rows || start.cols != mvs_cols {
@@ -264,6 +287,24 @@ fn motion_field_projection(
264 true287 true
265 }288 }
266 289
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+
267 /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to308 /// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to
268 /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order309 /// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order
269 /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when310 /// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when
@@ -287,6 +328,11 @@ pub fn setup_motion_field(
287 let cols = mi_cols.div_ceil(2);328 let cols = mi_cols.div_ceil(2);
288 let rows = mi_rows.div_ceil(2);329 let rows = mi_rows.div_ceil(2);
289 let mut cells = vec![None; cols * rows];330 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+ }
290 336
291 let slot_of =337 let slot_of =
292 |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref();338 |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(
294 340
295 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1341 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
296 342
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+
297 if let Some(last) = slot_of(LAST_FRAME) {364 if let Some(last) = slot_of(LAST_FRAME) {
298 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];365 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
299 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);366 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
@@ -464,14 +531,14 @@ mod tests {
464 // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV531 // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV
465 // against its own LAST_FRAME (order_hint 1). The current frame532 // against its own LAST_FRAME (order_hint 1). The current frame
466 // (order_hint 4) names that same slot as *its* LAST_FRAME.533 // (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);
468 mf.set(535 mf.set(
469 0,536 0,
470 0,537 0,
471- SavedMv {538+ Some(SavedMv {
472 mv: (-64, 0),539 mv: (-64, 0),
473 ref_frame: LAST_FRAME,540 ref_frame: LAST_FRAME,
474- },541+ }),
475 );542 );
476 let slots: [Option<MotionField>; 8] =543 let slots: [Option<MotionField>; 8] =
477 std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None });544 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>> {
616 header.mi_rows as usize,616 header.mi_rows as usize,
617 header.order_hint,617 header.order_hint,
618 ref_order_hints,618 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,
619 );622 );
620 (picture, end_cdfs, motion_field)623 (picture, end_cdfs, motion_field)
621 } else {624 } else {
@@ -4881,6 +4884,150 @@ mod tests {
4881 }4884 }
4882 }4885 }
4883 4886
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+
4884 #[test]5031 #[test]
4885 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter5032 // lane-inter4 r2: RED, kept (not weakened, not deleted) -- the rect inter
4886 // residual path IS implemented and reached, but no aomenc recipe swept5033 // residual path IS implemented and reached, but no aomenc recipe swept