forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

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