From 1a98a0ffef9f6cc4678d29a2690a6d0b1f93be2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 23:03:14 +0300 Subject: [PATCH] ec-vp8 perf: per-bool env lookups were 46% of decode profile MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 38 ++++++++++++++++++++++++++++ crates/ec-vp8/src/bool.rs | 3 +-- crates/ec-vp8/src/decode.rs | 16 ++++++------ crates/ec-vp8/src/header.rs | 4 +-- crates/ec-vp8/src/lib.rs | 34 +++++++++++++++++++++++++ crates/ec-vp8/src/tokens.rs | 6 ++--- 6 files changed, 86 insertions(+), 15 deletions(-) create mode 100644 crates/ec-vp8/examples/throughput.rs diff --git a/crates/ec-vp8/examples/throughput.rs b/crates/ec-vp8/examples/throughput.rs new file mode 100644 index 00000000..dd7b72e4 --- /dev/null +++ b/crates/ec-vp8/examples/throughput.rs @@ -0,0 +1,38 @@ +//! Perf-lane probe: decode an IVF repeatedly, report MP/s and fps. +//! Dims come from the IVF header; usage: `throughput [rounds]`. +use ec_vp8::decode::Decoder; +use std::time::Instant; + +fn main() { + let args: Vec = std::env::args().collect(); + let bytes = std::fs::read(&args[1]).unwrap(); + let w = u16::from_le_bytes([bytes[12], bytes[13]]) as u64; + let h = u16::from_le_bytes([bytes[14], bytes[15]]) as u64; + let rounds: u64 = args.get(2).map(|s| s.parse().unwrap()).unwrap_or(20); + let mut frames = Vec::new(); + let mut pos = 32; + while pos + 12 <= bytes.len() { + let sz = u32::from_le_bytes(bytes[pos..pos + 4].try_into().unwrap()) as usize; + frames.push(bytes[pos + 12..pos + 12 + sz].to_vec()); + pos += 12 + sz; + } + let nframes = frames.len(); + let shown = frames.iter().filter(|f| (f[0] >> 4) & 1 == 1).count() as u64; + let t = Instant::now(); + for _ in 0..rounds { + let mut dec = Decoder::new(); + for f in &frames { + dec.decode(f).unwrap(); + } + } + let dt = t.elapsed().as_secs_f64(); + let dec_mpx = rounds as f64 * nframes as f64 * w as f64 * h as f64 / 1e6 / dt; + let out_mpx = rounds as f64 * shown as f64 * w as f64 * h as f64 / 1e6 / dt; + println!( + "{}x{rounds} frames ({shown} shown/round) in {dt:.3}s: \ + decode {dec_mpx:.1} MP/s, output {out_mpx:.1} MP/s \ + ({:.1} shown fps @ {w}x{h})", + nframes, + rounds as f64 * shown as f64 / dt + ); +} diff --git a/crates/ec-vp8/src/bool.rs b/crates/ec-vp8/src/bool.rs index fb864df2..d473c88a 100644 --- a/crates/ec-vp8/src/bool.rs +++ b/crates/ec-vp8/src/bool.rs @@ -91,7 +91,6 @@ impl<'a> BoolDecoder<'a> { /// the same line scripts/vp8ref_model.py prints — so the two /// decoders can be diffed read-for-read. pub fn read_bool(&mut self, prob: u8) -> bool { - let trace = std::env::var_os("EC_VP8_TRACE").is_some(); let prob = u32::from(prob); let split = 1 + (((self.range - 1) * prob) >> 8); let bigsplit = split << 8; @@ -112,7 +111,7 @@ impl<'a> BoolDecoder<'a> { self.value |= self.next_byte(); } } - if trace { + if crate::trace_enabled() { eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit)); } bit diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs index 9aeaaf7d..49157cee 100644 --- a/crates/ec-vp8/src/decode.rs +++ b/crates/ec-vp8/src/decode.rs @@ -384,7 +384,7 @@ impl Decoder { // `r` (0-based) reads partition `r % n` like the reference. let part = (row - 1) % partitions.len(); for col in 1..=self.mb_cols { - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("M {} {}", row - 1, col - 1); } let mb = self.mbi(row, col).clone(); @@ -399,7 +399,7 @@ impl Decoder { y2_dc: dq.y2_dc, y2_ac: dq.y2_ac, }; - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("T {} {} hy2={}", row - 1, col - 1, has_y2); } let probs = self.state.coeff_probs; @@ -594,7 +594,7 @@ impl Decoder { self.token_ctxs.reset_above_row(); // Phase 1: every mode record of the frame, row-major (§16). - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("STAGE modes"); } for row in 1..=self.mb_rows { @@ -746,7 +746,7 @@ impl Decoder { let left = self.mv_neighbor(row, col - 1, sign_bias); let aboveleft = self.mv_neighbor(row - 1, col - 1, sign_bias); let (mut near_mvs, cnt) = modes::find_near_mvs(above, left, aboveleft, to_bias); - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("CNT r={} c={} cnt={:?} mvs={:?}", row - 1, col - 1, cnt, near_mvs); } @@ -856,7 +856,7 @@ impl Decoder { mv } }; - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!( "SP r={} c={} j={} k={} l=({},{}) a=({},{}) ctx={} mv=({},{}) best=({},{})", row - 1, @@ -894,7 +894,7 @@ impl Decoder { self.reconstruct_intra_mb(row, col, mb, coeffs); return; } - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!( "IMB r={} c={} ref={} mvref={} mv=({},{}) clamp={} skip={}", 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 { &mut pv, 16, 8, 8, self.mc_bilinear, ); } - if std::env::var_os("EC_VP8_TRACE").is_some() && row == 0 && col == 0 { + if crate::trace_enabled() && row == 0 && col == 0 { eprintln!( "CHROMA pred_u[0..8]={:?} refu_vis[0..8]={:?} coeffs.u0dcsum={}", &pu[0..8], @@ -1087,7 +1087,7 @@ impl Decoder { } else { [0; 16] }; - if std::env::var_os("EC_VP8_DEBUG").is_some() { + if crate::debug_enabled() { eprintln!( "MB({row},{col}) ymode={} uv={} y2={:?} y2has={} y0[:4]={:?} eobs24={} dcs={:?}", y_mode, diff --git a/crates/ec-vp8/src/header.rs b/crates/ec-vp8/src/header.rs index 3ad1d237..f8b591a2 100644 --- a/crates/ec-vp8/src/header.rs +++ b/crates/ec-vp8/src/header.rs @@ -392,7 +392,7 @@ impl FrameHeader { 128 }; // Interframe-only probability updates. - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("STAGE interprobs"); } let mut ymode_probs_updated = false; @@ -423,7 +423,7 @@ impl FrameHeader { } } } - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("YUV ymode = {:?} uv = {:?}", state.ymode_probs, state.uv_mode_probs); eprintln!("MVT c0 = {:?}", state.mv_probs[0]); eprintln!("MVT c1 = {:?}", state.mv_probs[1]); diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs index 051e93a7..30756bf3 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -29,3 +29,37 @@ pub mod transform; pub use ec_core::{Error, Result}; pub use header::PersistedState; + +/// Whether `EC_VP8_TRACE` decision tracing is enabled, resolved once per +/// process. A `var_os` per bool read was 46% of the decode profile (each +/// call locks std's ENV lock and allocates); `OnceLock::get_or_init` was +/// no better, so the hot path is a single relaxed atomic load. +pub(crate) fn trace_enabled() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static STATE: AtomicU8 = AtomicU8::new(0); + match STATE.load(Ordering::Relaxed) { + 0 => { + let on = std::env::var_os("EC_VP8_TRACE").is_some(); + STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); + on + } + 1 => false, + _ => true, + } +} + +/// Whether `EC_VP8_DEBUG` per-macroblock dumps are enabled (same shape as +/// [`trace_enabled`]; the check sits in the per-MB reconstruct path). +pub(crate) fn debug_enabled() -> bool { + use std::sync::atomic::{AtomicU8, Ordering}; + static STATE: AtomicU8 = AtomicU8::new(0); + match STATE.load(Ordering::Relaxed) { + 0 => { + let on = std::env::var_os("EC_VP8_DEBUG").is_some(); + STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed); + on + } + 1 => false, + _ => true, + } +} diff --git a/crates/ec-vp8/src/tokens.rs b/crates/ec-vp8/src/tokens.rs index d3904e36..8e43bf30 100644 --- a/crates/ec-vp8/src/tokens.rs +++ b/crates/ec-vp8/src/tokens.rs @@ -156,7 +156,7 @@ fn get_coeffs( ac_factor: i16, out: &mut [i16; 16], ) -> usize { - let trace = std::env::var_os("EC_VP8_TRACE").is_some(); + let trace = crate::trace_enabled(); // One token decision: decode the bool, then — under EC_VP8_TRACE — // print the consulted (n, band, ctx, prob) and the decoded bit so the // stream can be diffed read-for-read against scripts/vp8ref_model.py. @@ -268,11 +268,11 @@ pub(crate) fn decode_mb_tokens( let n0 = usize::from($ptype == 0); let (l, a) = ctxs.ctx_pair(mb_col, $idx); let ctx = (usize::from(l) + usize::from(a)).min(2); - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a); } let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot); - if std::env::var_os("EC_VP8_TRACE").is_some() { + if crate::trace_enabled() { eprintln!("TBE {} eob={}", $idx, eob); } out.eobs[$idx] = eob as u8;