forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00a6ca0Tahinli3 months ago1913 commits

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