forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

motion_field.rs582 lines, 20.3 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.
8
9use crate::mvstack::{ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME};
10
11/// One 8x8 cell's saved motion state, as libaom's `av1_copy_frame_mvs`
12/// leaves it after decoding the frame that owns this grid: the coded MV and
13/// the single reference frame (`LAST_FRAME..=ALTREF_FRAME`, 1..=7) it
14/// pointed to.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct SavedMv {
17 pub mv: (i32, i32),
18 pub ref_frame: i8,
19}
20
21/// A decoded inter frame's whole motion field (spec `MotionFieldMvs`... no
22/// — libaom's `cur_frame->mvs`), one [`SavedMv`] per 8x8 unit, plus the
23/// order-hint bookkeeping [`setup_motion_field`] needs to project it into a
24/// later frame: this frame's own `OrderHint` and the `OrderHint` of each of
25/// the 7 references *it* was coded against (`SavedOrderHints`/
26/// `ref_order_hints`).
27#[derive(Clone, Debug)]
28pub struct MotionField {
29 cols: usize,
30 rows: usize,
31 cells: Vec<Option<SavedMv>>,
32 pub order_hint: u32,
33 pub ref_order_hints: [u32; 7],
34 /// libaom `motion_field_projection`'s own first test: a start frame whose
35 /// `frame_type` is `KEY_FRAME`/`INTRA_ONLY_FRAME` is never projected at
36 /// all (`return 0`), so it also never spends a `ref_stamp` slot.
37 pub is_intra: bool,
38}
39
40impl MotionField {
41 /// A field sized for an `mi_cols` by `mi_rows` frame, all cells
42 /// initially unset (spec 7.9's own reset to `-1`/invalid before any
43 /// block writes into it).
44 pub fn new(
45 mi_cols: usize,
46 mi_rows: usize,
47 order_hint: u32,
48 ref_order_hints: [u32; 7],
49 is_intra: bool,
50 ) -> Self {
51 let cols = mi_cols.div_ceil(2);
52 let rows = mi_rows.div_ceil(2);
53 Self {
54 cols,
55 rows,
56 cells: vec![None; cols * rows],
57 order_hint,
58 ref_order_hints,
59 is_intra,
60 }
61 }
62
63 /// Records `saved` at the 8x8 cell containing 4x4 unit `(mi_row,
64 /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single
65 /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution
66 /// write.
67 /// `saved == None` is `av1_copy_frame_mvs`'s own leading clear
68 /// (`mv->ref_frame = NONE_FRAME; mv->mv.as_int = 0;`), which every block
69 /// of an inter frame performs -- an intra (or nothing-to-store) block
70 /// sharing an 8x8 cell with an earlier inter one wipes that cell.
71 pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: Option<SavedMv>) {
72 let (r, c) = (mi_row / 2, mi_col / 2);
73 if r < self.rows && c < self.cols {
74 self.cells[r * self.cols + c] = saved;
75 }
76 }
77
78 /// lane-mergefix r5 rung (`EC_TRACE_TPL`): occupancy map of the SAVED
79 /// field, the input side of [`setup_motion_field`]'s projection.
80 pub fn occupancy(&self) -> Vec<String> {
81 (0..self.rows)
82 .map(|r| {
83 (0..self.cols)
84 .map(|c| if self.cells[r * self.cols + c].is_some() { '#' } else { '.' })
85 .collect()
86 })
87 .collect()
88 }
89
90 fn get(&self, row8: usize, col8: usize) -> Option<SavedMv> {
91 if row8 < self.rows && col8 < self.cols {
92 self.cells[row8 * self.cols + col8]
93 } else {
94 None
95 }
96 }
97}
98
99/// The current frame's projected temporal motion field (spec 7.9.2's
100/// `MotionFieldMvs`): one projected `(mv, ref_frame_offset)` per 8x8 cell,
101/// `None` where no source candidate landed (libaom's `INVALID_MV`).
102#[derive(Clone, Debug)]
103pub struct TplField {
104 cols: usize,
105 rows: usize,
106 cells: Vec<Option<((i32, i32), i32)>>,
107}
108
109impl TplField {
110 /// lane-mergefix r5 rung (`EC_TPL`): how many 8x8 cells the projection
111 /// actually filled -- an empty field means every temporal candidate is
112 /// silently absent while the entropy stream still matches.
113 pub fn filled_cells(&self) -> usize {
114 self.cells.iter().filter(|c| c.is_some()).count()
115 }
116
117 fn get(&self, row8: usize, col8: usize) -> Option<((i32, i32), i32)> {
118 if row8 < self.rows && col8 < self.cols {
119 self.cells[row8 * self.cols + col8]
120 } else {
121 None
122 }
123 }
124}
125
126/// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range
127/// order hints roll over in at `order_hint_bits` width.
128pub fn get_relative_dist(order_hint_bits: u32, a: u32, b: u32) -> i32 {
129 if order_hint_bits == 0 {
130 return 0;
131 }
132 let diff = a as i32 - b as i32;
133 let m = 1i32 << (order_hint_bits - 1);
134 (diff & (m - 1)) - (diff & m)
135}
136
137/// spec `FRAME_OFFSET_BITS`-derived clamp (libaom `MAX_FRAME_DISTANCE`).
138const MAX_FRAME_DISTANCE: i32 = 31;
139
140/// libaom's `div_mult`: precomputed `16384 / den` (`av1_get_mv_projection`'s
141/// own comment: "all the values are strictly under 14 bits").
142const DIV_MULT: [i64; 32] = [
143 0, 16384, 8192, 5461, 4096, 3276, 2730, 2340, 2048, 1820, 1638, 1489, 1365, 1260, 1170, 1092,
144 1024, 963, 910, 862, 819, 780, 744, 712, 682, 655, 630, 606, 585, 564, 546, 528,
145];
146
147fn round_pow2_signed(value: i64, n: u32) -> i32 {
148 let half = 1i64 << (n - 1);
149 (if value < 0 {
150 -((-value + half) >> n)
151 } else {
152 (value + half) >> n
153 }) as i32
154}
155
156/// `av1_get_mv_projection` (spec 7.9.3): scales `mv` by the ratio of two
157/// frame-distance offsets.
158fn get_mv_projection(mv: (i32, i32), num: i32, den: i32) -> (i32, i32) {
159 let den = den.min(MAX_FRAME_DISTANCE);
160 let num = if num > 0 {
161 num.min(MAX_FRAME_DISTANCE)
162 } else {
163 num.max(-MAX_FRAME_DISTANCE)
164 };
165 let mult = DIV_MULT[den as usize];
166 let scale = |v: i32| round_pow2_signed(v as i64 * num as i64 * mult, 14).clamp(-16383, 16383);
167 (scale(mv.0), scale(mv.1))
168}
169
170/// `lower_mv_precision` (`mvref_common.h`), the `is_integer == false` half
171/// only — every stream this decoder ever reaches has `force_integer_mv ==
172/// false` on an inter frame (`allow_screen_content_tools`, the only source
173/// of a `true` value here, is refused outright at the stream level).
174pub fn lower_mv_precision(mv: (i32, i32), allow_high_precision_mv: bool) -> (i32, i32) {
175 if allow_high_precision_mv {
176 return mv;
177 }
178 let round = |v: i32| {
179 if v & 1 != 0 {
180 v + if v > 0 { -1 } else { 1 }
181 } else {
182 v
183 }
184 };
185 (round(mv.0), round(mv.1))
186}
187
188/// `get_block_position` (spec 7.9.2): the 8x8 cell a projected `mv` lands on
189/// starting from `(blk_row, blk_col)` (already in 8x8 units), or `None` when
190/// it falls outside the frame or outside the projection's own bound (a
191/// 64x64-superblock-aligned base block, spec's `MAX_OFFSET_WIDTH`/
192/// `MAX_OFFSET_HEIGHT`).
193fn get_block_position(
194 mvs_rows: usize,
195 mvs_cols: usize,
196 blk_row: usize,
197 blk_col: usize,
198 mv: (i32, i32),
199 sign_bias: bool,
200) -> Option<(usize, usize)> {
201 let base_blk_row = (blk_row >> 3) << 3;
202 let base_blk_col = (blk_col >> 3) << 3;
203 let row_offset = if mv.0 >= 0 {
204 mv.0 >> 6
205 } else {
206 -((-mv.0) >> 6)
207 };
208 let col_offset = if mv.1 >= 0 {
209 mv.1 >> 6
210 } else {
211 -((-mv.1) >> 6)
212 };
213 let row = if sign_bias {
214 blk_row as i64 - row_offset as i64
215 } else {
216 blk_row as i64 + row_offset as i64
217 };
218 let col = if sign_bias {
219 blk_col as i64 - col_offset as i64
220 } else {
221 blk_col as i64 + col_offset as i64
222 };
223 if row < 0 || row >= mvs_rows as i64 || col < 0 || col >= mvs_cols as i64 {
224 return None;
225 }
226 if row < base_blk_row as i64
227 || row >= base_blk_row as i64 + 8
228 || col < base_blk_col as i64 - 8
229 || col >= base_blk_col as i64 + 16
230 {
231 return None;
232 }
233 Some((row as usize, col as usize))
234}
235
236/// `motion_field_projection` (spec 7.9.2): projects `start`'s stored MVs
237/// into `tpl`, scaled by the OrderHint distance from `start` to the current
238/// frame. `dir` mirrors libaom's own parameter: `2` for a backward-looking
239/// source (`LAST_FRAME`/`LAST2_FRAME`, offset negated and `sign_bias`
240/// flipped), `0` for a forward one (`BWDREF_FRAME`/`ALTREF2_FRAME`/
241/// `ALTREF_FRAME`). Returns whether the projection ran at all (`start`'s
242/// frame size has to match the current frame's — always true for this
243/// decoder's fixed-size streams, but ported anyway).
244#[allow(clippy::too_many_arguments)]
245fn motion_field_projection(
246 start: &MotionField,
247 cur_order_hint: u32,
248 order_hint_bits: u32,
249 mi_rows: usize,
250 mi_cols: usize,
251 dir: u8,
252 tpl_cells: &mut [Option<((i32, i32), i32)>],
253) -> bool {
254 // libaom's own first two `return 0`s, in order: a key/intra-only start
255 // frame is never projected (and so never spends a `ref_stamp` slot --
256 // returning `true` here made a forward key frame, `--enable-fwd-kf=1`,
257 // consume the slot ALTREF/LAST2 should have had), then the frame-size
258 // test.
259 if start.is_intra {
260 return false;
261 }
262 let mvs_rows = mi_rows.div_ceil(2);
263 let mvs_cols = mi_cols.div_ceil(2);
264 if start.rows != mvs_rows || start.cols != mvs_cols {
265 return false;
266 }
267 let start_order_hint = start.order_hint;
268 let mut start_to_current = get_relative_dist(order_hint_bits, start_order_hint, cur_order_hint);
269 if dir == 2 {
270 start_to_current = -start_to_current;
271 }
272 let ref_offset: [i32; 8] = std::array::from_fn(|rf| {
273 if rf == 0 {
274 0
275 } else {
276 get_relative_dist(
277 order_hint_bits,
278 start_order_hint,
279 start.ref_order_hints[rf - 1],
280 )
281 }
282 });
283 for row8 in 0..start.rows {
284 for col8 in 0..start.cols {
285 let Some(saved) = start.get(row8, col8) else {
286 continue;
287 };
288 if saved.ref_frame <= 0 {
289 continue;
290 }
291 let ref_frame_offset = ref_offset[saved.ref_frame as usize];
292 let pos_valid = ref_frame_offset.abs() <= MAX_FRAME_DISTANCE
293 && ref_frame_offset > 0
294 && start_to_current.abs() <= MAX_FRAME_DISTANCE;
295 if !pos_valid {
296 continue;
297 }
298 let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset);
299 if let Some((r, c)) =
300 get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1)
301 {
302 tpl_cells[r * mvs_cols + c] = Some((saved.mv, ref_frame_offset));
303 }
304 }
305 }
306 true
307}
308
309thread_local! {
310 /// Frames whose `av1_setup_motion_field` saw at least one forward
311 /// references holding a key/intra-only frame -- the `ref_stamp` path
312 /// [`motion_field_projection`]'s intra early return governs.
313 static REFSTAMP_INTRA_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
314 /// The subset of those frames with TWO or more such references.
315 static REFSTAMP_INTRA2_FRAMES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
316}
317
318/// Reads the counter above (gate
319/// `a_real_aomenc_inter_sequence_with_forward_keyframes_and_temporal_mvs_decodes_pixel_exact`).
320pub fn refstamp_intra_frames() -> (usize, usize) {
321 (
322 REFSTAMP_INTRA_FRAMES.with(std::cell::Cell::get),
323 REFSTAMP_INTRA2_FRAMES.with(std::cell::Cell::get),
324 )
325}
326
327/// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to
328/// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order
329/// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when
330/// each is display-order-forward of the current frame, then `LAST2_FRAME`
331/// once the stack still has room) and projects each into the returned
332/// [`TplField`].
333///
334/// `slots` is the DPB's 8 reference-picture slots' saved [`MotionField`]s
335/// (a `None` slot, or one still holding an intra frame's — never
336/// constructed, so also `None` — motion field, contributes nothing);
337/// `ref_frame_idx` is the current frame header's own `ref_frame_idx`
338/// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).
339pub fn setup_motion_field(
340 slots: &[Option<MotionField>; 8],
341 ref_frame_idx: [u8; 7],
342 cur_order_hint: u32,
343 order_hint_bits: u32,
344 mi_rows: usize,
345 mi_cols: usize,
346) -> TplField {
347 let cols = mi_cols.div_ceil(2);
348 let rows = mi_rows.div_ceil(2);
349 let mut cells = vec![None; cols * rows];
350 // `av1_setup_motion_field`'s own head: `if (!enable_order_hint) return;`
351 // leaves every `tpl_mvs` cell INVALID.
352 if order_hint_bits == 0 {
353 return TplField { cols, rows, cells };
354 }
355
356 let slot_of =
357 |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref();
358 let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);
359
360 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
361
362 // Gate counter (lane-refstamp): frames whose forward references include at
363 // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the
364 // early return above fixes.
365 let intra_forward_refs = [
366 BWDREF_FRAME,
367 crate::mvstack::ALTREF2_FRAME,
368 ALTREF_FRAME,
369 ]
370 .into_iter()
371 .filter(|&rf| {
372 get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0
373 && slot_of(rf).is_some_and(|m| m.is_intra)
374 })
375 .count();
376 if intra_forward_refs >= 1 {
377 REFSTAMP_INTRA_FRAMES.with(|c| c.set(c.get() + 1));
378 }
379 if intra_forward_refs >= 2 {
380 REFSTAMP_INTRA2_FRAMES.with(|c| c.set(c.get() + 1));
381 }
382
383 if let Some(last) = slot_of(LAST_FRAME) {
384 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
385 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
386 if !is_lst_overlay {
387 motion_field_projection(
388 last,
389 cur_order_hint,
390 order_hint_bits,
391 mi_rows,
392 mi_cols,
393 2,
394 &mut cells,
395 );
396 }
397 ref_stamp -= 1;
398 }
399
400 if get_relative_dist(order_hint_bits, order_hint_of(BWDREF_FRAME), cur_order_hint) > 0
401 && let Some(bwd) = slot_of(BWDREF_FRAME)
402 && motion_field_projection(
403 bwd,
404 cur_order_hint,
405 order_hint_bits,
406 mi_rows,
407 mi_cols,
408 0,
409 &mut cells,
410 )
411 {
412 ref_stamp -= 1;
413 }
414
415 if get_relative_dist(
416 order_hint_bits,
417 order_hint_of(crate::mvstack::ALTREF2_FRAME),
418 cur_order_hint,
419 ) > 0
420 && let Some(alt2) = slot_of(crate::mvstack::ALTREF2_FRAME)
421 && motion_field_projection(
422 alt2,
423 cur_order_hint,
424 order_hint_bits,
425 mi_rows,
426 mi_cols,
427 0,
428 &mut cells,
429 )
430 {
431 ref_stamp -= 1;
432 }
433
434 if ref_stamp >= 0
435 && get_relative_dist(order_hint_bits, order_hint_of(ALTREF_FRAME), cur_order_hint) > 0
436 && let Some(alt) = slot_of(ALTREF_FRAME)
437 && motion_field_projection(
438 alt,
439 cur_order_hint,
440 order_hint_bits,
441 mi_rows,
442 mi_cols,
443 0,
444 &mut cells,
445 )
446 {
447 ref_stamp -= 1;
448 }
449
450 if ref_stamp >= 0
451 && let Some(last2) = slot_of(LAST2_FRAME)
452 {
453 motion_field_projection(
454 last2,
455 cur_order_hint,
456 order_hint_bits,
457 mi_rows,
458 mi_cols,
459 2,
460 &mut cells,
461 );
462 }
463
464 if std::env::var_os("EC_TRACE_TPL").is_some() {
465 eprintln!("EC_TPL_FIELD oh={cur_order_hint} rows={rows} cols={cols}");
466 for r in 0..rows {
467 let row: String = (0..cols)
468 .map(|c| if cells[r * cols + c].is_some() { '#' } else { '.' })
469 .collect();
470 eprintln!("EC_TPL_FIELD r{r} {row}");
471 }
472 }
473 TplField { cols, rows, cells }
474}
475
476/// The result [`add_tpl_ref_mv`] folds into a query block's MV stack: the
477/// projected candidate MV (already scaled to the block's own reference
478/// frame and MV-precision-lowered) plus whether the very first (`blk_row ==
479/// 0 && blk_col == 0`) sample differs enough from the zero vector to raise
480/// `GLOBALMV_OFFSET` (spec 7.10.2.8 — this decoder only ever reaches
481/// `IDENTITY` global motion, so the spec's `gm_get_motion_vector` compare
482/// collapses to "far from `(0, 0)`").
483pub struct TplCandidate {
484 pub mv: (i32, i32),
485}
486
487/// `add_tpl_ref_mv`'s single-reference half (spec 7.10.2.8, libaom
488/// `mvref_common.c`): probes one 8x8-unit offset `(blk_row, blk_col)` from
489/// `(mi_row, mi_col)` in [`TplField`] and, if it landed a candidate,
490/// projects it a second time — this time scaled to `cur_offset_0`, the
491/// distance from the current frame to the query block's own single
492/// reference frame, rather than `start_to_current_frame_offset` from the
493/// first (storage-time) projection.
494pub fn add_tpl_ref_mv(
495 tpl: &TplField,
496 mi_row: usize,
497 mi_col: usize,
498 blk_row: isize,
499 blk_col: isize,
500 cur_offset_0: i32,
501 allow_high_precision_mv: bool,
502) -> Option<TplCandidate> {
503 let pos_row = if mi_row & 1 != 0 {
504 blk_row
505 } else {
506 blk_row + 1
507 };
508 let pos_col = if mi_col & 1 != 0 {
509 blk_col
510 } else {
511 blk_col + 1
512 };
513 let row8 = mi_row as isize + pos_row;
514 let col8 = mi_col as isize + pos_col;
515 if row8 < 0 || col8 < 0 {
516 return None;
517 }
518 let probe = tpl.get(row8 as usize / 2, col8 as usize / 2);
519 if std::env::var_os("EC_TRACE_TPL").is_some() {
520 match probe {
521 None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
522 Some((m, rfo)) => eprintln!(
523 "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",
524 m.0, m.1
525 ),
526 }
527 }
528 let (fwd_mv, ref_frame_offset) = probe?;
529 let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset);
530 let mv = lower_mv_precision(projected, allow_high_precision_mv);
531 Some(TplCandidate { mv })
532}
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537
538 #[test]
539 fn relative_dist_wraps_at_order_hint_bits() {
540 // 7-bit order hints (aomenc's usual default): 1 - 126 should read as
541 // +3 (wrapping backward past 0), not -125.
542 assert_eq!(get_relative_dist(7, 1, 126), 3);
543 assert_eq!(get_relative_dist(7, 10, 5), 5);
544 }
545
546 #[test]
547 fn mv_projection_scales_by_the_distance_ratio() {
548 // A MV recorded across a 2-frame gap, projected across a 1-frame
549 // gap, should halve (libaom's own div_mult table is exact for small
550 // integer ratios).
551 let (row, col) = get_mv_projection((16, -32), 1, 2);
552 assert_eq!((row, col), (8, -16));
553 // Same-distance projection is the identity.
554 assert_eq!(get_mv_projection((7, -3), 4, 4), (7, -3));
555 }
556
557 #[test]
558 fn setup_motion_field_projects_last_frame_forward() {
559 // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV
560 // against its own LAST_FRAME (order_hint 1). The current frame
561 // (order_hint 4) names that same slot as *its* LAST_FRAME.
562 let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0], false);
563 mf.set(
564 0,
565 0,
566 Some(SavedMv {
567 mv: (-64, 0),
568 ref_frame: LAST_FRAME,
569 }),
570 );
571 let slots: [Option<MotionField>; 8] =
572 std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None });
573 let ref_frame_idx = [0u8; 7];
574 let tpl = setup_motion_field(&slots, ref_frame_idx, 4, 7, 16, 16);
575 // LAST_FRAME's own dir=2 projection: start_to_current = -get_relative_dist(2,4) = 2,
576 // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by
577 // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts
578 // the offset, landing at 8x8 cell (2, 0).
579 let cand = add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true);
580 assert!(cand.is_some(), "expected a projected temporal candidate");
581 }
582}