forge
Explore
Log in

Don't you dare go Hollow

ec-vp8 perf: per-bool env lookups were 46% of decode profile

Browse files at this commit

1a98a0ffef9f6cc4678d29a2690a6d0b1f93be2bAhmet Kaan GümüşParent: 781bd7a
std::env::var_os ran per bool read (bool.rs read_bool) and per MB
(decode.rs reconstruct) — each call takes std's ENV lock and allocates;
perf showed 46% of samples in getenv/__strlen. OnceLock::get_or_init
was no better (closure re-entry still hit the env path). Now both flags
resolve once per process into an AtomicU8 (relaxed load-only hot path).

Before -> after (decode MP/s): gop-160x96 32->82, clip-obs 51->122,
altref 16->55, gop-1280x720 137->211, big-obs-2560x1320 121->175
(35.7 -> 51.9 fps). Full witness suite byte-exact green.
crates/ec-vp8/examples/throughput.rsadded+38 -0
@@ -0,0 +1,38 @@
1+//! Perf-lane probe: decode an IVF repeatedly, report MP/s and fps.
2+//! Dims come from the IVF header; usage: `throughput <ivf> [rounds]`.
3+use ec_vp8::decode::Decoder;
4+use std::time::Instant;
5+
6+fn main() {
7+ let args: Vec<String> = std::env::args().collect();
8+ let bytes = std::fs::read(&args[1]).unwrap();
9+ let w = u16::from_le_bytes([bytes[12], bytes[13]]) as u64;
10+ let h = u16::from_le_bytes([bytes[14], bytes[15]]) as u64;
11+ let rounds: u64 = args.get(2).map(|s| s.parse().unwrap()).unwrap_or(20);
12+ let mut frames = Vec::new();
13+ let mut pos = 32;
14+ while pos + 12 <= bytes.len() {
15+ let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize;
16+ frames.push(bytes[pos + 12..pos + 12 + sz].to_vec());
17+ pos += 12 + sz;
18+ }
19+ let nframes = frames.len();
20+ let shown = frames.iter().filter(|f| (f[0] >> 4) & 1 == 1).count() as u64;
21+ let t = Instant::now();
22+ for _ in 0..rounds {
23+ let mut dec = Decoder::new();
24+ for f in &frames {
25+ dec.decode(f).unwrap();
26+ }
27+ }
28+ let dt = t.elapsed().as_secs_f64();
29+ let dec_mpx = rounds as f64 * nframes as f64 * w as f64 * h as f64 / 1e6 / dt;
30+ let out_mpx = rounds as f64 * shown as f64 * w as f64 * h as f64 / 1e6 / dt;
31+ println!(
32+ "{}x{rounds} frames ({shown} shown/round) in {dt:.3}s: \
33+ decode {dec_mpx:.1} MP/s, output {out_mpx:.1} MP/s \
34+ ({:.1} shown fps @ {w}x{h})",
35+ nframes,
36+ rounds as f64 * shown as f64 / dt
37+ );
38+}
crates/ec-vp8/src/bool.rsmodified+1 -2
@@ -91,7 +91,6 @@ impl<'a> BoolDecoder<'a> {
9191 /// the same line scripts/vp8ref_model.py prints — so the two
9292 /// decoders can be diffed read-for-read.
9393 pub fn read_bool(&mut self, prob: u8) -> bool {
94- let trace = std::env::var_os("EC_VP8_TRACE").is_some();
9594 let prob = u32::from(prob);
9695 let split = 1 + (((self.range - 1) * prob) >> 8);
9796 let bigsplit = split << 8;
@@ -112,7 +111,7 @@ impl<'a> BoolDecoder<'a> {
112111 self.value |= self.next_byte();
113112 }
114113 }
115- if trace {
114+ if crate::trace_enabled() {
116115 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
117116 }
118117 bit
crates/ec-vp8/src/decode.rsmodified+8 -8
@@ -384,7 +384,7 @@ impl Decoder {
384384 // `r` (0-based) reads partition `r % n` like the reference.
385385 let part = (row - 1) % partitions.len();
386386 for col in 1..=self.mb_cols {
387- if std::env::var_os("EC_VP8_TRACE").is_some() {
387+ if crate::trace_enabled() {
388388 eprintln!("M {} {}", row - 1, col - 1);
389389 }
390390 let mb = self.mbi(row, col).clone();
@@ -399,7 +399,7 @@ impl Decoder {
399399 y2_dc: dq.y2_dc,
400400 y2_ac: dq.y2_ac,
401401 };
402- if std::env::var_os("EC_VP8_TRACE").is_some() {
402+ if crate::trace_enabled() {
403403 eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2);
404404 }
405405 let probs = self.state.coeff_probs;
@@ -594,7 +594,7 @@ impl Decoder {
594594 self.token_ctxs.reset_above_row();
595595
596596 // Phase 1: every mode record of the frame, row-major (§16).
597- if std::env::var_os("EC_VP8_TRACE").is_some() {
597+ if crate::trace_enabled() {
598598 eprintln!("STAGE modes");
599599 }
600600 for row in 1..=self.mb_rows {
@@ -746,7 +746,7 @@ impl Decoder {
746746 let left = self.mv_neighbor(row, col - 1, sign_bias);
747747 let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias);
748748 let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias);
749- if std::env::var_os("EC_VP8_TRACE").is_some() {
749+ if crate::trace_enabled() {
750750 eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs);
751751 }
752752
@@ -856,7 +856,7 @@ impl Decoder {
856856 mv
857857 }
858858 };
859- if std::env::var_os("EC_VP8_TRACE").is_some() {
859+ if crate::trace_enabled() {
860860 eprintln!(
861861 "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})",
862862 row - 1,
@@ -894,7 +894,7 @@ impl Decoder {
894894 self.reconstruct_intra_mb(row, col, mb, coeffs);
895895 return;
896896 }
897- if std::env::var_os("EC_VP8_TRACE").is_some() {
897+ if crate::trace_enabled() {
898898 eprintln!(
899899 "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}",
900900 row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip
@@ -977,7 +977,7 @@ impl Decoder {
977977 &mut pv, 16, 8, 8, self.mc_bilinear,
978978 );
979979 }
980- if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 {
980+ if crate::trace_enabled() && row == 0 && col == 0 {
981981 eprintln!(
982982 "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}",
983983 &pu[0..8],
@@ -1087,7 +1087,7 @@ impl Decoder {
10871087 } else {
10881088 [0; 16]
10891089 };
1090- if std::env::var_os("EC_VP8_DEBUG").is_some() {
1090+ if crate::debug_enabled() {
10911091 eprintln!(
10921092 "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}",
10931093 y_mode,
crates/ec-vp8/src/header.rsmodified+2 -2
@@ -392,7 +392,7 @@ impl FrameHeader {
392392 128
393393 };
394394 // Interframe-only probability updates.
395- if std::env::var_os("EC_VP8_TRACE").is_some() {
395+ if crate::trace_enabled() {
396396 eprintln!("STAGE interprobs");
397397 }
398398 let mut ymode_probs_updated = false;
@@ -423,7 +423,7 @@ impl FrameHeader {
423423 }
424424 }
425425 }
426- if std::env::var_os("EC_VP8_TRACE").is_some() {
426+ if crate::trace_enabled() {
427427 eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs);
428428 eprintln!("MVT c0 = {:?}", state.mv_probs[0]);
429429 eprintln!("MVT c1 = {:?}", state.mv_probs[1]);
crates/ec-vp8/src/lib.rsmodified+34 -0
@@ -29,3 +29,37 @@ pub mod transform;
2929
3030 pub use ec_core::{Error, Result};
3131 pub use header::PersistedState;
32+
33+/// Whether `EC_VP8_TRACE` decision tracing is enabled, resolved once per
34+/// process. A `var_os` per bool read was 46% of the decode profile (each
35+/// call locks std's ENV lock and allocates); `OnceLock::get_or_init` was
36+/// no better, so the hot path is a single relaxed atomic load.
37+pub(crate) fn trace_enabled() -> bool {
38+ use std::sync::atomic::{AtomicU8, Ordering};
39+ static STATE: AtomicU8 = AtomicU8::new(0);
40+ match STATE.load(Ordering::Relaxed) {
41+ 0 => {
42+ let on = std::env::var_os("EC_VP8_TRACE").is_some();
43+ STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed);
44+ on
45+ }
46+ 1 => false,
47+ _ => true,
48+ }
49+}
50+
51+/// Whether `EC_VP8_DEBUG` per-macroblock dumps are enabled (same shape as
52+/// [`trace_enabled`]; the check sits in the per-MB reconstruct path).
53+pub(crate) fn debug_enabled() -> bool {
54+ use std::sync::atomic::{AtomicU8, Ordering};
55+ static STATE: AtomicU8 = AtomicU8::new(0);
56+ match STATE.load(Ordering::Relaxed) {
57+ 0 => {
58+ let on = std::env::var_os("EC_VP8_DEBUG").is_some();
59+ STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed);
60+ on
61+ }
62+ 1 => false,
63+ _ => true,
64+ }
65+}
crates/ec-vp8/src/tokens.rsmodified+3 -3
@@ -156,7 +156,7 @@ fn get_coeffs(
156156 ac_factor: i16,
157157 out: &mut [i16; 16],
158158 ) -> usize {
159- let trace = std::env::var_os("EC_VP8_TRACE").is_some();
159+ let trace = crate::trace_enabled();
160160 // One token decision: decode the bool, then — under EC_VP8_TRACE —
161161 // print the consulted (n, band, ctx, prob) and the decoded bit so the
162162 // stream can be diffed read-for-read against scripts/vp8ref_model.py.
@@ -268,11 +268,11 @@ pub(crate) fn decode_mb_tokens(
268268 let n0 = usize::from($ptype == 0);
269269 let (l, a) = ctxs.ctx_pair(mb_col, $idx);
270270 let ctx = (usize::from(l) + usize::from(a)).min(2);
271- if std::env::var_os("EC_VP8_TRACE").is_some() {
271+ if crate::trace_enabled() {
272272 eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a);
273273 }
274274 let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot);
275- if std::env::var_os("EC_VP8_TRACE").is_some() {
275+ if crate::trace_enabled() {
276276 eprintln!("TBE {} eob={}", $idx, eob);
277277 }
278278 out.eobs[$idx] = eob as u8;