forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1e4e107Tahinli2 months ago2830 commits

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