forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5591c0eTahinli3 months ago1014 commits

mvstack.rs2794 lines, 107.9 KiBHistoryRawDownload
1//! Reference MV list construction (AV1 spec 7.10.2, `find_mv_stack`),
2//! reduced to the single-reference, non-compound, `use_ref_frame_mvs = 0`
3//! case a key/inter frame without temporal MV projection needs.
4//!
5//! Implemented from the spec: the row-above scan (7.10.2.2), the col-left
6//! scan (7.10.2.3), a single top-right probe (the first of 7.10.2.4's extra
7//! positions), weight-based dedupe (7.10.2.5's `add_ref_mv_candidate`), the
8//! weight-descending sort (7.10.2.6), and the `NewMvContext`/`RefMvContext`/
9//! `ZeroMvContext`/`DrlCtx` derivations of 7.10.2.8, ported from libaom's
10//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, the `mode_context`
11//! switch around its `nearest_match`/`ref_match_count` and the
12//! `newmv_count > 0` tests) and `av1_drl_ctx` (`mvref_common.h`), plus MV
13//! clamping (7.10.2.14, libaom's `clamp_mv_ref`).
14//!
15//! This module's immediate row/col/top-right scan alone is *not* enough to
16//! get `RefMvContext` (`ref_mv_ctx`) right, *nor* `NewMvContext` at
17//! `nearest_match == 0` (see below). Ported straight from libaom's
18//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, `setup_ref_mv_list`,
19//! ~line 480 on): after the immediate row (-1), col (-1) and top-right
20//! probes settle `nearest_match` (and `mode_context`'s `new_mv` bits, which
21//! for `nearest_match >= 1` depend on `nearest_match` alone), libaom runs one
22//! more probe *before* computing `ref_match_count` — `scan_blk_mbmi` at the
23//! diagonal top-left corner `(-1, -1)` — whose match folds into
24//! `row_match_count` (and hence can flip `ref_match_count`'s row term true)
25//! without ever touching the already-captured `nearest_match`. So
26//! `ref_match_count >= nearest_match` always, sometimes strictly greater, and
27//! `ref_mv_ctx` (the `REFMV_OFFSET` half of libaom's `mode_context` switch,
28//! mvref_common.c ~line 619-643) genuinely depends on both counts, not
29//! `nearest_match` alone — that collapse was the bug this module shipped
30//! with for several rounds (see the crate report). The `case 0` arm of that
31//! same switch *also* sets `new_mv_ctx`'s own bit from `ref_match_count`
32//! (`mode_context[ref_frame] |= 1` when `ref_match_count >= 1`) — a second
33//! corner-probe dependency this module missed for several more rounds after
34//! the first fix, until real-content inter streams (I8 CLASS B) caught it:
35//! synthetic fixtures never produced a block with `nearest_match == 0` and a
36//! genuine corner match. [`find_mv_stack`] now runs that corner probe and
37//! computes both `ref_mv_ctx` and `new_mv_ctx` from the true
38//! `(nearest_match, ref_match_count)` pair.
39//!
40//! The corner probe's own candidate is added to the stack too (matching
41//! libaom: a genuinely new MV there becomes a real, if low-weight, entry),
42//! at libaom's real `2 * mi_size_wide[BLOCK_8X8]` (`CORNER_WEIGHT`, 4) —
43//! same as the top-right probe, which shares `scan_blk_mbmi`'s fixed weight
44//! in libaom too. The row/col scans (`scan_row`/`scan_col`) carry libaom's
45//! real per-block-run `len * weight` formula (`scan_row_mbmi`/
46//! `scan_col_mbmi`, mvref_common.c), not a flat per-cell weight: this
47//! module shipped a flat `IMMEDIATE_WEIGHT = 2` for several rounds, exact
48//! only for `tile.rs`'s own encoder (always a fixed `bw4 == bh4 == 8` query
49//! against same-size-8 neighbours, where the real formula's `bw4 <= n4`
50//! weight boost applies identically on every candidate and so never
51//! reorders anything) — decode.rs's real variable partition sizes need the
52//! real formula, since a same-or-wider neighbour against a *smaller* query
53//! block gets a real, non-flat weight boost there libaom's DRL-index
54//! selection depends on.
55//!
56//! The corner probe's own match does *not* count toward the real
57//! `newmv_count` that feeds `new_mv_ctx` (libaom passes it a `dummy_newmv_count`
58//! there) — only row/col/top-right do.
59//!
60//! Also ported (from `av1_drl_ctx`, `mvref_common.h`): the `REF_CAT_LEVEL`
61//! (640) bonus applies only to the entries the row/col/top-right scan found
62//! (`nearest_refmv_count`), added to their stored weight *before* the corner
63//! probe can add a new, unboosted entry — so `drl_ctx` can now be non-zero
64//! when the corner probe contributes a genuinely new candidate.
65//!
66//! The `GLOBALMV_OFFSET` bit of libaom's `mode_context` is set only inside
67//! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this
68//! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0
69//! here — exact for the case this module covers, not a stand-in.
70//!
71//! Deliberately reduced away (see the crate report, not reproduced bit-exact
72//! here): compound/multi-reference candidates, the temporal MV projection
73//! scan, and the single-reference "extension" pass that re-walks the same
74//! row/col
75//! neighbours through `process_single_ref_mv_candidate` (a no-op here: with
76//! only one reference frame ever in play, whatever it would add was already
77//! added by the row/col scan), and the "extra search" that pads a short
78//! 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.
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.
86static 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.
91pub(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).
104pub 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
115/// One 4x4 `mi` unit's motion state, as the encode loop will have filled it
116/// in by the time it asks for a block's MV stack.
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub struct MiInfo {
119 /// Whether this unit was coded inter (as opposed to intra).
120 pub is_inter: bool,
121 /// The single reference frame this unit's MV points into. Ignored (and
122 /// the unit contributes no candidate) when `is_inter` is `false`.
123 pub ref_frame: i8,
124 /// The unit's *second* reference frame when it was coded compound
125 /// (spec `RefFrames[1]`), `None` for a single-reference/intra unit --
126 /// compound-coded decode leaves set this. lane-av1idx r5:
127 /// [`find_mv_stack`]'s single-ref row/col/corner scans (via
128 /// `single_ref_match`) now also match a compound neighbour on this
129 /// second field, donating that side's own MV -- the real read #538
130 /// desync (a `new_mv_ctx` fed by a `newmv_count`/`nearest_match` that
131 /// silently dropped a compound neighbour's vote whenever its match sat
132 /// in this slot).
133 pub ref_frame1: Option<i8>,
134 /// The unit's motion vector, `(row, col)`, in the spec's 1/8-pel units.
135 pub mv: (i32, i32),
136 /// The unit's second motion vector, matching `ref_frame1` (spec
137 /// `Mvs[1]`) — `Some` only for a compound-coded unit, `None` otherwise.
138 pub mv1: Option<(i32, i32)>,
139 /// Whether this unit's own mode was `NEWMV` (spec's
140 /// `have_newmv_in_inter_mode`, compound modes excluded since this module
141 /// has no compound candidates). Feeds `NewMvContext` (7.10.2.8): a
142 /// neighbour's own coded-with-NEWMV state, not this block's.
143 pub is_new_mv: bool,
144 /// Whether this unit's own coded mode was `GLOBALMV`/`GLOBAL_GLOBALMV`
145 /// *and* the frame's global-motion model for its `ref_frame` is more
146 /// than `TRANSLATION` (libaom's `is_global_mv_block`, checked per
147 /// reference slot at donation time, mvref_common.c:88-92): when true,
148 /// a scan that matches this unit on its first ref slot donates the
149 /// *querying* block's own `gm_mv` there, not `mv`.
150 pub is_global_mv0: bool,
151 /// `is_global_mv0`, for the second ref slot (`ref_frame1`/`mv1`,
152 /// mvref_common.c:116-117).
153 pub is_global_mv1: bool,
154 /// The side, in 4x4 units, of the square block this unit belongs to (8
155 /// for a whole 32x32 block, 4 for a 16x16 leaf -- every block this crate
156 /// ever codes is square, so one dimension is enough). Feeds the extended
157 /// row/col scan's `processed_rows`/`processed_cols` (spec 7.10.2.2/.3,
158 /// libaom `scan_row_mbmi`/`scan_col_mbmi`'s `inc` term): a query block no
159 /// wider than its immediate neighbour has that neighbour's whole span
160 /// already covered by the immediate (-1) scan, so the extended scan
161 /// below only has to run past that. Set for *every* coded unit, intra or
162 /// inter -- libaom's `scan_row_mbmi` advances `processed_rows` from any
163 /// candidate's `bsize` regardless of whether it also casts a vote (that
164 /// requires a ref-frame match, checked separately in `add_ref_mv_candidate`).
165 pub size: usize,
166 /// The unit's height in 4x4 mi cells (== `size` for every square block;
167 /// differs only for rect partition strips, lane-rect r2). Row scans step
168 /// and weight by `size` (width), column scans by `size_h`.
169 pub size_h: usize,
170}
171
172/// The whole frame's `mi` grid, one [`MiInfo`] per 4x4 unit, in raster order.
173/// A unit an encode pass hasn't visited yet (or that sits outside the tile)
174/// reads as `None` and contributes nothing to any block's MV stack.
175#[derive(Clone, Debug)]
176pub struct MiGrid {
177 cols: usize,
178 rows: usize,
179 cells: Vec<Option<MiInfo>>,
180}
181
182impl MiGrid {
183 /// A grid of `cols` by `rows` 4x4 units, all initially unset.
184 pub fn new(cols: usize, rows: usize) -> Self {
185 Self {
186 cols,
187 rows,
188 cells: vec![None; cols * rows],
189 }
190 }
191
192 /// Records the unit at `(row, col)`. Out-of-range coordinates are a
193 /// no-op — the caller only ever addresses units inside the grid it built.
194 pub fn set(&mut self, row: usize, col: usize, info: MiInfo) {
195 if row < self.rows && col < self.cols {
196 self.cells[row * self.cols + col] = Some(info);
197 }
198 }
199
200 /// The unit at `(row, col)`, or `None` when it is outside the grid (the
201 /// tile) or hasn't been coded.
202 pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> {
203 if row < self.rows && col < self.cols {
204 self.cells[row * self.cols + col].as_ref()
205 } else {
206 None
207 }
208 }
209}
210
211/// One entry of the reference MV stack: a candidate motion vector and the
212/// total weight the neighbours that agreed on it contributed.
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub struct StackEntry {
215 /// The candidate `(row, col)` motion vector.
216 pub mv: (i32, i32),
217 /// The summed weight of every neighbour cell that voted for this MV.
218 pub weight: u32,
219}
220
221/// The result of [`find_mv_stack`]: the sorted candidate list, the two
222/// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a
223/// `NEWMV` residual is coded against, and the symbol contexts the block's
224/// mode and DRL-index syntax elements are coded with.
225#[derive(Clone, Debug, PartialEq, Eq)]
226pub struct MvStack {
227 /// The candidates, highest weight first (ties keep scan order: above,
228 /// then left, then top-right).
229 pub entries: Vec<StackEntry>,
230 /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty.
231 pub nearest_mv: (i32, i32),
232 /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two
233 /// entries.
234 pub near_mv: (i32, i32),
235 /// The predictor a `NEWMV` block's MV difference is coded against:
236 /// `nearest_mv` when the stack is non-empty, `(0, 0)` otherwise.
237 pub pred_mv: (i32, i32),
238 /// Context for the `new_mv` symbol.
239 pub new_mv_ctx: usize,
240 /// Context for the `ref_mv` symbol.
241 pub ref_mv_ctx: usize,
242 /// Context for the `zero_mv` symbol.
243 pub zero_mv_ctx: usize,
244 /// Context for each `drl_mode` symbol between consecutive stack
245 /// entries, `entries.len().saturating_sub(1)` long.
246 pub drl_ctx: Vec<usize>,
247}
248
249/// Spec 7.10.2.8's threshold a candidate's weight is compared against to
250/// pick its DRL context.
251const REF_CAT_LEVEL: u32 = 640;
252
253/// The most candidates a stack keeps (spec `MAX_REF_MV_STACK_SIZE`).
254const MAX_STACK_SIZE: usize = 8;
255
256/// The single-reference extension's own, *smaller* cap (spec's
257/// `MAX_MV_REF_CANDIDATES`, `av1/common/enums.h`): that pass only ever tops
258/// the stack up to two entries — enough to guarantee `NEARESTMV`/`NEARMV`
259/// predictors — never all the way to [`MAX_STACK_SIZE`]. libaom gates its
260/// two extension loops on `*refmv_count < MAX_MV_REF_CANDIDATES`, not the
261/// 8-entry stack cap; this module's prior hand-written pass used
262/// `MAX_STACK_SIZE` here, which is the wrong bound.
263const MAX_MV_REF_CANDIDATES: usize = 2;
264
265/// The floor libaom's `scan_row_mbmi`/`scan_col_mbmi` weight starts at
266/// before a same-or-wider candidate block can raise it (`uint16_t weight =
267/// 2;`, mvref_common.c).
268const ROW_COL_WEIGHT_FLOOR: u32 = 2;
269
270/// Fixed weight libaom's `scan_blk_mbmi` uses for both single-cell probes
271/// (`2 * mi_size_wide[BLOCK_8X8]` = `2 * 2`): the diagonal corner and the
272/// top-right, neither of which ever runs the row/col scans' real per-block
273/// weight below.
274const CORNER_WEIGHT: u32 = 4;
275
276/// Spec `MVREF_ROW_COLS`: the extended row/col scan runs at offsets `-3` and
277/// `-5` (`idx = 2..=3`), one past the immediate scan's own `-1`.
278const MVREF_ROW_COLS: usize = 3;
279
280/// Adds one candidate MV with `weight` to `candidates`, merging it into an
281/// existing entry with the same MV rather than duplicating it (spec
282/// `add_ref_mv_candidate`, 7.10.2.5).
283fn add_candidate(candidates: &mut Vec<StackEntry>, mv: (i32, i32), weight: u32) {
284 if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) {
285 entry.weight += weight;
286 } else {
287 candidates.push(StackEntry { mv, weight });
288 }
289}
290
291/// `cm->ref_frame_sign_bias[ref_frame]`, looked up from the frame header's
292/// own `ref_frame_sign_bias` (spec 5.9.2's `get_relative_dist(ref_order_hint,
293/// OrderHint) > 0` per active reference, already computed by
294/// `ec_av1_syntax::frame::read_uncompressed_header` and indexed exactly like
295/// `ref_frame_idx`: `table[ref_frame - LAST_FRAME]`). `find_mv_stack`'s
296/// no-sign-bias callers (this crate's own encoder, which only ever writes
297/// `LAST_FRAME`) pass an all-`false` table, matching this stub's old
298/// always-`false` behaviour exactly.
299fn sign_bias(table: &SignBiasTable, ref_frame: i8) -> bool {
300 table[(ref_frame - LAST_FRAME) as usize]
301}
302
303/// One `bool` per `MV_REFERENCE_FRAME` past `INTRA_FRAME`/`NONE`
304/// (`LAST_FRAME`..=`ALTREF_FRAME`), indexed `[ref_frame - LAST_FRAME]` --
305/// spec `ec_av1_syntax::frame::FrameHeader::ref_frame_sign_bias`'s own
306/// shape, threaded straight through.
307pub type SignBiasTable = [bool; 7];
308
309/// The all-`false` table every no-sign-bias caller (this crate's own
310/// encoder, and every test below) passes: correct as long as no candidate
311/// or query ever names a backward reference, exactly this module's old
312/// hardcoded `sign_bias` stub.
313pub const NO_SIGN_BIAS: SignBiasTable = [false; 7];
314
315/// One derived global-motion `(row, col)` mv per reference frame
316/// (`table[ref_frame - LAST_FRAME]`, same shape/indexing as
317/// [`SignBiasTable`]), all computed at the *querying* block's own position
318/// -- lane-gm: a neighbour donating a candidate under `MiInfo::is_global_mv0`/
319/// `MiInfo::is_global_mv1` contributes this table's entry for the matched
320/// ref frame, not its own stored `mv`/`mv1` (mvref_common.c:88-92/116-117).
321pub type GmMvTable = [(i32, i32); 7];
322
323/// The all-zero table every IDENTITY/no-gm caller passes: exact whenever no
324/// unit in the grid is ever `is_global_mv0`/`is_global_mv1` (the 14-pin
325/// list's own streams), since a substitution that never triggers reads as
326/// this reduction's old hardcoded-zero behaviour.
327pub const NO_GM_MV: GmMvTable = [(0, 0); 7];
328
329/// `table[ref_frame - LAST_FRAME]`, [`sign_bias`]'s shape for a
330/// [`GmMvTable`].
331fn gm_mv(table: &GmMvTable, ref_frame: i8) -> (i32, i32) {
332 table[(ref_frame - LAST_FRAME) as usize]
333}
334
335/// libaom's `process_single_ref_mv_candidate` (mvref_common.c): folds one
336/// already-coded neighbour into the stack as a low-weight (`2`, unboosted)
337/// filler entry, used only by the single-reference extension pass below.
338/// Unlike every scan above, this runs over *any* inter neighbour regardless
339/// of which reference frame it coded — that is the whole point of the
340/// pass (topping the stack up when the real scans found too few same-ref
341/// candidates) — and dedupes by MV value against the *whole* stack so far,
342/// silently dropping the candidate (no weight bump, unlike
343/// [`add_candidate`]) when a match is already there.
344///
345/// libaom's real signature loops `rf_idx` over the candidate's up to two
346/// coded reference-frame slots (a compound-coded neighbour donates two
347/// candidates, one per slot) -- now ported in full: a compound `candidate`
348/// (`ref_frame1`/`mv1` both `Some`) donates a second entry from its second
349/// slot too, each sign-flipped against its own reference frame independently.
350fn process_single_ref_mv_candidate(
351 candidate: &MiInfo,
352 ref_frame: i8,
353 sign_bias_table: &SignBiasTable,
354 candidates: &mut Vec<StackEntry>,
355) {
356 if !candidate.is_inter {
357 return;
358 }
359 // libaom's `process_single_ref_mv_candidate` (mvref_common.c ~440-475)
360 // reads `candidate->mv[rf_idx]` unconditionally here -- unlike
361 // `add_ref_mv_candidate`'s row/col/corner scans, this extension pass
362 // never checks `is_global_mv_block`/substitutes `gm_mv_candidates`.
363 let mut slots = [(candidate.ref_frame, candidate.mv); 2];
364 let mut n_slots = 1;
365 if let (Some(rf1), Some(mv1)) = (candidate.ref_frame1, candidate.mv1) {
366 slots[1] = (rf1, mv1);
367 n_slots = 2;
368 }
369 for &(rf, mv) in &slots[..n_slots] {
370 let mut this_mv = mv;
371 if sign_bias(sign_bias_table, rf) != sign_bias(sign_bias_table, ref_frame) {
372 this_mv = (-this_mv.0, -this_mv.1);
373 }
374 if !candidates.iter().any(|e| e.mv == this_mv) {
375 candidates.push(StackEntry {
376 mv: this_mv,
377 weight: 2,
378 });
379 }
380 }
381}
382
383/// The row scan (spec 7.10.2.2, libaom `scan_row_mbmi`): walks candidate
384/// *blocks* — not individual 4x4 cells — along the row `row_offset` mi units
385/// above the block's own row, in run-length steps sized by each candidate's
386/// own block width. Handles both the immediate probe (`row_offset == -1`)
387/// and the extended ones (`-3`, `-5`) libaom threads through the same
388/// function: `max_row_offset` is the immediate scan's own reach (spec
389/// 7.10.2.4's `find_valid_row_offset`, clamped to the tile's top edge), used
390/// only to size the weight boost below, not to gate whether this call runs
391/// at all (the caller does that via `processed_rows`/the tile edge).
392///
393/// Each matching candidate's vote is weighted `len * weight`: `len` is how
394/// many mi columns the run covers (the candidate's own width, floored to
395/// the query block's `bw4` and — at the wide/extended-scan geometries
396/// libaom's own `use_step_16`/`abs(row_offset) > 1` branches cover — raised
397/// to a block-size floor); `weight` starts at 2 and, only when the candidate
398/// is at least as wide as the query block (`bw4 <= n4`), rises to how much
399/// of `max_row_offset`'s remaining reach the candidate's own height can
400/// still cover. That `bw4 <= n4` condition is why this module's old flat
401/// `IMMEDIATE_WEIGHT = 2` was exact for every real caller before decode.rs
402/// existed: `tile.rs`'s own encoder only ever asks with `bw4 == 8` against
403/// neighbours it also always wrote at `size == 8`, and every synthetic test
404/// neighbour here uses `size: 1` (which the `n4 < weight`-floor condition
405/// keeps at the `2` floor regardless of `bw4`) — this real formula only
406/// diverges from that flat weight when a *bigger* candidate meets a
407/// *smaller* query block, which only decode.rs's variable partition sizes
408/// ever produce.
409///
410/// Threads `processed_rows` (`*mut` in libaom, `&mut` here) across every row
411/// call — immediate, then the two extended offsets — the way libaom's
412/// single stack `int` does: only the `bw4 <= n4` branch above updates it,
413/// same as libaom only updating `*processed_rows` there.
414#[allow(clippy::too_many_arguments)]
415fn scan_row(
416 grid: &MiGrid,
417 mi_row: usize,
418 mi_col: usize,
419 bw4: usize,
420 row_offset: isize,
421 max_row_offset: isize,
422 ref_frame: i8,
423 gm: &GmMvTable,
424 candidates: &mut Vec<StackEntry>,
425 newmv_count: &mut u32,
426 processed_rows: &mut usize,
427) -> bool {
428 let Some(row) = mi_row.checked_add_signed(row_offset) else {
429 return false;
430 };
431 let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 };
432 let use_step_16 = bw4 >= 16;
433 let end_mi = bw4.min(16);
434 let mut found = false;
435 let mut i = 0usize;
436 while i < end_mi {
437 let Some(info) = grid.get(row, mi_col + col_shift + i) else {
438 i += 1;
439 continue;
440 };
441 let n4 = info.size;
442 let mut len = bw4.min(n4);
443 if use_step_16 {
444 len = len.max(4);
445 } else if row_offset.unsigned_abs() > 1 {
446 len = len.max(2);
447 }
448 let mut weight = ROW_COL_WEIGHT_FLOOR;
449 if bw4 <= n4 {
450 let inc = ((-max_row_offset + row_offset + 1) as usize).min(info.size_h);
451 weight = weight.max(inc as u32);
452 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
453 }
454 if let Some(mv) = single_ref_match(info, ref_frame, gm) {
455 found = true;
456 add_candidate(candidates, mv, len as u32 * weight);
457 *newmv_count += u32::from(info.is_new_mv);
458 }
459 i += len.max(1);
460 }
461 found
462}
463
464/// libaom's `add_ref_mv_candidate` (mvref_common.c) for a single-reference
465/// query: a compound-coded neighbour still votes when *either* of its two
466/// coded reference frames matches `ref_frame`, contributing that side's own
467/// MV -- checked first slot then second, matching libaom's `for (ref = 0;
468/// ref < 1 + is_compound; ++ref)` loop order. The row/col/corner scans below
469/// used to check `info.ref_frame == ref_frame` alone, silently dropping a
470/// compound neighbour's vote whenever the match sat in its *second* slot
471/// (the class this crate's own compound-stack scan already had to close for
472/// [`find_mv_stack_compound`] -- see the module doc).
473fn single_ref_match(info: &MiInfo, ref_frame: i8, gm: &GmMvTable) -> Option<(i32, i32)> {
474 if !info.is_inter {
475 return None;
476 }
477 if info.ref_frame == ref_frame {
478 Some(if info.is_global_mv0 {
479 gm_mv(gm, ref_frame)
480 } else {
481 info.mv
482 })
483 } else if info.ref_frame1 == Some(ref_frame) {
484 if info.is_global_mv1 {
485 Some(gm_mv(gm, ref_frame))
486 } else {
487 info.mv1
488 }
489 } else {
490 None
491 }
492}
493
494/// The col scan (spec 7.10.2.3, libaom `scan_col_mbmi`): `scan_row`,
495/// transposed.
496#[allow(clippy::too_many_arguments)]
497fn scan_col(
498 grid: &MiGrid,
499 mi_row: usize,
500 mi_col: usize,
501 bh4: usize,
502 col_offset: isize,
503 max_col_offset: isize,
504 ref_frame: i8,
505 gm: &GmMvTable,
506 candidates: &mut Vec<StackEntry>,
507 newmv_count: &mut u32,
508 processed_cols: &mut usize,
509) -> bool {
510 let Some(col) = mi_col.checked_add_signed(col_offset) else {
511 return false;
512 };
513 let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 };
514 let use_step_16 = bh4 >= 16;
515 let end_mi = bh4.min(16);
516 let mut found = false;
517 let mut i = 0usize;
518 while i < end_mi {
519 let Some(info) = grid.get(mi_row + row_shift + i, col) else {
520 i += 1;
521 continue;
522 };
523 let n4 = info.size_h;
524 let mut len = bh4.min(n4);
525 if use_step_16 {
526 len = len.max(4);
527 } else if col_offset.unsigned_abs() > 1 {
528 len = len.max(2);
529 }
530 let mut weight = ROW_COL_WEIGHT_FLOOR;
531 if bh4 <= n4 {
532 let inc = ((-max_col_offset + col_offset + 1) as usize).min(info.size);
533 weight = weight.max(inc as u32);
534 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
535 }
536 if let Some(mv) = single_ref_match(info, ref_frame, gm) {
537 found = true;
538 add_candidate(candidates, mv, len as u32 * weight);
539 *newmv_count += u32::from(info.is_new_mv);
540 }
541 i += len.max(1);
542 }
543 found
544}
545
546/// The single top-right probe this reduction keeps of spec 7.10.2.4's extra
547/// scan positions, at the unit diagonally above-right of the block. Its
548/// vote is folded into the row scan's candidates (it sits on the same row
549/// as the block's neighbours above), which is what makes the row and column
550/// scans asymmetric under transposing a grid — spec has no matching
551/// bottom-left probe.
552fn scan_top_right(
553 grid: &MiGrid,
554 mi_row: usize,
555 mi_col: usize,
556 bw4: usize,
557 ref_frame: i8,
558 gm: &GmMvTable,
559 candidates: &mut Vec<StackEntry>,
560 newmv_count: &mut u32,
561) -> bool {
562 let Some(row) = mi_row.checked_sub(1) else {
563 return false;
564 };
565 let col = mi_col + bw4;
566 if let Some(info) = grid.get(row, col)
567 && let Some(mv) = single_ref_match(info, ref_frame, gm)
568 {
569 add_candidate(candidates, mv, CORNER_WEIGHT);
570 *newmv_count += u32::from(info.is_new_mv);
571 return true;
572 }
573 false
574}
575
576/// The diagonal top-left corner probe (libaom `scan_blk_mbmi` at
577/// `row_offset = col_offset = -1`, mvref_common.c's "second outer area",
578/// called *after* `nearest_match` is already captured): the single unit
579/// diagonally above-left of the block. Its match folds into the row bucket
580/// too (see module doc) but must never move `nearest_match` itself or the
581/// real `newmv_count` — callers pass a throwaway counter for the latter.
582fn scan_corner(
583 grid: &MiGrid,
584 mi_row: usize,
585 mi_col: usize,
586 ref_frame: i8,
587 gm: &GmMvTable,
588 candidates: &mut Vec<StackEntry>,
589 newmv_count: &mut u32,
590) -> bool {
591 let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
592 return false;
593 };
594 if let Some(info) = grid.get(row, col)
595 && let Some(mv) = single_ref_match(info, ref_frame, gm)
596 {
597 add_candidate(candidates, mv, CORNER_WEIGHT);
598 *newmv_count += u32::from(info.is_new_mv);
599 return true;
600 }
601 false
602}
603
604/// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added
605/// on top of the block's own span before a candidate is clamped to the
606/// frame.
607const MV_BORDER: i32 = 16 << 3;
608
609/// Clamps one candidate MV to the range spec 7.10.2.14 (libaom's
610/// `clamp_mv_ref`) allows for a `bw4`-by-`bh4` block at `(mi_row, mi_col)` in
611/// a `mi_cols`-by-`mi_rows` frame: the distance from the block's own edge to
612/// the matching frame edge, plus the block's own span and [`MV_BORDER`] of
613/// slack, in every direction.
614fn clamp_mv_ref(
615 mv: (i32, i32),
616 mi_row: usize,
617 mi_col: usize,
618 bw4: usize,
619 bh4: usize,
620 mi_cols: usize,
621 mi_rows: usize,
622) -> (i32, i32) {
623 // Pixels-to-1/8-pel: 4 mi units/pixel-row * 8 subpel steps/pixel.
624 let to_subpel = |mi_units: usize| (mi_units as i32) * 4 * 8;
625 let (bw8, bh8) = (to_subpel(bw4), to_subpel(bh4));
626 let to_left = -to_subpel(mi_col);
627 let to_right = to_subpel(mi_cols.saturating_sub(bw4).saturating_sub(mi_col));
628 let to_top = -to_subpel(mi_row);
629 let to_bottom = to_subpel(mi_rows.saturating_sub(bh4).saturating_sub(mi_row));
630
631 let (row, col) = mv;
632 (
633 row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER),
634 col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER),
635 )
636}
637
638/// Builds the reference MV stack for the `bw4`-by-`bh4` (in 4x4 units)
639/// block at `(mi_row, mi_col)`, predicting against `ref_frame`, in a frame
640/// that is `mi_cols`-by-`mi_rows` 4x4 units (used only to clamp the
641/// predictors to the frame, spec 7.10.2.14).
642pub fn find_mv_stack(
643 grid: &MiGrid,
644 mi_row: usize,
645 mi_col: usize,
646 bw4: usize,
647 bh4: usize,
648 ref_frame: i8,
649 mi_cols: usize,
650 mi_rows: usize,
651) -> MvStack {
652 find_mv_stack_with_sign_bias(
653 grid,
654 mi_row,
655 mi_col,
656 bw4,
657 bh4,
658 ref_frame,
659 mi_cols,
660 mi_rows,
661 &NO_SIGN_BIAS,
662 &NO_GM_MV,
663 None,
664 )
665}
666
667/// [`find_mv_stack`], with the frame header's real `ref_frame_sign_bias`
668/// (lane-av1refs: `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` are forward
669/// in display order, so the single-reference extension pass's borrowed-MV
670/// flip is no longer always inert once one of them is live next to a
671/// backward-biased neighbour).
672#[allow(clippy::too_many_arguments)]
673pub fn find_mv_stack_with_sign_bias(
674 grid: &MiGrid,
675 mi_row: usize,
676 mi_col: usize,
677 bw4: usize,
678 bh4: usize,
679 ref_frame: i8,
680 mi_cols: usize,
681 mi_rows: usize,
682 sign_bias_table: &SignBiasTable,
683 gm: &GmMvTable,
684 tpl: Option<TplArgs>,
685) -> MvStack {
686 let mut candidates = Vec::new();
687 let mut newmv_count = 0u32;
688
689 // libaom's `max_row_offset`/`max_col_offset` (`setup_ref_mv_list`): how
690 // far the row/col scans may reach, clamped to the tile's near edge
691 // (single-tile-per-frame here, so that's just the frame edge at 0) --
692 // `row_adj`/`col_adj` only ever fire for a sub-8x8 query block, which no
693 // real caller of this module ever is, but are ported anyway since
694 // nothing here relies on that.
695 let row_adj = bh4 < 2 && mi_row % 2 == 1;
696 let col_adj = bw4 < 2 && mi_col % 2 == 1;
697 let max_row_offset: isize = if mi_row > 0 {
698 let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj);
699 reach.max(-(mi_row as isize))
700 } else {
701 0
702 };
703 let max_col_offset: isize = if mi_col > 0 {
704 let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj);
705 reach.max(-(mi_col as isize))
706 } else {
707 0
708 };
709
710 let mut processed_rows = 0usize;
711 let mut processed_cols = 0usize;
712 let found_above = mi_row > 0
713 && scan_row(
714 grid,
715 mi_row,
716 mi_col,
717 bw4,
718 -1,
719 max_row_offset,
720 ref_frame,
721 gm,
722 &mut candidates,
723 &mut newmv_count,
724 &mut processed_rows,
725 );
726 let found_left = mi_col > 0
727 && scan_col(
728 grid,
729 mi_row,
730 mi_col,
731 bh4,
732 -1,
733 max_col_offset,
734 ref_frame,
735 gm,
736 &mut candidates,
737 &mut newmv_count,
738 &mut processed_cols,
739 );
740 let found_top_right = scan_top_right(
741 grid,
742 mi_row,
743 mi_col,
744 bw4,
745 ref_frame,
746 gm,
747 &mut candidates,
748 &mut newmv_count,
749 );
750
751 // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the
752 // top-right probe into the row side, so "found above" for context
753 // purposes means the row scan *or* the top-right one matched.
754 let row_matched = found_above || found_top_right;
755 let nearest_match = usize::from(row_matched) + usize::from(found_left);
756
757 // av1_find_mv_stack boosts only the entries the immediate scan found —
758 // exactly `candidates` at this point, before the corner probe (below)
759 // can add anything else (mvref_common.c ~line 544-545).
760 for entry in &mut candidates {
761 entry.weight += REF_CAT_LEVEL;
762 }
763
764 // Temporal MV candidates (spec 7.10.2.8's `add_tpl_ref_mv`, only reached
765 // when the frame header set `use_ref_frame_mvs`): probed over a grid of
766 // 8x8-unit offsets spanning the block (libaom's own `blk_row_end`/
767 // `blk_col_end`/`step_h`/`step_w`, every real block this crate ever
768 // codes being square and no wider than 32x32 — `BLOCK_64X64`'s own
769 // 16x16-mi-unit step branch is dead here, ported anyway since nothing
770 // relies on that), plus three "extension" samples past the block's own
771 // span (`tpl_sample_pos`) once the block is at least 8x8 and smaller
772 // than 64x64 (`allow_extension` — true for every block size this crate
773 // codes). Folded in *after* the row/col/top-right scan's own
774 // `REF_CAT_LEVEL` boost above and *before* the corner probe, matching
775 // libaom's call order in `setup_ref_mv_list` exactly (a temporal
776 // candidate never gets the boost, and the corner probe can still add a
777 // genuinely new, lower-weight entry after it).
778 let mut zero_mv_ctx = 0usize;
779 if let Some(TplArgs {
780 field,
781 cur_offset_0,
782 allow_high_precision_mv,
783 }) = tpl
784 {
785 let mut any_hit = false;
786 let voffset = bh4.max(2);
787 let hoffset = bw4.max(2);
788 let blk_row_end = bh4.min(16);
789 let blk_col_end = bw4.min(16);
790 let step_h = if bh4 >= 16 { 4 } else { 2 };
791 let step_w = if bw4 >= 16 { 4 } else { 2 };
792 let mut first_sample_missing = true;
793 let mut first_sample_far = false;
794 let mut blk_row = 0usize;
795 while blk_row < blk_row_end {
796 let mut blk_col = 0usize;
797 while blk_col < blk_col_end {
798 if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
799 field,
800 mi_row,
801 mi_col,
802 blk_row as isize,
803 blk_col as isize,
804 cur_offset_0,
805 allow_high_precision_mv,
806 ) {
807 any_hit = true;
808 if blk_row == 0 && blk_col == 0 {
809 first_sample_missing = false;
810 let this_gm_mv = gm_mv(gm, ref_frame);
811 first_sample_far = (cand.mv.0 - this_gm_mv.0).abs() >= 16
812 || (cand.mv.1 - this_gm_mv.1).abs() >= 16;
813 }
814 add_candidate(&mut candidates, cand.mv, 2);
815 }
816 blk_col += step_w;
817 }
818 blk_row += step_h;
819 }
820 // Three "extension" samples past the block's own span (libaom
821 // `tpl_sample_pos`), reachable for every 8x8..32x32 block this crate
822 // codes (`allow_extension`), gated on staying inside the block's own
823 // 64x64 superblock (`check_sb_border`).
824 let allow_extension = (2..16).contains(&bh4) && (2..16).contains(&bw4);
825 if allow_extension {
826 let sb_mask = 16isize;
827 for (row_off, col_off) in [
828 (voffset as isize, -2isize),
829 (voffset as isize, hoffset as isize),
830 (voffset as isize - 2, hoffset as isize),
831 ] {
832 let row = (mi_row as isize & (sb_mask - 1)) + row_off;
833 let col = (mi_col as isize & (sb_mask - 1)) + col_off;
834 if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask {
835 continue;
836 }
837 if let Some(cand) = crate::motion_field::add_tpl_ref_mv(
838 field,
839 mi_row,
840 mi_col,
841 row_off,
842 col_off,
843 cur_offset_0,
844 allow_high_precision_mv,
845 ) {
846 any_hit = true;
847 add_candidate(&mut candidates, cand.mv, 2);
848 }
849 }
850 }
851 if any_hit {
852 TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
853 }
854 zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
855 }
856
857 // The diagonal top-left corner probe (module doc): folds into the row
858 // side for `ref_match_count` without moving the already-captured
859 // `nearest_match`, and its own newmv-ness is a dummy count libaom
860 // discards (`&dummy_newmv_count` at the real call site).
861 let mut dummy_newmv_count = 0u32;
862 let corner_matched = scan_corner(
863 grid,
864 mi_row,
865 mi_col,
866 ref_frame,
867 gm,
868 &mut candidates,
869 &mut dummy_newmv_count,
870 );
871 // The extended row/col scan (spec 7.10.2.4's `idx = 2..MVREF_ROW_COLS`,
872 // libaom's second `scan_row_mbmi`/`scan_col_mbmi` loop): reachable only
873 // once the immediate scan's own reach (`processed_rows`/`processed_cols`,
874 // threaded across calls the way libaom's own `int`s are) leaves a gap
875 // `max_row_offset`/`max_col_offset` (the tile edge) doesn't already
876 // clip. At this module's fixed 8-mi `tile.rs` geometry with every coded
877 // cell (intra or inter) feeding coverage, that reach always hits
878 // `MVREF_ROW_COLS`'s farthest offset first -- a true no-op there (see
879 // `extended_scan_is_a_no_op_at_8mi_geometry` below); decode.rs's smaller
880 // query blocks can leave real gaps this now actually scans. Folds into
881 // the row/col match booleans, never `nearest_match`; shares the corner
882 // probe's `dummy_newmv_count` (libaom's `setup_ref_mv_list` does too).
883 let mut row_matched_ext = false;
884 let mut col_matched_ext = false;
885 for idx in 2..=MVREF_ROW_COLS {
886 let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj);
887 let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj);
888 if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs()
889 && row_offset.unsigned_abs() > processed_rows
890 && scan_row(
891 grid,
892 mi_row,
893 mi_col,
894 bw4,
895 row_offset,
896 max_row_offset,
897 ref_frame,
898 gm,
899 &mut candidates,
900 &mut dummy_newmv_count,
901 &mut processed_rows,
902 )
903 {
904 row_matched_ext = true;
905 }
906 if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs()
907 && col_offset.unsigned_abs() > processed_cols
908 && scan_col(
909 grid,
910 mi_row,
911 mi_col,
912 bh4,
913 col_offset,
914 max_col_offset,
915 ref_frame,
916 gm,
917 &mut candidates,
918 &mut dummy_newmv_count,
919 &mut processed_cols,
920 )
921 {
922 col_matched_ext = true;
923 }
924 }
925 let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
926 + usize::from(found_left || col_matched_ext);
927
928 // Highest weight first; a stable sort keeps scan order (above, left,
929 // top-right, corner) among ties, matching spec 7.10.2.6. The corner
930 // probe's un-boosted entry (if new) always sorts after the boosted
931 // ones above, matching libaom's separate two-phase ranking.
932 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
933 candidates.truncate(MAX_STACK_SIZE);
934
935 // libaom's "single reference frame extension" (`setup_ref_mv_list`,
936 // mvref_common.c, the `else` branch under "Handle single reference
937 // frame extension", calling `process_single_ref_mv_candidate`): when
938 // fewer than [`MAX_MV_REF_CANDIDATES`] (2, *not* `MAX_STACK_SIZE`) survive
939 // the scans above, top the stack up to that guarantee by re-walking the
940 // row directly above and the column directly left, gated on
941 // `refmv_count < MAX_MV_REF_CANDIDATES` per step (so it can stop after
942 // just one addition) -- over *any* inter neighbour regardless of which
943 // reference frame it coded, not just `ref_frame`. This module's doc
944 // used to call this pass a no-op ("whatever it would add was already
945 // added by the row/col scan"), true only while a stream ever has one
946 // live reference frame: once a second reference (`GOLDEN_FRAME`) is
947 // live next to `LAST_FRAME` blocks, this pass pulls in the other
948 // reference's MV as a low-weight (`2`, unboosted -- below
949 // `REF_CAT_LEVEL`) filler entry purely to make `entries.len()` (and
950 // hence how many `drl_mode` bits a `NEWMV` block reads) match the real
951 // bitstream -- round 10 (lane-av1golden8) traced a `GOLDEN_FRAME`
952 // `NEWMV` block desyncing its own `read_mv` by exactly this gap (real
953 // stack `len=2`, this module's `len=1`, one missing `drl_mode` bit).
954 // Round 11 replaced that round's hand-proved reduction (a bespoke
955 // re-scan gated on `MAX_STACK_SIZE`, weighing every hit `2` unconditionally)
956 // with this exact port: real gate is `MAX_MV_REF_CANDIDATES` (2), real
957 // reach is the block's own `bw4`/`bh4` (see `mi_size` below, not a flat
958 // 16), and dedup/weight/sign-bias now live in
959 // [`process_single_ref_mv_candidate`] itself, ported from libaom's
960 // function of the same name rather than re-derived by hand.
961 // libaom's `mi_size` for this pass (`setup_ref_mv_list`): the block's
962 // own span (`xd->width`/`xd->height`, i.e. `bw4`/`bh4` here), capped at
963 // a 64x64 superblock's 16 mi units, further clipped to the frame edge —
964 // never just "16, clipped to the frame edge" the way the prior
965 // hand-written pass had it, which over-walked past a small query
966 // block's own row/col run into cells that real neighbour scan (a wider
967 // block covering more than `bw4`/`bh4`) had already folded in above.
968 let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col));
969 let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row));
970 let mi_size = mi_width.min(mi_height);
971 if max_row_offset.unsigned_abs() >= 1 {
972 let mut idx = 0usize;
973 while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES {
974 let cand = grid.get(mi_row - 1, mi_col + idx);
975 let step = cand.map_or(1, |c| c.size).max(1);
976 if let Some(c) = cand {
977 process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
978 }
979 idx += step;
980 }
981 }
982 if max_col_offset.unsigned_abs() >= 1 {
983 let mut idx = 0usize;
984 while idx < mi_size && candidates.len() < MAX_MV_REF_CANDIDATES {
985 let cand = grid.get(mi_row + idx, mi_col - 1);
986 let step = cand.map_or(1, |c| c.size_h).max(1);
987 if let Some(c) = cand {
988 process_single_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut candidates);
989 }
990 idx += step;
991 }
992 }
993
994 let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
995 // libaom `av1_find_mv_refs` clamps EVERY stack entry once the stack is
996 // built -- the NEWMV predictor is the DRL-selected entry itself, so a
997 // raw out-of-range candidate (left neighbour coding past the frame
998 // edge) must not survive here (pinned warp-flake-5.obu: pred col 520
999 // vs libaom's clamped 384, a value-equal-entropy mv drift).
1000 for e in candidates.iter_mut() {
1001 e.mv = clamp(e.mv);
1002 }
1003 // libaom `setup_ref_mv_list`'s single-reference-extension tail
1004 // (mvref_common.c ~778-780): once the real scan/extension passes are
1005 // done, every `mv_ref_list` slot still empty (`idx >= refmv_count`, up
1006 // to `MAX_MV_REF_CANDIDATES`=2) is filled with `gm_mv_candidates[0]` --
1007 // this query block's OWN global motion vector for `ref_frame`, not a
1008 // zero fallback -- and that fill is UNclamped (only the real
1009 // `ref_mv_stack` entries go through `clamp_mv_ref` above). r6: this was
1010 // `(0, 0)` here, invisible whenever a live ref's global motion is
1011 // itself translation/identity (an unclamped gm mv of exactly (0,0)),
1012 // and wrong the moment a ref carries a real ROTZOOM/AFFINE model and a
1013 // query block's stack comes up short -- e.g. the very first block of a
1014 // frame (mi=(0,0), no neighbours at all, `nearest_match`/`ref_match_count`
1015 // both 0) coded NEWMV against a ROTZOOM-global ref: range-ladder against
1016 // aomdec's `EC_TRACE_MODE` confirmed identical symbol consumption (same
1017 // `rng` before/after mode info) with a different final mv purely from
1018 // this predictor gap.
1019 let gm_fallback = gm_mv(gm, ref_frame);
1020 let nearest_mv = candidates.first().map_or(gm_fallback, |e| clamp(e.mv));
1021 let near_mv = candidates.get(1).map_or(gm_fallback, |e| clamp(e.mv));
1022 let pred_mv = nearest_mv;
1023
1024 // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c
1025 // ~line 619-643). `new_mv_ctx` depends on `nearest_match` and the real
1026 // `newmv_count` alone — libaom's switch never reads `ref_match_count`
1027 // for those bits, so this half was already exact before this round.
1028 let new_mv_ctx = match nearest_match {
1029 // libaom's `case 0` also sets this bit from `ref_match_count`
1030 // (`mode_context[ref_frame] |= 1` when `ref_match_count >= 1`,
1031 // mvref_common.c ~line 621) — the corner-probe-derived count, not
1032 // `nearest_match` alone, despite this module's doc comment above
1033 // having claimed the opposite for several rounds.
1034 0 => usize::from(ref_match_count >= 1),
1035 1 => {
1036 if newmv_count > 0 {
1037 2
1038 } else {
1039 3
1040 }
1041 }
1042 _ => {
1043 if newmv_count >= 1 {
1044 4
1045 } else {
1046 5
1047 }
1048 }
1049 };
1050 // `ref_mv_ctx` (the `REFMV_OFFSET` half of the same switch) genuinely
1051 // depends on both counts — this is the part that was wrongly collapsed
1052 // to `nearest_match` alone (see module doc / crate report).
1053 let ref_mv_ctx = match nearest_match {
1054 0 => match ref_match_count {
1055 0 => 0,
1056 1 => 1,
1057 _ => 2,
1058 },
1059 1 => {
1060 if ref_match_count >= 2 {
1061 4
1062 } else {
1063 3
1064 }
1065 }
1066 _ => 5,
1067 };
1068 // `zero_mv_ctx` was already computed above, from the temporal-MV pass
1069 // when `tpl` is `Some` (GLOBALMV_OFFSET, spec 7.10.2.8) — `0` otherwise,
1070 // exactly this reduction's old always-0 behaviour when
1071 // `use_ref_frame_mvs` is unset.
1072
1073 // av1_drl_ctx (mvref_common.h): weight was boosted in place above for
1074 // the nearest entries only, so this now compares the real stored weight
1075 // against the threshold directly, the way libaom does.
1076 let drl_ctx = candidates
1077 .windows(2)
1078 .map(|w| {
1079 let (a, b) = (w[0].weight, w[1].weight);
1080 if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
1081 0
1082 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
1083 1
1084 } else {
1085 2
1086 }
1087 })
1088 .collect();
1089
1090 MvStack {
1091 entries: candidates,
1092 nearest_mv,
1093 near_mv,
1094 pred_mv,
1095 new_mv_ctx,
1096 ref_mv_ctx,
1097 zero_mv_ctx,
1098 drl_ctx,
1099 }
1100}
1101
1102/// One neighbour's vote for a compound-reference (spec `RefFrame[0]` *and*
1103/// `RefFrame[1]` both active) candidate: two full motion vectors and the
1104/// combined weight — spec 7.10.2's compound half of `add_ref_mv_candidate`
1105/// (libaom `mvref_common.c`, the `is_compound` branch of `scan_row_mbmi`/
1106/// `scan_col_mbmi`/`scan_blk_mbmi`).
1107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1108pub struct CompoundStackEntry {
1109 /// The candidate's vote for `RefFrame[0]`'s motion vector.
1110 pub mv0: (i32, i32),
1111 /// The candidate's vote for `RefFrame[1]`'s motion vector.
1112 pub mv1: (i32, i32),
1113 /// The summed weight of every neighbour cell that voted for this pair.
1114 pub weight: u32,
1115}
1116
1117/// [`find_mv_stack_compound`]'s result — [`MvStack`]'s shape, doubled for
1118/// the reference pair.
1119#[derive(Clone, Debug, PartialEq, Eq)]
1120pub struct CompoundMvStack {
1121 /// The candidates, highest weight first.
1122 pub entries: Vec<CompoundStackEntry>,
1123 /// `RefStackMv[0]` for both refs, or `((0,0),(0,0))` when the stack is
1124 /// empty.
1125 pub nearest_mv: ((i32, i32), (i32, i32)),
1126 /// `RefStackMv[1]` for both refs, or `((0,0),(0,0))` when the stack has
1127 /// fewer than two entries.
1128 pub near_mv: ((i32, i32), (i32, i32)),
1129 /// The predictor pair a `NEW_NEWMV`-family block's MV differences are
1130 /// coded against.
1131 pub pred_mv: ((i32, i32), (i32, i32)),
1132 /// Context for the compound `new_mv` symbol.
1133 pub new_mv_ctx: usize,
1134 /// Context for the compound `ref_mv` symbol.
1135 pub ref_mv_ctx: usize,
1136 /// Context for the compound `zero_mv` symbol.
1137 pub zero_mv_ctx: usize,
1138 /// Context for each `drl_mode` symbol between consecutive stack entries.
1139 pub drl_ctx: Vec<usize>,
1140}
1141
1142/// [`add_candidate`], doubled: dedupes on the whole `(mv0, mv1)` pair.
1143fn add_compound_candidate(
1144 candidates: &mut Vec<CompoundStackEntry>,
1145 mv0: (i32, i32),
1146 mv1: (i32, i32),
1147 weight: u32,
1148) {
1149 if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) {
1150 entry.weight += weight;
1151 } else {
1152 candidates.push(CompoundStackEntry { mv0, mv1, weight });
1153 }
1154}
1155
1156/// The compound row scan (spec 7.10.2.2's compound branch, libaom
1157/// `scan_row_mbmi`'s `is_compound` path): [`scan_row`]'s weight/run-length
1158/// math unchanged, but a candidate only votes when *both* its `ref_frame`
1159/// and `ref_frame1` equal the query's pair exactly, in that order — a
1160/// compound pair is always encoded forward-then-backward
1161/// (`RefFrame[0]`/`RefFrame[1]`), so unlike [`process_single_ref_mv_candidate`]'s
1162/// extension pass, no sign-bias flip ever applies to an exact-pair scan
1163/// match (libaom's own `scan_row_mbmi` compound branch doesn't flip either).
1164#[allow(clippy::too_many_arguments)]
1165fn scan_row_compound(
1166 grid: &MiGrid,
1167 mi_row: usize,
1168 mi_col: usize,
1169 bw4: usize,
1170 row_offset: isize,
1171 max_row_offset: isize,
1172 ref_frame: (i8, i8),
1173 gm: &GmMvTable,
1174 candidates: &mut Vec<CompoundStackEntry>,
1175 newmv_count: &mut u32,
1176 processed_rows: &mut usize,
1177) -> bool {
1178 let Some(row) = mi_row.checked_add_signed(row_offset) else {
1179 return false;
1180 };
1181 let col_shift: usize = if row_offset.unsigned_abs() > 1 { 1 } else { 0 };
1182 let use_step_16 = bw4 >= 16;
1183 let end_mi = bw4.min(16);
1184 let mut found = false;
1185 let mut i = 0usize;
1186 while i < end_mi {
1187 let Some(info) = grid.get(row, mi_col + col_shift + i) else {
1188 i += 1;
1189 continue;
1190 };
1191 let n4 = info.size;
1192 let mut len = bw4.min(n4);
1193 if use_step_16 {
1194 len = len.max(4);
1195 } else if row_offset.unsigned_abs() > 1 {
1196 len = len.max(2);
1197 }
1198 let mut weight = ROW_COL_WEIGHT_FLOOR;
1199 if bw4 <= n4 {
1200 let inc = ((-max_row_offset + row_offset + 1) as usize).min(info.size_h);
1201 weight = weight.max(inc as u32);
1202 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
1203 }
1204 if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1205 found = true;
1206 add_compound_candidate(
1207 candidates,
1208 if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { info.mv },
1209 if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { info.mv1.unwrap_or((0, 0)) },
1210 len as u32 * weight,
1211 );
1212 *newmv_count += u32::from(info.is_new_mv);
1213 }
1214 i += len.max(1);
1215 }
1216 found
1217}
1218
1219/// The compound col scan (spec 7.10.2.3's compound branch): [`scan_row_compound`],
1220/// transposed — mirrors [`scan_col`]/[`scan_row`]'s own relationship.
1221#[allow(clippy::too_many_arguments)]
1222fn scan_col_compound(
1223 grid: &MiGrid,
1224 mi_row: usize,
1225 mi_col: usize,
1226 bh4: usize,
1227 col_offset: isize,
1228 max_col_offset: isize,
1229 ref_frame: (i8, i8),
1230 gm: &GmMvTable,
1231 candidates: &mut Vec<CompoundStackEntry>,
1232 newmv_count: &mut u32,
1233 processed_cols: &mut usize,
1234) -> bool {
1235 let Some(col) = mi_col.checked_add_signed(col_offset) else {
1236 return false;
1237 };
1238 let row_shift: usize = if col_offset.unsigned_abs() > 1 { 1 } else { 0 };
1239 let use_step_16 = bh4 >= 16;
1240 let end_mi = bh4.min(16);
1241 let mut found = false;
1242 let mut i = 0usize;
1243 while i < end_mi {
1244 let Some(info) = grid.get(mi_row + row_shift + i, col) else {
1245 i += 1;
1246 continue;
1247 };
1248 let n4 = info.size_h;
1249 let mut len = bh4.min(n4);
1250 if use_step_16 {
1251 len = len.max(4);
1252 } else if col_offset.unsigned_abs() > 1 {
1253 len = len.max(2);
1254 }
1255 let mut weight = ROW_COL_WEIGHT_FLOOR;
1256 if bh4 <= n4 {
1257 let inc = ((-max_col_offset + col_offset + 1) as usize).min(info.size);
1258 weight = weight.max(inc as u32);
1259 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
1260 }
1261 if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 == Some(ref_frame.1) {
1262 found = true;
1263 add_compound_candidate(
1264 candidates,
1265 if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { info.mv },
1266 if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { info.mv1.unwrap_or((0, 0)) },
1267 len as u32 * weight,
1268 );
1269 *newmv_count += u32::from(info.is_new_mv);
1270 }
1271 i += len.max(1);
1272 }
1273 found
1274}
1275
1276/// The compound top-right probe ([`scan_top_right`]'s pair-matched twin).
1277#[allow(clippy::too_many_arguments)]
1278fn scan_top_right_compound(
1279 grid: &MiGrid,
1280 mi_row: usize,
1281 mi_col: usize,
1282 bw4: usize,
1283 ref_frame: (i8, i8),
1284 gm: &GmMvTable,
1285 candidates: &mut Vec<CompoundStackEntry>,
1286 newmv_count: &mut u32,
1287) -> bool {
1288 let Some(row) = mi_row.checked_sub(1) else {
1289 return false;
1290 };
1291 let col = mi_col + bw4;
1292 if let Some(info) = grid.get(row, col)
1293 && info.is_inter
1294 && info.ref_frame == ref_frame.0
1295 && info.ref_frame1 == Some(ref_frame.1)
1296 {
1297 add_compound_candidate(
1298 candidates,
1299 if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { info.mv },
1300 if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { info.mv1.unwrap_or((0, 0)) },
1301 CORNER_WEIGHT,
1302 );
1303 *newmv_count += u32::from(info.is_new_mv);
1304 return true;
1305 }
1306 false
1307}
1308
1309/// The compound diagonal corner probe ([`scan_corner`]'s pair-matched twin).
1310fn scan_corner_compound(
1311 grid: &MiGrid,
1312 mi_row: usize,
1313 mi_col: usize,
1314 ref_frame: (i8, i8),
1315 gm: &GmMvTable,
1316 candidates: &mut Vec<CompoundStackEntry>,
1317 newmv_count: &mut u32,
1318) -> bool {
1319 let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else {
1320 return false;
1321 };
1322 if let Some(info) = grid.get(row, col)
1323 && info.is_inter
1324 && info.ref_frame == ref_frame.0
1325 && info.ref_frame1 == Some(ref_frame.1)
1326 {
1327 add_compound_candidate(
1328 candidates,
1329 if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { info.mv },
1330 if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { info.mv1.unwrap_or((0, 0)) },
1331 CORNER_WEIGHT,
1332 );
1333 *newmv_count += u32::from(info.is_new_mv);
1334 return true;
1335 }
1336 false
1337}
1338
1339/// Per-side unresolved-MV accumulator [`process_compound_ref_mv_candidate`]
1340/// fills across every candidate the compound extension pass walks: up to two
1341/// motion vectors that matched `ref_frame.0`/`.1` exactly (`ref_id`), and up
1342/// to two more borrowed from a differently-referenced but still-inter
1343/// neighbour under the sign-bias flip [`process_single_ref_mv_candidate`]
1344/// also applies (`ref_diff`). Ported from libaom's `setup_ref_mv_list`
1345/// (`mvref_common.c`, `process_compound_ref_mv_candidate` ~line 380-430 plus
1346/// the combine step at ~696-762): the extension walk fills this once across
1347/// the whole row-then-col scan, and [`combine_compound_candidates`] below
1348/// zips the two independently-filled sides back into full pair candidates.
1349#[derive(Default)]
1350struct CompoundRefLists {
1351 ref_id: [Vec<(i32, i32)>; 2],
1352 ref_diff: [Vec<(i32, i32)>; 2],
1353}
1354
1355/// libaom's `process_compound_ref_mv_candidate`: folds one already-coded
1356/// neighbour's up to two reference slots into `lists`, split by which side
1357/// of `ref_frame` (the query block's own compound pair) each slot's own
1358/// reference frame matches — an exact match goes to that side's `ref_id`
1359/// list, anything else (still inter, wrong reference) goes to `ref_diff`
1360/// under the usual sign-bias flip.
1361fn process_compound_ref_mv_candidate(
1362 candidate: &MiInfo,
1363 ref_frame: (i8, i8),
1364 sign_bias_table: &SignBiasTable,
1365 lists: &mut CompoundRefLists,
1366) {
1367 if !candidate.is_inter {
1368 return;
1369 }
1370 let slots = [
1371 Some((candidate.ref_frame, candidate.mv)),
1372 candidate
1373 .ref_frame1
1374 // An interintra neighbour stores INTRA_FRAME (0) here; libaom's
1375 // ref-diff scan requires `can_rf > INTRA_FRAME`
1376 // (process_compound_ref_mv_candidate), so it contributes nothing.
1377 .filter(|&rf1| rf1 > 0)
1378 .map(|rf1| (rf1, candidate.mv1.unwrap_or((0, 0)))),
1379 ];
1380 for (candidate_ref, candidate_mv) in slots.into_iter().flatten() {
1381 for (i, side_ref) in [ref_frame.0, ref_frame.1].into_iter().enumerate() {
1382 if candidate_ref == side_ref {
1383 if lists.ref_id[i].len() < 2 {
1384 lists.ref_id[i].push(candidate_mv);
1385 }
1386 } else if lists.ref_diff[i].len() < 2 {
1387 let mut mv = candidate_mv;
1388 if sign_bias(sign_bias_table, candidate_ref) != sign_bias(sign_bias_table, side_ref)
1389 {
1390 mv = (-mv.0, -mv.1);
1391 }
1392 lists.ref_diff[i].push(mv);
1393 }
1394 }
1395 }
1396}
1397
1398/// libaom's combine step (`setup_ref_mv_list`, `mvref_common.c` ~696-720):
1399/// zips each side's `ref_id` (exact matches) then `ref_diff` (borrowed,
1400/// sign-flipped) entries, position-wise and independently per side, into up
1401/// to two full `(mv0, mv1)` pair candidates — missing slots default to
1402/// `(0, 0)`, matching libaom's zero-initialized `combined_mvs`.
1403fn combine_compound_candidates(lists: &CompoundRefLists) -> [((i32, i32), (i32, i32)); 2] {
1404 let side_slots = |side: usize| -> [(i32, i32); 2] {
1405 let merged: Vec<(i32, i32)> = lists.ref_id[side]
1406 .iter()
1407 .chain(lists.ref_diff[side].iter())
1408 .take(2)
1409 .copied()
1410 .collect();
1411 std::array::from_fn(|i| merged.get(i).copied().unwrap_or((0, 0)))
1412 };
1413 let side0 = side_slots(0);
1414 let side1 = side_slots(1);
1415 [(side0[0], side1[0]), (side0[1], side1[1])]
1416}
1417
1418/// [`find_mv_stack_with_sign_bias`]'s compound-reference twin (spec
1419/// 7.10.2's `is_compound` path throughout): builds the reference MV stack
1420/// for a block predicted against *two* simultaneously-active reference
1421/// frames (`ref_frame.0`, `ref_frame.1`), keeping every existing
1422/// single-reference caller of [`find_mv_stack`]/[`find_mv_stack_with_sign_bias`]
1423/// untouched — this is a new, parallel entry point, not an extension of the
1424/// single-ref one. Same reduction scope as the single-ref module doc
1425/// (single tile, square blocks, `IDENTITY` global motion only); the
1426/// mode-context switch below reuses the identical `(nearest_match,
1427/// ref_match_count)` derivation the single-ref path uses, since libaom's own
1428/// switch statement (`mvref_common.c` ~619-643) is ref-count-agnostic — it
1429/// only ever reads those two counts, regardless of which `MODE_CTX_REF_FRAMES`
1430/// slot `mode_context` it's indexing.
1431///
1432/// The compound extension combine step (`setup_ref_mv_list`, ~line 700-754)
1433/// and the temporal `add_tpl_ref_mv` fold-in (~line 341-433) are both exact
1434/// ports of libaom's real behaviour as of r5 — see the inline comments at
1435/// each site.
1436#[allow(clippy::too_many_arguments)]
1437#[allow(clippy::too_many_arguments)]
1438pub fn find_mv_stack_compound(
1439 grid: &MiGrid,
1440 mi_row: usize,
1441 mi_col: usize,
1442 bw4: usize,
1443 bh4: usize,
1444 ref_frame: (i8, i8),
1445 mi_cols: usize,
1446 mi_rows: usize,
1447 sign_bias_table: &SignBiasTable,
1448 gm: &GmMvTable,
1449 tpl: Option<CompoundTplArgs>,
1450) -> CompoundMvStack {
1451 let mut candidates: Vec<CompoundStackEntry> = Vec::new();
1452 let mut newmv_count = 0u32;
1453
1454 let row_adj = bh4 < 2 && mi_row % 2 == 1;
1455 let col_adj = bw4 < 2 && mi_col % 2 == 1;
1456 let max_row_offset: isize = if mi_row > 0 {
1457 let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj);
1458 reach.max(-(mi_row as isize))
1459 } else {
1460 0
1461 };
1462 let max_col_offset: isize = if mi_col > 0 {
1463 let reach = if bw4 < 2 { -4 } else { -6 } + isize::from(col_adj);
1464 reach.max(-(mi_col as isize))
1465 } else {
1466 0
1467 };
1468
1469 let mut processed_rows = 0usize;
1470 let mut processed_cols = 0usize;
1471 let found_above = mi_row > 0
1472 && scan_row_compound(
1473 grid,
1474 mi_row,
1475 mi_col,
1476 bw4,
1477 -1,
1478 max_row_offset,
1479 ref_frame,
1480 gm,
1481 &mut candidates,
1482 &mut newmv_count,
1483 &mut processed_rows,
1484 );
1485 let found_left = mi_col > 0
1486 && scan_col_compound(
1487 grid,
1488 mi_row,
1489 mi_col,
1490 bh4,
1491 -1,
1492 max_col_offset,
1493 ref_frame,
1494 gm,
1495 &mut candidates,
1496 &mut newmv_count,
1497 &mut processed_cols,
1498 );
1499 let found_top_right = scan_top_right_compound(
1500 grid,
1501 mi_row,
1502 mi_col,
1503 bw4,
1504 ref_frame,
1505 gm,
1506 &mut candidates,
1507 &mut newmv_count,
1508 );
1509
1510 let row_matched = found_above || found_top_right;
1511 let nearest_match = usize::from(row_matched) + usize::from(found_left);
1512
1513 for entry in &mut candidates {
1514 entry.weight += REF_CAT_LEVEL;
1515 }
1516
1517 // Temporal compound candidates (spec 7.10.2.8's compound
1518 // `add_tpl_ref_mv`): the same projected field, read once per side of the
1519 // pair through the existing single-ref [`crate::motion_field::add_tpl_ref_mv`]
1520 // — each side's own `cur_offset` scales the *same* stored candidate to
1521 // that side's reference frame. libaom's real `add_tpl_ref_mv` looks up
1522 // the stored `mfmv0`/`ref_frame_offset` pair exactly once per `(blk_row,
1523 // blk_col)` and, if present, always projects it to *both* sides (the
1524 // lookup itself never fails for one side and succeeds for the other);
1525 // a missing side there is `INVALID_MV`/global-motion zero-fill, never a
1526 // dropped candidate. Ported exactly: each side is read independently and
1527 // a missing side zero-fills rather than vetoing the pair.
1528 let mut zero_mv_ctx = 0usize;
1529 if let Some(CompoundTplArgs {
1530 field,
1531 cur_offset_0,
1532 cur_offset_1,
1533 allow_high_precision_mv,
1534 }) = tpl
1535 {
1536 let mut any_hit = false;
1537 let blk_row_end = bh4.min(16);
1538 let blk_col_end = bw4.min(16);
1539 let step_h = if bh4 >= 16 { 4 } else { 2 };
1540 let step_w = if bw4 >= 16 { 4 } else { 2 };
1541 let mut first_sample_missing = true;
1542 let mut first_sample_far = false;
1543 let mut blk_row = 0usize;
1544 while blk_row < blk_row_end {
1545 let mut blk_col = 0usize;
1546 while blk_col < blk_col_end {
1547 let cand0 = crate::motion_field::add_tpl_ref_mv(
1548 field,
1549 mi_row,
1550 mi_col,
1551 blk_row as isize,
1552 blk_col as isize,
1553 cur_offset_0,
1554 allow_high_precision_mv,
1555 );
1556 let cand1 = crate::motion_field::add_tpl_ref_mv(
1557 field,
1558 mi_row,
1559 mi_col,
1560 blk_row as isize,
1561 blk_col as isize,
1562 cur_offset_1,
1563 allow_high_precision_mv,
1564 );
1565 if cand0.is_some() || cand1.is_some() {
1566 any_hit = true;
1567 let mv0 = cand0.map_or((0, 0), |c| c.mv);
1568 let mv1 = cand1.map_or((0, 0), |c| c.mv);
1569 if blk_row == 0 && blk_col == 0 {
1570 first_sample_missing = false;
1571 let this_gm0 = gm_mv(gm, ref_frame.0);
1572 let this_gm1 = gm_mv(gm, ref_frame.1);
1573 first_sample_far = (mv0.0 - this_gm0.0).abs() >= 16
1574 || (mv0.1 - this_gm0.1).abs() >= 16
1575 || (mv1.0 - this_gm1.0).abs() >= 16
1576 || (mv1.1 - this_gm1.1).abs() >= 16;
1577 }
1578 add_compound_candidate(&mut candidates, mv0, mv1, 2);
1579 }
1580 blk_col += step_w;
1581 }
1582 blk_row += step_h;
1583 }
1584 if any_hit {
1585 TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1586 }
1587 zero_mv_ctx = usize::from(first_sample_missing || first_sample_far);
1588 }
1589
1590 let mut dummy_newmv_count = 0u32;
1591 let corner_matched = scan_corner_compound(
1592 grid,
1593 mi_row,
1594 mi_col,
1595 ref_frame,
1596 gm,
1597 &mut candidates,
1598 &mut dummy_newmv_count,
1599 );
1600 let mut row_matched_ext = false;
1601 let mut col_matched_ext = false;
1602 for idx in 2..=MVREF_ROW_COLS {
1603 let row_offset = -((idx as isize) * 2) + 1 + isize::from(row_adj);
1604 let col_offset = -((idx as isize) * 2) + 1 + isize::from(col_adj);
1605 if row_offset.unsigned_abs() <= max_row_offset.unsigned_abs()
1606 && row_offset.unsigned_abs() > processed_rows
1607 && scan_row_compound(
1608 grid,
1609 mi_row,
1610 mi_col,
1611 bw4,
1612 row_offset,
1613 max_row_offset,
1614 ref_frame,
1615 gm,
1616 &mut candidates,
1617 &mut dummy_newmv_count,
1618 &mut processed_rows,
1619 )
1620 {
1621 row_matched_ext = true;
1622 }
1623 if col_offset.unsigned_abs() <= max_col_offset.unsigned_abs()
1624 && col_offset.unsigned_abs() > processed_cols
1625 && scan_col_compound(
1626 grid,
1627 mi_row,
1628 mi_col,
1629 bh4,
1630 col_offset,
1631 max_col_offset,
1632 ref_frame,
1633 gm,
1634 &mut candidates,
1635 &mut dummy_newmv_count,
1636 &mut processed_cols,
1637 )
1638 {
1639 col_matched_ext = true;
1640 }
1641 }
1642 let ref_match_count = usize::from(row_matched || corner_matched || row_matched_ext)
1643 + usize::from(found_left || col_matched_ext);
1644
1645 candidates.sort_by_key(|e| std::cmp::Reverse(e.weight));
1646 candidates.truncate(MAX_STACK_SIZE);
1647
1648 // The compound extension pass (libaom's `setup_ref_mv_list`, "Handle
1649 // compound reference frame extension"): gather across the row directly
1650 // above and the column directly left (same `mi_size` reach as the
1651 // single-ref pass), then combine once.
1652 let mi_width = (16usize).min(bw4).min(mi_cols.saturating_sub(mi_col));
1653 let mi_height = (16usize).min(bh4).min(mi_rows.saturating_sub(mi_row));
1654 let mi_size = mi_width.min(mi_height);
1655 if candidates.len() < MAX_MV_REF_CANDIDATES {
1656 let mut lists = CompoundRefLists::default();
1657 if max_row_offset.unsigned_abs() >= 1 {
1658 let mut idx = 0usize;
1659 while idx < mi_size {
1660 let cand = grid.get(mi_row - 1, mi_col + idx);
1661 let step = cand.map_or(1, |c| c.size).max(1);
1662 if let Some(c) = cand {
1663 process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1664 }
1665 idx += step;
1666 }
1667 }
1668 if max_col_offset.unsigned_abs() >= 1 {
1669 let mut idx = 0usize;
1670 while idx < mi_size {
1671 let cand = grid.get(mi_row + idx, mi_col - 1);
1672 let step = cand.map_or(1, |c| c.size_h).max(1);
1673 if let Some(c) = cand {
1674 process_compound_ref_mv_candidate(c, ref_frame, sign_bias_table, &mut lists);
1675 }
1676 idx += step;
1677 }
1678 }
1679 // libaom's real dedup (`setup_ref_mv_list` ~735-754): when the stack
1680 // already has exactly one entry, compare only `comp_list[0]` against
1681 // it and, on a match, take `comp_list[1]` instead (skip, no weight
1682 // bump) — otherwise append `comp_list[0]` as a brand-new entry. When
1683 // the stack is empty, both `comp_list[0]` and `comp_list[1]` are
1684 // appended unconditionally, with no dedup check at all.
1685 let comp_list = combine_compound_candidates(&lists);
1686 if candidates.len() == 1 {
1687 let (mv0, mv1) = if comp_list[0] == (candidates[0].mv0, candidates[0].mv1) {
1688 comp_list[1]
1689 } else {
1690 comp_list[0]
1691 };
1692 candidates.push(CompoundStackEntry {
1693 mv0,
1694 mv1,
1695 weight: 2,
1696 });
1697 } else if candidates.is_empty() {
1698 for (mv0, mv1) in comp_list {
1699 candidates.push(CompoundStackEntry {
1700 mv0,
1701 mv1,
1702 weight: 2,
1703 });
1704 }
1705 }
1706 }
1707
1708 let clamp = |mv| clamp_mv_ref(mv, mi_row, mi_col, bw4, bh4, mi_cols, mi_rows);
1709 // Same as the single-ref builder: libaom clamps every stack entry, and
1710 // DRL reads the entries directly.
1711 for e in candidates.iter_mut() {
1712 e.mv0 = clamp(e.mv0);
1713 e.mv1 = clamp(e.mv1);
1714 }
1715 let nearest_mv = candidates
1716 .first()
1717 .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1718 let near_mv = candidates
1719 .get(1)
1720 .map_or(((0, 0), (0, 0)), |e| (clamp(e.mv0), clamp(e.mv1)));
1721 let pred_mv = if candidates.is_empty() {
1722 ((0, 0), (0, 0))
1723 } else {
1724 nearest_mv
1725 };
1726
1727 let new_mv_ctx = match nearest_match {
1728 0 => usize::from(ref_match_count >= 1),
1729 1 => {
1730 if newmv_count > 0 {
1731 2
1732 } else {
1733 3
1734 }
1735 }
1736 _ => {
1737 if newmv_count >= 1 {
1738 4
1739 } else {
1740 5
1741 }
1742 }
1743 };
1744 let ref_mv_ctx = match nearest_match {
1745 0 => match ref_match_count {
1746 0 => 0,
1747 1 => 1,
1748 _ => 2,
1749 },
1750 1 => {
1751 if ref_match_count >= 2 {
1752 4
1753 } else {
1754 3
1755 }
1756 }
1757 _ => 5,
1758 };
1759
1760 let drl_ctx = candidates
1761 .windows(2)
1762 .map(|w| {
1763 let (a, b) = (w[0].weight, w[1].weight);
1764 if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL {
1765 0
1766 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL {
1767 1
1768 } else {
1769 2
1770 }
1771 })
1772 .collect();
1773
1774 CompoundMvStack {
1775 entries: candidates,
1776 nearest_mv,
1777 near_mv,
1778 pred_mv,
1779 new_mv_ctx,
1780 ref_mv_ctx,
1781 zero_mv_ctx,
1782 drl_ctx,
1783 }
1784}
1785
1786/// [`find_mv_stack_compound`]'s temporal-MV inputs — [`TplArgs`], doubled:
1787/// one `cur_offset` per side of the pair (`get_relative_dist(OrderHint,
1788/// OrderHints[ref_frame.N - LAST_FRAME])`, spec 7.9.3), since a compound
1789/// query projects the same stored field twice, once per reference.
1790pub struct CompoundTplArgs<'a> {
1791 /// The current frame's projected temporal motion field.
1792 pub field: &'a crate::motion_field::TplField,
1793 /// `get_relative_dist` for `ref_frame.0`.
1794 pub cur_offset_0: i32,
1795 /// `get_relative_dist` for `ref_frame.1`.
1796 pub cur_offset_1: i32,
1797 /// The frame header's own `allow_high_precision_mv`.
1798 pub allow_high_precision_mv: bool,
1799}
1800
1801/// The single-reference context shared by the `single_ref_p1`/`p3`/`p4`
1802/// binary decisions this crate's LAST-only reference chain codes (spec
1803/// 5.11.25; libaom's `av1_get_pred_context_single_ref_p1/p3/p4`,
1804/// `pred_common.c`). Each of those three functions compares a forward-ref
1805/// neighbour count against a same-direction count that is always zero in a
1806/// LAST-only world (no LAST2/LAST3/GOLDEN/backward candidate ever exists
1807/// here), which collapses all three of libaom's formulas to the same
1808/// two-valued test: "is there an inter neighbour at all". `has_inter`
1809/// gathers that over the block's whole span, the way spec 5.11.39 reads any
1810/// neighbour-derived context.
1811pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize {
1812 if has_inter_neighbour { 2 } else { 1 }
1813}
1814
1815/// `MV_REFERENCE_FRAME` values a single (non-compound) reference can name
1816/// (spec 6.10.24's `ref_frame` alphabet; libaom `av1/common/enums.h`).
1817pub(crate) const LAST_FRAME: i8 = 1;
1818pub(crate) const LAST2_FRAME: i8 = 2;
1819pub(crate) const LAST3_FRAME: i8 = 3;
1820pub(crate) const GOLDEN_FRAME: i8 = 4;
1821pub(crate) const BWDREF_FRAME: i8 = 5;
1822pub(crate) const ALTREF2_FRAME: i8 = 6;
1823pub(crate) const ALTREF_FRAME: i8 = 7;
1824
1825/// libaom `pred_common.c`'s shared shape behind every `single_ref_p*`/
1826/// `comp_ref*` context function once compound prediction (a second ref per
1827/// neighbour) is out of scope: count how many of the immediate above/left
1828/// neighbours (spec 5.11.25's own single-neighbour read, not a whole-span
1829/// scan -- `av1_collect_neighbors_ref_counts`, `MACROBLOCKD::above_mbmi`/
1830/// `left_mbmi`) coded a reference in `a_set` vs. `b_set`, and compare: fewer
1831/// `a`s than `b`s is context 0, equal is 1 (also every unavailable-neighbour
1832/// case, both counts zero), more `a`s is 2.
1833// libaom `av1_collect_neighbors_ref_counts` (mvref_common.h): a neighbour
1834// contributes ONE count per reference frame it actually names, which for a
1835// compound neighbour is BOTH `ref_frame[0]` and `ref_frame[1]` -- not just
1836// its first. Every one of these vote functions takes each side's pair
1837// (`ref0` always, `ref1` only for a compound neighbour) so a compound
1838// neighbour is not undercounted the way a single scalar per side would.
1839#[allow(clippy::too_many_arguments)]
1840fn ref_ctx(
1841 above0: Option<i8>,
1842 above1: Option<i8>,
1843 left0: Option<i8>,
1844 left1: Option<i8>,
1845 a_set: &[i8],
1846 b_set: &[i8],
1847) -> usize {
1848 let refs = [above0, above1, left0, left1];
1849 let a = refs.into_iter().flatten().filter(|r| a_set.contains(r)).count();
1850 let b = refs.into_iter().flatten().filter(|r| b_set.contains(r)).count();
1851 match a.cmp(&b) {
1852 std::cmp::Ordering::Less => 0,
1853 std::cmp::Ordering::Equal => 1,
1854 std::cmp::Ordering::Greater => 2,
1855 }
1856}
1857
1858const FORWARD_REFS: [i8; 4] = [LAST_FRAME, LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME];
1859const BACKWARD_REFS: [i8; 3] = [BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME];
1860
1861/// `av1_get_pred_context_single_ref_p1`: forward vs. backward reference.
1862pub(crate) fn single_ref_p1_ctx(
1863 above0: Option<i8>,
1864 above1: Option<i8>,
1865 left0: Option<i8>,
1866 left1: Option<i8>,
1867) -> usize {
1868 ref_ctx(above0, above1, left0, left1, &FORWARD_REFS, &BACKWARD_REFS)
1869}
1870
1871/// `av1_get_pred_context_single_ref_p2`
1872/// (`get_pred_context_brfarf2_or_arf`): `BWDREF`/`ALTREF2` vs. `ALTREF`.
1873pub(crate) fn single_ref_p2_ctx(
1874 above0: Option<i8>,
1875 above1: Option<i8>,
1876 left0: Option<i8>,
1877 left1: Option<i8>,
1878) -> usize {
1879 ref_ctx(
1880 above0,
1881 above1,
1882 left0,
1883 left1,
1884 &[BWDREF_FRAME, ALTREF2_FRAME],
1885 &[ALTREF_FRAME],
1886 )
1887}
1888
1889/// `av1_get_pred_context_single_ref_p3`
1890/// (`get_pred_context_ll2_or_l3gld`): `LAST`/`LAST2` vs. `LAST3`/`GOLDEN`.
1891pub(crate) fn single_ref_p3_ctx(
1892 above0: Option<i8>,
1893 above1: Option<i8>,
1894 left0: Option<i8>,
1895 left1: Option<i8>,
1896) -> usize {
1897 ref_ctx(
1898 above0,
1899 above1,
1900 left0,
1901 left1,
1902 &[LAST_FRAME, LAST2_FRAME],
1903 &[LAST3_FRAME, GOLDEN_FRAME],
1904 )
1905}
1906
1907/// `av1_get_pred_context_single_ref_p4`
1908/// (`get_pred_context_last_or_last2`): `LAST` vs. `LAST2`.
1909pub(crate) fn single_ref_p4_ctx(
1910 above0: Option<i8>,
1911 above1: Option<i8>,
1912 left0: Option<i8>,
1913 left1: Option<i8>,
1914) -> usize {
1915 ref_ctx(above0, above1, left0, left1, &[LAST_FRAME], &[LAST2_FRAME])
1916}
1917
1918/// `av1_get_pred_context_single_ref_p5`
1919/// (`get_pred_context_last3_or_gld`): `LAST3` vs. `GOLDEN`.
1920pub(crate) fn single_ref_p5_ctx(
1921 above0: Option<i8>,
1922 above1: Option<i8>,
1923 left0: Option<i8>,
1924 left1: Option<i8>,
1925) -> usize {
1926 ref_ctx(above0, above1, left0, left1, &[LAST3_FRAME], &[GOLDEN_FRAME])
1927}
1928
1929/// `av1_get_pred_context_single_ref_p6`
1930/// (`get_pred_context_brf_or_arf2`): `BWDREF` vs. `ALTREF2`.
1931pub(crate) fn single_ref_p6_ctx(
1932 above0: Option<i8>,
1933 above1: Option<i8>,
1934 left0: Option<i8>,
1935 left1: Option<i8>,
1936) -> usize {
1937 ref_ctx(above0, above1, left0, left1, &[BWDREF_FRAME], &[ALTREF2_FRAME])
1938}
1939
1940/// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,
1941/// conditioned on a unidirectional pair known to be one of the three
1942/// `LAST`-anchored ones (lane-av1comp).
1943pub(crate) fn uni_comp_ref_p1_ctx(
1944 above0: Option<i8>,
1945 above1: Option<i8>,
1946 left0: Option<i8>,
1947 left1: Option<i8>,
1948) -> usize {
1949 ref_ctx(
1950 above0,
1951 above1,
1952 left0,
1953 left1,
1954 &[LAST2_FRAME],
1955 &[LAST3_FRAME, GOLDEN_FRAME],
1956 )
1957}
1958
1959/// One neighbouring block's reference-frame shape, as
1960/// [`reference_mode_ctx`]/[`comp_reference_type_ctx`] need it: `None` for an
1961/// out-of-frame neighbour, `Some(ref0, None)` for an intra or single-ref
1962/// inter block, `Some(ref0, Some(ref1))` for a compound one. `uni` is
1963/// `ref1`'s meaning only when compound: whether the pair libaom's
1964/// `has_uni_comp_refs` would call unidirectional (both refs on the same
1965/// side of the current frame).
1966#[derive(Clone, Copy)]
1967pub(crate) struct NeighbourRef {
1968 pub is_inter: bool,
1969 pub ref0: i8,
1970 pub ref1: Option<i8>,
1971 pub uni: bool,
1972}
1973
1974fn is_backward(r: i8) -> bool {
1975 (BWDREF_FRAME..=ALTREF_FRAME).contains(&r)
1976}
1977
1978/// `av1_get_reference_mode_context` (spec 5.11.25's `comp_mode` context,
1979/// libaom `pred_common.c`): 5 contexts from how many of the above/left
1980/// neighbours are themselves compound-predicted, and (when neither/one is)
1981/// whether their single reference is a backward one.
1982pub(crate) fn reference_mode_ctx(above: Option<NeighbourRef>, left: Option<NeighbourRef>) -> usize {
1983 match (above, left) {
1984 (Some(a), Some(l)) => match (a.ref1.is_some(), l.ref1.is_some()) {
1985 (false, false) => usize::from(is_backward(a.ref0) ^ is_backward(l.ref0)),
1986 (false, true) => 2 + usize::from(is_backward(a.ref0) || !a.is_inter),
1987 (true, false) => 2 + usize::from(is_backward(l.ref0) || !l.is_inter),
1988 (true, true) => 4,
1989 },
1990 (Some(e), None) | (None, Some(e)) => {
1991 if e.ref1.is_some() {
1992 3
1993 } else {
1994 usize::from(is_backward(e.ref0))
1995 }
1996 }
1997 (None, None) => 1,
1998 }
1999}
2000
2001/// `av1_get_comp_reference_type_context` (spec 5.11.25's
2002/// `comp_reference_type` context, libaom `pred_common.c`): 5 contexts from
2003/// whether the above/left neighbours are intra, single-ref, unidirectional
2004/// compound, or bidirectional compound.
2005pub(crate) fn comp_reference_type_ctx(
2006 above: Option<NeighbourRef>,
2007 left: Option<NeighbourRef>,
2008) -> usize {
2009 match (above, left) {
2010 (Some(a), Some(l)) => match (a.is_inter, l.is_inter) {
2011 (false, false) => 2,
2012 (false, true) | (true, false) => {
2013 let inter = if a.is_inter { a } else { l };
2014 if inter.ref1.is_none() {
2015 2
2016 } else {
2017 1 + 2 * usize::from(inter.uni)
2018 }
2019 }
2020 (true, true) => {
2021 let (a_sg, l_sg) = (a.ref1.is_none(), l.ref1.is_none());
2022 if a_sg && l_sg {
2023 1 + 2 * usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
2024 } else if a_sg || l_sg {
2025 let uni = if a_sg { l.uni } else { a.uni };
2026 if !uni {
2027 1
2028 } else {
2029 3 + usize::from(!(is_backward(a.ref0) ^ is_backward(l.ref0)))
2030 }
2031 } else if !a.uni && !l.uni {
2032 0
2033 } else if !a.uni || !l.uni {
2034 2
2035 } else {
2036 3 + usize::from(!((a.ref0 == BWDREF_FRAME) ^ (l.ref0 == BWDREF_FRAME)))
2037 }
2038 }
2039 },
2040 (Some(e), None) | (None, Some(e)) => {
2041 if !e.is_inter {
2042 2
2043 } else if e.ref1.is_none() {
2044 2
2045 } else {
2046 4 * usize::from(e.uni)
2047 }
2048 }
2049 (None, None) => 2,
2050 }
2051}
2052
2053#[cfg(test)]
2054mod tests {
2055 use super::*;
2056
2057 fn inter(mv: (i32, i32)) -> MiInfo {
2058 MiInfo {
2059 is_inter: true,
2060 ref_frame: 1,
2061 ref_frame1: None,
2062 mv1: None,
2063 mv,
2064 is_new_mv: false,
2065 // 1: smaller than every `bw4`/`bh4` these small-grid tests use,
2066 // so it never trips the extended-scan coverage boost -- these
2067 // tests only exercise the immediate/corner/top-right scans.
2068 size: 1,
2069 size_h: 1,
2070 is_global_mv0: false,
2071 is_global_mv1: false,
2072 }
2073 }
2074
2075 #[test]
2076 fn all_same_mv_neighbourhood_dedupes_to_one_entry() {
2077 let mut grid = MiGrid::new(8, 8);
2078 // Block at (2, 2), 2x2 mi units. Above row 1, cols 2..4; left col 1,
2079 // rows 2..4; top-right at (1, 4). All the same MV.
2080 let mv = (4, 4);
2081 grid.set(1, 2, inter(mv));
2082 grid.set(1, 3, inter(mv));
2083 grid.set(2, 1, inter(mv));
2084 grid.set(3, 1, inter(mv));
2085 grid.set(1, 4, inter(mv));
2086
2087 let stack = find_mv_stack(&grid, 2, 2, 2, 2, 1, 8, 8);
2088
2089 assert_eq!(stack.entries.len(), 1);
2090 assert_eq!(stack.entries[0].mv, mv);
2091 // 2 above cells + 2 left cells (weight 2 each, `size: 1` neighbours
2092 // below the `bw4 <= n4` weight-boost floor) + 1 top-right (libaom's
2093 // real `scan_blk_mbmi` weight, `CORNER_WEIGHT` = 4, not a flat 2),
2094 // plus the REF_CAT_LEVEL boost av1_find_mv_stack applies to every
2095 // entry the immediate row/col/top-right scan found (module doc).
2096 assert_eq!(stack.entries[0].weight, 12 + REF_CAT_LEVEL);
2097 assert_eq!(stack.nearest_mv, mv);
2098 // Exact ctx (see module doc): both sides matched (nearest_match=2)
2099 // and no neighbour was coded NEWMV, which is libaom's
2100 // `mode_context[ref_frame] |= 5` branch.
2101 assert_eq!(stack.new_mv_ctx, 5);
2102 assert_eq!(stack.ref_mv_ctx, 5);
2103 assert_eq!(stack.zero_mv_ctx, 0);
2104 }
2105
2106 #[test]
2107 fn two_distinct_neighbour_mvs_yield_two_entries_in_weight_order() {
2108 let mut grid = MiGrid::new(8, 8);
2109 // Block at (3, 3), bw4=2, bh4=3: above spans 2 cells (weight 4),
2110 // left spans 3 cells (weight 6) — distinct MVs, distinct weights.
2111 let above_mv = (4, 4);
2112 let left_mv = (8, 8);
2113 grid.set(2, 3, inter(above_mv));
2114 grid.set(2, 4, inter(above_mv));
2115 grid.set(3, 2, inter(left_mv));
2116 grid.set(4, 2, inter(left_mv));
2117 grid.set(5, 2, inter(left_mv));
2118
2119 let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8);
2120
2121 // Both are entries the immediate scan found, so both get the
2122 // REF_CAT_LEVEL boost (module doc) — their relative order is
2123 // unaffected.
2124 assert_eq!(stack.entries.len(), 2);
2125 assert_eq!(
2126 stack.entries[0],
2127 StackEntry {
2128 mv: left_mv,
2129 weight: 6 + REF_CAT_LEVEL
2130 }
2131 );
2132 assert_eq!(
2133 stack.entries[1],
2134 StackEntry {
2135 mv: above_mv,
2136 weight: 4 + REF_CAT_LEVEL
2137 }
2138 );
2139 assert_eq!(stack.nearest_mv, left_mv);
2140 assert_eq!(stack.near_mv, above_mv);
2141 }
2142
2143 #[test]
2144 fn transposing_above_and_left_produces_a_different_stack() {
2145 // Grid A: above = (4,4) x2 cells, left = (8,8) x2 cells, top-right
2146 // matches the above MV (so it folds into the above bucket, making
2147 // it heavier than left).
2148 let mut a = MiGrid::new(8, 8);
2149 a.set(1, 2, inter((4, 4)));
2150 a.set(1, 3, inter((4, 4)));
2151 a.set(2, 1, inter((8, 8)));
2152 a.set(3, 1, inter((8, 8)));
2153 a.set(1, 4, inter((4, 4)));
2154 let stack_a = find_mv_stack(&a, 2, 2, 2, 2, 1, 8, 8);
2155
2156 // Grid B: the naive transpose — swap which MV sits above vs left —
2157 // with the top-right probe again matching whatever now sits above.
2158 let mut b = MiGrid::new(8, 8);
2159 b.set(1, 2, inter((8, 8)));
2160 b.set(1, 3, inter((8, 8)));
2161 b.set(2, 1, inter((4, 4)));
2162 b.set(3, 1, inter((4, 4)));
2163 b.set(1, 4, inter((8, 8)));
2164 let stack_b = find_mv_stack(&b, 2, 2, 2, 2, 1, 8, 8);
2165
2166 assert_ne!(stack_a, stack_b);
2167 assert_eq!(stack_a.entries[0].mv, (4, 4));
2168 assert_eq!(stack_b.entries[0].mv, (8, 8));
2169 }
2170
2171 #[test]
2172 fn mi_units_outside_the_tile_contribute_nothing() {
2173 let grid = MiGrid::new(4, 4);
2174 // Block at the tile's top-left corner: no row above, no col left,
2175 // and the top-right probe is also off the top edge.
2176 let stack = find_mv_stack(&grid, 0, 0, 2, 2, 1, 4, 4);
2177
2178 assert!(stack.entries.is_empty());
2179 assert_eq!(stack.nearest_mv, (0, 0));
2180 assert_eq!(stack.near_mv, (0, 0));
2181 assert_eq!(stack.pred_mv, (0, 0));
2182 assert!(stack.drl_ctx.is_empty());
2183 assert_eq!(stack.new_mv_ctx, 0);
2184 assert_eq!(stack.ref_mv_ctx, 0);
2185
2186 // Out-of-range reads are also inert directly against the grid.
2187 assert!(grid.get(0, 10).is_none());
2188 assert!(grid.get(10, 0).is_none());
2189 }
2190
2191 #[test]
2192 fn a_candidate_far_outside_the_frame_is_clamped_to_it() {
2193 // A 4x4-mi frame (16x16 px), block 1x1 mi at (1, 1): room for one
2194 // neighbour above and one to the left, tight edges on every side.
2195 let mut grid = MiGrid::new(4, 4);
2196 grid.set(0, 1, inter((100_000, 100_000)));
2197
2198 let stack = find_mv_stack(&grid, 1, 1, 1, 1, 1, 4, 4);
2199
2200 // Unclamped this candidate is (100000, 100000); spec 7.10.2.14 caps
2201 // it at the frame edge (2 mi below/right) plus the block's own 4x4
2202 // span plus MV_BORDER (128), all in 1/8-pel: (2*4)*8 + 1*4*8 + 128 =
2203 // 64 + 32 + 128 = 224.
2204 assert_eq!(stack.nearest_mv, (224, 224));
2205 // libaom `av1_find_mv_refs` clamps every stack ENTRY too -- the DRL
2206 // reads entries directly, so a raw candidate must not survive
2207 // (pinned warp-flake-5.obu regression).
2208 assert_eq!(stack.entries[0].mv, (224, 224));
2209 }
2210
2211 #[test]
2212 fn a_neighbour_coded_newmv_raises_the_new_mv_context() {
2213 let mut grid = MiGrid::new(8, 8);
2214 grid.set(
2215 1,
2216 2,
2217 MiInfo {
2218 is_inter: true,
2219 ref_frame: 1,
2220 ref_frame1: None,
2221 mv1: None,
2222 mv: (4, 4),
2223 is_new_mv: true,
2224 size: 1,
2225 size_h: 1,
2226 is_global_mv0: false,
2227 is_global_mv1: false,
2228 },
2229 );
2230 // Only the row matches (nearest_match == 1): newmv_count > 0 picks
2231 // libaom's `mode_context[ref_frame] |= 2` branch.
2232 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2233 assert_eq!(stack.new_mv_ctx, 2);
2234 assert_eq!(stack.ref_mv_ctx, 3);
2235 }
2236
2237 #[test]
2238 fn a_diagonal_corner_match_raises_ref_mv_ctx_past_nearest_match() {
2239 // Block at (2, 2), 1x1 mi unit: only the col to the left matches
2240 // (nearest_match == 1, so a pre-fix `ref_mv_ctx` collapse would say
2241 // 3 regardless of anything else — this is the exact round-10 defect
2242 // shape). The row above has no match of its own, but the diagonal
2243 // top-left corner (1, 1) does; libaom folds that into the row side
2244 // of `ref_match_count` (raising it to 2) without ever touching the
2245 // already-captured `nearest_match`.
2246 let mut grid = MiGrid::new(8, 8);
2247 grid.set(2, 1, inter((4, 4)));
2248 grid.set(1, 1, inter((8, 8)));
2249
2250 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2251
2252 assert_eq!(stack.new_mv_ctx, 3); // depends on nearest_match alone: unchanged
2253 assert_eq!(stack.ref_mv_ctx, 4); // nearest_match=1, ref_match_count=2
2254 // The corner's distinct MV becomes its own low-weight stack entry,
2255 // ranked behind the boosted nearest one — DRL context sees a real
2256 // (non-nearest) second candidate for the first time.
2257 assert_eq!(stack.entries.len(), 2);
2258 assert_eq!(stack.entries[0].mv, (4, 4));
2259 assert_eq!(stack.entries[1].mv, (8, 8));
2260 assert_eq!(stack.drl_ctx, vec![1]);
2261 }
2262
2263 #[test]
2264 fn a_corner_only_match_raises_new_mv_ctx_even_when_nearest_match_is_zero() {
2265 // Block at (2, 2), 1x1 mi unit: row above (1, 2), col left (2, 1)
2266 // and top-right (1, 3) all empty — nearest_match == 0 — but the
2267 // diagonal top-left corner (1, 1) matches. libaom's `case 0` arm
2268 // (mvref_common.c ~line 621) sets `new_mv_ctx`'s own bit from
2269 // `ref_match_count` here, not just `ref_mv_ctx`'s: this is I8 CLASS
2270 // B's real-content bitstream desync (real clips hit blocks whose
2271 // *only* neighbour match is diagonal; the repo's synthetic tests
2272 // never had one until this case).
2273 let mut grid = MiGrid::new(8, 8);
2274 grid.set(1, 1, inter((4, 4)));
2275
2276 let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8);
2277
2278 assert_eq!(stack.entries.len(), 1);
2279 assert_eq!(stack.new_mv_ctx, 1); // ref_match_count == 1, not the old hard-0
2280 assert_eq!(stack.ref_mv_ctx, 1); // nearest_match=0, ref_match_count=1
2281 }
2282
2283 /// The class this round ports: a query block *smaller* than its
2284 /// same-row neighbour (decode.rs's real variable partition sizes, never
2285 /// `tile.rs`'s fixed `bw4 == 8`) gets libaom's real, non-flat weight —
2286 /// hand-computed against `scan_row_mbmi` (mvref_common.c): `bw4 = 2`
2287 /// against an `n4 = 8` neighbour 6 mi rows from the frame's top edge
2288 /// gives `len = min(bw4, n4) = 2`, `inc = min(-max_row_offset +
2289 /// row_offset + 1, n4) = min(6 - 1 + 1, 8) = 6`, `weight = max(2, inc) =
2290 /// 6`, total `len * weight = 12` -- not the flat `IMMEDIATE_WEIGHT = 2`
2291 /// this module used to report for every match regardless of block size.
2292 #[test]
2293 fn a_wider_neighbour_than_the_query_block_gets_libaoms_real_weight() {
2294 let mut grid = MiGrid::new(32, 32);
2295 let (mi_row, mi_col) = (8, 8);
2296 let mv = (4, 4);
2297 grid.set(
2298 mi_row - 1,
2299 mi_col,
2300 MiInfo {
2301 is_inter: true,
2302 ref_frame: 1,
2303 ref_frame1: None,
2304 mv1: None,
2305 mv,
2306 is_new_mv: false,
2307 size: 8,
2308 size_h: 8,
2309 is_global_mv0: false,
2310 is_global_mv1: false,
2311 },
2312 );
2313
2314 let stack = find_mv_stack(&grid, mi_row, mi_col, 2, 2, 1, 32, 32);
2315
2316 assert_eq!(stack.entries.len(), 1);
2317 assert_eq!(stack.entries[0].mv, mv);
2318 assert_eq!(stack.entries[0].weight, 12 + REF_CAT_LEVEL);
2319 }
2320
2321 #[test]
2322 fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() {
2323 assert_eq!(single_ref_ctx(false), 1);
2324 assert_eq!(single_ref_ctx(true), 2);
2325 }
2326
2327 /// An 8-mi-sized (`size: 8`) coded-but-intra neighbour: contributes no
2328 /// vote (`is_inter: false`) but must still count for extended-scan
2329 /// coverage, the way libaom's `scan_row_mbmi`/`scan_col_mbmi` advance
2330 /// `processed_rows`/`processed_cols` from any candidate's `bsize` alone.
2331 fn intra8() -> MiInfo {
2332 MiInfo {
2333 is_inter: false,
2334 ref_frame: -1,
2335 ref_frame1: None,
2336 mv1: None,
2337 mv: (0, 0),
2338 is_new_mv: false,
2339 size: 8,
2340 size_h: 8,
2341 is_global_mv0: false,
2342 is_global_mv1: false,
2343 }
2344 }
2345
2346 /// An 8-mi-sized inter neighbour with an arbitrary, distinctive `mv` --
2347 /// used below as a "would this get picked up" tracer at extended-scan
2348 /// offsets that a correct implementation must never reach at 8-mi
2349 /// geometry.
2350 fn inter8(mv: (i32, i32)) -> MiInfo {
2351 MiInfo {
2352 is_inter: true,
2353 ref_frame: 1,
2354 ref_frame1: None,
2355 mv1: None,
2356 mv,
2357 is_new_mv: false,
2358 size: 8,
2359 size_h: 8,
2360 is_global_mv0: false,
2361 is_global_mv1: false,
2362 }
2363 }
2364
2365 /// The class of bug this round fixed: at 8-mi geometry, an intra
2366 /// neighbour directly above the query block must suppress the extended
2367 /// row scan exactly as an inter one would (spec 7.10.2.2's
2368 /// `processed_rows` tracks *coded* neighbours, not merely *matching*
2369 /// ones). Two tracer candidates sit at the row's extended-scan offsets
2370 /// (-3 and -5, spec 7.10.2.4) with MVs no other scan could produce; if
2371 /// the coverage bug regresses, they show up in `stack.entries`.
2372 #[test]
2373 fn extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
2374 let mut grid = MiGrid::new(32, 32);
2375 let (mi_row, mi_col) = (10, 10);
2376 for col in mi_col..mi_col + 8 {
2377 grid.set(mi_row - 1, col, intra8());
2378 }
2379 for col in mi_col + 1..mi_col + 1 + 8 {
2380 grid.set(mi_row - 3, col, inter8((999, 999)));
2381 grid.set(mi_row - 5, col, inter8((888, 888)));
2382 }
2383
2384 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2385
2386 assert!(
2387 stack.entries.is_empty(),
2388 "extended row scan fired at 8-mi geometry: {:?}",
2389 stack.entries
2390 );
2391 }
2392
2393 /// `extended_row_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour`,
2394 /// transposed to the col-left scan.
2395 #[test]
2396 fn extended_col_scan_is_a_no_op_at_8mi_geometry_even_behind_an_intra_neighbour() {
2397 let mut grid = MiGrid::new(32, 32);
2398 let (mi_row, mi_col) = (10, 10);
2399 for row in mi_row..mi_row + 8 {
2400 grid.set(row, mi_col - 1, intra8());
2401 }
2402 for row in mi_row + 1..mi_row + 1 + 8 {
2403 grid.set(row, mi_col - 3, inter8((999, 999)));
2404 grid.set(row, mi_col - 5, inter8((888, 888)));
2405 }
2406
2407 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2408
2409 assert!(
2410 stack.entries.is_empty(),
2411 "extended col scan fired at 8-mi geometry: {:?}",
2412 stack.entries
2413 );
2414 }
2415
2416 /// Same shape, but the immediate neighbour is itself inter (a same-size
2417 /// vote) rather than intra -- the geometry-only coverage path must not
2418 /// have broken the ordinary matching one.
2419 #[test]
2420 fn extended_row_scan_is_a_no_op_at_8mi_geometry_behind_an_inter_neighbour() {
2421 let mut grid = MiGrid::new(32, 32);
2422 let (mi_row, mi_col) = (10, 10);
2423 for col in mi_col..mi_col + 8 {
2424 grid.set(mi_row - 1, col, inter8((4, 4)));
2425 }
2426 for col in mi_col + 1..mi_col + 1 + 8 {
2427 grid.set(mi_row - 3, col, inter8((999, 999)));
2428 grid.set(mi_row - 5, col, inter8((888, 888)));
2429 }
2430
2431 let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, 1, 32, 32);
2432
2433 assert_eq!(stack.entries.len(), 1);
2434 assert_eq!(stack.entries[0].mv, (4, 4));
2435 }
2436
2437 fn single(ref0: i8) -> NeighbourRef {
2438 NeighbourRef {
2439 is_inter: true,
2440 ref0,
2441 ref1: None,
2442 uni: false,
2443 }
2444 }
2445 fn comp(ref0: i8, ref1: i8, uni: bool) -> NeighbourRef {
2446 NeighbourRef {
2447 is_inter: true,
2448 ref0,
2449 ref1: Some(ref1),
2450 uni,
2451 }
2452 }
2453 fn intra() -> NeighbourRef {
2454 NeighbourRef {
2455 is_inter: false,
2456 ref0: 0,
2457 ref1: None,
2458 uni: false,
2459 }
2460 }
2461
2462 /// `av1_get_reference_mode_context`, no edges available: libaom's `ctx
2463 /// = 1` fallback.
2464 #[test]
2465 fn reference_mode_ctx_no_edges_is_one() {
2466 assert_eq!(reference_mode_ctx(None, None), 1);
2467 }
2468
2469 /// Both edges single-ref, same forward/backward-ness: `ctx = 0`; one of
2470 /// each: `ctx = 1` (the XOR in libaom's `ctx = IS_BACKWARD(above) ^
2471 /// IS_BACKWARD(left)`).
2472 #[test]
2473 fn reference_mode_ctx_single_single() {
2474 assert_eq!(
2475 reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2476 0
2477 );
2478 assert_eq!(
2479 reference_mode_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2480 1
2481 );
2482 }
2483
2484 /// One edge compound, the other single forward: libaom's `2 +
2485 /// IS_BACKWARD(above)` collapses to `2` here (forward, inter).
2486 #[test]
2487 fn reference_mode_ctx_single_and_compound() {
2488 assert_eq!(
2489 reference_mode_ctx(
2490 Some(single(LAST_FRAME)),
2491 Some(comp(LAST_FRAME, LAST2_FRAME, true))
2492 ),
2493 2
2494 );
2495 assert_eq!(
2496 reference_mode_ctx(
2497 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2498 Some(single(LAST_FRAME))
2499 ),
2500 2
2501 );
2502 }
2503
2504 /// Both edges compound: libaom's fixed `ctx = 4`.
2505 #[test]
2506 fn reference_mode_ctx_compound_compound_is_four() {
2507 assert_eq!(
2508 reference_mode_ctx(
2509 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2510 Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2511 ),
2512 4
2513 );
2514 }
2515
2516 /// `av1_get_comp_reference_type_context`, no edges: libaom's `ctx = 2`
2517 /// fallback.
2518 #[test]
2519 fn comp_reference_type_ctx_no_edges_is_two() {
2520 assert_eq!(comp_reference_type_ctx(None, None), 2);
2521 }
2522
2523 /// Both edges intra: libaom's `ctx = 2`.
2524 #[test]
2525 fn comp_reference_type_ctx_intra_intra_is_two() {
2526 assert_eq!(comp_reference_type_ctx(Some(intra()), Some(intra())), 2);
2527 }
2528
2529 /// Both edges single/single: forward-vs-backward split doubles the same
2530 /// way `single_ref_p1`'s own XOR does (libaom's `1 + 2 * !(a ^ l)`).
2531 #[test]
2532 fn comp_reference_type_ctx_single_single() {
2533 assert_eq!(
2534 comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(LAST2_FRAME))),
2535 3
2536 );
2537 assert_eq!(
2538 comp_reference_type_ctx(Some(single(LAST_FRAME)), Some(single(BWDREF_FRAME))),
2539 1
2540 );
2541 }
2542
2543 /// Both edges bidirectional compound: libaom's `ctx = 0`.
2544 #[test]
2545 fn comp_reference_type_ctx_bidir_bidir_is_zero() {
2546 assert_eq!(
2547 comp_reference_type_ctx(
2548 Some(comp(LAST_FRAME, BWDREF_FRAME, false)),
2549 Some(comp(LAST2_FRAME, ALTREF_FRAME, false))
2550 ),
2551 0
2552 );
2553 }
2554
2555 /// Both edges unidirectional compound: libaom's `3 + !(a==BWDREF ^
2556 /// l==BWDREF)`.
2557 #[test]
2558 fn comp_reference_type_ctx_unidir_unidir() {
2559 assert_eq!(
2560 comp_reference_type_ctx(
2561 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2562 Some(comp(LAST_FRAME, LAST3_FRAME, true))
2563 ),
2564 4
2565 );
2566 assert_eq!(
2567 comp_reference_type_ctx(
2568 Some(comp(LAST_FRAME, LAST2_FRAME, true)),
2569 Some(comp(BWDREF_FRAME, ALTREF_FRAME, true))
2570 ),
2571 3
2572 );
2573 }
2574
2575 /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` beats `LAST3`/
2576 /// `GOLDEN` in the vote, context 2 (libaom's `<` branch reversed --
2577 /// fewer `a`s than `b`s is context 0, matching [`ref_ctx`]'s shared
2578 /// convention).
2579 #[test]
2580 fn uni_comp_ref_p1_ctx_matches_ref_ctx_shape() {
2581 assert_eq!(uni_comp_ref_p1_ctx(Some(LAST2_FRAME), None, None, None), 2);
2582 assert_eq!(uni_comp_ref_p1_ctx(Some(LAST3_FRAME), None, None, None), 0);
2583 assert_eq!(uni_comp_ref_p1_ctx(None, None, None, None), 1);
2584 }
2585
2586 // --- lane-av1comp step 4: compound mvstack (find_mv_stack_compound) ---
2587
2588 const COMP_PAIR: (i8, i8) = (LAST_FRAME, ALTREF_FRAME);
2589
2590 fn comp_inter(mv0: (i32, i32), mv1: (i32, i32)) -> MiInfo {
2591 MiInfo {
2592 is_inter: true,
2593 ref_frame: COMP_PAIR.0,
2594 ref_frame1: Some(COMP_PAIR.1),
2595 mv: mv0,
2596 mv1: Some(mv1),
2597 is_new_mv: false,
2598 size: 1,
2599 size_h: 1,
2600 is_global_mv0: false,
2601 is_global_mv1: false,
2602 }
2603 }
2604
2605 #[test]
2606 fn compound_scan_only_matches_the_exact_pair() {
2607 let mut grid = MiGrid::new(8, 8);
2608 // Same-side single-ref neighbour (LAST only) must not vote.
2609 grid.set(1, 2, inter((4, 4)));
2610 // Wrong second ref (GOLDEN, not ALTREF) must not vote either.
2611 grid.set(
2612 1,
2613 3,
2614 MiInfo {
2615 is_inter: true,
2616 ref_frame: LAST_FRAME,
2617 ref_frame1: Some(GOLDEN_FRAME),
2618 mv: (9, 9),
2619 mv1: Some((9, 9)),
2620 is_new_mv: false,
2621 size: 1,
2622 size_h: 1,
2623 is_global_mv0: false,
2624 is_global_mv1: false,
2625 },
2626 );
2627 // Exact pair match.
2628 let (mv0, mv1) = ((2, 2), (-6, 3));
2629 grid.set(2, 1, comp_inter(mv0, mv1));
2630
2631 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
2632
2633 // The exact-pair immediate scan lands one boosted entry; the
2634 // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)
2635 // separately tops it up with a low-weight combo built from the two
2636 // near-miss neighbours it's allowed to gather over regardless of
2637 // reference frame -- a real second entry, not spurious.
2638 assert_eq!(stack.entries.len(), 2);
2639 assert_eq!(stack.entries[0].mv0, mv0);
2640 assert_eq!(stack.entries[0].mv1, mv1);
2641 assert_eq!(stack.entries[0].weight, 2 + REF_CAT_LEVEL);
2642 assert_eq!(stack.nearest_mv, (mv0, mv1));
2643 }
2644
2645 #[test]
2646 fn compound_dedupes_same_pair_and_sums_weight() {
2647 let mut grid = MiGrid::new(8, 8);
2648 let (mv0, mv1) = ((4, 4), (-4, -4));
2649 // Block at (2, 2), 2x2 mi units: above spans cols 2..4, left rows 2..4.
2650 grid.set(1, 2, comp_inter(mv0, mv1));
2651 grid.set(1, 3, comp_inter(mv0, mv1));
2652 grid.set(2, 1, comp_inter(mv0, mv1));
2653 grid.set(3, 1, comp_inter(mv0, mv1));
2654
2655 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
2656
2657 // Exact libaom `is_dup` port: with exactly one entry already in the
2658 // stack (the four identical-pair neighbours deduped by the
2659 // immediate-scan pass), the extension combine step compares only
2660 // `comp_list[0]` against that entry -- a match here, since both are
2661 // built from the same identical-pair neighbours -- so it takes
2662 // `comp_list[1]` (the *second* ref_id slot, still the same (mv0,
2663 // mv1) pair) as a brand-new stack entry rather than folding weight
2664 // into the existing one. Two entries, same pair, not merged.
2665 assert_eq!(stack.entries.len(), 2);
2666 assert_eq!(stack.entries[0].mv0, mv0);
2667 assert_eq!(stack.entries[0].mv1, mv1);
2668 // 2 above + 2 left cells, weight 2 each (size:1 floor), plus the
2669 // REF_CAT_LEVEL boost every immediate-scan entry gets.
2670 assert_eq!(stack.entries[0].weight, 8 + REF_CAT_LEVEL);
2671 assert_eq!(stack.entries[1].mv0, mv0);
2672 assert_eq!(stack.entries[1].mv1, mv1);
2673 assert_eq!(stack.entries[1].weight, 2);
2674 }
2675
2676 #[test]
2677 fn compound_two_distinct_pairs_sort_by_weight() {
2678 let mut grid = MiGrid::new(8, 8);
2679 let above = ((4, 4), (1, 1));
2680 let left = ((8, 8), (2, 2));
2681 grid.set(2, 3, comp_inter(above.0, above.1));
2682 grid.set(2, 4, comp_inter(above.0, above.1));
2683 grid.set(3, 2, comp_inter(left.0, left.1));
2684 grid.set(4, 2, comp_inter(left.0, left.1));
2685 grid.set(5, 2, comp_inter(left.0, left.1));
2686
2687 let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
2688
2689 assert_eq!(stack.entries.len(), 2);
2690 assert_eq!(stack.entries[0].mv0, left.0);
2691 assert_eq!(stack.entries[0].mv1, left.1);
2692 assert_eq!(stack.entries[1].mv0, above.0);
2693 assert_eq!(stack.entries[1].mv1, above.1);
2694 assert_eq!(stack.nearest_mv, left);
2695 assert_eq!(stack.near_mv, above);
2696 }
2697
2698 #[test]
2699 fn combine_compound_candidates_zips_ref_id_then_ref_diff_per_side() {
2700 let mut lists = CompoundRefLists::default();
2701 lists.ref_id[0].push((1, 1));
2702 lists.ref_diff[0].push((2, 2));
2703 lists.ref_id[1].push((3, 3));
2704 // side 1 has only one entry -> comp_idx 1 falls back to ref_diff.
2705 lists.ref_diff[1].push((4, 4));
2706
2707 let combined = combine_compound_candidates(&lists);
2708 assert_eq!(combined[0], ((1, 1), (3, 3)));
2709 assert_eq!(combined[1], ((2, 2), (4, 4)));
2710 }
2711
2712 #[test]
2713 fn process_compound_ref_mv_candidate_splits_exact_vs_borrowed() {
2714 let mut lists = CompoundRefLists::default();
2715 // Exact match on side 0 (LAST_FRAME), wrong ref on side 1 -> borrowed
2716 // into ref_diff[1] with no sign flip (NO_SIGN_BIAS).
2717 let candidate = MiInfo {
2718 is_inter: true,
2719 ref_frame: LAST_FRAME,
2720 ref_frame1: None,
2721 mv: (5, 5),
2722 mv1: None,
2723 is_new_mv: false,
2724 size: 1,
2725 size_h: 1,
2726 is_global_mv0: false,
2727 is_global_mv1: false,
2728 };
2729 process_compound_ref_mv_candidate(&candidate, COMP_PAIR, &NO_SIGN_BIAS, &mut lists);
2730 assert_eq!(lists.ref_id[0], vec![(5, 5)]);
2731 assert_eq!(lists.ref_diff[1], vec![(5, 5)]);
2732 assert!(lists.ref_id[1].is_empty());
2733 assert!(lists.ref_diff[0].is_empty());
2734 }
2735
2736 #[test]
2737 fn compound_extension_pass_tops_up_a_short_stack() {
2738 // No exact-pair neighbour at all, but a LAST-only neighbour above and
2739 // an ALTREF-only neighbour left: the extension pass should combine
2740 // them into one topped-up candidate rather than leaving the stack
2741 // empty.
2742 let mut grid = MiGrid::new(8, 8);
2743 grid.set(
2744 1,
2745 2,
2746 MiInfo {
2747 is_inter: true,
2748 ref_frame: LAST_FRAME,
2749 ref_frame1: None,
2750 mv: (7, 7),
2751 mv1: None,
2752 is_new_mv: false,
2753 size: 8,
2754 size_h: 8,
2755 is_global_mv0: false,
2756 is_global_mv1: false,
2757 },
2758 );
2759 grid.set(
2760 2,
2761 1,
2762 MiInfo {
2763 is_inter: true,
2764 ref_frame: ALTREF_FRAME,
2765 ref_frame1: None,
2766 mv: (-3, -3),
2767 mv1: None,
2768 is_new_mv: false,
2769 size: 8,
2770 size_h: 8,
2771 is_global_mv0: false,
2772 is_global_mv1: false,
2773 },
2774 );
2775
2776 let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
2777
2778 // The combine step (libaom's real "Handle compound reference frame
2779 // extension") zips each side's ref_id-then-ref_diff lists
2780 // independently, producing *two* distinct combos here (the exact
2781 // match and the borrowed one land on opposite sides for each combo
2782 // index) — both get added, `MAX_MV_REF_CANDIDATES` (2) is exactly
2783 // this stack's cap.
2784 assert_eq!(stack.entries.len(), 2);
2785 assert_eq!(stack.entries[0].weight, 2);
2786 // combo 0: side 0's own exact ref_id match, side 1's borrowed one.
2787 assert_eq!(stack.entries[0].mv0, (7, 7));
2788 assert_eq!(stack.entries[0].mv1, (-3, -3));
2789 // combo 1: the mirror -- side 0's borrowed entry, side 1's own exact
2790 // ref_id match.
2791 assert_eq!(stack.entries[1].mv0, (-3, -3));
2792 assert_eq!(stack.entries[1].mv1, (7, 7));
2793 }
2794}