From e08e4e454bdf7b9c0454d2f9aaa8f08674823b91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 13:49:26 +0300 Subject: [PATCH] perf(av1): hoist the temporal-MV probe out of the per-sample loop, thread-local the mvstack gate counters `add_tpl_ref_mv` re-derived the parity, the field bounds and the row base on every one of the (up to 19) 8x8 probes a query block makes. Those are per-BLOCK quantities: `row8 = mi_row + blk_row + (mi_row even)` means the cell index is `(mi_row + 1 - (mi_row & 1) + blk_row) >> 1`, and an arithmetic shift keeps the spec's `row8 < 0` rejection exact. `TplProbe` holds the two bases plus the cell slice, so a probe is an add, a shift and a bounds check; the compound stack reads the cell ONCE and projects it to both sides instead of walking the field twice. `EC_TRACE_TPL`'s per-sample dump is unchanged: the flag is read once per block and the traced path still goes through `add_tpl_ref_mv` itself. The four mvstack firing counters (`TMV_HITS` per inter block, `STACK_FULL_DROPS` per candidate insertion, `COMP_GM_FILL_HITS`, `TILE_REACH_CLIPS`) were process-global atomics: one shared cache line bumped by 16 frame threads on the parse critical path. They are now thread-local `Cell`s, the form every other gate counter in the crate already uses; the gates that read them decode on their own thread. -0.21% instructions on the 4K segment at 1 thread (443.29 vs 444.24 G); the counter step is flat there and inside the box's noise at 16 threads. Byte-exact: all 12 gate hashes unchanged at 1/4/16 threads. --- crates/ec-av1/src/motion_field.rs | 131 +++++++++++++++---- crates/ec-av1/src/mvstack.rs | 203 +++++++++++++++++------------- 2 files changed, 220 insertions(+), 114 deletions(-) diff --git a/crates/ec-av1/src/motion_field.rs b/crates/ec-av1/src/motion_field.rs index 71dfee0d..b0217d1c 100644 --- a/crates/ec-av1/src/motion_field.rs +++ b/crates/ec-av1/src/motion_field.rs @@ -114,13 +114,6 @@ impl TplField { self.cells.iter().filter(|c| c.is_some()).count() } - 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 @@ -508,22 +501,7 @@ pub fn add_tpl_ref_mv( 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 probe = tpl.get(row8 as usize / 2, col8 as usize / 2); + let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col); if crate::envflags::env_flag!("EC_TRACE_TPL") { match probe { None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"), @@ -534,15 +512,116 @@ pub fn add_tpl_ref_mv( } } let (fwd_mv, ref_frame_offset) = probe?; - 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 }) + Some(TplCandidate { + mv: project_tpl_mv(fwd_mv, cur_offset_0, ref_frame_offset, allow_high_precision_mv), + }) +} + +/// The projection half of [`add_tpl_ref_mv`], split out so a caller holding a +/// [`TplProbe`] cell can project it to more than one reference offset without +/// reading the field twice (lane-tpl: the compound stack does exactly that). +#[inline] +pub fn project_tpl_mv( + fwd_mv: (i32, i32), + cur_offset: i32, + ref_frame_offset: i32, + allow_high_precision_mv: bool, +) -> (i32, i32) { + let projected = get_mv_projection(fwd_mv, cur_offset, ref_frame_offset); + lower_mv_precision(projected, allow_high_precision_mv) +} + +/// One query block's view of [`TplField`] (lane-tpl). `add_tpl_ref_mv`'s +/// parity derivation and row base are the same for every `(blk_row, +/// blk_col)` the mv stack probes, so they are hoisted here and the per-sample +/// cost drops to an add, a shift and the bounds check: `row8 = mi_row + +/// pos_row` with `pos_row = blk_row + (mi_row even)` means the cell index is +/// `(mi_row + 1 - (mi_row & 1) + blk_row) >> 1`, and an arithmetic shift +/// keeps the spec's `row8 < 0` rejection exact (`row8 < 0` iff the shifted +/// index is negative). +pub struct TplProbe<'a> { + cells: &'a [Option<((i32, i32), i32)>], + cols: isize, + rows: isize, + base_row: isize, + base_col: isize, +} + +impl TplField { + /// [`TplProbe`] for the query block at `(mi_row, mi_col)`. + #[inline] + pub fn probe(&self, mi_row: usize, mi_col: usize) -> TplProbe<'_> { + TplProbe { + cells: &self.cells, + cols: self.cols as isize, + rows: self.rows as isize, + base_row: mi_row as isize + 1 - (mi_row & 1) as isize, + base_col: mi_col as isize + 1 - (mi_col & 1) as isize, + } + } +} + +impl TplProbe<'_> { + /// The stored `(mv, ref_frame_offset)` at the 8x8-unit offset + /// `(blk_row, blk_col)` from the query block, or `None` where the spec's + /// probe falls outside the field. + #[inline] + pub fn cell(&self, blk_row: isize, blk_col: isize) -> Option<((i32, i32), i32)> { + let row = (self.base_row + blk_row) >> 1; + let col = (self.base_col + blk_col) >> 1; + if row < 0 || col < 0 || row >= self.rows || col >= self.cols { + return None; + } + self.cells[(row * self.cols + col) as usize] + } } #[cfg(test)] mod tests { use super::*; + /// lane-tpl: `TplProbe::cell` replaced `add_tpl_ref_mv`'s per-sample + /// parity derivation with one hoisted base; this pins it against that + /// derivation, spelled out, over every parity and every offset the mv + /// stack (and its extension samples) can probe with. + #[test] + fn probe_cell_matches_the_spec_parity_derivation() { + let (rows, cols) = (5usize, 6usize); + let cells: Vec> = (0..rows * cols) + .map(|i| Some(((i as i32, -(i as i32)), 1))) + .collect(); + let tpl = TplField { cols, rows, cells }; + for mi_row in 0..2 * rows { + for mi_col in 0..2 * cols { + let probe = tpl.probe(mi_row, mi_col); + for blk_row in -4isize..=16 { + for blk_col in -4isize..=16 { + // the spec's own derivation (7.10.2.8) + 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; + let want = if row8 < 0 || col8 < 0 { + None + } else { + let (r, c) = (row8 as usize / 2, col8 as usize / 2); + if r < rows && c < cols { + tpl.cells[r * cols + c] + } else { + None + } + }; + assert_eq!( + probe.cell(blk_row, blk_col), + want, + "mi=({mi_row},{mi_col}) blk=({blk_row},{blk_col})" + ); + } + } + } + } + } + #[test] fn relative_dist_wraps_at_order_hint_bits() { // 7-bit order hints (aomenc's usual default): 1 - 126 should read as diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index acaadf03..3a57194b 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -78,52 +78,61 @@ //! 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); +thread_local! { + /// 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. + /// lane-tpl: thread-local (like `restoration`'s stripe counters), not an + /// atomic -- this one is bumped once per inter block, and a shared cache line + /// on 16 frame threads' critical path costs more than the counter is worth. + /// Every gate that reads it decodes on its own thread (`EC_AV1_THREADS` + /// defaults to 1, which is the single-threaded decoder unchanged). + static TMV_HITS: std::cell::Cell = const { std::cell::Cell::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. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tmv_hits() -> usize { - TMV_HITS.load(std::sync::atomic::Ordering::Relaxed) + TMV_HITS.with(|c| c.get()) } -/// lane-mvtwin r1 firing counters, one per divergence this round closed. -/// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot -/// came from `gm_mv_candidates[side]` rather than a scanned neighbour, and -/// where that global mv was NOT `(0, 0)` (the only case the old zero fill -/// could not fake). `STACK_FULL_DROPS`: distinct candidates libaom drops at -/// `MAX_REF_MV_STACK_SIZE` on insertion. `TILE_REACH_CLIPS`: row/col reaches -/// shortened by a tile origin past mi 0, which the old frame-edge clamp -/// missed entirely. -static COMP_GM_FILL_HITS: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); -static STACK_FULL_DROPS: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); -static TILE_REACH_CLIPS: std::sync::atomic::AtomicUsize = - std::sync::atomic::AtomicUsize::new(0); +thread_local! { + /// lane-mvtwin r1 firing counters, one per divergence this round closed. + /// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot + /// came from `gm_mv_candidates[side]` rather than a scanned neighbour, and + /// where that global mv was NOT `(0, 0)` (the only case the old zero fill + /// could not fake). `STACK_FULL_DROPS`: distinct candidates libaom drops at + /// `MAX_REF_MV_STACK_SIZE` on insertion. `TILE_REACH_CLIPS`: row/col reaches + /// shortened by a tile origin past mi 0, which the old frame-edge clamp + /// missed entirely. + /// lane-tpl: thread-local for the same reason as [`TMV_HITS`] + /// (`STACK_FULL_DROPS` is bumped per candidate insertion, the hottest of the + /// four). + static COMP_GM_FILL_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static STACK_FULL_DROPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static TILE_REACH_CLIPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} /// [`COMP_GM_FILL_HITS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn comp_gm_fill_hits() -> usize { - COMP_GM_FILL_HITS.load(std::sync::atomic::Ordering::Relaxed) + COMP_GM_FILL_HITS.with(|c| c.get()) } /// [`STACK_FULL_DROPS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn stack_full_drops() -> usize { - STACK_FULL_DROPS.load(std::sync::atomic::Ordering::Relaxed) + STACK_FULL_DROPS.with(|c| c.get()) } /// [`TILE_REACH_CLIPS`]. #[allow(dead_code)] // read only from the `#[cfg(test)]` gates pub(crate) fn tile_reach_clips() -> usize { - TILE_REACH_CLIPS.load(std::sync::atomic::Ordering::Relaxed) + TILE_REACH_CLIPS.with(|c| c.get()) } /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV @@ -372,7 +381,7 @@ fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) if let Some(entry) = candidates.iter_mut().find(|e| e.mv == mv) { entry.weight += weight; } else if candidates.len() >= MAX_STACK_SIZE { - STACK_FULL_DROPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STACK_FULL_DROPS.with(|c| c.set(c.get() + 1)); } else { // libaom `add_ref_mv_candidate` (mvref_common.c:100) and // `add_tpl_ref_mv` (:388) only push when @@ -932,7 +941,7 @@ pub fn find_mv_stack_with_sign_bias( // `None` for the cells outside the tile. let (tile_row0, tile_col0) = grid.tile_origin(); if tile_row0 > 0 || tile_col0 > 0 { - TILE_REACH_CLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TILE_REACH_CLIPS.with(|c| c.set(c.get() + 1)); } let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); @@ -1036,27 +1045,48 @@ pub fn find_mv_stack_with_sign_bias( 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( + // lane-tpl: the parity/bounds derivation and the field's row base are + // per BLOCK, not per sample -- hoisted into `TplProbe` here so each of + // the (up to 19) probes below costs an add, a shift and a bounds + // check. The `EC_TRACE_TPL` dump lives in `add_tpl_ref_mv` itself, so + // the traced path keeps calling it and the hot path never re-reads the + // flag. + let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL"); + let probe = field.probe(mi_row, mi_col); + let sample = |blk_row: isize, blk_col: isize| -> Option<(i32, i32)> { + if trace_tpl { + return crate::motion_field::add_tpl_ref_mv( field, mi_row, mi_col, - blk_row as isize, - blk_col as isize, + blk_row, + blk_col, cur_offset_0, allow_high_precision_mv, - ) { + ) + .map(|c| c.mv); + } + let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?; + Some(crate::motion_field::project_tpl_mv( + fwd_mv, + cur_offset_0, + rfo, + allow_high_precision_mv, + )) + }; + 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(mv) = sample(blk_row as isize, blk_col as isize) { any_hit = true; if blk_row == 0 && blk_col == 0 { first_sample_missing = false; let this_gm_mv = gm_mv(gm, ref_frame); - first_sample_far = (cand.mv.0 - this_gm_mv.0).abs() >= 16 - || (cand.mv.1 - this_gm_mv.1).abs() >= 16; + first_sample_far = (mv.0 - this_gm_mv.0).abs() >= 16 + || (mv.1 - this_gm_mv.1).abs() >= 16; } - add_candidate(&mut candidates, cand.mv, 2); + add_candidate(&mut candidates, mv, 2); } blk_col += step_w; } @@ -1079,22 +1109,14 @@ pub fn find_mv_stack_with_sign_bias( 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, - ) { + if let Some(mv) = sample(row_off, col_off) { any_hit = true; - add_candidate(&mut candidates, cand.mv, 2); + add_candidate(&mut candidates, mv, 2); } } } if any_hit { - TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TMV_HITS.with(|c| c.set(c.get() + 1)); } zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); } @@ -1394,7 +1416,7 @@ fn add_compound_candidate( if let Some(entry) = candidates.iter_mut().find(|e| e.mv0 == mv0 && e.mv1 == mv1) { entry.weight += weight; } else if candidates.len() >= MAX_STACK_SIZE { - STACK_FULL_DROPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + STACK_FULL_DROPS.with(|c| c.set(c.get() + 1)); } else { // Same insertion cap as [`add_candidate`]: libaom's compound branch // of `add_ref_mv_candidate` (mvref_common.c:128) and `add_tpl_ref_mv` @@ -1682,7 +1704,7 @@ fn combine_compound_candidates( std::array::from_fn(|i| { merged.get(i).copied().unwrap_or_else(|| { if gm_mv_candidates[side] != (0, 0) { - COMP_GM_FILL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + COMP_GM_FILL_HITS.with(|c| c.set(c.get() + 1)); } gm_mv_candidates[side] }) @@ -1742,7 +1764,7 @@ pub fn find_mv_stack_compound( // `None` for the cells outside the tile. let (tile_row0, tile_col0) = grid.tile_origin(); if tile_row0 > 0 || tile_col0 > 0 { - TILE_REACH_CLIPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TILE_REACH_CLIPS.with(|c| c.set(c.get() + 1)); } let max_row_offset: isize = if mi_row > tile_row0 { let reach = if bh4 < 2 { -4 } else { -6 } + isize::from(row_adj); @@ -1836,32 +1858,50 @@ pub fn find_mv_stack_compound( 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 { - let cand0 = crate::motion_field::add_tpl_ref_mv( - field, - mi_row, - mi_col, - blk_row as isize, - blk_col as isize, + // lane-tpl: the parity/bounds derivation and the field's row base are + // per BLOCK, not per sample -- hoisted into `TplProbe` here so each of + // the (up to 19) probes below costs an add, a shift and a bounds + // check. The `EC_TRACE_TPL` dump lives in `add_tpl_ref_mv` itself, so + // the traced path keeps calling it and the hot path never re-reads the + // flag. + let trace_tpl = crate::envflags::env_flag!("EC_TRACE_TPL"); + let probe = field.probe(mi_row, mi_col); + let sample = |blk_row: isize, blk_col: isize| -> Option<((i32, i32), (i32, i32))> { + if trace_tpl { + for off in [cur_offset_0, cur_offset_1] { + let _ = crate::motion_field::add_tpl_ref_mv( + field, + mi_row, + mi_col, + blk_row, + blk_col, + off, + allow_high_precision_mv, + ); + } + } + let (fwd_mv, rfo) = probe.cell(blk_row, blk_col)?; + Some(( + crate::motion_field::project_tpl_mv( + fwd_mv, cur_offset_0, + rfo, allow_high_precision_mv, - ); - let cand1 = crate::motion_field::add_tpl_ref_mv( - field, - mi_row, - mi_col, - blk_row as isize, - blk_col as isize, + ), + crate::motion_field::project_tpl_mv( + fwd_mv, cur_offset_1, + rfo, allow_high_precision_mv, - ); - if cand0.is_some() || cand1.is_some() { + ), + )) + }; + 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((mv0, mv1)) = sample(blk_row as isize, blk_col as isize) { any_hit = true; - let mv0 = cand0.map_or((0, 0), |c| c.mv); - let mv1 = cand1.map_or((0, 0), |c| c.mv); if blk_row == 0 && blk_col == 0 { first_sample_missing = false; let this_gm0 = gm_mv(gm, ref_frame.0); @@ -1899,27 +1939,14 @@ pub fn find_mv_stack_compound( if row < 0 || row >= sb_mask || col < 0 || col >= sb_mask { continue; } - let cand0 = crate::motion_field::add_tpl_ref_mv( - field, mi_row, mi_col, row_off, col_off, cur_offset_0, - allow_high_precision_mv, - ); - let cand1 = crate::motion_field::add_tpl_ref_mv( - field, mi_row, mi_col, row_off, col_off, cur_offset_1, - allow_high_precision_mv, - ); - if cand0.is_some() || cand1.is_some() { + if let Some((mv0, mv1)) = sample(row_off, col_off) { any_hit = true; - add_compound_candidate( - &mut candidates, - cand0.map_or((0, 0), |c| c.mv), - cand1.map_or((0, 0), |c| c.mv), - 2, - ); + add_compound_candidate(&mut candidates, mv0, mv1, 2); } } } if any_hit { - TMV_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + TMV_HITS.with(|c| c.set(c.get() + 1)); } zero_mv_ctx = usize::from(first_sample_missing || first_sample_far); }