From fc982dba9c966e5570f227a90fd6d8d1879d35f9 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 15:30:45 +0300 Subject: [PATCH] perf(av1): heap-free MV stack and row-fill mi publication The MV stack was two heap allocations per inter block (`entries` plus `drl_ctx`); both lists are bounded by a spec constant, so they move into a fixed-capacity inline `SmallVec` that derefs to the same slice API. Mode-info publication stamped its block footprint cell by cell through `MiGrid::set`; rows are contiguous, so `MiGrid::fill_rect` fills each row with one `slice::fill` of the `Copy` cell instead. Byte-exact: all four gate streams hash unchanged at 1 thread. instructions:u on the 4K segment 412.376 -> 410.629 G at 1 thread, 421.419 -> 419.746 G at (16,4,2). --- crates/ec-av1/src/decode.rs | 368 +++++++++++++++++------------------ crates/ec-av1/src/mvstack.rs | 138 +++++++++++-- 2 files changed, 292 insertions(+), 214 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 9e57261c..199571c4 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -24231,31 +24231,29 @@ fn decode_inter_block( // too -- a square `bw4`x`bw4` stamp here claims a rect strip's // NEXT strip's own rows/cols before it decodes, corrupting // every later mvstack scan that reads this cell back. - for dr in 0..bh4 { - for dc in 0..bw4 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame: ref0, - ref_frame1: Some(ref1), - mv1: Some(mv1), - mv: mv0, - is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), - size: bw4 as u8, - size_h: bh4 as u8, - // libaom `is_global_mv_block`: per-ref-slot, mode - // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's - // own gm model > TRANSLATION (IDENTITY excluded - // too -- the two-predicate trap, distinct from - // `gm_nontrans` above which allows IDENTITY). - is_global_mv0, - is_global_mv1, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + bh4, + bw4, + MiInfo { + is_inter: true, + ref_frame: ref0, + ref_frame1: Some(ref1), + mv1: Some(mv1), + mv: mv0, + is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), + size: bw4 as u8, + size_h: bh4 as u8, + // libaom `is_global_mv_block`: per-ref-slot, mode + // GLOBAL_GLOBALMV, block >= 8x8, and THAT slot's + // own gm model > TRANSLATION (IDENTITY excluded + // too -- the two-predicate trap, distinct from + // `gm_nontrans` above which allows IDENTITY). + is_global_mv0, + is_global_mv1, + }, + ); // spec 5.11.25's `comp_group_idx`/`compound_idx`: only read when // masked compound / distance-weighted compound are actually // enabled for this stream -- `is_any_masked_compound_used_here` @@ -25787,32 +25785,30 @@ fn decode_inter_block( // lane-rect r2: see the compound path's matching comment above -- // `grid` must be stamped with the block's true bh4/bw4 span, not // a square `bw4`x`bw4` guess. - for dr in 0..bh4 { - for dc in 0..bw4 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame, - // An interintra block records ref_frame[1] == - // INTRA_FRAME (0): warp-sample gathering - // (libaom av1_findSamples, mvref_common.c:1155) - // requires ref_frame[1] == NONE_FRAME, so such a - // neighbour must not donate samples or count in - // num_proj_ref. - ref_frame1: interintra_mode.map(|_| 0), - mv1: None, - mv, - is_new_mv, - size: bw4 as u8, - size_h: bh4 as u8, - is_global_mv0: is_global_mv_block, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + bh4, + bw4, + MiInfo { + is_inter: true, + ref_frame, + // An interintra block records ref_frame[1] == + // INTRA_FRAME (0): warp-sample gathering + // (libaom av1_findSamples, mvref_common.c:1155) + // requires ref_frame[1] == NONE_FRAME, so such a + // neighbour must not donate samples or count in + // num_proj_ref. + ref_frame1: interintra_mode.map(|_| 0), + mv1: None, + mv, + is_new_mv, + size: bw4 as u8, + size_h: bh4 as u8, + is_global_mv0: is_global_mv_block, + is_global_mv1: false, + }, + ); mode_for_tx = 0; uv_predict_mode = DC_PRED; @@ -26619,26 +26615,24 @@ fn decode_inter_block( // lane's `r * SUB_MI` re-derivation would snap a sub-SUB strip to // its enclosing 16-px cell. let (mi_r0, mi_c0) = (rmi, cmi); - for dr in 0..write_h / MI { - for dc in 0..write_w / MI { - grid.set( - mi_r0 + dr, - mi_c0 + dc, - MiInfo { - is_inter: false, - ref_frame: -1, - ref_frame1: None, - mv1: None, - mv: (0, 0), - is_new_mv: false, - size: (write_w / MI) as u8, - size_h: (write_h / MI) as u8, - is_global_mv0: false, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_r0, + mi_c0, + write_h / MI, + write_w / MI, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: (write_w / MI) as u8, + size_h: (write_h / MI) as u8, + is_global_mv0: false, + is_global_mv1: false, + }, + ); neighbours.record_inter_rect_mi( at, write_w / MI, @@ -26843,26 +26837,24 @@ fn decode_inter_block( ref_frame_for_lf = 0; globalmv_for_lf = false; let (mi_row, mi_col) = (rmi, cmi); - for dr in 0..side / 4 { - for dc in 0..side / 4 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: false, - ref_frame: -1, - ref_frame1: None, - mv1: None, - mv: (0, 0), - is_new_mv: false, - size: (side / 4) as u8, - size_h: (side / 4) as u8, - is_global_mv0: false, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + side / 4, + side / 4, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: (side / 4) as u8, + size_h: (side / 4) as u8, + is_global_mv0: false, + is_global_mv1: false, + }, + ); // lane-intrainter r1: an intra block in an inter frame reads the same // `tx_depth` symbol a key-frame block does, and when it splits, the @@ -28294,26 +28286,24 @@ fn decode_intra_sub8_leaf( // intra-in-inter block writes them: `is_inter = 0`, `INTRA_FRAME` ref, no // interpolation filter, no skip mode. neighbours.record_inter_rect_mi(lmi, w_mi, h_mi, skip, false, 0, [3, 3], false); - for dr in 0..h_mi { - for dc in 0..w_mi { - grid.set( - lmi.0 + dr, - lmi.1 + dc, - MiInfo { - is_inter: false, - ref_frame: -1, - ref_frame1: None, - mv1: None, - mv: (0, 0), - is_new_mv: false, - size: w_mi as u8, - size_h: h_mi as u8, - is_global_mv0: false, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + lmi.0, + lmi.1, + h_mi, + w_mi, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: w_mi as u8, + size_h: h_mi as u8, + is_global_mv0: false, + is_global_mv1: false, + }, + ); SUB8_INTRA_RECT_HITS.with(|h| { let mut s = h.get(); s[usize::from(vert)] += 1; @@ -28999,26 +28989,24 @@ fn grid_stamp_rect( mv: (i32, i32), is_new_mv: bool, ) { - for dr in 0..h_mi { - for dc in 0..w_mi { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame, - ref_frame1: None, - mv1: None, - mv, - is_new_mv, - size: w_mi as u8, - size_h: h_mi as u8, - is_global_mv0: false, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + h_mi, + w_mi, + MiInfo { + is_inter: true, + ref_frame, + ref_frame1: None, + mv1: None, + mv, + is_new_mv, + size: w_mi as u8, + size_h: h_mi as u8, + is_global_mv0: false, + is_global_mv1: false, + }, + ); } /// Decodes one 8x8 leaf of a straddling 16x16 inter-frame block @@ -29580,26 +29568,24 @@ fn decode_inter_block8( COMPOUND_WARP_HITS.with(|c| c.set(c.get() + 1)); COMPOUND_WARP_HITS_8.with(|c| c.set(c.get() + 1)); } - for dr in 0..2 { - for dc in 0..2 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame: ref0, - ref_frame1: Some(ref1), - mv1: Some(mv1), - mv: mv0, - is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), - size: 2, - size_h: 2, - is_global_mv0: is_global_mv0_c, - is_global_mv1: is_global_mv1_c, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + 2, + 2, + MiInfo { + is_inter: true, + ref_frame: ref0, + ref_frame1: Some(ref1), + mv1: Some(mv1), + mv: mv0, + is_new_mv: matches!(compound_mode, 2 | 3 | 4 | 5 | 7), + size: 2, + size_h: 2, + is_global_mv0: is_global_mv0_c, + is_global_mv1: is_global_mv1_c, + }, + ); mode_for_tx = 0; let mut inter0_y = vec![0i32; SIDE * SIDE]; @@ -30257,28 +30243,26 @@ fn decode_inter_block8( warp_params.is_some(), ); } - for dr in 0..2 { - for dc in 0..2 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: true, - ref_frame, - // INTRA_FRAME marker for interintra blocks -- keeps - // them out of warp-sample gathering (see 16/32 site). - ref_frame1: interintra_mode.map(|_| 0), - mv1: None, - mv, - is_new_mv, - size: 2, - size_h: 2, - is_global_mv0: is_global_mv_block, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + 2, + 2, + MiInfo { + is_inter: true, + ref_frame, + // INTRA_FRAME marker for interintra blocks -- keeps + // them out of warp-sample gathering (see 16/32 site). + ref_frame1: interintra_mode.map(|_| 0), + mv1: None, + mv, + is_new_mv, + size: 2, + size_h: 2, + is_global_mv0: is_global_mv_block, + is_global_mv1: false, + }, + ); mode_for_tx = 0; // lane-scaledref r1: this leaf's own prediction is always `Regular` @@ -30721,26 +30705,24 @@ fn decode_inter_block8( }); mode_for_tx = mode; let (mi_row, mi_col) = leaf_mi; - for dr in 0..2 { - for dc in 0..2 { - grid.set( - mi_row + dr, - mi_col + dc, - MiInfo { - is_inter: false, - ref_frame: -1, - ref_frame1: None, - mv1: None, - mv: (0, 0), - is_new_mv: false, - size: 2, - size_h: 2, - is_global_mv0: false, - is_global_mv1: false, - }, - ); - } - } + grid.fill_rect( + mi_row, + mi_col, + 2, + 2, + MiInfo { + is_inter: false, + ref_frame: -1, + ref_frame1: None, + mv1: None, + mv: (0, 0), + is_new_mv: false, + size: 2, + size_h: 2, + is_global_mv0: false, + is_global_mv1: false, + }, + ); // lane-leaf8tx r1: the 8x8 leaf's own intra `tx_depth` (libaom // `read_tx_size` -> `read_selected_tx_size`, max depth 1 at diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 3a57194b..212c3f34 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -272,6 +272,23 @@ impl MiGrid { } } + /// Records one block's whole `bh4` x `bw4` footprint at once. Every + /// caller published a block cell-by-cell through [`Self::set`]; the rows + /// are contiguous, so this fills each of them with one `slice::fill` of + /// the (`Copy`) cell instead, the way the neighbour grids' own span fills + /// do. + pub fn fill_rect(&mut self, row: usize, col: usize, h: usize, w: usize, info: MiInfo) { + if col >= self.cols || row >= self.rows { + return; + } + let w = w.min(self.cols - col); + let cell = Some(info); + for r in row..(row + h).min(self.rows) { + let base = r * self.cols + col; + self.cells[base..base + w].fill(cell); + } + } + /// The unit at `(row, col)`, or `None` when it is outside the grid, hasn't /// been coded, or sits outside the current tile's own bounds ([`Self::set_tile_bounds`]). pub fn get(&self, row: usize, col: usize) -> Option<&MiInfo> { @@ -307,7 +324,7 @@ impl MiGrid { /// One entry of the reference MV stack: a candidate motion vector and the /// total weight the neighbours that agreed on it contributed. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct StackEntry { /// The candidate `(row, col)` motion vector. pub mv: (i32, i32), @@ -315,6 +332,85 @@ pub struct StackEntry { pub weight: u32, } +/// A fixed-capacity, heap-free candidate list. The MV stack is rebuilt for +/// EVERY inter block, so the `Vec` this replaces was one malloc/free pair per +/// block (plus one for `drl_ctx`); capacity is a spec constant +/// ([`MAX_STACK_SIZE`]), so the storage is inline and `Deref` hands every +/// consumer the same slice API a `Vec` did. +#[derive(Clone, Copy, Debug)] +pub struct SmallVec { + len: u8, + buf: [T; N], +} + +impl Default for SmallVec { + fn default() -> Self { + Self { + len: 0, + buf: [T::default(); N], + } + } +} + +impl SmallVec { + /// Appends `v`. Callers gate on [`MAX_STACK_SIZE`] before pushing (the + /// spec drops the overflowing candidate at insertion), so a full list + /// here is a bug, not a stream property. + pub fn push(&mut self, v: T) { + debug_assert!((self.len as usize) < N); + self.buf[self.len as usize] = v; + self.len += 1; + } + + /// `Vec::truncate`. + pub fn truncate(&mut self, n: usize) { + if n < self.len as usize { + self.len = n as u8; + } + } +} + +impl FromIterator for SmallVec { + fn from_iter>(iter: I) -> Self { + let mut out = Self::default(); + for v in iter { + out.push(v); + } + out + } +} + +impl std::ops::Deref for SmallVec { + type Target = [T]; + fn deref(&self) -> &[T] { + &self.buf[..self.len as usize] + } +} + +impl std::ops::DerefMut for SmallVec { + fn deref_mut(&mut self) -> &mut [T] { + &mut self.buf[..self.len as usize] + } +} + +impl PartialEq for SmallVec { + fn eq(&self, other: &Self) -> bool { + **self == **other + } +} + +impl Eq for SmallVec {} + +/// The single-reference MV stack's own list type. +pub type StackVec = SmallVec; + +/// The compound MV stack's own list type. +pub type CompoundStackVec = SmallVec; + +/// `drl_ctx`: one context per adjacent stack pair, so at most +/// `MAX_STACK_SIZE - 1` of them. +pub type DrlVec = SmallVec; + /// The result of [`find_mv_stack`]: the sorted candidate list, the two /// predictors a `NEARESTMV`/`NEARMV` block reads from it, the predictor a /// `NEWMV` residual is coded against, and the symbol contexts the block's @@ -323,7 +419,7 @@ pub struct StackEntry { pub struct MvStack { /// The candidates, highest weight first (ties keep scan order: above, /// then left, then top-right). - pub entries: Vec, + pub entries: StackVec, /// `RefStackMv[0]`, or `(0, 0)` when the stack is empty. pub nearest_mv: (i32, i32), /// `RefStackMv[1]`, or `(0, 0)` when the stack has fewer than two @@ -340,7 +436,7 @@ pub struct MvStack { pub zero_mv_ctx: usize, /// Context for each `drl_mode` symbol between consecutive stack /// entries, `entries.len().saturating_sub(1)` long. - pub drl_ctx: Vec, + pub drl_ctx: DrlVec, } /// Spec 7.10.2.8's threshold a candidate's weight is compared against to @@ -377,7 +473,7 @@ const MVREF_ROW_COLS: usize = 3; /// Adds one candidate MV with `weight` to `candidates`, merging it into an /// existing entry with the same MV rather than duplicating it (spec /// `add_ref_mv_candidate`, 7.10.2.5). -fn add_candidate(candidates: &mut Vec, mv: (i32, i32), weight: u32) { +fn add_candidate(candidates: &mut StackVec, 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 { @@ -468,7 +564,7 @@ fn process_single_ref_mv_candidate( candidate: &MiInfo, ref_frame: i8, sign_bias_table: &SignBiasTable, - candidates: &mut Vec, + candidates: &mut StackVec, ) { if !candidate.is_inter { return; @@ -538,7 +634,7 @@ fn scan_row( max_row_offset: isize, ref_frame: i8, gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut StackVec, newmv_count: &mut u32, processed_rows: &mut usize, ) -> bool { @@ -626,7 +722,7 @@ fn scan_col( max_col_offset: isize, ref_frame: i8, gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut StackVec, newmv_count: &mut u32, processed_cols: &mut usize, ) -> bool { @@ -762,7 +858,7 @@ fn scan_top_right( bw4: usize, ref_frame: i8, gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut StackVec, newmv_count: &mut u32, ) -> bool { let Some(row) = mi_row.checked_sub(1) else { @@ -791,7 +887,7 @@ fn scan_corner( mi_col: usize, ref_frame: i8, gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut StackVec, newmv_count: &mut u32, ) -> bool { let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else { @@ -919,7 +1015,7 @@ pub fn find_mv_stack_with_sign_bias( ) -> MvStack { // lane-alloc: the stack is capped at MAX_STACK_SIZE entries, so the pushes // below grew (and memcpy'd) a fresh allocation up to 4 times per block. - let mut candidates = Vec::with_capacity(MAX_STACK_SIZE); + let mut candidates = StackVec::default(); let mut newmv_count = 0u32; // libaom's `max_row_offset`/`max_col_offset` (`setup_ref_mv_list`): how @@ -1011,7 +1107,7 @@ pub fn find_mv_stack_with_sign_bias( // av1_find_mv_stack boosts only the entries the immediate scan found — // exactly `candidates` at this point, before the corner probe (below) // can add anything else (mvref_common.c ~line 544-545). - for entry in &mut candidates { + for entry in candidates.iter_mut() { entry.weight += REF_CAT_LEVEL; } @@ -1371,7 +1467,7 @@ pub fn find_mv_stack_with_sign_bias( /// combined weight — spec 7.10.2's compound half of `add_ref_mv_candidate` /// (libaom `mvref_common.c`, the `is_compound` branch of `scan_row_mbmi`/ /// `scan_col_mbmi`/`scan_blk_mbmi`). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct CompoundStackEntry { /// The candidate's vote for `RefFrame[0]`'s motion vector. pub mv0: (i32, i32), @@ -1386,7 +1482,7 @@ pub struct CompoundStackEntry { #[derive(Clone, Debug, PartialEq, Eq)] pub struct CompoundMvStack { /// The candidates, highest weight first. - pub entries: Vec, + pub entries: CompoundStackVec, /// `RefStackMv[0]` for both refs, or `((0,0),(0,0))` when the stack is /// empty. pub nearest_mv: ((i32, i32), (i32, i32)), @@ -1403,12 +1499,12 @@ pub struct CompoundMvStack { /// Context for the compound `zero_mv` symbol. pub zero_mv_ctx: usize, /// Context for each `drl_mode` symbol between consecutive stack entries. - pub drl_ctx: Vec, + pub drl_ctx: DrlVec, } /// [`add_candidate`], doubled: dedupes on the whole `(mv0, mv1)` pair. fn add_compound_candidate( - candidates: &mut Vec, + candidates: &mut CompoundStackVec, mv0: (i32, i32), mv1: (i32, i32), weight: u32, @@ -1443,7 +1539,7 @@ fn scan_row_compound( max_row_offset: isize, ref_frame: (i8, i8), gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut CompoundStackVec, newmv_count: &mut u32, processed_rows: &mut usize, ) -> bool { @@ -1506,7 +1602,7 @@ fn scan_col_compound( max_col_offset: isize, ref_frame: (i8, i8), gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut CompoundStackVec, newmv_count: &mut u32, processed_cols: &mut usize, ) -> bool { @@ -1566,7 +1662,7 @@ fn scan_top_right_compound( bw4: usize, ref_frame: (i8, i8), gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut CompoundStackVec, newmv_count: &mut u32, ) -> bool { let Some(row) = mi_row.checked_sub(1) else { @@ -1597,7 +1693,7 @@ fn scan_corner_compound( mi_col: usize, ref_frame: (i8, i8), gm: &GmMvTable, - candidates: &mut Vec, + candidates: &mut CompoundStackVec, newmv_count: &mut u32, ) -> bool { let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else { @@ -1748,7 +1844,7 @@ pub fn find_mv_stack_compound( gm: &GmMvTable, tpl: Option, ) -> CompoundMvStack { - let mut candidates: Vec = Vec::with_capacity(MAX_STACK_SIZE); + let mut candidates = CompoundStackVec::default(); let mut newmv_count = 0u32; let row_adj = bh4 < 2 && mi_row % 2 == 1; @@ -1828,7 +1924,7 @@ pub fn find_mv_stack_compound( let row_matched = found_above || found_top_right; let nearest_match = usize::from(row_matched) + usize::from(found_left); - for entry in &mut candidates { + for entry in candidates.iter_mut() { entry.weight += REF_CAT_LEVEL; }