forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB34789daTahinli3 months ago1757 commits

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