forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

motion_field.rs783 lines, 29.6 KiBHistoryRawDownload
1//! Temporal MV projection (AV1 spec 7.9, `use_ref_frame_mvs`): projects a
2//! previously decoded frame's stored motion vectors into the current
3//! frame's own 8x8 motion field, ported from libaom's
4//! `av1_setup_motion_field`/`motion_field_projection`
5//! (`av1/common/mvref_common.c`) and the projection math `add_tpl_ref_mv`
6//! (same file) applies a second time, per query block, against the block's
7//! own single reference frame.
8use crate::hits::hit;
9
10use crate::mvstack::{ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME};
11
12/// One 8x8 cell's saved motion state, as libaom's `av1_copy_frame_mvs`
13/// leaves it after decoding the frame that owns this grid: the coded MV and
14/// the single reference frame (`LAST_FRAME..=ALTREF_FRAME`, 1..=7) it
15/// pointed to.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct SavedMv {
18 pub mv: (i32, i32),
19 pub ref_frame: i8,
20}
21
22/// A decoded inter frame's whole motion field (spec `MotionFieldMvs`... no
23/// — libaom's `cur_frame->mvs`), one [`SavedMv`] per 8x8 unit, plus the
24/// order-hint bookkeeping [`setup_motion_field`] needs to project it into a
25/// later frame: this frame's own `OrderHint` and the `OrderHint` of each of
26/// the 7 references *it* was coded against (`SavedOrderHints`/
27/// `ref_order_hints`).
28#[derive(Clone, Debug)]
29pub struct MotionField {
30 cols: usize,
31 rows: usize,
32 cells: Vec<Option<SavedMv>>,
33 pub order_hint: u32,
34 pub ref_order_hints: [u32; 7],
35 /// libaom `motion_field_projection`'s own first test: a start frame whose
36 /// `frame_type` is `KEY_FRAME`/`INTRA_ONLY_FRAME` is never projected at
37 /// all (`return 0`), so it also never spends a `ref_stamp` slot.
38 pub is_intra: bool,
39}
40
41impl MotionField {
42 /// A field sized for an `mi_cols` by `mi_rows` frame, all cells
43 /// initially unset (spec 7.9's own reset to `-1`/invalid before any
44 /// block writes into it).
45 pub fn new(
46 mi_cols: usize,
47 mi_rows: usize,
48 order_hint: u32,
49 ref_order_hints: [u32; 7],
50 is_intra: bool,
51 ) -> Self {
52 let cols = mi_cols.div_ceil(2);
53 let rows = mi_rows.div_ceil(2);
54 Self {
55 cols,
56 rows,
57 cells: vec![None; cols * rows],
58 order_hint,
59 ref_order_hints,
60 is_intra,
61 }
62 }
63
64 /// Records `saved` at the 8x8 cell containing 4x4 unit `(mi_row,
65 /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single
66 /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution
67 /// write.
68 /// `saved == None` is `av1_copy_frame_mvs`'s own leading clear
69 /// (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which every block
70 /// of an inter frame performs -- an intra (or nothing-to-store) block
71 /// sharing an 8x8 cell with an earlier inter one wipes that cell.
72 #[allow(dead_code)] // lane-mf: the frame build now fills cell rows directly; kept for the module's tests
73 pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: Option<SavedMv>) {
74 let (r, c) = (mi_row / 2, mi_col / 2);
75 if r < self.rows && c < self.cols {
76 self.cells[r * self.cols + c] = saved;
77 }
78 }
79
80 /// lane-mergefix r5 rung (`EC_TRACE_TPL`): occupancy map of the SAVED
81 /// field, the input side of [`setup_motion_field`]'s projection.
82 pub fn occupancy(&self) -> Vec<String> {
83 (0..self.rows)
84 .map(|r| {
85 (0..self.cols)
86 .map(|c| if self.cells[r * self.cols + c].is_some() { '#' } else { '.' })
87 .collect()
88 })
89 .collect()
90 }
91
92 /// lane-mf: the cell grid itself (`cols`, `rows`, cells in row-major
93 /// order), so [`crate::decode::build_motion_field`] can fill disjoint
94 /// row bands of it in parallel. Cell row `r` owns `cells[r * cols..][..cols]`.
95 pub(crate) fn cells_mut(&mut self) -> (usize, usize, &mut [Option<SavedMv>]) {
96 (self.cols, self.rows, &mut self.cells)
97 }
98}
99
100/// lane-mvstack3: one 8x8 temporal-MV cell -- the projected `(mv,
101/// ref_frame_offset)` pair. `motion_field_projection` writes a cell only
102/// with a STRICTLY POSITIVE `ref_frame_offset` (its own `pos_valid` test),
103/// so `0` is exactly libaom's own "this `tpl_mvs` entry was never projected"
104/// marker and the `Option` tag this used to carry was redundant: it cost 8
105/// bytes per cell (20 vs 12) over a field that is 2.6 MB at 4K, read up to
106/// 19 times per inter block.
107pub(crate) type TplCell = ((i32, i32), i32);
108
109/// An unprojected [`TplCell`].
110const TPL_EMPTY: TplCell = ((0, 0), 0);
111
112/// The current frame's projected temporal motion field (spec 7.9.2's
113/// `MotionFieldMvs`): one projected [`TplCell`] per 8x8 cell, its
114/// `ref_frame_offset` left at `0` where no source candidate landed
115/// (libaom's `INVALID_MV`).
116#[derive(Clone, Debug)]
117pub struct TplField {
118 cols: usize,
119 rows: usize,
120 cells: Vec<TplCell>,
121}
122
123impl TplField {
124 /// lane-mergefix r5 rung (`EC_TPL`): how many 8x8 cells the projection
125 /// actually filled -- an empty field means every temporal candidate is
126 /// silently absent while the entropy stream still matches.
127 pub fn filled_cells(&self) -> usize {
128 self.cells.iter().filter(|c| c.1 != 0).count()
129 }
130
131}
132
133/// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range
134/// order hints roll over in at `order_hint_bits` width.
135pub fn get_relative_dist(order_hint_bits: u32, a: u32, b: u32) -> i32 {
136 if order_hint_bits == 0 {
137 return 0;
138 }
139 let diff = a as i32 - b as i32;
140 let m = 1i32 << (order_hint_bits - 1);
141 (diff & (m - 1)) - (diff & m)
142}
143
144/// spec `FRAME_OFFSET_BITS`-derived clamp (libaom `MAX_FRAME_DISTANCE`).
145const MAX_FRAME_DISTANCE: i32 = 31;
146
147/// libaom's `div_mult`: precomputed `16384 / den` (`av1_get_mv_projection`'s
148/// own comment: "all the values are strictly under 14 bits").
149const DIV_MULT: [i64; 32] = [
150 0, 16384, 8192, 5461, 4096, 3276, 2730, 2340, 2048, 1820, 1638, 1489, 1365, 1260, 1170, 1092,
151 1024, 963, 910, 862, 819, 780, 744, 712, 682, 655, 630, 606, 585, 564, 546, 528,
152];
153
154fn round_pow2_signed(value: i64, n: u32) -> i32 {
155 let half = 1i64 << (n - 1);
156 (if value < 0 {
157 -((-value + half) >> n)
158 } else {
159 (value + half) >> n
160 }) as i32
161}
162
163/// `av1_get_mv_projection` (spec 7.9.3): scales `mv` by the ratio of two
164/// frame-distance offsets.
165fn get_mv_projection(mv: (i32, i32), num: i32, den: i32) -> (i32, i32) {
166 let den = den.min(MAX_FRAME_DISTANCE);
167 let num = if num > 0 {
168 num.min(MAX_FRAME_DISTANCE)
169 } else {
170 num.max(-MAX_FRAME_DISTANCE)
171 };
172 let mult = DIV_MULT[den as usize];
173 let scale = |v: i32| round_pow2_signed(v as i64 * num as i64 * mult, 14).clamp(-16383, 16383);
174 (scale(mv.0), scale(mv.1))
175}
176
177/// `lower_mv_precision` (`mvref_common.h`), both halves. lane-dgolomb: the
178/// `is_integer` half used to be dropped as unreachable on the claim that
179/// `allow_screen_content_tools` is refused at the stream level -- it is not,
180/// and libaom turns screen-content tools on for dark, smooth FILM (its
181/// `av1_set_screen_content_options` counts near-flat blocks), so a real
182/// libaom stream carries `force_integer_mv == 1` on an inter frame and every
183/// temporal MV candidate has to be rounded to full pel. Without it the
184/// candidates were 1/8-pel values libaom never produces: a whole-frame
185/// prediction mismatch behind a clean parse (class
186/// `branch-dropped-as-unreachable`).
187pub fn lower_mv_precision(
188 mv: (i32, i32),
189 allow_high_precision_mv: bool,
190 force_integer_mv: bool,
191) -> (i32, i32) {
192 if force_integer_mv {
193 // `integer_mv_precision`: drop to the nearest full pel, ties away
194 // from zero (`abs(mod) > 4`).
195 let round = |v: i32| {
196 let m = v % 8;
197 match m {
198 0 => v,
199 _ if m > 4 => v - m + 8,
200 _ if m < -4 => v - m - 8,
201 _ => v - m,
202 }
203 };
204 let out = (round(mv.0), round(mv.1));
205 if out != mv && crate::envflags::env_flag!("EC_TRACE_TPL") {
206 eprintln!("EC_INTMV rounded {mv:?} -> {out:?}");
207 }
208 return out;
209 }
210 if allow_high_precision_mv {
211 return mv;
212 }
213 let round = |v: i32| {
214 if v & 1 != 0 {
215 v + if v > 0 { -1 } else { 1 }
216 } else {
217 v
218 }
219 };
220 (round(mv.0), round(mv.1))
221}
222
223/// `get_block_position` (spec 7.9.2): the 8x8 cell a projected `mv` lands on
224/// starting from `(blk_row, blk_col)` (already in 8x8 units), or `None` when
225/// it falls outside the frame or outside the projection's own bound (a
226/// 64x64-superblock-aligned base block, spec's `MAX_OFFSET_WIDTH`/
227/// `MAX_OFFSET_HEIGHT`).
228fn get_block_position(
229 mvs_rows: usize,
230 mvs_cols: usize,
231 blk_row: usize,
232 blk_col: usize,
233 mv: (i32, i32),
234 sign_bias: bool,
235) -> Option<(usize, usize)> {
236 let base_blk_row = (blk_row >> 3) << 3;
237 let base_blk_col = (blk_col >> 3) << 3;
238 let row_offset = if mv.0 >= 0 {
239 mv.0 >> 6
240 } else {
241 -((-mv.0) >> 6)
242 };
243 let col_offset = if mv.1 >= 0 {
244 mv.1 >> 6
245 } else {
246 -((-mv.1) >> 6)
247 };
248 let row = if sign_bias {
249 blk_row as i64 - row_offset as i64
250 } else {
251 blk_row as i64 + row_offset as i64
252 };
253 let col = if sign_bias {
254 blk_col as i64 - col_offset as i64
255 } else {
256 blk_col as i64 + col_offset as i64
257 };
258 if row < 0 || row >= mvs_rows as i64 || col < 0 || col >= mvs_cols as i64 {
259 return None;
260 }
261 if row < base_blk_row as i64
262 || row >= base_blk_row as i64 + 8
263 || col < base_blk_col as i64 - 8
264 || col >= base_blk_col as i64 + 16
265 {
266 return None;
267 }
268 Some((row as usize, col as usize))
269}
270
271/// `motion_field_projection` (spec 7.9.2): projects `start`'s stored MVs
272/// into `tpl`, scaled by the OrderHint distance from `start` to the current
273/// frame. `dir` mirrors libaom's own parameter: `2` for a backward-looking
274/// source (`LAST_FRAME`/`LAST2_FRAME`, offset negated and `sign_bias`
275/// flipped), `0` for a forward one (`BWDREF_FRAME`/`ALTREF2_FRAME`/
276/// `ALTREF_FRAME`). Returns whether the projection ran at all (`start`'s
277/// frame size has to match the current frame's — always true for this
278/// decoder's fixed-size streams, but ported anyway).
279#[allow(clippy::too_many_arguments)]
280fn motion_field_projection(
281 start: &MotionField,
282 cur_order_hint: u32,
283 order_hint_bits: u32,
284 mi_rows: usize,
285 mi_cols: usize,
286 dir: u8,
287 tpl_cells: &mut [TplCell],
288) -> bool {
289 // libaom's own first two `return 0`s, in order: a key/intra-only start
290 // frame is never projected (and so never spends a `ref_stamp` slot --
291 // returning `true` here made a forward key frame, `--enable-fwd-kf=1`,
292 // consume the slot ALTREF/LAST2 should have had), then the frame-size
293 // test.
294 if start.is_intra {
295 return false;
296 }
297 let mvs_rows = mi_rows.div_ceil(2);
298 let mvs_cols = mi_cols.div_ceil(2);
299 if start.rows != mvs_rows || start.cols != mvs_cols {
300 return false;
301 }
302 let start_order_hint = start.order_hint;
303 let mut start_to_current = get_relative_dist(order_hint_bits, start_order_hint, cur_order_hint);
304 if dir == 2 {
305 start_to_current = -start_to_current;
306 }
307 let ref_offset: [i32; 8] = std::array::from_fn(|rf| {
308 if rf == 0 {
309 0
310 } else {
311 get_relative_dist(
312 order_hint_bits,
313 start_order_hint,
314 start.ref_order_hints[rf - 1],
315 )
316 }
317 });
318 // lane-mvstack3: two of libaom's three `pos_valid` terms do not depend on
319 // the cell at all -- `start_to_current` is one value for the whole field,
320 // and a reference's own offset is one value per `ref_frame` -- so fold
321 // them into a per-ref table read once instead of re-deriving them for
322 // every 8x8 cell (a 4K field is 129600 of them, per direction, per
323 // frame). Same terms, same order of rejection.
324 if start_to_current.abs() > MAX_FRAME_DISTANCE {
325 return true;
326 }
327 let ref_valid: [bool; 8] =
328 std::array::from_fn(|rf| ref_offset[rf] > 0 && ref_offset[rf] <= MAX_FRAME_DISTANCE);
329 let cols = start.cols;
330 for row8 in 0..start.rows {
331 // The row is contiguous, so walk it as a slice: `MotionField::get`'s
332 // per-cell bounds test is the same test the loop bounds already make.
333 let row = &start.cells[row8 * cols..][..cols];
334 for (col8, cell) in row.iter().enumerate() {
335 let Some(saved) = *cell else {
336 continue;
337 };
338 if saved.ref_frame <= 0 {
339 continue;
340 }
341 let ref_frame_offset = ref_offset[saved.ref_frame as usize];
342 if !ref_valid[saved.ref_frame as usize] {
343 continue;
344 }
345 let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset);
346 if let Some((r, c)) =
347 get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1)
348 {
349 tpl_cells[r * mvs_cols + c] = (saved.mv, ref_frame_offset);
350 }
351 }
352 }
353 true
354}
355
356thread_local! {
357 /// Frames whose `av1_setup_motion_field` saw at least one forward
358 /// references holding a key/intra-only frame -- the `ref_stamp` path
359 /// [`motion_field_projection`]'s intra early return governs.
360 static REFSTAMP_INTRA_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
361 /// The subset of those frames with TWO or more such references.
362 static REFSTAMP_INTRA2_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
363}
364
365/// Reads the counter above (gate
366/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`).
367#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
368pub fn refstamp_intra_frames() -> (usize, usize) {
369 (
370 REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get),
371 REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get),
372 )
373}
374
375/// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to
376/// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order
377/// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when
378/// each is display-order-forward of the current frame, then `LAST2_FRAME`
379/// once the stack still has room) and projects each into the returned
380/// [`TplField`].
381///
382/// `slots` is the DPB's 8 reference-picture slots' saved [`MotionField`]s
383/// (a `None` slot, or one still holding an intra frame's — never
384/// constructed, so also `None` — motion field, contributes nothing);
385/// `ref_frame_idx` is the current frame header's own `ref_frame_idx`
386/// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).
387pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
388 slots: &[Option<M>; 8],
389 ref_frame_idx: [u8; 7],
390 cur_order_hint: u32,
391 order_hint_bits: u32,
392 mi_rows: usize,
393 mi_cols: usize,
394) -> TplField {
395 let cols = mi_cols.div_ceil(2);
396 let rows = mi_rows.div_ceil(2);
397 let mut cells = vec![TPL_EMPTY; cols * rows];
398 // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;`
399 // leaves every `tpl_mvs` cell INVALID.
400 if order_hint_bits == 0 {
401 return TplField { cols, rows, cells };
402 }
403
404 let slot_of =
405 // lane-thread3: `M` is an owned `MotionField` on the single-threaded
406 // path and a `&MotionField` borrowed out of a resolved reference-slot
407 // promise on a worker; the projection reads the same field either way.
408 |ref_frame: i8| {
409 slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize]
410 .as_ref()
411 .map(M::borrow)
412 };
413 let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);
414
415 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
416
417 // Gate counter (lane-refstamp): frames whose forward references include at
418 // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the
419 // early return above fixes.
420 let intra_forward_refs = [
421 BWDREF_FRAME,
422 crate::mvstack::ALTREF2_FRAME,
423 ALTREF_FRAME,
424 ]
425 .into_iter()
426 .filter(|&rf| {
427 get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0
428 && slot_of(rf).is_some_and(|m| m.is_intra)
429 })
430 .count();
431 if intra_forward_refs >= 1 {
432 hit!(REFSTAMP_INTRA_FRAMES);
433 }
434 if intra_forward_refs >= 2 {
435 hit!(REFSTAMP_INTRA2_FRAMES);
436 }
437
438 if let Some(last) = slot_of(LAST_FRAME) {
439 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
440 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
441 if !is_lst_overlay {
442 motion_field_projection(
443 last,
444 cur_order_hint,
445 order_hint_bits,
446 mi_rows,
447 mi_cols,
448 2,
449 &mut cells,
450 );
451 }
452 ref_stamp -= 1;
453 }
454
455 if get_relative_dist(order_hint_bits, order_hint_of(BWDREF_FRAME), cur_order_hint) > 0
456 && let Some(bwd) = slot_of(BWDREF_FRAME)
457 && motion_field_projection(
458 bwd,
459 cur_order_hint,
460 order_hint_bits,
461 mi_rows,
462 mi_cols,
463 0,
464 &mut cells,
465 )
466 {
467 ref_stamp -= 1;
468 }
469
470 if get_relative_dist(
471 order_hint_bits,
472 order_hint_of(crate::mvstack::ALTREF2_FRAME),
473 cur_order_hint,
474 ) > 0
475 && let Some(alt2) = slot_of(crate::mvstack::ALTREF2_FRAME)
476 && motion_field_projection(
477 alt2,
478 cur_order_hint,
479 order_hint_bits,
480 mi_rows,
481 mi_cols,
482 0,
483 &mut cells,
484 )
485 {
486 ref_stamp -= 1;
487 }
488
489 if ref_stamp >= 0
490 && get_relative_dist(order_hint_bits, order_hint_of(ALTREF_FRAME), cur_order_hint) > 0
491 && let Some(alt) = slot_of(ALTREF_FRAME)
492 && motion_field_projection(
493 alt,
494 cur_order_hint,
495 order_hint_bits,
496 mi_rows,
497 mi_cols,
498 0,
499 &mut cells,
500 )
501 {
502 ref_stamp -= 1;
503 }
504
505 if ref_stamp >= 0
506 && let Some(last2) = slot_of(LAST2_FRAME)
507 {
508 motion_field_projection(
509 last2,
510 cur_order_hint,
511 order_hint_bits,
512 mi_rows,
513 mi_cols,
514 2,
515 &mut cells,
516 );
517 }
518
519 if crate::envflags::env_flag!("EC_TRACE_TPL") {
520 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");
521 for r in 0..rows {
522 let row: String = (0..cols)
523 .map(|c| if cells[r * cols + c].1 != 0 { '#' } else { '.' })
524 .collect();
525 eprintln!("EC_TPL_FIELD r{r} {row}");
526 }
527 }
528 TplField { cols, rows, cells }
529}
530
531/// The result [`add_tpl_ref_mv`] folds into a query block's MV stack: the
532/// projected candidate MV (already scaled to the block's own reference
533/// frame and MV-precision-lowered) plus whether the very first (`blk_row ==
534/// 0 && blk_col == 0`) sample differs enough from the zero vector to raise
535/// `GLOBALMV_OFFSET` (spec 7.10.2.8 — this decoder only ever reaches
536/// `IDENTITY` global motion, so the spec's `gm_get_motion_vector` compare
537/// collapses to "far from `(0, 0)`").
538pub struct TplCandidate {
539 pub mv: (i32, i32),
540}
541
542/// `add_tpl_ref_mv`'s single-reference half (spec 7.10.2.8, libaom
543/// `mvref_common.c`): probes one 8x8-unit offset `(blk_row, blk_col)` from
544/// `(mi_row, mi_col)` in [`TplField`] and, if it landed a candidate,
545/// projects it a second time — this time scaled to `cur_offset_0`, the
546/// distance from the current frame to the query block's own single
547/// reference frame, rather than `start_to_current_frame_offset` from the
548/// first (storage-time) projection.
549// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
550#[allow(clippy::too_many_arguments)]
551pub fn add_tpl_ref_mv(
552 tpl: &TplField,
553 mi_row: usize,
554 mi_col: usize,
555 blk_row: isize,
556 blk_col: isize,
557 cur_offset_0: i32,
558 allow_high_precision_mv: bool,
559 force_integer_mv: bool,
560) -> Option<TplCandidate> {
561 let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col);
562 if crate::envflags::env_flag!("EC_TRACE_TPL") {
563 match probe {
564 None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
565 Some((m, rfo)) => eprintln!(
566 "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",
567 m.0, m.1
568 ),
569 }
570 }
571 let (fwd_mv, ref_frame_offset) = probe?;
572 Some(TplCandidate {
573 mv: project_tpl_mv(
574 fwd_mv,
575 cur_offset_0,
576 ref_frame_offset,
577 allow_high_precision_mv,
578 force_integer_mv,
579 ),
580 })
581}
582
583/// The projection half of [`add_tpl_ref_mv`], split out so a caller holding a
584/// [`TplProbe`] cell can project it to more than one reference offset without
585/// reading the field twice (lane-tpl: the compound stack does exactly that).
586#[inline]
587pub fn project_tpl_mv(
588 fwd_mv: (i32, i32),
589 cur_offset: i32,
590 ref_frame_offset: i32,
591 allow_high_precision_mv: bool,
592 force_integer_mv: bool,
593) -> (i32, i32) {
594 let projected = get_mv_projection(fwd_mv, cur_offset, ref_frame_offset);
595 lower_mv_precision(projected, allow_high_precision_mv, force_integer_mv)
596}
597
598/// One query block's view of [`TplField`] (lane-tpl). `add_tpl_ref_mv`'s
599/// parity derivation and row base are the same for every `(blk_row,
600/// blk_col)` the mv stack probes, so they are hoisted here and the per-sample
601/// cost drops to an add, a shift and the bounds check: `row8 = mi_row +
602/// pos_row` with `pos_row = blk_row + (mi_row even)` means the cell index is
603/// `(mi_row + 1 - (mi_row & 1) + blk_row) >> 1`, and an arithmetic shift
604/// keeps the spec's `row8 < 0` rejection exact (`row8 < 0` iff the shifted
605/// index is negative).
606pub struct TplProbe<'a> {
607 cells: &'a [TplCell],
608 cols: isize,
609 rows: isize,
610 base_row: isize,
611 base_col: isize,
612}
613
614impl TplField {
615 /// [`TplProbe`] for the query block at `(mi_row, mi_col)`.
616 #[inline]
617 pub fn probe(&self, mi_row: usize, mi_col: usize) -> TplProbe<'_> {
618 TplProbe {
619 cells: &self.cells,
620 cols: self.cols as isize,
621 rows: self.rows as isize,
622 base_row: mi_row as isize + 1 - (mi_row & 1) as isize,
623 base_col: mi_col as isize + 1 - (mi_col & 1) as isize,
624 }
625 }
626}
627
628impl TplProbe<'_> {
629 /// The stored `(mv, ref_frame_offset)` at the 8x8-unit offset
630 /// `(blk_row, blk_col)` from the query block, or `None` where the spec's
631 /// probe falls outside the field.
632 #[inline]
633 pub fn cell(&self, blk_row: isize, blk_col: isize) -> Option<((i32, i32), i32)> {
634 let row = (self.base_row + blk_row) >> 1;
635 let col = (self.base_col + blk_col) >> 1;
636 if row < 0 || col < 0 || row >= self.rows || col >= self.cols {
637 return None;
638 }
639 let cell = self.cells[(row * self.cols + col) as usize];
640 if cell.1 == 0 { None } else { Some(cell) }
641 }
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 /// lane-tpl: `TplProbe::cell` replaced `add_tpl_ref_mv`'s per-sample
649 /// parity derivation with one hoisted base; this pins it against that
650 /// derivation, spelled out, over every parity and every offset the mv
651 /// stack (and its extension samples) can probe with.
652 #[test]
653 fn probe_cell_matches_the_spec_parity_derivation() {
654 let (rows, cols) = (5usize, 6usize);
655 let cells: Vec<TplCell> = (0..rows * cols)
656 .map(|i| ((i as i32, -(i as i32)), 1))
657 .collect();
658 let tpl = TplField { cols, rows, cells };
659 for mi_row in 0..2 * rows {
660 for mi_col in 0..2 * cols {
661 let probe = tpl.probe(mi_row, mi_col);
662 for blk_row in -4isize..=16 {
663 for blk_col in -4isize..=16 {
664 // the spec's own derivation (7.10.2.8)
665 let pos_row = if mi_row & 1 != 0 { blk_row } else { blk_row + 1 };
666 let pos_col = if mi_col & 1 != 0 { blk_col } else { blk_col + 1 };
667 let row8 = mi_row as isize + pos_row;
668 let col8 = mi_col as isize + pos_col;
669 let want = if row8 < 0 || col8 < 0 {
670 None
671 } else {
672 let (r, c) = (row8 as usize / 2, col8 as usize / 2);
673 if r < rows && c < cols {
674 Some(tpl.cells[r * cols + c])
675 } else {
676 None
677 }
678 };
679 assert_eq!(
680 probe.cell(blk_row, blk_col),
681 want,
682 "mi=({mi_row},{mi_col}) blk=({blk_row},{blk_col})"
683 );
684 }
685 }
686 }
687 }
688 }
689
690 /// lane-mvstack3: [`TplCell`] dropped its `Option` tag for the
691 /// `ref_frame_offset == 0` sentinel `motion_field_projection` already
692 /// guarantees (it only ever stores a strictly positive offset). This pins
693 /// that sentinel: an unprojected cell must still read as `None` through
694 /// [`TplProbe::cell`], and a projected one with a zero MV must not.
695 #[test]
696 fn an_unprojected_tpl_cell_reads_as_none_but_a_zero_mv_one_does_not() {
697 let (rows, cols) = (2usize, 2usize);
698 let cells: Vec<TplCell> = vec![TPL_EMPTY, ((0, 0), 3), ((7, -7), 1), TPL_EMPTY];
699 let tpl = TplField { cols, rows, cells };
700 // mi=(0,0) probes cell (0,0) at blk (-1,-1) and (0,1) at blk (-1,1).
701 let probe = tpl.probe(0, 0);
702 assert_eq!(probe.cell(-1, -1), None, "unprojected cell");
703 assert_eq!(probe.cell(-1, 1), Some(((0, 0), 3)), "projected zero mv");
704 assert_eq!(probe.cell(1, -1), Some(((7, -7), 1)));
705 assert_eq!(probe.cell(1, 1), None, "unprojected cell");
706 assert_eq!(tpl.filled_cells(), 2);
707 }
708
709 #[test]
710 fn relative_dist_wraps_at_order_hint_bits() {
711 // 7-bit order hints (aomenc's usual default): 1 - 126 should read as
712 // +3 (wrapping backward past 0), not -125.
713 assert_eq!(get_relative_dist(7, 1, 126), 3);
714 assert_eq!(get_relative_dist(7, 10, 5), 5);
715 }
716
717 #[test]
718 fn mv_projection_scales_by_the_distance_ratio() {
719 // A MV recorded across a 2-frame gap, projected across a 1-frame
720 // gap, should halve (libaom's own div_mult table is exact for small
721 // integer ratios).
722 let (row, col) = get_mv_projection((16, -32), 1, 2);
723 assert_eq!((row, col), (8, -16));
724 // Same-distance projection is the identity.
725 assert_eq!(get_mv_projection((7, -3), 4, 4), (7, -3));
726 }
727
728 #[test]
729 fn setup_motion_field_projects_last_frame_forward() {
730 // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV
731 // against its own LAST_FRAME (order_hint 1). The current frame
732 // (order_hint 4) names that same slot as *its* LAST_FRAME.
733 let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0], false);
734 mf.set(
735 0,
736 0,
737 Some(SavedMv {
738 mv: (-64, 0),
739 ref_frame: LAST_FRAME,
740 }),
741 );
742 let slots: [Option<MotionField>; 8] =
743 std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None });
744 let ref_frame_idx = [0u8; 7];
745 let tpl = setup_motion_field(&slots, ref_frame_idx, 4, 7, 16, 16);
746 // LAST_FRAME's own dir=2 projection: start_to_current = -get_relative_dist(2,4) = 2,
747 // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by
748 // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts
749 // the offset, landing at 8x8 cell (2, 0).
750 let cand =
751 add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true, false);
752 assert!(cand.is_some(), "expected a projected temporal candidate");
753 }
754
755 /// lane-dgolomb: `lower_mv_precision`'s `force_integer_mv` half, which
756 /// this decoder used to drop as unreachable. The values are the ones a
757 /// real libaom stream (film B, `-cpu-used 6 -crf 35`, the one inter frame
758 /// whose header carries `force_integer_mv == 1`) produces at its first
759 /// 128x128 block: the same 16 temporal probes, projected and then rounded
760 /// to full pel, are what put `(16,0)`/`(16,-8)`/`(8,-40)` in libaom's own
761 /// traced mv stack where the eighth-pel values were `(14,-4)`/`(12,-2)`/
762 /// `(12,-38)`/`(16,-4)`.
763 #[test]
764 fn force_integer_mv_rounds_a_projected_candidate_to_full_pel() {
765 // (mfmv0, ref_frame_offset) -> (eighth-pel value, full-pel value),
766 // all at cur_offset_0 == 1.
767 for (mv, rfo, eighth, integer) in [
768 ((74, -20), 5, (14, -4), (16, 0)),
769 ((74, -24), 5, (14, -4), (16, -8)),
770 ((82, -24), 5, (16, -4), (16, -8)),
771 ((66, -16), 5, (12, -2), (16, 0)),
772 ((24, -76), 2, (12, -38), (8, -40)),
773 ] {
774 assert_eq!(project_tpl_mv(mv, 1, rfo, false, false), eighth, "{mv:?}");
775 assert_eq!(project_tpl_mv(mv, 1, rfo, false, true), integer, "{mv:?}");
776 }
777 // `integer_mv_precision`'s tie rule is away from zero on |mod| > 4
778 // only, and it is signed-symmetric.
779 assert_eq!(lower_mv_precision((4, -4), false, true), (0, 0));
780 assert_eq!(lower_mv_precision((5, -5), false, true), (8, -8));
781 assert_eq!(lower_mv_precision((-12, 8), false, true), (-8, 8));
782 }
783}