forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB66045bcTahinli3 months ago1500 commits

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