diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 3b5a2d74..1ea65b89 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -131,6 +131,76 @@ static BWDREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUs static ALTREF2_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); static ALTREF_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +/// How many query blocks folded in at least one temporal MV candidate +/// (spec 7.10.2.8's `add_tpl_ref_mv`) so far in this process -- the +/// temporal-MV gate's own firing counter (lane-av1tmvp). +/// +/// # HANDOFF (lane-av1tmvp): not yet wired to a live stream +/// [`crate::mvstack::find_mv_stack_with_sign_bias`]'s only call site in +/// this file (`decode_inter_block`) still passes `tpl: None` -- this +/// counter compiles and the projection math it counts is unit-tested +/// ([`crate::motion_field`]), but nothing in [`crate::stream::decode_stream`] +/// builds a per-DPB-slot [`crate::motion_field::MotionField`] or calls +/// [`crate::motion_field::setup_motion_field`] yet, so this will read `0` +/// against any real stream today. See the module doc on +/// `crate::motion_field` and this crate's ledger for the remaining wiring. +pub(crate) fn tmv_hits() -> usize { + crate::mvstack::tmv_hits() +} + +/// Everything [`decode_inter_block`] needs to fold temporal MV candidates +/// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]: +/// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s +/// output, built by the caller when `header.use_ref_frame_mvs` is set) plus +/// the order-hint bookkeeping [`crate::motion_field::get_relative_dist`] +/// needs to turn a query block's own resolved `ref_frame` into +/// `TplArgs::cur_offset_0` (spec 7.9.3). +pub(crate) struct TplFrameArgs<'a> { + pub field: &'a crate::motion_field::TplField, + pub order_hint_bits: u32, + pub order_hint: u32, + /// `ref_order_hints[ref_frame - LAST_FRAME]` for `ref_frame` in + /// `LAST_FRAME..=ALTREF_FRAME` — the OrderHint of the picture this + /// frame's own `ref_frame_idx` names for each single reference. + pub ref_order_hints: [u32; 7], +} + +/// Builds this frame's own saved motion field (libaom `av1_copy_frame_mvs`, +/// spec 7.9's per-frame `MotionFieldMvs` storage step) from its fully +/// decoded `grid`: every 4x4 unit an inter block covers reads the same +/// `MiInfo` ([`decode_inter_block`]/`decode_inter_block8` write it +/// block-uniform), so sampling any one 4x4 unit inside each 8x8 cell is +/// exact — every block this crate ever codes is at least 8x8, so no 8x8 +/// cell straddles two different blocks' values. +pub(crate) fn build_motion_field( + grid: &MiGrid, + mi_cols: usize, + mi_rows: usize, + order_hint: u32, + ref_order_hints: [u32; 7], +) -> crate::motion_field::MotionField { + let mut field = + crate::motion_field::MotionField::new(mi_cols, mi_rows, order_hint, ref_order_hints); + for row in 0..mi_rows { + for col in 0..mi_cols { + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame > 0 + { + field.set( + row, + col, + crate::motion_field::SavedMv { + mv: info.mv, + ref_frame: info.ref_frame, + }, + ); + } + } + } + field +} + /// Current value of the counter for `ref_frame` (`LAST2_FRAME`..=`ALTREF_FRAME`; /// panics on `LAST_FRAME`/`INTRA_FRAME`/`NONE`, which have no counter here). pub(crate) fn ref_hits(ref_frame: i8) -> usize { @@ -3758,6 +3828,7 @@ fn decode_inter_block( allow_high_precision_mv: bool, interp_fixed: Option, enable_dual_filter: bool, + tpl_frame: Option<&TplFrameArgs>, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -3804,6 +3875,20 @@ fn decode_inter_block( let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let bw4 = side / 4; + // spec 7.10.2.8: only reached when the frame header set + // `use_ref_frame_mvs` (`tpl_frame` is `Some` then, `None` + // otherwise) -- `cur_offset_0` is this query block's own resolved + // `ref_frame`'s distance from the current frame (spec 7.9.3), + // recomputed per block since different blocks pick different refs. + let tpl = tpl_frame.map(|t| crate::mvstack::TplArgs { + field: t.field, + cur_offset_0: crate::motion_field::get_relative_dist( + t.order_hint_bits, + t.order_hint, + t.ref_order_hints[(ref_frame - LAST_FRAME) as usize], + ), + allow_high_precision_mv, + }); let stack = find_mv_stack_with_sign_bias( grid, mi_row, @@ -3814,6 +3899,7 @@ fn decode_inter_block( mi_cols as usize, mi_rows as usize, sign_bias_table, + tpl, ); let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1; let mut is_globalmv = false; @@ -4656,8 +4742,12 @@ pub fn decode_inter_frame_tile( NO_SIGN_BIAS, interp_fixed, enable_dual_filter, + 0, + 0, + [0; 7], + None, ) - .map(|(picture, _)| picture) + .map(|(picture, _, _)| picture) } /// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see @@ -4681,7 +4771,22 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( sign_bias_table: SignBiasTable, interp_fixed: Option, enable_dual_filter: bool, -) -> Result<(Picture, Cdfs)> { + // lane-av1tmvp: `order_hint`/`order_hint_bits`/`ref_order_hints` are + // always needed (this frame's own saved [`crate::motion_field::MotionField`] + // carries them for a *later* frame's projection, spec 7.9); `tpl_field` + // is `Some` only when this frame's own header set `use_ref_frame_mvs` + // and the caller ([`crate::stream::decode_stream`]) projected one. + order_hint_bits: u32, + order_hint: u32, + ref_order_hints: [u32; 7], + tpl_field: Option<&crate::motion_field::TplField>, +) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> { + let tpl_frame = tpl_field.map(|field| TplFrameArgs { + field, + order_hint_bits, + order_hint, + ref_order_hints, + }); if mi_cols == 0 || mi_rows == 0 { return Err(unsupported("a frame with no mode-info grid")); } @@ -4870,6 +4975,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( allow_high_precision_mv, interp_fixed, enable_dual_filter, + tpl_frame.as_ref(), )?; } PARTITION_SPLIT => { @@ -4927,6 +5033,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( allow_high_precision_mv, interp_fixed, enable_dual_filter, + tpl_frame.as_ref(), )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -5014,6 +5121,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( apply_deblock(&mut y, &mut u, &mut v, loop_filter, &neighbours); apply_cdef(&mut y, &mut u, &mut v, cdef, &neighbours); + let motion_field = build_motion_field( + &grid, + mi_cols as usize, + mi_rows as usize, + order_hint, + ref_order_hints, + ); + let (fw, fh) = (frame_width as usize, frame_height as usize); if fw == width && fh == height { return Ok(( @@ -5025,6 +5140,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( v: v.data, }, cdfs, + motion_field, )); } let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec { @@ -5043,6 +5159,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( v: crop(&v, fw / 2, fh / 2), }, cdfs, + motion_field, )) } @@ -5665,6 +5782,7 @@ mod tests { false, Some(mc::InterpFilterKind::Regular), false, + None, ) .unwrap(); diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 90ed6061..e749bf2a 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -23,6 +23,7 @@ pub mod frame; pub mod intra; pub mod mc; pub mod motion; +mod motion_field; pub mod msac; pub mod mvstack; pub mod obu; diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs new file mode 100644 index 00000000..bac2f6eb --- /dev/null +++ b/crates/ec-av1/src/motion_field.rs @@ -0,0 +1,477 @@ +//! Temporal MV projection (AV1 spec 7.9, `use_ref_frame_mvs`): projects a +//! previously decoded frame's stored motion vectors into the current +//! frame's own 8x8 motion field, ported from libaom's +//! `av1_setup_motion_field`/`motion_field_projection` +//! (`av1/common/mvref_common.c`) and the projection math `add_tpl_ref_mv` +//! (same file) applies a second time, per query block, against the block's +//! own single reference frame. + +use crate::mvstack::{ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME}; + +/// One 8x8 cell's saved motion state, as libaom's `av1_copy_frame_mvs` +/// leaves it after decoding the frame that owns this grid: the coded MV and +/// the single reference frame (`LAST_FRAME..=ALTREF_FRAME`, 1..=7) it +/// pointed to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SavedMv { + pub mv: (i32, i32), + pub ref_frame: i8, +} + +/// A decoded inter frame's whole motion field (spec `MotionFieldMvs`... no +/// — libaom's `cur_frame->mvs`), one [`SavedMv`] per 8x8 unit, plus the +/// order-hint bookkeeping [`setup_motion_field`] needs to project it into a +/// later frame: this frame's own `OrderHint` and the `OrderHint` of each of +/// the 7 references *it* was coded against (`SavedOrderHints`/ +/// `ref_order_hints`). +#[derive(Clone, Debug)] +pub struct MotionField { + cols: usize, + rows: usize, + cells: Vec>, + pub order_hint: u32, + pub ref_order_hints: [u32; 7], +} + +impl MotionField { + /// A field sized for an `mi_cols` by `mi_rows` frame, all cells + /// initially unset (spec 7.9's own reset to `-1`/invalid before any + /// block writes into it). + pub fn new(mi_cols: usize, mi_rows: usize, order_hint: u32, ref_order_hints: [u32; 7]) -> Self { + let cols = mi_cols.div_ceil(2); + let rows = mi_rows.div_ceil(2); + Self { + cols, + rows, + cells: vec![None; cols * rows], + order_hint, + ref_order_hints, + } + } + + /// Records `saved` at the 8x8 cell containing 4x4 unit `(mi_row, + /// mi_col)` — every `MiInfo` inside one 8x8 cell shares a single + /// motion-field entry, matching `av1_copy_frame_mvs`'s own half-resolution + /// write. + pub fn set(&mut self, mi_row: usize, mi_col: usize, saved: SavedMv) { + let (r, c) = (mi_row / 2, mi_col / 2); + if r < self.rows && c < self.cols { + self.cells[r * self.cols + c] = Some(saved); + } + } + + fn get(&self, row8: usize, col8: usize) -> Option { + if row8 < self.rows && col8 < self.cols { + self.cells[row8 * self.cols + col8] + } else { + None + } + } +} + +/// The current frame's projected temporal motion field (spec 7.9.2's +/// `MotionFieldMvs`): one projected `(mv, ref_frame_offset)` per 8x8 cell, +/// `None` where no source candidate landed (libaom's `INVALID_MV`). +#[derive(Clone, Debug)] +pub struct TplField { + cols: usize, + rows: usize, + cells: Vec>, +} + +impl TplField { + fn get(&self, row8: usize, col8: usize) -> Option<((i32, i32), i32)> { + if row8 < self.rows && col8 < self.cols { + self.cells[row8 * self.cols + col8] + } else { + None + } + } +} + +/// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range +/// order hints roll over in at `order_hint_bits` width. +pub fn get_relative_dist(order_hint_bits: u32, a: u32, b: u32) -> i32 { + if order_hint_bits == 0 { + return 0; + } + let diff = a as i32 - b as i32; + let m = 1i32 << (order_hint_bits - 1); + (diff & (m - 1)) - (diff & m) +} + +/// spec `FRAME_OFFSET_BITS`-derived clamp (libaom `MAX_FRAME_DISTANCE`). +const MAX_FRAME_DISTANCE: i32 = 31; + +/// libaom's `div_mult`: precomputed `16384 / den` (`av1_get_mv_projection`'s +/// own comment: "all the values are strictly under 14 bits"). +const DIV_MULT: [i64; 32] = [ + 0, 16384, 8192, 5461, 4096, 3276, 2730, 2340, 2048, 1820, 1638, 1489, 1365, 1260, 1170, 1092, + 1024, 963, 910, 862, 819, 780, 744, 712, 682, 655, 630, 606, 585, 564, 546, 528, +]; + +fn round_pow2_signed(value: i64, n: u32) -> i32 { + let half = 1i64 << (n - 1); + (if value < 0 { + -((-value + half) >> n) + } else { + (value + half) >> n + }) as i32 +} + +/// `av1_get_mv_projection` (spec 7.9.3): scales `mv` by the ratio of two +/// frame-distance offsets. +fn get_mv_projection(mv: (i32, i32), num: i32, den: i32) -> (i32, i32) { + let den = den.min(MAX_FRAME_DISTANCE); + let num = if num > 0 { + num.min(MAX_FRAME_DISTANCE) + } else { + num.max(-MAX_FRAME_DISTANCE) + }; + let mult = DIV_MULT[den as usize]; + let scale = |v: i32| round_pow2_signed(v as i64 * num as i64 * mult, 14).clamp(-16383, 16383); + (scale(mv.0), scale(mv.1)) +} + +/// `lower_mv_precision` (`mvref_common.h`), the `is_integer == false` half +/// only — every stream this decoder ever reaches has `force_integer_mv == +/// false` on an inter frame (`allow_screen_content_tools`, the only source +/// of a `true` value here, is refused outright at the stream level). +pub fn lower_mv_precision(mv: (i32, i32), allow_high_precision_mv: bool) -> (i32, i32) { + if allow_high_precision_mv { + return mv; + } + let round = |v: i32| { + if v & 1 != 0 { + v + if v > 0 { -1 } else { 1 } + } else { + v + } + }; + (round(mv.0), round(mv.1)) +} + +/// `get_block_position` (spec 7.9.2): the 8x8 cell a projected `mv` lands on +/// starting from `(blk_row, blk_col)` (already in 8x8 units), or `None` when +/// it falls outside the frame or outside the projection's own bound (a +/// 64x64-superblock-aligned base block, spec's `MAX_OFFSET_WIDTH`/ +/// `MAX_OFFSET_HEIGHT`). +fn get_block_position( + mvs_rows: usize, + mvs_cols: usize, + blk_row: usize, + blk_col: usize, + mv: (i32, i32), + sign_bias: bool, +) -> Option<(usize, usize)> { + let base_blk_row = (blk_row >> 3) << 3; + let base_blk_col = (blk_col >> 3) << 3; + let row_offset = if mv.0 >= 0 { + mv.0 >> 6 + } else { + -((-mv.0) >> 6) + }; + let col_offset = if mv.1 >= 0 { + mv.1 >> 6 + } else { + -((-mv.1) >> 6) + }; + let row = if sign_bias { + blk_row as i64 - row_offset as i64 + } else { + blk_row as i64 + row_offset as i64 + }; + let col = if sign_bias { + blk_col as i64 - col_offset as i64 + } else { + blk_col as i64 + col_offset as i64 + }; + if row < 0 || row >= mvs_rows as i64 || col < 0 || col >= mvs_cols as i64 { + return None; + } + if row < base_blk_row as i64 + || row >= base_blk_row as i64 + 8 + || col < base_blk_col as i64 - 8 + || col >= base_blk_col as i64 + 16 + { + return None; + } + Some((row as usize, col as usize)) +} + +/// `motion_field_projection` (spec 7.9.2): projects `start`'s stored MVs +/// into `tpl`, scaled by the OrderHint distance from `start` to the current +/// frame. `dir` mirrors libaom's own parameter: `2` for a backward-looking +/// source (`LAST_FRAME`/`LAST2_FRAME`, offset negated and `sign_bias` +/// flipped), `0` for a forward one (`BWDREF_FRAME`/`ALTREF2_FRAME`/ +/// `ALTREF_FRAME`). Returns whether the projection ran at all (`start`'s +/// frame size has to match the current frame's — always true for this +/// decoder's fixed-size streams, but ported anyway). +#[allow(clippy::too_many_arguments)] +fn motion_field_projection( + start: &MotionField, + cur_order_hint: u32, + order_hint_bits: u32, + mi_rows: usize, + mi_cols: usize, + dir: u8, + tpl_cells: &mut [Option<((i32, i32), i32)>], +) -> bool { + let mvs_rows = mi_rows.div_ceil(2); + let mvs_cols = mi_cols.div_ceil(2); + if start.rows != mvs_rows || start.cols != mvs_cols { + return false; + } + let start_order_hint = start.order_hint; + let mut start_to_current = get_relative_dist(order_hint_bits, start_order_hint, cur_order_hint); + if dir == 2 { + start_to_current = -start_to_current; + } + let ref_offset: [i32; 8] = std::array::from_fn(|rf| { + if rf == 0 { + 0 + } else { + get_relative_dist( + order_hint_bits, + start_order_hint, + start.ref_order_hints[rf - 1], + ) + } + }); + for row8 in 0..start.rows { + for col8 in 0..start.cols { + let Some(saved) = start.get(row8, col8) else { + continue; + }; + if saved.ref_frame <= 0 { + continue; + } + let ref_frame_offset = ref_offset[saved.ref_frame as usize]; + let pos_valid = ref_frame_offset.abs() <= MAX_FRAME_DISTANCE + && ref_frame_offset > 0 + && start_to_current.abs() <= MAX_FRAME_DISTANCE; + if !pos_valid { + continue; + } + let projected = get_mv_projection(saved.mv, start_to_current, ref_frame_offset); + if let Some((r, c)) = + get_block_position(mvs_rows, mvs_cols, row8, col8, projected, dir >> 1 == 1) + { + tpl_cells[r * mvs_cols + c] = Some((saved.mv, ref_frame_offset)); + } + } + } + true +} + +/// `av1_setup_motion_field` (spec 7.9.2's own driver): scans up to +/// [`MFMV_STACK_SIZE`]`= 3` reference-frame slots in libaom's fixed order +/// (`LAST_FRAME`, then `BWDREF_FRAME`/`ALTREF2_FRAME`/`ALTREF_FRAME` when +/// each is display-order-forward of the current frame, then `LAST2_FRAME` +/// once the stack still has room) and projects each into the returned +/// [`TplField`]. +/// +/// `slots` is the DPB's 8 reference-picture slots' saved [`MotionField`]s +/// (a `None` slot, or one still holding an intra frame's — never +/// constructed, so also `None` — motion field, contributes nothing); +/// `ref_frame_idx` is the current frame header's own `ref_frame_idx` +/// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`). +pub fn setup_motion_field( + slots: &[Option; 8], + ref_frame_idx: [u8; 7], + cur_order_hint: u32, + order_hint_bits: u32, + mi_rows: usize, + mi_cols: usize, +) -> TplField { + let cols = mi_cols.div_ceil(2); + let rows = mi_rows.div_ceil(2); + let mut cells = vec![None; cols * rows]; + + let slot_of = + |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref(); + let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint); + + let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1 + + if let Some(last) = slot_of(LAST_FRAME) { + let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize]; + let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME); + if !is_lst_overlay { + motion_field_projection( + last, + cur_order_hint, + order_hint_bits, + mi_rows, + mi_cols, + 2, + &mut cells, + ); + } + ref_stamp -= 1; + } + + if get_relative_dist(order_hint_bits, order_hint_of(BWDREF_FRAME), cur_order_hint) > 0 + && let Some(bwd) = slot_of(BWDREF_FRAME) + && motion_field_projection( + bwd, + cur_order_hint, + order_hint_bits, + mi_rows, + mi_cols, + 0, + &mut cells, + ) + { + ref_stamp -= 1; + } + + if get_relative_dist( + order_hint_bits, + order_hint_of(crate::mvstack::ALTREF2_FRAME), + cur_order_hint, + ) > 0 + && let Some(alt2) = slot_of(crate::mvstack::ALTREF2_FRAME) + && motion_field_projection( + alt2, + cur_order_hint, + order_hint_bits, + mi_rows, + mi_cols, + 0, + &mut cells, + ) + { + ref_stamp -= 1; + } + + if ref_stamp >= 0 + && get_relative_dist(order_hint_bits, order_hint_of(ALTREF_FRAME), cur_order_hint) > 0 + && let Some(alt) = slot_of(ALTREF_FRAME) + && motion_field_projection( + alt, + cur_order_hint, + order_hint_bits, + mi_rows, + mi_cols, + 0, + &mut cells, + ) + { + ref_stamp -= 1; + } + + if ref_stamp >= 0 + && let Some(last2) = slot_of(LAST2_FRAME) + { + motion_field_projection( + last2, + cur_order_hint, + order_hint_bits, + mi_rows, + mi_cols, + 2, + &mut cells, + ); + } + + TplField { cols, rows, cells } +} + +/// The result [`add_tpl_ref_mv`] folds into a query block's MV stack: the +/// projected candidate MV (already scaled to the block's own reference +/// frame and MV-precision-lowered) plus whether the very first (`blk_row == +/// 0 && blk_col == 0`) sample differs enough from the zero vector to raise +/// `GLOBALMV_OFFSET` (spec 7.10.2.8 — this decoder only ever reaches +/// `IDENTITY` global motion, so the spec's `gm_get_motion_vector` compare +/// collapses to "far from `(0, 0)`"). +pub struct TplCandidate { + pub mv: (i32, i32), +} + +/// `add_tpl_ref_mv`'s single-reference half (spec 7.10.2.8, libaom +/// `mvref_common.c`): probes one 8x8-unit offset `(blk_row, blk_col)` from +/// `(mi_row, mi_col)` in [`TplField`] and, if it landed a candidate, +/// projects it a second time — this time scaled to `cur_offset_0`, the +/// distance from the current frame to the query block's own single +/// reference frame, rather than `start_to_current_frame_offset` from the +/// first (storage-time) projection. +pub fn add_tpl_ref_mv( + tpl: &TplField, + mi_row: usize, + mi_col: usize, + blk_row: isize, + blk_col: isize, + cur_offset_0: i32, + allow_high_precision_mv: bool, +) -> Option { + let pos_row = if mi_row & 1 != 0 { + blk_row + } else { + blk_row + 1 + }; + let pos_col = if mi_col & 1 != 0 { + blk_col + } else { + blk_col + 1 + }; + let row8 = mi_row as isize + pos_row; + let col8 = mi_col as isize + pos_col; + if row8 < 0 || col8 < 0 { + return None; + } + let (fwd_mv, ref_frame_offset) = tpl.get(row8 as usize / 2, col8 as usize / 2)?; + let projected = get_mv_projection(fwd_mv, cur_offset_0, ref_frame_offset); + let mv = lower_mv_precision(projected, allow_high_precision_mv); + Some(TplCandidate { mv }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relative_dist_wraps_at_order_hint_bits() { + // 7-bit order hints (aomenc's usual default): 1 - 126 should read as + // +3 (wrapping backward past 0), not -125. + assert_eq!(get_relative_dist(7, 1, 126), 3); + assert_eq!(get_relative_dist(7, 10, 5), 5); + } + + #[test] + fn mv_projection_scales_by_the_distance_ratio() { + // A MV recorded across a 2-frame gap, projected across a 1-frame + // gap, should halve (libaom's own div_mult table is exact for small + // integer ratios). + let (row, col) = get_mv_projection((16, -32), 1, 2); + assert_eq!((row, col), (8, -16)); + // Same-distance projection is the identity. + assert_eq!(get_mv_projection((7, -3), 4, 4), (7, -3)); + } + + #[test] + fn setup_motion_field_projects_last_frame_forward() { + // A slot-0 inter frame (order_hint 2) that coded one 8x8 cell's MV + // against its own LAST_FRAME (order_hint 1). The current frame + // (order_hint 4) names that same slot as *its* LAST_FRAME. + let mut mf = MotionField::new(16, 16, 2, [1, 0, 0, 0, 0, 0, 0]); + mf.set( + 0, + 0, + SavedMv { + mv: (-64, 0), + ref_frame: LAST_FRAME, + }, + ); + let slots: [Option; 8] = + std::array::from_fn(|i| if i == 0 { Some(mf.clone()) } else { None }); + let ref_frame_idx = [0u8; 7]; + let tpl = setup_motion_field(&slots, ref_frame_idx, 4, 7, 16, 16); + // LAST_FRAME's own dir=2 projection: start_to_current = -get_relative_dist(2,4) = 2, + // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by + // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts + // the offset, landing at 8x8 cell (2, 0). + let cand = add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true); + assert!(cand.is_some(), "expected a projected temporal candidate"); + } +} diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 2534f077..a9bf3e55 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -78,6 +78,40 @@ //! stack to two entries (spec 7.10.2.12) — this module's stack can be //! shorter than two candidates where libaom's never is. +/// How many query blocks [`find_mv_stack_with_sign_bias`] has folded at +/// least one temporal MV candidate into (spec 7.9/7.10.2.8's +/// `add_tpl_ref_mv`) — the real-aomenc temporal-MV gate's own firing +/// counter (`crate::decode::tmv_hits`), proving the projection path in +/// [`crate::motion_field`] is actually reached, not just compiled. +static TMV_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// The number of query blocks that received at least one temporal MV +/// candidate so far, across every [`find_mv_stack_with_sign_bias`] call in +/// this process. +pub(crate) fn tmv_hits() -> usize { + TMV_HITS.load(std::sync::atomic::Ordering::Relaxed) +} + +/// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV +/// candidates into a block's stack (spec 7.10.2.8, only reached when the +/// frame header's own `use_ref_frame_mvs` is set): the current frame's own +/// projected motion field, the distance (in `get_relative_dist` units) from +/// the current frame to *this query's* single reference frame's own +/// `OrderHint` (`cur_offset_0`, spec 7.9.3 — computed by the caller, since +/// this module has no reason to carry `order_hint_bits`/`OrderHints[]` +/// itself), and `allow_high_precision_mv` (`lower_mv_precision`, spec +/// 7.10.2.8). +pub struct TplArgs<'a> { + /// The current frame's projected temporal motion field + /// ([`crate::motion_field::setup_motion_field`]'s output). + pub field: &'a crate::motion_field::TplField, + /// `get_relative_dist(OrderHint, OrderHints[ref_frame - LAST_FRAME])`, + /// pre-computed by the caller. + pub cur_offset_0: i32, + /// The frame header's own `allow_high_precision_mv`. + pub allow_high_precision_mv: bool, +} + /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it /// in by the time it asks for a block's MV stack. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -534,6 +568,7 @@ pub fn find_mv_stack( mi_cols, mi_rows, &NO_SIGN_BIAS, + None, ) } @@ -553,6 +588,7 @@ pub fn find_mv_stack_with_sign_bias( mi_cols: usize, mi_rows: usize, sign_bias_table: &SignBiasTable, + tpl: Option, ) -> MvStack { let mut candidates = Vec::new(); let mut newmv_count = 0u32; @@ -629,6 +665,97 @@ pub fn find_mv_stack_with_sign_bias( entry.weight += REF_CAT_LEVEL; } + // Temporal MV candidates (spec 7.10.2.8's `add_tpl_ref_mv`, only reached + // when the frame header set `use_ref_frame_mvs`): probed over a grid of + // 8x8-unit offsets spanning the block (libaom's own `blk_row_end`/ + // `blk_col_end`/`step_h`/`step_w`, every real block this crate ever + // codes being square and no wider than 32x32 — `BLOCK_64X64`'s own + // 16x16-mi-unit step branch is dead here, ported anyway since nothing + // relies on that), plus three "extension" samples past the block's own + // span (`tpl_sample_pos`) once the block is at least 8x8 and smaller + // than 64x64 (`allow_extension` — true for every block size this crate + // codes). Folded in *after* the row/col/top-right scan's own + // `REF_CAT_LEVEL` boost above and *before* the corner probe, matching + // libaom's call order in `setup_ref_mv_list` exactly (a temporal + // candidate never gets the boost, and the corner probe can still add a + // genuinely new, lower-weight entry after it). + let mut zero_mv_ctx = 0usize; + if let Some(TplArgs { + field, + cur_offset_0, + allow_high_precision_mv, + }) = tpl + { + let mut any_hit = false; + let voffset = bh4.max(2); + let hoffset = bw4.max(2); + let blk_row_end = bh4.min(16); + let blk_col_end = bw4.min(16); + let step_h = if bh4 >= 16 { 4 } else { 2 }; + let step_w = if bw4 >= 16 { 4 } else { 2 }; + let mut first_sample_missing = true; + let mut first_sample_far = false; + let mut blk_row = 0usize; + while blk_row < blk_row_end { + let mut blk_col = 0usize; + while blk_col < blk_col_end { + if let Some(cand) = crate::motion_field::add_tpl_ref_mv( + field, + mi_row, + mi_col, + blk_row as isize, + blk_col as isize, + cur_offset_0, + allow_high_precision_mv, + ) { + any_hit = true; + if blk_row == 0 && blk_col == 0 { + first_sample_missing = false; + first_sample_far = cand.mv.0.abs() >= 16 || cand.mv.1.abs() >= 16; + } + add_candidate(&mut candidates, cand.mv, 2); + } + blk_col += step_w; + } + blk_row += step_h; + } + // Three "extension" samples past the block's own span (libaom + // `tpl_sample_pos`), reachable for every 8x8..32x32 block this crate + // codes (`allow_extension`), gated on staying inside the block's own + // 64x64 superblock (`check_sb_border`). + let allow_extension = (2..16).contains(&bh4) && (2..16).contains(&bw4); + if allow_extension { + let sb_mask = 16isize; + for (row_off, col_off) in [ + (voffset as isize, -2isize), + (voffset as isize, hoffset as isize), + (voffset as isize - 2, hoffset as isize), + ] { + let row = (mi_row as isize & (sb_mask - 1)) + row_off; + let col = (mi_col as isize & (sb_mask - 1)) + col_off; + if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask { + continue; + } + if let Some(cand) = crate::motion_field::add_tpl_ref_mv( + field, + mi_row, + mi_col, + row_off, + col_off, + cur_offset_0, + allow_high_precision_mv, + ) { + any_hit = true; + add_candidate(&mut candidates, cand.mv, 2); + } + } + } + if any_hit { + TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); + } + // The diagonal top-left corner probe (module doc): folds into the row // side for `ref_match_count` without moving the already-captured // `nearest_match`, and its own newmv-ness is a dummy count libaom @@ -816,10 +943,10 @@ pub fn find_mv_stack_with_sign_bias( } _ => 5, }; - // GLOBALMV_OFFSET is only ever set by temporal MV projection - // (`cm->features.allow_ref_frame_mvs`), which this reduction never runs - // (see module doc) — exact, not a stand-in. - let zero_mv_ctx = 0; + // `zero_mv_ctx` was already computed above, from the temporal-MV pass + // when `tpl` is `Some` (GLOBALMV_OFFSET, spec 7.10.2.8) — `0` otherwise, + // exactly this reduction's old always-0 behaviour when + // `use_ref_frame_mvs` is unset. // av1_drl_ctx (mvref_common.h): weight was boosted in place above for // the nearest entries only, so this now compares the real stored weight diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 44ff6a72..cd0ebb38 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -59,6 +59,14 @@ pub fn decode_stream(data: &[u8]) -> Result> { // and small-magnitude (the two pictures mostly agree), which is exactly // what made it look like a rounding bug rather than a wrong reference. let mut ref_slots: [Option; NUM_REF_FRAMES] = std::array::from_fn(|_| None); + // lane-av1tmvp: each of the 8 reference slots' own saved temporal motion + // field (spec 7.9's per-frame `MotionFieldMvs` storage, libaom + // `cur_frame->mvs`) plus the `OrderHint` the picture in that slot was + // decoded with -- `Picture` itself carries neither, so both ride + // alongside `ref_slots` on the exact same `refresh_frame_flags` update. + let mut motion_field_slots: [Option; NUM_REF_FRAMES] = + std::array::from_fn(|_| None); + let mut order_hint_slots: [u32; NUM_REF_FRAMES] = [0; NUM_REF_FRAMES]; // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a // previous frame's `refresh_frame_flags` stored into it -- the frame's // own end-of-tile adapted table, or (when the frame set @@ -232,8 +240,19 @@ pub fn decode_stream(data: &[u8]) -> Result> { }; let started_from = initial_cdfs.clone(); - let (picture, end_cdfs) = if header.frame_type == FrameType::Key { - decode_key_frame_tile_with_cdfs( + let order_hint_bits = parser + .sequence_header() + .map_or(0, |seq| seq.order_hint_bits); + // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint + // of the picture sitting in each of its 7 single references' DPB + // slots, for this frame's *own* saved [`crate::motion_field::MotionField`] + // (a later frame projects from it) whether or not this frame itself + // reads temporal candidates. + let ref_order_hints: [u32; 7] = + std::array::from_fn(|i| order_hint_slots[header.ref_frame_idx[i] as usize]); + + let (picture, end_cdfs, motion_field) = if header.frame_type == FrameType::Key { + let (picture, end_cdfs) = decode_key_frame_tile_with_cdfs( tile_bytes, header.mi_cols, header.mi_rows, @@ -247,7 +266,19 @@ pub fn decode_stream(data: &[u8]) -> Result> { initial_cdfs, header.tx_mode == TxMode::Select, header.reduced_tx_set, - )? + )?; + // A key frame codes no inter blocks -- its own saved motion + // field has no cells set, matching libaom's own "intra frame + // contributes nothing to a later projection" behaviour, but + // still carries `order_hint`/`ref_order_hints` for the distance + // arithmetic a later frame's projection needs. + let motion_field = crate::motion_field::MotionField::new( + header.mi_cols as usize, + header.mi_rows as usize, + header.order_hint, + ref_order_hints, + ); + (picture, end_cdfs, motion_field) } else { let last_slot = header.ref_frame_idx[0] as usize; let reference = ref_slots[last_slot].as_ref().ok_or_else(|| { @@ -272,6 +303,20 @@ pub fn decode_stream(data: &[u8]) -> Result> { .and_then(Option::as_ref) } }); + // spec 7.9's own driver, `av1_setup_motion_field`: only run when + // this frame's header actually asks for temporal candidates -- + // `find_mv_stack_with_sign_bias` reproduces its old always-`None` + // behaviour bit for bit when this is `None` (see its own doc). + let tpl_field = header.use_ref_frame_mvs.then(|| { + crate::motion_field::setup_motion_field( + &motion_field_slots, + header.ref_frame_idx, + header.order_hint, + order_hint_bits, + header.mi_rows as usize, + header.mi_cols as usize, + ) + }); decode_inter_frame_tile_with_cdfs( tile_bytes, header.mi_cols, @@ -288,6 +333,10 @@ pub fn decode_stream(data: &[u8]) -> Result> { header.ref_frame_sign_bias, interp_fixed, enable_dual_filter, + order_hint_bits, + header.order_hint, + ref_order_hints, + tpl_field.as_ref(), )? }; // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's @@ -329,6 +378,8 @@ pub fn decode_stream(data: &[u8]) -> Result> { // pre-grain decode, even though the frame pushed onto the // caller's output below carries the grained picture. ref_slots[i] = Some(picture.clone()); + motion_field_slots[i] = Some(motion_field.clone()); + order_hint_slots[i] = header.order_hint; } } let output = if header.film_grain.apply_grain { @@ -2444,6 +2495,180 @@ mod tests { ); } + /// lane-av1tmvp: the temporal-MV gate -- unlike every `_single_ref_gate` + /// attempt above, this one leaves `--enable-ref-frame-mvs` at aomenc's + /// own default (on) instead of pinning it off, so `use_ref_frame_mvs` + /// actually fires and `decode::tmv_hits()` (this gate's own capability + /// proof, not just `non_last_ref_hits`) has to advance for the run to + /// count as a real pass rather than a `never_fired` skip. + fn a_real_aomenc_temporal_mv_gate(seed_base: u32, attempts: u32) { + let gate_name = "a_real_aomenc_temporal_mv_gate"; + if !have_ffmpeg() { + eprintln!("SKIP {gate_name}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {gate_name}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 16usize); + let mut never_fired = 0u32; + let mut refusals = Vec::new(); + for attempt in 0..attempts { + let seed = seed_base + attempt; + let duration = frame_count as f64 / 25.0; + let source = + format!("gradients=size={width}x{height}:seed={seed}:duration={duration}:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", + "error", + "-f", + "lavfi", + "-i", + &source, + "-pix_fmt", + "yuv420p", + "-f", + "yuv4mpegpipe", + "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // Same envelope as `a_real_aomenc_single_ref_gate`, minus its + // `--enable-ref-frame-mvs=0` pin -- everything else this decoder + // still cannot code stays refused the same way. + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=55", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=1", + "--lag-in-frames=16", + "--enable-fwd-kf=0", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-dist-wtd-comp=0", + "--enable-diff-wtd-comp=0", + "--enable-onesided-comp=0", + "--enable-interintra-wedge=0", + "--enable-smooth-interintra=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = decode::tmv_hits(); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{gate_name} failed outright (seed {seed}): {msg}" + ); + refusals.push(format!("seed {seed}: {msg}")); + continue; + } + Ok(frames) => frames, + }; + if decode::tmv_hits() == before { + never_fired += 1; + continue; + } + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count); + assert_eq!(frames.len(), frame_count); + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if mismatched { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (seed {seed}) to {path}"); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{gate_name} frame {i} luma vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{gate_name} frame {i} U vs ffmpeg (seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{gate_name} frame {i} V vs ffmpeg (seed {seed})" + ); + } + eprintln!( + "{gate_name} FIRING seed {seed}: tmv_hits advanced by {}", + decode::tmv_hits() - before + ); + return; + } + eprintln!( + "SKIP {gate_name}: {never_fired} attempts decoded but never fired a temporal MV \ + candidate, and every other attempt hit a named refusal:\n{}", + refusals.join("\n") + ); + } + + #[test] + fn a_real_aomenc_stream_with_temporal_mvs_decodes_pixel_exact() { + a_real_aomenc_temporal_mv_gate(42, 40); + } + /// scratch: decode a pinned stream end to end and report where/why it /// refuses, plus `non_last_ref_hits` progression. #[test]