From d4c852ef10cddb4beba46f58336ab8ee103d487e 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 09:27:04 +0300 Subject: [PATCH] perf(av1): remove four per-block allocation sites from the parse path lane-alloc. A tracking global allocator (new `alloc_probe` example: size histogram plus a sampled backtrace per 512 allocations, with line numbers) ranked the decoder's allocation sites on the 4K segment -- 83.6 M allocations over 272 frames. Four of the top sites are removed here: * `find_samples` built a `String` per warp block (`format!("{mi_row}, {mi_col}")` plus the env snapshot's own `String` clone) to compare against an unset debug flag; the OBMC blend did the same for `EC_MCB`. Both now sit behind the per-call-site `env_flag!` load. * `Edges::build` allocated four vectors per intra prediction (collect, grow, then a second buffer to prepend the corner); it builds each edge once, corner first. `directional`'s two working buffers were a copy of those same vectors, so it takes the `Edges` by value instead. * `obmc_neighbour_pred` allocated its prediction buffer per neighbour per plane; the caller now keeps one buffer per plane for the whole block. * The MV stacks and the OBMC neighbour lists are capped (8 entries / `max_neighbors`), so they reserve once rather than growing and memcpying up to four times. seg4k at one thread: 601.657 -> 599.329 G instructions:u (-0.39%, perf stat -r 3). Reverting only the reserve step measured 600.014 G, so it stays despite raising the raw allocation COUNT (an empty stack now allocates): the saved reallocation memcpys outweigh the extra tcache hits. Byte-exact: sha6t hashes equal the reference for all four streams at threads 1, 4 and 16 (the last with FILTER_THREADS=4 RECON_THREADS=2). --- crates/ec-av1/examples/alloc_probe.rs | 87 +++++++++++++++++++++++++++ crates/ec-av1/src/decode.rs | 50 +++++++++------ crates/ec-av1/src/intra.rs | 49 +++++++-------- crates/ec-av1/src/mvstack.rs | 6 +- 4 files changed, 147 insertions(+), 45 deletions(-) create mode 100644 crates/ec-av1/examples/alloc_probe.rs diff --git a/crates/ec-av1/examples/alloc_probe.rs b/crates/ec-av1/examples/alloc_probe.rs new file mode 100644 index 00000000..95314dd3 --- /dev/null +++ b/crates/ec-av1/examples/alloc_probe.rs @@ -0,0 +1,87 @@ +//! Temporary lane-alloc instrument: count allocations and sample backtraces. +use std::alloc::{GlobalAlloc, Layout, System}; +use std::cell::Cell; +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static COUNT: AtomicUsize = AtomicUsize::new(0); +static BYTES: AtomicUsize = AtomicUsize::new(0); +static SIZES: [AtomicUsize; 24] = [const { AtomicUsize::new(0) }; 24]; +static TRACES: Mutex>> = Mutex::new(None); + +thread_local! { static IN: Cell = const { Cell::new(false) }; } + +struct Track; +unsafe impl GlobalAlloc for Track { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + let n = COUNT.fetch_add(1, Ordering::Relaxed); + BYTES.fetch_add(l.size(), Ordering::Relaxed); + let cls = (usize::BITS - l.size().leading_zeros()) as usize; + SIZES[cls.min(23)].fetch_add(1, Ordering::Relaxed); + if n % 512 == 0 { + let re = IN.with(|f| f.replace(true)); + if !re { + let bt = format!("{}", std::backtrace::Backtrace::force_capture()); + let mut key: Vec = Vec::new(); + let lines: Vec<&str> = bt.lines().collect(); + for (i, l) in lines.iter().enumerate() { + if l.contains("ec_av1::") && key.len() < 6 { + let at = lines + .get(i + 1) + .filter(|n| n.trim_start().starts_with("at ")) + .map(|n| n.trim().to_string()) + .unwrap_or_default(); + key.push(format!("{} {}", l.trim(), at)); + } + } + let mut g = TRACES.lock().unwrap(); + *g.get_or_insert_with(HashMap::new).entry(key.join(" <- ")).or_insert(0) += 1; + drop(g); + IN.with(|f| f.set(false)); + } + } + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, new: usize) -> *mut u8 { + unsafe { System.realloc(p, l, new) } + } +} + +#[global_allocator] +static A: Track = Track; + +fn main() { + let path = std::env::args().nth(1).expect("usage: alloc_probe "); + let data = std::fs::read(&path).expect("read"); + let mut shown = 0usize; + let r = ec_av1::stream::decode_stream_with(&data, |_f, _i, s| { + if s { + shown += 1; + } + Ok(()) + }); + println!("shown={shown} result={:?}", r.is_ok()); + println!( + "allocs={} bytes={}", + COUNT.load(Ordering::Relaxed), + BYTES.load(Ordering::Relaxed) + ); + for (i, c) in SIZES.iter().enumerate() { + let v = c.load(Ordering::Relaxed); + if v > 0 { + println!("size 2^{i} : {v}"); + } + } + let g = TRACES.lock().unwrap(); + if let Some(m) = g.as_ref() { + let mut v: Vec<_> = m.iter().collect(); + v.sort_by_key(|(_, c)| std::cmp::Reverse(**c)); + for (k, c) in v.into_iter().take(30) { + println!("{c:6} {k}"); + } + } +} diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 73dd43eb..41760d61 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -21984,7 +21984,8 @@ fn overlappable_above( mi_cols: usize, max_neighbors: usize, ) -> Vec<(usize, usize, MiInfo, usize)> { - let mut out = Vec::new(); + // lane-alloc: bounded by `max_neighbors`, so size it once. + let mut out = Vec::with_capacity(max_neighbors); if mi_row == 0 { return out; } @@ -22036,7 +22037,8 @@ fn overlappable_left( mi_rows: usize, max_neighbors: usize, ) -> Vec<(usize, usize, MiInfo, usize)> { - let mut out = Vec::new(); + // lane-alloc: bounded by `max_neighbors`, so size it once. + let mut out = Vec::with_capacity(max_neighbors); if mi_col == 0 { return out; } @@ -22114,8 +22116,11 @@ fn find_samples( // sample candidates in libaom's own order (above, left, top-left, // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol // motion_mode alphabet over the 2-symbol obmc one. - let proj_dbg = crate::envflags::var("EC_PROJ_MI") - .is_ok_and(|v| v == format!("{mi_row},{mi_col}")); + // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on + // every warp block; the flag itself is a process constant. + let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI") + && crate::envflags::var("EC_PROJ_MI") + .is_ok_and(|v| v == format!("{mi_row},{mi_col}")); let single_ref_match = |info: &MiInfo| { let m = info.ref_frame == ref_frame && info.ref_frame1.is_none(); if proj_dbg { @@ -22394,9 +22399,15 @@ fn obmc_neighbour_pred( // reference (derived from luma widths, applied unchanged to chroma whose // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes // the ordinary stride-1 path bit-exact. - x_scale_fp: i64, fctx: &crate::decode::FrameCtx, -) -> Vec { - let mut out = vec![0u16; w * h]; + x_scale_fp: i64, + // lane-alloc: the caller keeps one buffer per plane and reuses it across + // every neighbour of both passes -- this was a fresh `vec![0u16; w * h]` + // per neighbour per plane. + out: &mut Vec, + fctx: &crate::decode::FrameCtx, +) { + out.clear(); + out.resize(w * h, 0); if x_scale_fp == mc::REF_NO_SCALE { mc::predict_with_filters( &refplane.data, @@ -22409,7 +22420,7 @@ fn obmc_neighbour_pred( h, h_kind, v_kind, - &mut out, fctx, + out, fctx, ); } else { mc::predict_scaled( @@ -22424,10 +22435,9 @@ fn obmc_neighbour_pred( h, h_kind, v_kind, - &mut out, fctx, + out, fctx, ); } - out } /// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by @@ -22716,11 +22726,17 @@ fn obmc_blend( // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the // ABOVE pass skips chroma entirely, the LEFT pass still blends it. let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16)); + // lane-alloc: one neighbour-prediction buffer per plane for the whole + // block, reused by every neighbour of the above and left passes. + let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new()); // lane-t900 r13 rung: EC_MCB="::[:]" (chroma plane // 1 only) prints this block's chroma prediction rows before and after the // OBMC blend, matching the instrumented aomdec's EC_MCB dump. - let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::var("EC_MCB").ok().and_then(|v| { + let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB") + .then(|| crate::envflags::var("EC_MCB").ok()) + .flatten() + .and_then(|v| { let f: Vec<&str> = v.split(':').collect(); if f.len() < 3 || f[0] != "1" { return None; @@ -22773,7 +22789,7 @@ fn obmc_blend( let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4); // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice // included); only the WRITE is clipped to this block's own buffer. - let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx); obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y); if !skip_chroma_above { // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp @@ -22785,9 +22801,9 @@ fn obmc_blend( // 13 B -> 11007 B. let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2); let cw = cbw.min(write_w / 2 - cox); - let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx); obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u); - let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx); obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v); } } @@ -22807,10 +22823,10 @@ fn obmc_blend( OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1)); } let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4); - let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx); obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y); let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2); - let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx); if let Some((_, _, idx)) = ec_mcb { eprintln!( "OUR_MCB left f={idx} off4={off4} span4={span4} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}", @@ -22823,7 +22839,7 @@ fn obmc_blend( } let ch = cbh.min(write_h / 2 - coy); obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u); - let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx); + obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx); obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v); } if let Some((_, _, idx)) = ec_mcb { diff --git a/crates/ec-av1/src/intra.rs b/crates/ec-av1/src/intra.rs index e7da29a7..017a773d 100644 --- a/crates/ec-av1/src/intra.rs +++ b/crates/ec-av1/src/intra.rs @@ -152,12 +152,6 @@ impl Edges { bh: usize, fctx: &crate::decode::FrameCtx, ) -> Self { let want = bw + bh; - let extend = |samples: &[u16]| { - let mut row: Vec = samples.iter().map(|&s| i32::from(s)).collect(); - let last = *row.last().expect("an edge that exists has samples"); - row.resize(want, last); - row - }; // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)` // (128 at 8-bit): `base - 1` above, `base + 1` left, `base` corner // (libaom `reconintra.c`'s own diagram: the shared top-left corner @@ -167,31 +161,33 @@ impl Edges { // 127/129 for the corner instead and made a passing 16x16 fixture // regress, which is what caught the misreading). let base = 1i32 << (crate::decode::bit_depth(fctx) - 1); - let above_row = match (above, left) { - (Some(a), _) => extend(a), - (None, Some(l)) => vec![i32::from(l[0]); want], - (None, None) => vec![base - 1; want], - }; - let left_col = match (left, above) { - (Some(l), _) => extend(l), - (None, Some(a)) => vec![i32::from(a[0]); want], - (None, None) => vec![base + 1; want], - }; let corner = match (corner, above, left) { (Some(c), Some(_), Some(_)) => i32::from(c), (_, Some(a), _) => i32::from(a[0]), (_, None, Some(l)) => i32::from(l[0]), (_, None, None) => base, }; - let with_corner = |edge: Vec| { - let mut v = Vec::with_capacity(want + 1); + // lane-alloc: one allocation per edge instead of four (collect, grow, + // then a second buffer to prepend the corner) -- the corner goes in + // first and the samples are extended/truncated to `want` in place, so + // the contents are what `extend` + `with_corner` produced before. + let build_edge = |samples: Option<&[u16]>, other: Option<&[u16]>, none_fill: i32| { + let mut v: Vec = Vec::with_capacity(want + 1); v.push(corner); - v.extend(edge); + match (samples, other) { + (Some(s), _) => { + v.extend(s.iter().map(|&x| i32::from(x))); + let last = *v.last().expect("an edge that exists has samples"); + v.resize(want + 1, last); + } + (None, Some(o)) => v.resize(want + 1, i32::from(o[0])), + (None, None) => v.resize(want + 1, none_fill), + } v }; Self { - above: with_corner(above_row), - left: with_corner(left_col), + above: build_edge(above, left, base - 1), + left: build_edge(left, above, base + 1), } } @@ -302,7 +298,7 @@ pub(crate) fn predict( let n_left = left.map_or(0, |a| a.len().min(bh)); directional( angle as u16, - &edges, + edges, bw, bh, enable_edge_filter, @@ -491,7 +487,7 @@ fn upsample_intra_edge(buf: &[i32], fctx: &crate::decode::FrameCtx) -> Vec #[allow(clippy::too_many_arguments)] fn directional( angle: u16, - edges: &Edges, + edges: Edges, bw: usize, bh: usize, enable_edge_filter: bool, @@ -507,9 +503,10 @@ fn directional( let need_right = angle < 90; let need_bottom = angle > 180; - // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner. - let mut above: Vec = (-1..reach).map(|p| edges.above(p)).collect(); - let mut left: Vec = (-1..reach).map(|p| edges.left(p)).collect(); + // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner: + // that is exactly `Edges`' own layout (lane-alloc), so take the buffers + // rather than copying them into two fresh ones per directional block. + let Edges { mut above, mut left } = edges; if enable_edge_filter && angle != 90 && angle != 180 { if need_above && need_left && reach >= 24 { diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 50d6f925..741b63f7 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -908,7 +908,9 @@ pub fn find_mv_stack_with_sign_bias( gm: &GmMvTable, tpl: Option, ) -> MvStack { - let mut candidates = Vec::new(); + // 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 newmv_count = 0u32; // libaom's `max_row_offset`/`max_col_offset` (`setup_ref_mv_list`): how @@ -1724,7 +1726,7 @@ pub fn find_mv_stack_compound( gm: &GmMvTable, tpl: Option, ) -> CompoundMvStack { - let mut candidates: Vec = Vec::new(); + let mut candidates: Vec = Vec::with_capacity(MAX_STACK_SIZE); let mut newmv_count = 0u32; let row_adj = bh4 < 2 && mi_row % 2 == 1;