forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-alloc' (ac8f45db): per-block allocation cut (debug format! strings behind env flags, intra Edges 4 vecs -> 2, OBMC neighbour buffer caller-held, mv stacks reserve their cap) + alloc_probe tracking-allocator instrument; byte-exact, -0.39% instructions on the 4K segment

Browse files at this commit

95d7ceb5fd47a94e29665333471da35c11242270Ahmet Kaan GümüşParent: 9346288d4c852e
crates/ec-av1/examples/alloc_probe.rsadded+87 -0
@@ -0,0 +1,87 @@
1+//! Temporary lane-alloc instrument: count allocations and sample backtraces.
2+use std::alloc::{GlobalAlloc, Layout, System};
3+use std::cell::Cell;
4+use std::collections::HashMap;
5+use std::sync::Mutex;
6+use std::sync::atomic::{AtomicUsize, Ordering};
7+
8+static COUNT: AtomicUsize = AtomicUsize::new(0);
9+static BYTES: AtomicUsize = AtomicUsize::new(0);
10+static SIZES: [AtomicUsize; 24] = [const { AtomicUsize::new(0) }; 24];
11+static TRACES: Mutex<Option<HashMap<String, usize>>> = Mutex::new(None);
12+
13+thread_local! { static IN: Cell<bool> = const { Cell::new(false) }; }
14+
15+struct Track;
16+unsafe impl GlobalAlloc for Track {
17+ unsafe fn alloc(&self, l: Layout) -> *mut u8 {
18+ let n = COUNT.fetch_add(1, Ordering::Relaxed);
19+ BYTES.fetch_add(l.size(), Ordering::Relaxed);
20+ let cls = (usize::BITS - l.size().leading_zeros()) as usize;
21+ SIZES[cls.min(23)].fetch_add(1, Ordering::Relaxed);
22+ if n % 512 == 0 {
23+ let re = IN.with(|f| f.replace(true));
24+ if !re {
25+ let bt = format!("{}", std::backtrace::Backtrace::force_capture());
26+ let mut key: Vec<String> = Vec::new();
27+ let lines: Vec<&str> = bt.lines().collect();
28+ for (i, l) in lines.iter().enumerate() {
29+ if l.contains("ec_av1::") && key.len() < 6 {
30+ let at = lines
31+ .get(i + 1)
32+ .filter(|n| n.trim_start().starts_with("at "))
33+ .map(|n| n.trim().to_string())
34+ .unwrap_or_default();
35+ key.push(format!("{} {}", l.trim(), at));
36+ }
37+ }
38+ let mut g = TRACES.lock().unwrap();
39+ *g.get_or_insert_with(HashMap::new).entry(key.join(" <- ")).or_insert(0) += 1;
40+ drop(g);
41+ IN.with(|f| f.set(false));
42+ }
43+ }
44+ unsafe { System.alloc(l) }
45+ }
46+ unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
47+ unsafe { System.dealloc(p, l) }
48+ }
49+ unsafe fn realloc(&self, p: *mut u8, l: Layout, new: usize) -> *mut u8 {
50+ unsafe { System.realloc(p, l, new) }
51+ }
52+}
53+
54+#[global_allocator]
55+static A: Track = Track;
56+
57+fn main() {
58+ let path = std::env::args().nth(1).expect("usage: alloc_probe <stream.obu>");
59+ let data = std::fs::read(&path).expect("read");
60+ let mut shown = 0usize;
61+ let r = ec_av1::stream::decode_stream_with(&data, |_f, _i, s| {
62+ if s {
63+ shown += 1;
64+ }
65+ Ok(())
66+ });
67+ println!("shown={shown} result={:?}", r.is_ok());
68+ println!(
69+ "allocs={} bytes={}",
70+ COUNT.load(Ordering::Relaxed),
71+ BYTES.load(Ordering::Relaxed)
72+ );
73+ for (i, c) in SIZES.iter().enumerate() {
74+ let v = c.load(Ordering::Relaxed);
75+ if v > 0 {
76+ println!("size 2^{i} : {v}");
77+ }
78+ }
79+ let g = TRACES.lock().unwrap();
80+ if let Some(m) = g.as_ref() {
81+ let mut v: Vec<_> = m.iter().collect();
82+ v.sort_by_key(|(_, c)| std::cmp::Reverse(**c));
83+ for (k, c) in v.into_iter().take(30) {
84+ println!("{c:6} {k}");
85+ }
86+ }
87+}
crates/ec-av1/src/decode.rsmodified+33 -17
@@ -21984,7 +21984,8 @@ fn overlappable_above(
2198421984 mi_cols: usize,
2198521985 max_neighbors: usize,
2198621986 ) -> Vec<(usize, usize, MiInfo, usize)> {
21987- let mut out = Vec::new();
21987+ // lane-alloc: bounded by `max_neighbors`, so size it once.
21988+ let mut out = Vec::with_capacity(max_neighbors);
2198821989 if mi_row == 0 {
2198921990 return out;
2199021991 }
@@ -22036,7 +22037,8 @@ fn overlappable_left(
2203622037 mi_rows: usize,
2203722038 max_neighbors: usize,
2203822039 ) -> Vec<(usize, usize, MiInfo, usize)> {
22039- let mut out = Vec::new();
22040+ // lane-alloc: bounded by `max_neighbors`, so size it once.
22041+ let mut out = Vec::with_capacity(max_neighbors);
2204022042 if mi_col == 0 {
2204122043 return out;
2204222044 }
@@ -22114,8 +22116,11 @@ fn find_samples(
2211422116 // sample candidates in libaom's own order (above, left, top-left,
2211522117 // top-right) -- `num_proj_ref >= 1` is what picks the 3-symbol
2211622118 // motion_mode alphabet over the 2-symbol obmc one.
22117- let proj_dbg = crate::envflags::var("EC_PROJ_MI")
22118- .is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
22119+ // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on
22120+ // every warp block; the flag itself is a process constant.
22121+ let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI")
22122+ && crate::envflags::var("EC_PROJ_MI")
22123+ .is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
2211922124 let single_ref_match = |info: &MiInfo| {
2212022125 let m = info.ref_frame == ref_frame && info.ref_frame1.is_none();
2212122126 if proj_dbg {
@@ -22394,9 +22399,15 @@ fn obmc_neighbour_pred(
2239422399 // reference (derived from luma widths, applied unchanged to chroma whose
2239522400 // x_q4 is already in its own plane's pixel units). `REF_NO_SCALE` takes
2239622401 // the ordinary stride-1 path bit-exact.
22397- x_scale_fp: i64, fctx: &crate::decode::FrameCtx,
22398-) -> Vec<u16> {
22399- let mut out = vec![0u16; w * h];
22402+ x_scale_fp: i64,
22403+ // lane-alloc: the caller keeps one buffer per plane and reuses it across
22404+ // every neighbour of both passes -- this was a fresh `vec![0u16; w * h]`
22405+ // per neighbour per plane.
22406+ out: &mut Vec<u16>,
22407+ fctx: &crate::decode::FrameCtx,
22408+) {
22409+ out.clear();
22410+ out.resize(w * h, 0);
2240022411 if x_scale_fp == mc::REF_NO_SCALE {
2240122412 mc::predict_with_filters(
2240222413 &refplane.data,
@@ -22409,7 +22420,7 @@ fn obmc_neighbour_pred(
2240922420 h,
2241022421 h_kind,
2241122422 v_kind,
22412- &mut out, fctx,
22423+ out, fctx,
2241322424 );
2241422425 } else {
2241522426 mc::predict_scaled(
@@ -22424,10 +22435,9 @@ fn obmc_neighbour_pred(
2242422435 h,
2242522436 h_kind,
2242622437 v_kind,
22427- &mut out, fctx,
22438+ out, fctx,
2242822439 );
2242922440 }
22430- out
2243122441 }
2243222442
2243322443 /// Blends `tmp` into `dst` (stride `stride`) at `(ox, oy)`, mask varying by
@@ -22716,11 +22726,17 @@ fn obmc_blend(
2271622726 // BLOCK_4X4/8X4/4X8 (an 8x8, 16x8 or 8x16 luma block at 4:2:0): the
2271722727 // ABOVE pass skips chroma entirely, the LEFT pass still blends it.
2271822728 let skip_chroma_above = matches!((write_w, write_h), (8, 8) | (16, 8) | (8, 16));
22729+ // lane-alloc: one neighbour-prediction buffer per plane for the whole
22730+ // block, reused by every neighbour of the above and left passes.
22731+ let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());
2271922732
2272022733 // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
2272122734 // 1 only) prints this block's chroma prediction rows before and after the
2272222735 // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
22723- let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::var("EC_MCB").ok().and_then(|v| {
22736+ let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB")
22737+ .then(|| crate::envflags::var("EC_MCB").ok())
22738+ .flatten()
22739+ .and_then(|v| {
2272422740 let f: Vec<&str> = v.split(':').collect();
2272522741 if f.len() < 3 || f[0] != "1" {
2272622742 return None;
@@ -22773,7 +22789,7 @@ fn obmc_blend(
2277322789 let (bw, bh, ox) = (span4 * 4, overlap_above, off4 * 4);
2277422790 // lane-t900 r14: the prediction is `op_mi_size` wide (kernel choice
2277522791 // included); only the WRITE is clipped to this block's own buffer.
22776- let tmp_y = obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, fctx);
22792+ obmc_neighbour_pred(ny, px + ox, py, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx);
2277722793 obmc_blend_v(pred_y, side, ox, 0, bw.min(write_w - ox), bh, bw, &tmp_y);
2277822794 if !skip_chroma_above {
2277922795 // lane-t900 r13 (measured, NOT a defect): libaom's min-4 clamp
@@ -22785,9 +22801,9 @@ fn obmc_blend(
2278522801 // 13 B -> 11007 B.
2278622802 let (cbw, cbh, cox) = (bw / 2, overlap_above / 2, ox / 2);
2278722803 let cw = cbw.min(write_w / 2 - cox);
22788- let tmp_u = obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx);
22804+ obmc_neighbour_pred(nu, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx);
2278922805 obmc_blend_v(pred_u, chroma_side, cox, 0, cw, cbh, cbw, &tmp_u);
22790- let tmp_v = obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx);
22806+ obmc_neighbour_pred(nv, cpx + cox, cpy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx);
2279122807 obmc_blend_v(pred_v, chroma_side, cox, 0, cw, cbh, cbw, &tmp_v);
2279222808 }
2279322809 }
@@ -22807,10 +22823,10 @@ fn obmc_blend(
2280722823 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
2280822824 }
2280922825 let (bw, bh, oy) = (overlap_left, span4 * 4, off4 * 4);
22810- let tmp_y = obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, fctx);
22826+ obmc_neighbour_pred(ny, px, py + oy, nb.mv, bw, bh, true, h_kind, v_kind, nb_scale, &mut tmp_y, fctx);
2281122827 obmc_blend_h(pred_y, side, 0, oy, bw, bh.min(write_h - oy), &tmp_y);
2281222828 let (cbw, cbh, coy) = (overlap_left / 2, bh / 2, oy / 2);
22813- let tmp_u = obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx);
22829+ obmc_neighbour_pred(nu, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_u, fctx);
2281422830 if let Some((_, _, idx)) = ec_mcb {
2281522831 eprintln!(
2281622832 "OUR_MCB left f={idx} off4={off4} span4={span4} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
@@ -22823,7 +22839,7 @@ fn obmc_blend(
2282322839 }
2282422840 let ch = cbh.min(write_h / 2 - coy);
2282522841 obmc_blend_h(pred_u, chroma_side, 0, coy, cbw, ch, &tmp_u);
22826- let tmp_v = obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, fctx);
22842+ obmc_neighbour_pred(nv, cpx, cpy + coy, nb.mv, cbw, cbh, false, h_kind, v_kind, nb_scale, &mut tmp_v, fctx);
2282722843 obmc_blend_h(pred_v, chroma_side, 0, coy, cbw, ch, &tmp_v);
2282822844 }
2282922845 if let Some((_, _, idx)) = ec_mcb {
crates/ec-av1/src/intra.rsmodified+23 -26
@@ -152,12 +152,6 @@ impl Edges {
152152 bh: usize, fctx: &crate::decode::FrameCtx,
153153 ) -> Self {
154154 let want = bw + bh;
155- let extend = |samples: &[u16]| {
156- let mut row: Vec<i32> = samples.iter().map(|&s| i32::from(s)).collect();
157- let last = *row.last().expect("an edge that exists has samples");
158- row.resize(want, last);
159- row
160- };
161155 // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)`
162156 // (128 at 8-bit): `base - 1` above, `base + 1` left, `base` corner
163157 // (libaom `reconintra.c`'s own diagram: the shared top-left corner
@@ -167,31 +161,33 @@ impl Edges {
167161 // 127/129 for the corner instead and made a passing 16x16 fixture
168162 // regress, which is what caught the misreading).
169163 let base = 1i32 << (crate::decode::bit_depth(fctx) - 1);
170- let above_row = match (above, left) {
171- (Some(a), _) => extend(a),
172- (None, Some(l)) => vec![i32::from(l[0]); want],
173- (None, None) => vec![base - 1; want],
174- };
175- let left_col = match (left, above) {
176- (Some(l), _) => extend(l),
177- (None, Some(a)) => vec![i32::from(a[0]); want],
178- (None, None) => vec![base + 1; want],
179- };
180164 let corner = match (corner, above, left) {
181165 (Some(c), Some(_), Some(_)) => i32::from(c),
182166 (_, Some(a), _) => i32::from(a[0]),
183167 (_, None, Some(l)) => i32::from(l[0]),
184168 (_, None, None) => base,
185169 };
186- let with_corner = |edge: Vec<i32>| {
187- let mut v = Vec::with_capacity(want + 1);
170+ // lane-alloc: one allocation per edge instead of four (collect, grow,
171+ // then a second buffer to prepend the corner) -- the corner goes in
172+ // first and the samples are extended/truncated to `want` in place, so
173+ // the contents are what `extend` + `with_corner` produced before.
174+ let build_edge = |samples: Option<&[u16]>, other: Option<&[u16]>, none_fill: i32| {
175+ let mut v: Vec<i32> = Vec::with_capacity(want + 1);
188176 v.push(corner);
189- v.extend(edge);
177+ match (samples, other) {
178+ (Some(s), _) => {
179+ v.extend(s.iter().map(|&x| i32::from(x)));
180+ let last = *v.last().expect("an edge that exists has samples");
181+ v.resize(want + 1, last);
182+ }
183+ (None, Some(o)) => v.resize(want + 1, i32::from(o[0])),
184+ (None, None) => v.resize(want + 1, none_fill),
185+ }
190186 v
191187 };
192188 Self {
193- above: with_corner(above_row),
194- left: with_corner(left_col),
189+ above: build_edge(above, left, base - 1),
190+ left: build_edge(left, above, base + 1),
195191 }
196192 }
197193
@@ -302,7 +298,7 @@ pub(crate) fn predict(
302298 let n_left = left.map_or(0, |a| a.len().min(bh));
303299 directional(
304300 angle as u16,
305- &edges,
301+ edges,
306302 bw,
307303 bh,
308304 enable_edge_filter,
@@ -491,7 +487,7 @@ fn upsample_intra_edge(buf: &[i32], fctx: &crate::decode::FrameCtx) -> Vec<i32>
491487 #[allow(clippy::too_many_arguments)]
492488 fn directional(
493489 angle: u16,
494- edges: &Edges,
490+ edges: Edges,
495491 bw: usize,
496492 bh: usize,
497493 enable_edge_filter: bool,
@@ -507,9 +503,10 @@ fn directional(
507503 let need_right = angle < 90;
508504 let need_bottom = angle > 180;
509505
510- // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner.
511- let mut above: Vec<i32> = (-1..reach).map(|p| edges.above(p)).collect();
512- let mut left: Vec<i32> = (-1..reach).map(|p| edges.left(p)).collect();
506+ // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner:
507+ // that is exactly `Edges`' own layout (lane-alloc), so take the buffers
508+ // rather than copying them into two fresh ones per directional block.
509+ let Edges { mut above, mut left } = edges;
513510
514511 if enable_edge_filter && angle != 90 && angle != 180 {
515512 if need_above && need_left && reach >= 24 {
crates/ec-av1/src/mvstack.rsmodified+4 -2
@@ -908,7 +908,9 @@ pub fn find_mv_stack_with_sign_bias(
908908 gm: &GmMvTable,
909909 tpl: Option<TplArgs>,
910910 ) -> MvStack {
911- let mut candidates = Vec::new();
911+ // lane-alloc: the stack is capped at MAX_STACK_SIZE entries, so the pushes
912+ // below grew (and memcpy'd) a fresh allocation up to 4 times per block.
913+ let mut candidates = Vec::with_capacity(MAX_STACK_SIZE);
912914 let mut newmv_count = 0u32;
913915
914916 // libaom's `max_row_offset`/`max_col_offset` (`setup_ref_mv_list`): how
@@ -1724,7 +1726,7 @@ pub fn find_mv_stack_compound(
17241726 gm: &GmMvTable,
17251727 tpl: Option<CompoundTplArgs>,
17261728 ) -> CompoundMvStack {
1727- let mut candidates: Vec<CompoundStackEntry> = Vec::new();
1729+ let mut candidates: Vec<CompoundStackEntry> = Vec::with_capacity(MAX_STACK_SIZE);
17281730 let mut newmv_count = 0u32;
17291731
17301732 let row_adj = bh4 < 2 && mi_row % 2 == 1;