forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

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