forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBca4790fTahinli3 months ago1157 commits

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