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> {
91 /// the same line scripts/vp8ref_model.py prints — so the two91 /// the same line scripts/vp8ref_model.py prints — so the two
92 /// decoders can be diffed read-for-read.92 /// decoders can be diffed read-for-read.
93 pub fn read_bool(&mut self, prob: u8) -> bool {93 pub fn read_bool(&mut self, prob: u8) -> bool {
94- let trace = std::env::var_os("EC_VP8_TRACE").is_some();
95 let prob = u32::from(prob);94 let prob = u32::from(prob);
96 let split = 1 + (((self.range - 1) * prob) >> 8);95 let split = 1 + (((self.range - 1) * prob) >> 8);
97 let bigsplit = split << 8;96 let bigsplit = split << 8;
@@ -112,7 +111,7 @@ impl<'a> BoolDecoder<'a> {
112 self.value |= self.next_byte();111 self.value |= self.next_byte();
113 }112 }
114 }113 }
115- if trace {114+ if crate::trace_enabled() {
116 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));115 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
117 }116 }
118 bit117 bit
crates/ec-vp8/src/decode.rsmodified+8 -8
@@ -384,7 +384,7 @@ impl Decoder {
384 // `r` (0-based) reads partition `r % n` like the reference.384 // `r` (0-based) reads partition `r % n` like the reference.
385 let part = (row - 1) % partitions.len();385 let part = (row - 1) % partitions.len();
386 for col in 1..=self.mb_cols {386 for col in 1..=self.mb_cols {
387- if std::env::var_os("EC_VP8_TRACE").is_some() {387+ if crate::trace_enabled() {
388 eprintln!("M {} {}", row - 1, col - 1);388 eprintln!("M {} {}", row - 1, col - 1);
389 }389 }
390 let mb = self.mbi(row, col).clone();390 let mb = self.mbi(row, col).clone();
@@ -399,7 +399,7 @@ impl Decoder {
399 y2_dc: dq.y2_dc,399 y2_dc: dq.y2_dc,
400 y2_ac: dq.y2_ac,400 y2_ac: dq.y2_ac,
401 };401 };
402- if std::env::var_os("EC_VP8_TRACE").is_some() {402+ if crate::trace_enabled() {
403 eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2);403 eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2);
404 }404 }
405 let probs = self.state.coeff_probs;405 let probs = self.state.coeff_probs;
@@ -594,7 +594,7 @@ impl Decoder {
594 self.token_ctxs.reset_above_row();594 self.token_ctxs.reset_above_row();
595 595
596 // Phase 1: every mode record of the frame, row-major (§16).596 // 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() {
598 eprintln!("STAGE modes");598 eprintln!("STAGE modes");
599 }599 }
600 for row in 1..=self.mb_rows {600 for row in 1..=self.mb_rows {
@@ -746,7 +746,7 @@ impl Decoder {
746 let left = self.mv_neighbor(row, col - 1, sign_bias);746 let left = self.mv_neighbor(row, col - 1, sign_bias);
747 let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias);747 let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias);
748 let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias);748 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() {
750 eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs);750 eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs);
751 }751 }
752 752
@@ -856,7 +856,7 @@ impl Decoder {
856 mv856 mv
857 }857 }
858 };858 };
859- if std::env::var_os("EC_VP8_TRACE").is_some() {859+ if crate::trace_enabled() {
860 eprintln!(860 eprintln!(
861 "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})",861 "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})",
862 row - 1,862 row - 1,
@@ -894,7 +894,7 @@ impl Decoder {
894 self.reconstruct_intra_mb(row, col, mb, coeffs);894 self.reconstruct_intra_mb(row, col, mb, coeffs);
895 return;895 return;
896 }896 }
897- if std::env::var_os("EC_VP8_TRACE").is_some() {897+ if crate::trace_enabled() {
898 eprintln!(898 eprintln!(
899 "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}",899 "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}",
900 row, col, mb.ref_frame, mb.mv_ref, mb.mv.0, mb.mv.1, mb.mv_clamp, mb.skip900 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 {
977 &mut pv, 16, 8, 8, self.mc_bilinear,977 &mut pv, 16, 8, 8, self.mc_bilinear,
978 );978 );
979 }979 }
980- if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 {980+ if crate::trace_enabled() && row == 0 && col == 0 {
981 eprintln!(981 eprintln!(
982 "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}",982 "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}",
983 &pu[0..8],983 &pu[0..8],
@@ -1087,7 +1087,7 @@ impl Decoder {
1087 } else {1087 } else {
1088 [0; 16]1088 [0; 16]
1089 };1089 };
1090- if std::env::var_os("EC_VP8_DEBUG").is_some() {1090+ if crate::debug_enabled() {
1091 eprintln!(1091 eprintln!(
1092 "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}",1092 "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}",
1093 y_mode,1093 y_mode,
crates/ec-vp8/src/header.rsmodified+2 -2
@@ -392,7 +392,7 @@ impl FrameHeader {
392 128392 128
393 };393 };
394 // Interframe-only probability updates.394 // Interframe-only probability updates.
395- if std::env::var_os("EC_VP8_TRACE").is_some() {395+ if crate::trace_enabled() {
396 eprintln!("STAGE interprobs");396 eprintln!("STAGE interprobs");
397 }397 }
398 let mut ymode_probs_updated = false;398 let mut ymode_probs_updated = false;
@@ -423,7 +423,7 @@ impl FrameHeader {
423 }423 }
424 }424 }
425 }425 }
426- if std::env::var_os("EC_VP8_TRACE").is_some() {426+ if crate::trace_enabled() {
427 eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs);427 eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs);
428 eprintln!("MVT c0 = {:?}", state.mv_probs[0]);428 eprintln!("MVT c0 = {:?}", state.mv_probs[0]);
429 eprintln!("MVT c1 = {:?}", state.mv_probs[1]);429 eprintln!("MVT c1 = {:?}", state.mv_probs[1]);
crates/ec-vp8/src/lib.rsmodified+34 -0
@@ -29,3 +29,37 @@ pub mod transform;
29 29
30 pub use ec_core::{Error, Result};30 pub use ec_core::{Error, Result};
31 pub use header::PersistedState;31 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(
156 ac_factor: i16,156 ac_factor: i16,
157 out: &mut [i16; 16],157 out: &mut [i16; 16],
158 ) -> usize {158 ) -> usize {
159- let trace = std::env::var_os("EC_VP8_TRACE").is_some();159+ let trace = crate::trace_enabled();
160 // One token decision: decode the bool, then — under EC_VP8_TRACE —160 // One token decision: decode the bool, then — under EC_VP8_TRACE —
161 // print the consulted (n, band, ctx, prob) and the decoded bit so the161 // print the consulted (n, band, ctx, prob) and the decoded bit so the
162 // stream can be diffed read-for-read against scripts/vp8ref_model.py.162 // stream can be diffed read-for-read against scripts/vp8ref_model.py.
@@ -268,11 +268,11 @@ pub(crate) fn decode_mb_tokens(
268 let n0 = usize::from($ptype == 0);268 let n0 = usize::from($ptype == 0);
269 let (l, a) = ctxs.ctx_pair(mb_col, $idx);269 let (l, a) = ctxs.ctx_pair(mb_col, $idx);
270 let ctx = (usize::from(l) + usize::from(a)).min(2);270 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() {
272 eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a);272 eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a);
273 }273 }
274 let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot);274 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() {
276 eprintln!("TBE {} eob={}", $idx, eob);276 eprintln!("TBE {} eob={}", $idx, eob);
277 }277 }
278 out.eobs[$idx] = eob as u8;278 out.eobs[$idx] = eob as u8;