forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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