forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1tmvp'

Browse files at this commit

12297933a7e5c64f197ca6e5768cb8c591830d63Ahmet Kaan GümüşParent: 2bcbc81253fdd8
crates/ec-av1/src/decode.rsmodified+120 -2
@@ -131,6 +131,76 @@ static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUs
131 static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);131 static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
132 static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);132 static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
133 133
134+/// How many query blocks folded in at least one temporal MV candidate
135+/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the
136+/// temporal-MV gate's own firing counter (lane-av1tmvp).
137+///
138+/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream
139+/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in
140+/// this file (`decode_inter_block`) still passes `tpl: None` -- this
141+/// counter compiles and the projection math it counts is unit-tested
142+/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`]
143+/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls
144+/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0`
145+/// against any real stream today. See the module doc on
146+/// `crate::motion_field` and this crate's ledger for the remaining wiring.
147+pub(crate) fn tmv_hits() -> usize {
148+ crate::mvstack::tmv_hits()
149+}
150+
151+/// Everything [`decode_inter_block`] needs to fold temporal MV candidates
152+/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
153+/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
154+/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus
155+/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`]
156+/// needs to turn a query block's own resolved `ref_frame` into
157+/// `TplArgs::cur_offset_0` (spec 7.9.3).
158+pub(crate) struct TplFrameArgs<'a> {
159+ pub field: &'a crate::motion_field::TplField,
160+ pub order_hint_bits: u32,
161+ pub order_hint: u32,
162+ /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in
163+ /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this
164+ /// frame's own `ref_frame_idx` names for each single reference.
165+ pub ref_order_hints: [u32; 7],
166+}
167+
168+/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`,
169+/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully
170+/// decoded `grid`: every 4x4 unit an inter block covers reads the same
171+/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it
172+/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is
173+/// exact — every block this crate ever codes is at least 8x8, so no 8x8
174+/// cell straddles two different blocks' values.
175+pub(crate) fn build_motion_field(
176+ grid: &MiGrid,
177+ mi_cols: usize,
178+ mi_rows: usize,
179+ order_hint: u32,
180+ ref_order_hints: [u32; 7],
181+) -> crate::motion_field::MotionField {
182+ let mut field =
183+ crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints);
184+ for row in 0..mi_rows {
185+ for col in 0..mi_cols {
186+ if let Some(info) = grid.get(row, col)
187+ && info.is_inter
188+ && info.ref_frame > 0
189+ {
190+ field.set(
191+ row,
192+ col,
193+ crate::motion_field::SavedMv {
194+ mv: info.mv,
195+ ref_frame: info.ref_frame,
196+ },
197+ );
198+ }
199+ }
200+ }
201+ field
202+}
203+
134 /// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;204 /// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`;
135 /// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).205 /// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here).
136 pub(crate) fn ref_hits(ref_frame: i8) -> usize {206 pub(crate) fn ref_hits(ref_frame: i8) -> usize {
@@ -3758,6 +3828,7 @@ fn decode_inter_block(
3758 allow_high_precision_mv: bool,3828 allow_high_precision_mv: bool,
3759 interp_fixed: Option<mc::InterpFilterKind>,3829 interp_fixed: Option<mc::InterpFilterKind>,
3760 enable_dual_filter: bool,3830 enable_dual_filter: bool,
3831+ tpl_frame: Option<&TplFrameArgs>,
3761 ) -> Result<()> {3832 ) -> Result<()> {
3762 let (r, c) = at;3833 let (r, c) = at;
3763 let (px, py) = (c * SUB, r * SUB);3834 let (px, py) = (c * SUB, r * SUB);
@@ -3804,6 +3875,20 @@ fn decode_inter_block(
3804 3875
3805 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);3876 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
3806 let bw4 = side / 4;3877 let bw4 = side / 4;
3878+ // spec 7.10.2.8: only reached when the frame header set
3879+ // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None`
3880+ // otherwise) -- `cur_offset_0` is this query block's own resolved
3881+ // `ref_frame`'s distance from the current frame (spec 7.9.3),
3882+ // recomputed per block since different blocks pick different refs.
3883+ let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs {
3884+ field: t.field,
3885+ cur_offset_0: crate::motion_field::get_relative_dist(
3886+ t.order_hint_bits,
3887+ t.order_hint,
3888+ t.ref_order_hints[(ref_frame - LAST_FRAME) as usize],
3889+ ),
3890+ allow_high_precision_mv,
3891+ });
3807 let stack = find_mv_stack_with_sign_bias(3892 let stack = find_mv_stack_with_sign_bias(
3808 grid,3893 grid,
3809 mi_row,3894 mi_row,
@@ -3814,6 +3899,7 @@ fn decode_inter_block(
3814 mi_cols as usize,3899 mi_cols as usize,
3815 mi_rows as usize,3900 mi_rows as usize,
3816 sign_bias_table,3901 sign_bias_table,
3902+ tpl,
3817 );3903 );
3818 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;3904 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
3819 let mut is_globalmv = false;3905 let mut is_globalmv = false;
@@ -4656,8 +4742,12 @@ pub fn decode_inter_frame_tile(
4656 NO_SIGN_BIAS,4742 NO_SIGN_BIAS,
4657 interp_fixed,4743 interp_fixed,
4658 enable_dual_filter,4744 enable_dual_filter,
4745+ 0,
4746+ 0,
4747+ [0; 7],
4748+ None,
4659 )4749 )
4660- .map(|(picture, _)| picture)4750+ .map(|(picture, _, _)| picture)
4661 }4751 }
4662 4752
4663 /// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see4753 /// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
@@ -4681,7 +4771,22 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4681 sign_bias_table: SignBiasTable,4771 sign_bias_table: SignBiasTable,
4682 interp_fixed: Option<mc::InterpFilterKind>,4772 interp_fixed: Option<mc::InterpFilterKind>,
4683 enable_dual_filter: bool,4773 enable_dual_filter: bool,
4684-) -> Result<(Picture, Cdfs)> {4774+ // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are
4775+ // always needed (this frame's own saved [`crate::motion_field::MotionField`]
4776+ // carries them for a *later* frame's projection, spec 7.9); `tpl_field`
4777+ // is `Some` only when this frame's own header set `use_ref_frame_mvs`
4778+ // and the caller ([`crate::stream::decode_stream`]) projected one.
4779+ order_hint_bits: u32,
4780+ order_hint: u32,
4781+ ref_order_hints: [u32; 7],
4782+ tpl_field: Option<&crate::motion_field::TplField>,
4783+) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
4784+ let tpl_frame = tpl_field.map(|field| TplFrameArgs {
4785+ field,
4786+ order_hint_bits,
4787+ order_hint,
4788+ ref_order_hints,
4789+ });
4685 if mi_cols == 0 || mi_rows == 0 {4790 if mi_cols == 0 || mi_rows == 0 {
4686 return Err(unsupported("a frame with no mode-info grid"));4791 return Err(unsupported("a frame with no mode-info grid"));
4687 }4792 }
@@ -4870,6 +4975,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4870 allow_high_precision_mv,4975 allow_high_precision_mv,
4871 interp_fixed,4976 interp_fixed,
4872 enable_dual_filter,4977 enable_dual_filter,
4978+ tpl_frame.as_ref(),
4873 )?;4979 )?;
4874 }4980 }
4875 PARTITION_SPLIT => {4981 PARTITION_SPLIT => {
@@ -4927,6 +5033,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
4927 allow_high_precision_mv,5033 allow_high_precision_mv,
4928 interp_fixed,5034 interp_fixed,
4929 enable_dual_filter,5035 enable_dual_filter,
5036+ tpl_frame.as_ref(),
4930 )?;5037 )?;
4931 } else {5038 } else {
4932 let ctx16 = neighbours.partition_ctx(at16, SUB);5039 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -5014,6 +5121,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5014 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);5121 apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours);
5015 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);5122 apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours);
5016 5123
5124+ let motion_field = build_motion_field(
5125+ &grid,
5126+ mi_cols as usize,
5127+ mi_rows as usize,
5128+ order_hint,
5129+ ref_order_hints,
5130+ );
5131+
5017 let (fw, fh) = (frame_width as usize, frame_height as usize);5132 let (fw, fh) = (frame_width as usize, frame_height as usize);
5018 if fw == width && fh == height {5133 if fw == width && fh == height {
5019 return Ok((5134 return Ok((
@@ -5025,6 +5140,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5025 v: v.data,5140 v: v.data,
5026 },5141 },
5027 cdfs,5142 cdfs,
5143+ motion_field,
5028 ));5144 ));
5029 }5145 }
5030 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {5146 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
@@ -5043,6 +5159,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
5043 v: crop(&v, fw / 2, fh / 2),5159 v: crop(&v, fw / 2, fh / 2),
5044 },5160 },
5045 cdfs,5161 cdfs,
5162+ motion_field,
5046 ))5163 ))
5047 }5164 }
5048 5165
@@ -5665,6 +5782,7 @@ mod tests {
5665 false,5782 false,
5666 Some(mc::InterpFilterKind::Regular),5783 Some(mc::InterpFilterKind::Regular),
5667 false,5784 false,
5785+ None,
5668 )5786 )
5669 .unwrap();5787 .unwrap();
5670 5788
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -23,6 +23,7 @@ pub mod frame;
23 pub mod intra;23 pub mod intra;
24 pub mod mc;24 pub mod mc;
25 pub mod motion;25 pub mod motion;
26+mod motion_field;
26 pub mod msac;27 pub mod msac;
27 pub mod mvstack;28 pub mod mvstack;
28 pub mod obu;29 pub mod obu;
crates/ec-av1/src/motion_field.rsadded+477 -0
@@ -0,0 +1,477 @@
1+//! Temporal MV projection (AV1 spec 7.9, `use_ref_frame_mvs`): projects a
2+//! previously decoded frame's stored motion vectors into the current
3+//! frame's own 8x8 motion field, ported from libaom's
4+//! `av1_setup_motion_field`/`motion_field_projection`
5+//! (`av1/common/mvref_common.c`) and the projection math `add_tpl_ref_mv`
6+//! (same file) applies a second time, per query block, against the block's
7+//! own single reference frame.
8+
9+use crate::mvstack::{ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME};
10+
11+/// One 8x8 cell's saved motion state, as libaom's `av1_copy_frame_mvs`
12+/// leaves it after decoding the frame that owns this grid: the coded MV and
13+/// the single reference frame (`LAST_FRAME..=ALTREF_FRAME`, 1..=7) it
14+/// pointed to.
15+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16+pub struct SavedMv {
17+ pub mv: (i32, i32),
18+ pub ref_frame: i8,
19+}
20+
21+/// A decoded inter frame's whole motion field (spec `MotionFieldMvs`... no
22+/// — libaom's `cur_frame->mvs`), one [`SavedMv`] per 8x8 unit, plus the
23+/// order-hint bookkeeping [`setup_motion_field`] needs to project it into a
24+/// later frame: this frame's own `OrderHint` and the `OrderHint` of each of
25+/// the 7 references *it* was coded against (`SavedOrderHints`/
26+/// `ref_order_hints`).
27+#[derive(Clone, Debug)]
28+pub struct MotionField {
29+ cols: usize,
30+ rows: usize,
31+ cells: Vec<Option<SavedMv>>,
32+ pub order_hint: u32,
33+ pub ref_order_hints: [u32; 7],
34+}
35+
36+impl MotionField {
37+ /// 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 any
39+ /// block writes into it).
40+ pub fn new(mi_cols: usize, mi_rows: usize, order_hint: u32, ref_order_hints: [u32; 7]) -> Self {
41+ let cols = mi_cols.div_ceil(2);
42+ let rows = mi_rows.div_ceil(2);
43+ Self {
44+ cols,
45+ rows,
46+ cells: vec![None; cols * rows],
47+ order_hint,
48+ ref_order_hints,
49+ }
50+ }
51+
52+ /// Records `saved` at the 8x8 cell containing 4x4 unit `(mi_row,
53+ /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single
54+ /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution
55+ /// write.
56+ pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: SavedMv) {
57+ let (r, c) = (mi_row / 2, mi_col / 2);
58+ if r < self.rows && c < self.cols {
59+ self.cells[r * self.cols + c] = Some(saved);
60+ }
61+ }
62+
63+ fn get(&self, row8: usize, col8: usize) -> Option<SavedMv> {
64+ if row8 < self.rows && col8 < self.cols {
65+ self.cells[row8 * self.cols + col8]
66+ } else {
67+ None
68+ }
69+ }
70+}
71+
72+/// The current frame's projected temporal motion field (spec 7.9.2's
73+/// `MotionFieldMvs`): one projected `(mv, ref_frame_offset)` per 8x8 cell,
74+/// `None` where no source candidate landed (libaom's `INVALID_MV`).
75+#[derive(Clone, Debug)]
76+pub struct TplField {
77+ cols: usize,
78+ rows: usize,
79+ cells: Vec<Option<((i32, i32), i32)>>,
80+}
81+
82+impl TplField {
83+ fn get(&self, row8: usize, col8: usize) -> Option<((i32, i32), i32)> {
84+ if row8 < self.rows && col8 < self.cols {
85+ self.cells[row8 * self.cols + col8]
86+ } else {
87+ None
88+ }
89+ }
90+}
91+
92+/// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range
93+/// order hints roll over in at `order_hint_bits` width.
94+pub fn get_relative_dist(order_hint_bits: u32, a: u32, b: u32) -> i32 {
95+ if order_hint_bits == 0 {
96+ return 0;
97+ }
98+ let diff = a as i32 - b as i32;
99+ let m = 1i32 << (order_hint_bits - 1);
100+ (diff & (m - 1)) - (diff & m)
101+}
102+
103+/// spec `FRAME_OFFSET_BITS`-derived clamp (libaom `MAX_FRAME_DISTANCE`).
104+const MAX_FRAME_DISTANCE: i32 = 31;
105+
106+/// libaom's `div_mult`: precomputed `16384 / den` (`av1_get_mv_projection`'s
107+/// own comment: "all the values are strictly under 14 bits").
108+const DIV_MULT: [i64; 32] = [
109+ 0, 16384, 8192, 5461, 4096, 3276, 2730, 2340, 2048, 1820, 1638, 1489, 1365, 1260, 1170, 1092,
110+ 1024, 963, 910, 862, 819, 780, 744, 712, 682, 655, 630, 606, 585, 564, 546, 528,
111+];
112+
113+fn round_pow2_signed(value: i64, n: u32) -> i32 {
114+ let half = 1i64 << (n - 1);
115+ (if value < 0 {
116+ -((-value + half) >> n)
117+ } else {
118+ (value + half) >> n
119+ }) as i32
120+}
121+
122+/// `av1_get_mv_projection` (spec 7.9.3): scales `mv` by the ratio of two
123+/// frame-distance offsets.
124+fn get_mv_projection(mv: (i32, i32), num: i32, den: i32) -> (i32, i32) {
125+ let den = den.min(MAX_FRAME_DISTANCE);
126+ let num = if num > 0 {
127+ num.min(MAX_FRAME_DISTANCE)
128+ } else {
129+ num.max(-MAX_FRAME_DISTANCE)
130+ };
131+ let mult = DIV_MULT[den as usize];
132+ let scale = |v: i32| round_pow2_signed(v as i64 * num as i64 * mult, 14).clamp(-16383, 16383);
133+ (scale(mv.0), scale(mv.1))
134+}
135+
136+/// `lower_mv_precision` (`mvref_common.h`), the `is_integer == false` half
137+/// only — every stream this decoder ever reaches has `force_integer_mv ==
138+/// false` on an inter frame (`allow_screen_content_tools`, the only source
139+/// of a `true` value here, is refused outright at the stream level).
140+pub fn lower_mv_precision(mv: (i32, i32), allow_high_precision_mv: bool) -> (i32, i32) {
141+ if allow_high_precision_mv {
142+ return mv;
143+ }
144+ let round = |v: i32| {
145+ if v & 1 != 0 {
146+ v + if v > 0 { -1 } else { 1 }
147+ } else {
148+ v
149+ }
150+ };
151+ (round(mv.0), round(mv.1))
152+}
153+
154+/// `get_block_position` (spec 7.9.2): the 8x8 cell a projected `mv` lands on
155+/// starting from `(blk_row, blk_col)` (already in 8x8 units), or `None` when
156+/// it falls outside the frame or outside the projection's own bound (a
157+/// 64x64-superblock-aligned base block, spec's `MAX_OFFSET_WIDTH`/
158+/// `MAX_OFFSET_HEIGHT`).
159+fn get_block_position(
160+ mvs_rows: usize,
161+ mvs_cols: usize,
162+ blk_row: usize,
163+ blk_col: usize,
164+ mv: (i32, i32),
165+ sign_bias: bool,
166+) -> Option<(usize, usize)> {
167+ let base_blk_row = (blk_row >> 3) << 3;
168+ let base_blk_col = (blk_col >> 3) << 3;
169+ let row_offset = if mv.0 >= 0 {
170+ mv.0 >> 6
171+ } else {
172+ -((-mv.0) >> 6)
173+ };
174+ let col_offset = if mv.1 >= 0 {
175+ mv.1 >> 6
176+ } else {
177+ -((-mv.1) >> 6)
178+ };
179+ let row = if sign_bias {
180+ blk_row as i64 - row_offset as i64
181+ } else {
182+ blk_row as i64 + row_offset as i64
183+ };
184+ let col = if sign_bias {
185+ blk_col as i64 - col_offset as i64
186+ } else {
187+ blk_col as i64 + col_offset as i64
188+ };
189+ if row < 0 || row >= mvs_rows as i64 || col < 0 || col >= mvs_cols as i64 {
190+ return None;
191+ }
192+ if row < base_blk_row as i64
193+ || row >= base_blk_row as i64 + 8
194+ || col < base_blk_col as i64 - 8
195+ || col >= base_blk_col as i64 + 16
196+ {
197+ return None;
198+ }
199+ Some((row as usize, col as usize))
200+}
201+
202+/// `motion_field_projection` (spec 7.9.2): projects `start`'s stored MVs
203+/// into `tpl`, scaled by the OrderHint distance from `start` to the current
204+/// frame. `dir` mirrors libaom's own parameter: `2` for a backward-looking
205+/// source (`LAST_FRAME`/`LAST2_FRAME`, offset negated and `sign_bias`
206+/// flipped), `0` for a forward one (`BWDREF_FRAME`/`ALTREF2_FRAME`/
207+/// `ALTREF_FRAME`). Returns whether the projection ran at all (`start`'s
208+/// frame size has to match the current frame's — always true for this
209+/// decoder's fixed-size streams, but ported anyway).
210+#[allow(clippy::too_many_arguments)]
211+fn motion_field_projection(
212+ start: &MotionField,
213+ cur_order_hint: u32,
214+ order_hint_bits: u32,
215+ mi_rows: usize,
216+ mi_cols: usize,
217+ dir: u8,
218+ tpl_cells: &mut [Option<((i32, i32), i32)>],
219+) -> bool {
220+ let mvs_rows = mi_rows.div_ceil(2);
221+ let mvs_cols = mi_cols.div_ceil(2);
222+ if start.rows != mvs_rows || start.cols != mvs_cols {
223+ return false;
224+ }
225+ let start_order_hint = start.order_hint;
226+ let mut start_to_current = get_relative_dist(order_hint_bits, start_order_hint, cur_order_hint);
227+ if dir == 2 {
228+ start_to_current = -start_to_current;
229+ }
230+ let ref_offset: [i32; 8] = std::array::from_fn(|rf| {
231+ if rf == 0 {
232+ 0
233+ } else {
234+ get_relative_dist(
235+ order_hint_bits,
236+ start_order_hint,
237+ start.ref_order_hints[rf - 1],
238+ )
239+ }
240+ });
241+ for row8 in 0..start.rows {
242+ for col8 in 0..start.cols {
243+ let Some(saved) = start.get(row8, col8) else {
244+ continue;
245+ };
246+ if saved.ref_frame <= 0 {
247+ continue;
248+ }
249+ let ref_frame_offset = ref_offset[saved.ref_frame as usize];
250+ let pos_valid = ref_frame_offset.abs() <= MAX_FRAME_DISTANCE
251+ && ref_frame_offset > 0
252+ && start_to_current.abs() <= MAX_FRAME_DISTANCE;
253+ if !pos_valid {
254+ continue;
255+ }
256+ let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset);
257+ if let Some((r, c)) =
258+ get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1)
259+ {
260+ tpl_cells[r * mvs_cols + c] = Some((saved.mv, ref_frame_offset));
261+ }
262+ }
263+ }
264+ true
265+}
266+
267+/// `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 order
269+/// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when
270+/// each is display-order-forward of the current frame, then `LAST2_FRAME`
271+/// once the stack still has room) and projects each into the returned
272+/// [`TplField`].
273+///
274+/// `slots` is the DPB's 8 reference-picture slots' saved [`MotionField`]s
275+/// (a `None` slot, or one still holding an intra frame's — never
276+/// constructed, so also `None` — motion field, contributes nothing);
277+/// `ref_frame_idx` is the current frame header's own `ref_frame_idx`
278+/// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).
279+pub fn setup_motion_field(
280+ slots: &[Option<MotionField>; 8],
281+ ref_frame_idx: [u8; 7],
282+ cur_order_hint: u32,
283+ order_hint_bits: u32,
284+ mi_rows: usize,
285+ mi_cols: usize,
286+) -> TplField {
287+ let cols = mi_cols.div_ceil(2);
288+ let rows = mi_rows.div_ceil(2);
289+ let mut cells = vec![None; cols * rows];
290+
291+ let slot_of =
292+ |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref();
293+ let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);
294+
295+ let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
296+
297+ if let Some(last) = slot_of(LAST_FRAME) {
298+ 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);
300+ if !is_lst_overlay {
301+ motion_field_projection(
302+ last,
303+ cur_order_hint,
304+ order_hint_bits,
305+ mi_rows,
306+ mi_cols,
307+ 2,
308+ &mut cells,
309+ );
310+ }
311+ ref_stamp -= 1;
312+ }
313+
314+ if get_relative_dist(order_hint_bits, order_hint_of(BWDREF_FRAME), cur_order_hint) > 0
315+ && let Some(bwd) = slot_of(BWDREF_FRAME)
316+ && motion_field_projection(
317+ bwd,
318+ cur_order_hint,
319+ order_hint_bits,
320+ mi_rows,
321+ mi_cols,
322+ 0,
323+ &mut cells,
324+ )
325+ {
326+ ref_stamp -= 1;
327+ }
328+
329+ if get_relative_dist(
330+ order_hint_bits,
331+ order_hint_of(crate::mvstack::ALTREF2_FRAME),
332+ cur_order_hint,
333+ ) > 0
334+ && let Some(alt2) = slot_of(crate::mvstack::ALTREF2_FRAME)
335+ && motion_field_projection(
336+ alt2,
337+ cur_order_hint,
338+ order_hint_bits,
339+ mi_rows,
340+ mi_cols,
341+ 0,
342+ &mut cells,
343+ )
344+ {
345+ ref_stamp -= 1;
346+ }
347+
348+ if ref_stamp >= 0
349+ && get_relative_dist(order_hint_bits, order_hint_of(ALTREF_FRAME), cur_order_hint) > 0
350+ && let Some(alt) = slot_of(ALTREF_FRAME)
351+ && motion_field_projection(
352+ alt,
353+ cur_order_hint,
354+ order_hint_bits,
355+ mi_rows,
356+ mi_cols,
357+ 0,
358+ &mut cells,
359+ )
360+ {
361+ ref_stamp -= 1;
362+ }
363+
364+ if ref_stamp >= 0
365+ && let Some(last2) = slot_of(LAST2_FRAME)
366+ {
367+ motion_field_projection(
368+ last2,
369+ cur_order_hint,
370+ order_hint_bits,
371+ mi_rows,
372+ mi_cols,
373+ 2,
374+ &mut cells,
375+ );
376+ }
377+
378+ TplField { cols, rows, cells }
379+}
380+
381+/// The result [`add_tpl_ref_mv`] folds into a query block's MV stack: the
382+/// projected candidate MV (already scaled to the block's own reference
383+/// frame and MV-precision-lowered) plus whether the very first (`blk_row ==
384+/// 0 && blk_col == 0`) sample differs enough from the zero vector to raise
385+/// `GLOBALMV_OFFSET` (spec 7.10.2.8 — this decoder only ever reaches
386+/// `IDENTITY` global motion, so the spec's `gm_get_motion_vector` compare
387+/// collapses to "far from `(0, 0)`").
388+pub struct TplCandidate {
389+ pub mv: (i32, i32),
390+}
391+
392+/// `add_tpl_ref_mv`'s single-reference half (spec 7.10.2.8, libaom
393+/// `mvref_common.c`): probes one 8x8-unit offset `(blk_row, blk_col)` from
394+/// `(mi_row, mi_col)` in [`TplField`] and, if it landed a candidate,
395+/// projects it a second time — this time scaled to `cur_offset_0`, the
396+/// distance from the current frame to the query block's own single
397+/// reference frame, rather than `start_to_current_frame_offset` from the
398+/// first (storage-time) projection.
399+pub fn add_tpl_ref_mv(
400+ tpl: &TplField,
401+ mi_row: usize,
402+ mi_col: usize,
403+ blk_row: isize,
404+ blk_col: isize,
405+ cur_offset_0: i32,
406+ allow_high_precision_mv: bool,
407+) -> Option<TplCandidate> {
408+ let pos_row = if mi_row & 1 != 0 {
409+ blk_row
410+ } else {
411+ blk_row + 1
412+ };
413+ let pos_col = if mi_col & 1 != 0 {
414+ blk_col
415+ } else {
416+ blk_col + 1
417+ };
418+ let row8 = mi_row as isize + pos_row;
419+ let col8 = mi_col as isize + pos_col;
420+ if row8 < 0 || col8 < 0 {
421+ return None;
422+ }
423+ let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?;
424+ let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset);
425+ let mv = lower_mv_precision(projected, allow_high_precision_mv);
426+ Some(TplCandidate { mv })
427+}
428+
429+#[cfg(test)]
430+mod tests {
431+ use super::*;
432+
433+ #[test]
434+ fn relative_dist_wraps_at_order_hint_bits() {
435+ // 7-bit order hints (aomenc's usual default): 1 - 126 should read as
436+ // +3 (wrapping backward past 0), not -125.
437+ assert_eq!(get_relative_dist(7, 1, 126), 3);
438+ assert_eq!(get_relative_dist(7, 10, 5), 5);
439+ }
440+
441+ #[test]
442+ fn mv_projection_scales_by_the_distance_ratio() {
443+ // A MV recorded across a 2-frame gap, projected across a 1-frame
444+ // gap, should halve (libaom's own div_mult table is exact for small
445+ // integer ratios).
446+ let (row, col) = get_mv_projection((16, -32), 1, 2);
447+ assert_eq!((row, col), (8, -16));
448+ // Same-distance projection is the identity.
449+ assert_eq!(get_mv_projection((7, -3), 4, 4), (7, -3));
450+ }
451+
452+ #[test]
453+ fn setup_motion_field_projects_last_frame_forward() {
454+ // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV
455+ // against its own LAST_FRAME (order_hint 1). The current frame
456+ // (order_hint 4) names that same slot as *its* LAST_FRAME.
457+ let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0]);
458+ mf.set(
459+ 0,
460+ 0,
461+ SavedMv {
462+ mv: (-64, 0),
463+ ref_frame: LAST_FRAME,
464+ },
465+ );
466+ let slots: [Option<MotionField>; 8] =
467+ std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None });
468+ let ref_frame_idx = [0u8; 7];
469+ let tpl = setup_motion_field(&slots, ref_frame_idx, 4, 7, 16, 16);
470+ // LAST_FRAME's own dir=2 projection: start_to_current = -get_relative_dist(2,4) = 2,
471+ // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by
472+ // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts
473+ // the offset, landing at 8x8 cell (2, 0).
474+ let cand = add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true);
475+ assert!(cand.is_some(), "expected a projected temporal candidate");
476+ }
477+}
crates/ec-av1/src/mvstack.rsmodified+131 -4
@@ -78,6 +78,40 @@
78 //! stack to two entries (spec 7.10.2.12) — this module's stack can be78 //! stack to two entries (spec 7.10.2.12) — this module's stack can be
79 //! shorter than two candidates where libaom's never is.79 //! shorter than two candidates where libaom's never is.
80 80
81+/// How many query blocks [`find_mv_stack_with_sign_bias`] has folded at
82+/// least one temporal MV candidate into (spec 7.9/7.10.2.8's
83+/// `add_tpl_ref_mv`) — the real-aomenc temporal-MV gate's own firing
84+/// counter (`crate::decode::tmv_hits`), proving the projection path in
85+/// [`crate::motion_field`] is actually reached, not just compiled.
86+static TMV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
87+
88+/// The number of query blocks that received at least one temporal MV
89+/// candidate so far, across every [`find_mv_stack_with_sign_bias`] call in
90+/// this process.
91+pub(crate) fn tmv_hits() -> usize {
92+ TMV_HITS.load(std::sync::atomic::Ordering::Relaxed)
93+}
94+
95+/// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV
96+/// candidates into a block's stack (spec 7.10.2.8, only reached when the
97+/// frame header's own `use_ref_frame_mvs` is set): the current frame's own
98+/// projected motion field, the distance (in `get_relative_dist` units) from
99+/// the current frame to *this query's* single reference frame's own
100+/// `OrderHint` (`cur_offset_0`, spec 7.9.3 — computed by the caller, since
101+/// this module has no reason to carry `order_hint_bits`/`OrderHints[]`
102+/// itself), and `allow_high_precision_mv` (`lower_mv_precision`, spec
103+/// 7.10.2.8).
104+pub struct TplArgs<'a> {
105+ /// The current frame's projected temporal motion field
106+ /// ([`crate::motion_field::setup_motion_field`]'s output).
107+ pub field: &'a crate::motion_field::TplField,
108+ /// `get_relative_dist(OrderHint, OrderHints[ref_frame - LAST_FRAME])`,
109+ /// pre-computed by the caller.
110+ pub cur_offset_0: i32,
111+ /// The frame header's own `allow_high_precision_mv`.
112+ pub allow_high_precision_mv: bool,
113+}
114+
81 /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it115 /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
82 /// in by the time it asks for a block's MV stack.116 /// in by the time it asks for a block's MV stack.
83 #[derive(Clone, Copy, Debug, PartialEq, Eq)]117 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -534,6 +568,7 @@ pub fn find_mv_stack(
534 mi_cols,568 mi_cols,
535 mi_rows,569 mi_rows,
536 &NO_SIGN_BIAS,570 &NO_SIGN_BIAS,
571+ None,
537 )572 )
538 }573 }
539 574
@@ -553,6 +588,7 @@ pub fn find_mv_stack_with_sign_bias(
553 mi_cols: usize,588 mi_cols: usize,
554 mi_rows: usize,589 mi_rows: usize,
555 sign_bias_table: &SignBiasTable,590 sign_bias_table: &SignBiasTable,
591+ tpl: Option<TplArgs>,
556 ) -> MvStack {592 ) -> MvStack {
557 let mut candidates = Vec::new();593 let mut candidates = Vec::new();
558 let mut newmv_count = 0u32;594 let mut newmv_count = 0u32;
@@ -629,6 +665,97 @@ pub fn find_mv_stack_with_sign_bias(
629 entry.weight += REF_CAT_LEVEL;665 entry.weight += REF_CAT_LEVEL;
630 }666 }
631 667
668+ // Temporal MV candidates (spec 7.10.2.8's `add_tpl_ref_mv`, only reached
669+ // when the frame header set `use_ref_frame_mvs`): probed over a grid of
670+ // 8x8-unit offsets spanning the block (libaom's own `blk_row_end`/
671+ // `blk_col_end`/`step_h`/`step_w`, every real block this crate ever
672+ // codes being square and no wider than 32x32 — `BLOCK_64X64`'s own
673+ // 16x16-mi-unit step branch is dead here, ported anyway since nothing
674+ // relies on that), plus three "extension" samples past the block's own
675+ // span (`tpl_sample_pos`) once the block is at least 8x8 and smaller
676+ // than 64x64 (`allow_extension` — true for every block size this crate
677+ // codes). Folded in *after* the row/col/top-right scan's own
678+ // `REF_CAT_LEVEL` boost above and *before* the corner probe, matching
679+ // libaom's call order in `setup_ref_mv_list` exactly (a temporal
680+ // candidate never gets the boost, and the corner probe can still add a
681+ // genuinely new, lower-weight entry after it).
682+ let mut zero_mv_ctx = 0usize;
683+ if let Some(TplArgs {
684+ field,
685+ cur_offset_0,
686+ allow_high_precision_mv,
687+ }) = tpl
688+ {
689+ let mut any_hit = false;
690+ let voffset = bh4.max(2);
691+ let hoffset = bw4.max(2);
692+ let blk_row_end = bh4.min(16);
693+ let blk_col_end = bw4.min(16);
694+ let step_h = if bh4 >= 16 { 4 } else { 2 };
695+ let step_w = if bw4 >= 16 { 4 } else { 2 };
696+ let mut first_sample_missing = true;
697+ let mut first_sample_far = false;
698+ let mut blk_row = 0usize;
699+ while blk_row < blk_row_end {
700+ let mut blk_col = 0usize;
701+ while blk_col < blk_col_end {
702+ if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
703+ field,
704+ mi_row,
705+ mi_col,
706+ blk_row as isize,
707+ blk_col as isize,
708+ cur_offset_0,
709+ allow_high_precision_mv,
710+ ) {
711+ any_hit = true;
712+ if blk_row == 0 && blk_col == 0 {
713+ first_sample_missing = false;
714+ first_sample_far = cand.mv.0.abs() >= 16 || cand.mv.1.abs() >= 16;
715+ }
716+ add_candidate(&mut candidates, cand.mv, 2);
717+ }
718+ blk_col += step_w;
719+ }
720+ blk_row += step_h;
721+ }
722+ // Three "extension" samples past the block's own span (libaom
723+ // `tpl_sample_pos`), reachable for every 8x8..32x32 block this crate
724+ // codes (`allow_extension`), gated on staying inside the block's own
725+ // 64x64 superblock (`check_sb_border`).
726+ let allow_extension = (2..16).contains(&bh4) && (2..16).contains(&bw4);
727+ if allow_extension {
728+ let sb_mask = 16isize;
729+ for (row_off, col_off) in [
730+ (voffset as isize, -2isize),
731+ (voffset as isize, hoffset as isize),
732+ (voffset as isize - 2, hoffset as isize),
733+ ] {
734+ let row = (mi_row as isize & (sb_mask - 1)) + row_off;
735+ let col = (mi_col as isize & (sb_mask - 1)) + col_off;
736+ if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask {
737+ continue;
738+ }
739+ if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
740+ field,
741+ mi_row,
742+ mi_col,
743+ row_off,
744+ col_off,
745+ cur_offset_0,
746+ allow_high_precision_mv,
747+ ) {
748+ any_hit = true;
749+ add_candidate(&mut candidates, cand.mv, 2);
750+ }
751+ }
752+ }
753+ if any_hit {
754+ TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
755+ }
756+ zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
757+ }
758+
632 // The diagonal top-left corner probe (module doc): folds into the row759 // The diagonal top-left corner probe (module doc): folds into the row
633 // side for `ref_match_count` without moving the already-captured760 // side for `ref_match_count` without moving the already-captured
634 // `nearest_match`, and its own newmv-ness is a dummy count libaom761 // `nearest_match`, and its own newmv-ness is a dummy count libaom
@@ -816,10 +943,10 @@ pub fn find_mv_stack_with_sign_bias(
816 }943 }
817 _ => 5,944 _ => 5,
818 };945 };
819- // GLOBALMV_OFFSET is only ever set by temporal MV projection946+ // `zero_mv_ctx` was already computed above, from the temporal-MV pass
820- // (`cm->features.allow_ref_frame_mvs`), which this reduction never runs947+ // when `tpl` is `Some` (GLOBALMV_OFFSET, spec 7.10.2.8) — `0` otherwise,
821- // (see module doc) — exact, not a stand-in.948+ // exactly this reduction's old always-0 behaviour when
822- let zero_mv_ctx = 0;949+ // `use_ref_frame_mvs` is unset.
823 950
824 // av1_drl_ctx (mvref_common.h): weight was boosted in place above for951 // av1_drl_ctx (mvref_common.h): weight was boosted in place above for
825 // the nearest entries only, so this now compares the real stored weight952 // the nearest entries only, so this now compares the real stored weight
crates/ec-av1/src/stream.rsmodified+228 -3
@@ -59,6 +59,14 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
59 // and small-magnitude (the two pictures mostly agree), which is exactly59 // and small-magnitude (the two pictures mostly agree), which is exactly
60 // what made it look like a rounding bug rather than a wrong reference.60 // what made it look like a rounding bug rather than a wrong reference.
61 let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);61 let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
62+ // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion
63+ // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom
64+ // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was
65+ // decoded with -- `Picture` itself carries neither, so both ride
66+ // alongside `ref_slots` on the exact same `refresh_frame_flags` update.
67+ let mut motion_field_slots: [Option<crate::motion_field::MotionField>; NUM_REF_FRAMES] =
68+ std::array::from_fn(|_| None);
69+ let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES];
62 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a70 // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
63 // previous frame's `refresh_frame_flags` stored into it -- the frame's71 // previous frame's `refresh_frame_flags` stored into it -- the frame's
64 // own end-of-tile adapted table, or (when the frame set72 // own end-of-tile adapted table, or (when the frame set
@@ -232,8 +240,19 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
232 };240 };
233 let started_from = initial_cdfs.clone();241 let started_from = initial_cdfs.clone();
234 242
235- let (picture, end_cdfs) = if header.frame_type == FrameType::Key {243+ let order_hint_bits = parser
236- decode_key_frame_tile_with_cdfs(244+ .sequence_header()
245+ .map_or(0, |seq| seq.order_hint_bits);
246+ // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
247+ // of the picture sitting in each of its 7 single references' DPB
248+ // slots, for this frame's *own* saved [`crate::motion_field::MotionField`]
249+ // (a later frame projects from it) whether or not this frame itself
250+ // reads temporal candidates.
251+ let ref_order_hints: [u32; 7] =
252+ std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]);
253+
254+ let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key {
255+ let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs(
237 tile_bytes,256 tile_bytes,
238 header.mi_cols,257 header.mi_cols,
239 header.mi_rows,258 header.mi_rows,
@@ -247,7 +266,19 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
247 initial_cdfs,266 initial_cdfs,
248 header.tx_mode == TxMode::Select,267 header.tx_mode == TxMode::Select,
249 header.reduced_tx_set,268 header.reduced_tx_set,
250- )?269+ )?;
270+ // A key frame codes no inter blocks -- its own saved motion
271+ // field has no cells set, matching libaom's own "intra frame
272+ // contributes nothing to a later projection" behaviour, but
273+ // still carries `order_hint`/`ref_order_hints` for the distance
274+ // arithmetic a later frame's projection needs.
275+ let motion_field = crate::motion_field::MotionField::new(
276+ header.mi_cols as usize,
277+ header.mi_rows as usize,
278+ header.order_hint,
279+ ref_order_hints,
280+ );
281+ (picture, end_cdfs, motion_field)
251 } else {282 } else {
252 let last_slot = header.ref_frame_idx[0] as usize;283 let last_slot = header.ref_frame_idx[0] as usize;
253 let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {284 let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
@@ -272,6 +303,20 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
272 .and_then(Option::as_ref)303 .and_then(Option::as_ref)
273 }304 }
274 });305 });
306+ // spec 7.9's own driver, `av1_setup_motion_field`: only run when
307+ // this frame's header actually asks for temporal candidates --
308+ // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
309+ // behaviour bit for bit when this is `None` (see its own doc).
310+ let tpl_field = header.use_ref_frame_mvs.then(|| {
311+ crate::motion_field::setup_motion_field(
312+ &motion_field_slots,
313+ header.ref_frame_idx,
314+ header.order_hint,
315+ order_hint_bits,
316+ header.mi_rows as usize,
317+ header.mi_cols as usize,
318+ )
319+ });
275 decode_inter_frame_tile_with_cdfs(320 decode_inter_frame_tile_with_cdfs(
276 tile_bytes,321 tile_bytes,
277 header.mi_cols,322 header.mi_cols,
@@ -288,6 +333,10 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
288 header.ref_frame_sign_bias,333 header.ref_frame_sign_bias,
289 interp_fixed,334 interp_fixed,
290 enable_dual_filter,335 enable_dual_filter,
336+ order_hint_bits,
337+ header.order_hint,
338+ ref_order_hints,
339+ tpl_field.as_ref(),
291 )?340 )?
292 };341 };
293 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's342 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
@@ -329,6 +378,8 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
329 // pre-grain decode, even though the frame pushed onto the378 // pre-grain decode, even though the frame pushed onto the
330 // caller's output below carries the grained picture.379 // caller's output below carries the grained picture.
331 ref_slots[i] = Some(picture.clone());380 ref_slots[i] = Some(picture.clone());
381+ motion_field_slots[i] = Some(motion_field.clone());
382+ order_hint_slots[i] = header.order_hint;
332 }383 }
333 }384 }
334 let output = if header.film_grain.apply_grain {385 let output = if header.film_grain.apply_grain {
@@ -2444,6 +2495,180 @@ mod tests {
2444 );2495 );
2445 }2496 }
2446 2497
2498+ /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate`
2499+ /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's
2500+ /// own default (on) instead of pinning it off, so `use_ref_frame_mvs`
2501+ /// actually fires and `decode::tmv_hits()` (this gate's own capability
2502+ /// proof, not just `non_last_ref_hits`) has to advance for the run to
2503+ /// count as a real pass rather than a `never_fired` skip.
2504+ fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) {
2505+ let gate_name = "a_real_aomenc_temporal_mv_gate";
2506+ if !have_ffmpeg() {
2507+ eprintln!("SKIP {gate_name}: no ffmpeg");
2508+ return;
2509+ }
2510+ if !have_aomenc() {
2511+ eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display());
2512+ return;
2513+ }
2514+ let (width, height, frame_count) = (64usize, 64usize, 16usize);
2515+ let mut never_fired = 0u32;
2516+ let mut refusals = Vec::new();
2517+ for attempt in 0..attempts {
2518+ let seed = seed_base + attempt;
2519+ let duration = frame_count as f64 / 25.0;
2520+ let source =
2521+ format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25");
2522+ let y4m = Command::new("ffmpeg")
2523+ .args([
2524+ "-v",
2525+ "error",
2526+ "-f",
2527+ "lavfi",
2528+ "-i",
2529+ &source,
2530+ "-pix_fmt",
2531+ "yuv420p",
2532+ "-f",
2533+ "yuv4mpegpipe",
2534+ "-",
2535+ ])
2536+ .stdin(Stdio::null())
2537+ .stdout(Stdio::piped())
2538+ .stderr(Stdio::piped())
2539+ .output()
2540+ .expect("ffmpeg failed to run");
2541+ assert!(
2542+ y4m.status.success(),
2543+ "ffmpeg fixture: {}",
2544+ String::from_utf8_lossy(&y4m.stderr)
2545+ );
2546+ // Same envelope as `a_real_aomenc_single_ref_gate`, minus its
2547+ // `--enable-ref-frame-mvs=0` pin -- everything else this decoder
2548+ // still cannot code stays refused the same way.
2549+ let args: Vec<&str> = vec![
2550+ "--codec=av1",
2551+ "--passes=1",
2552+ "--end-usage=q",
2553+ "--cq-level=55",
2554+ "--cpu-used=0",
2555+ "--kf-max-dist=1000",
2556+ "--threads=1",
2557+ "--row-mt=0",
2558+ "--auto-alt-ref=1",
2559+ "--lag-in-frames=16",
2560+ "--enable-fwd-kf=0",
2561+ "--enable-warped-motion=0",
2562+ "--enable-obmc=0",
2563+ "--enable-masked-comp=0",
2564+ "--enable-interintra-comp=0",
2565+ "--enable-dist-wtd-comp=0",
2566+ "--enable-diff-wtd-comp=0",
2567+ "--enable-onesided-comp=0",
2568+ "--enable-interintra-wedge=0",
2569+ "--enable-smooth-interintra=0",
2570+ "--enable-rect-partitions=0",
2571+ "--enable-ab-partitions=0",
2572+ "--enable-1to4-partitions=0",
2573+ "--enable-filter-intra=0",
2574+ "--enable-smooth-intra=0",
2575+ "--enable-paeth-intra=0",
2576+ "--enable-directional-intra=0",
2577+ "--enable-angle-delta=0",
2578+ "--enable-tx-size-search=0",
2579+ "--enable-cdef=0",
2580+ "--enable-restoration=0",
2581+ "--max-partition-size=32",
2582+ "--min-partition-size=32",
2583+ "--enable-palette=0",
2584+ "--enable-intrabc=0",
2585+ "--enable-cfl-intra=0",
2586+ "--obu",
2587+ "-o",
2588+ "-",
2589+ "-",
2590+ ];
2591+ let mut child = Command::new(aomenc_path())
2592+ .args(&args)
2593+ .stdin(Stdio::piped())
2594+ .stdout(Stdio::piped())
2595+ .stderr(Stdio::piped())
2596+ .spawn()
2597+ .expect("aomenc failed to start");
2598+ child
2599+ .stdin
2600+ .take()
2601+ .expect("aomenc stdin")
2602+ .write_all(&y4m.stdout)
2603+ .expect("writing y4m to aomenc");
2604+ let out = child.wait_with_output().expect("aomenc failed to run");
2605+ assert!(
2606+ out.status.success(),
2607+ "aomenc refused the fixture: {}",
2608+ String::from_utf8_lossy(&out.stderr)
2609+ );
2610+ let stream = out.stdout;
2611+ let before = decode::tmv_hits();
2612+ let frames = match decode_stream(&stream) {
2613+ Err(e) => {
2614+ let msg = e.to_string();
2615+ assert!(
2616+ msg.contains("unsupported"),
2617+ "{gate_name} failed outright (seed {seed}): {msg}"
2618+ );
2619+ refusals.push(format!("seed {seed}: {msg}"));
2620+ continue;
2621+ }
2622+ Ok(frames) => frames,
2623+ };
2624+ if decode::tmv_hits() == before {
2625+ never_fired += 1;
2626+ continue;
2627+ }
2628+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
2629+ assert_eq!(frames.len(), frame_count);
2630+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") {
2631+ let mismatched = frames
2632+ .iter()
2633+ .zip(&ffmpeg_frames)
2634+ .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v);
2635+ if mismatched {
2636+ std::fs::write(&path, &stream).expect("writing pinned stream");
2637+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}");
2638+ }
2639+ }
2640+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
2641+ assert_eq!(
2642+ got.y, want.y,
2643+ "{gate_name} frame {i} luma vs ffmpeg (seed {seed})"
2644+ );
2645+ assert_eq!(
2646+ got.u, want.u,
2647+ "{gate_name} frame {i} U vs ffmpeg (seed {seed})"
2648+ );
2649+ assert_eq!(
2650+ got.v, want.v,
2651+ "{gate_name} frame {i} V vs ffmpeg (seed {seed})"
2652+ );
2653+ }
2654+ eprintln!(
2655+ "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}",
2656+ decode::tmv_hits() - before
2657+ );
2658+ return;
2659+ }
2660+ eprintln!(
2661+ "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \
2662+ candidate, and every other attempt hit a named refusal:\n{}",
2663+ refusals.join("\n")
2664+ );
2665+ }
2666+
2667+ #[test]
2668+ fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() {
2669+ a_real_aomenc_temporal_mv_gate(42, 40);
2670+ }
2671+
2447 /// scratch: decode a pinned stream end to end and report where/why it2672 /// scratch: decode a pinned stream end to end and report where/why it
2448 /// refuses, plus `non_last_ref_hits` progression.2673 /// refuses, plus `non_last_ref_hits` progression.
2449 #[test]2674 #[test]