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..9523e116 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -29,3 +29,45 @@ 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, + } +} + +/// Cached AVX2 availability for the explicit-SIMD kernels (`mc`). +#[cfg(target_arch = "x86_64")] +pub(crate) fn avx2_supported() -> bool { + static AVX2: std::sync::LazyLock = + std::sync::LazyLock::new(|| std::arch::is_x86_feature_detected!("avx2")); + *AVX2 +} + +/// 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/loopfilter.rs b/crates/ec-vp8/src/loopfilter.rs index 2039fc19..f716fb20 100644 --- a/crates/ec-vp8/src/loopfilter.rs +++ b/crates/ec-vp8/src/loopfilter.rs @@ -401,39 +401,44 @@ fn filter_mb_v_edge( hev: i32, size: usize, ) { + // Taps are contiguous around each anchor: one slice read per pixel; + // most pixels fail the threshold, so stores stay conditional. for row in 0..8 * size { let a = anchor + row * stride; debug_assert!(a >= 4 && a + 3 < plane.len()); - let px = [ - i32::from(plane[a - 4]), - i32::from(plane[a - 3]), - i32::from(plane[a - 2]), - i32::from(plane[a - 1]), - i32::from(plane[a]), - i32::from(plane[a + 1]), - i32::from(plane[a + 2]), - i32::from(plane[a + 3]), + let mut px = [0u8; 8]; + px.copy_from_slice(&plane[a - 4..a + 4]); + let c = [ + i32::from(px[0]), + i32::from(px[1]), + i32::from(px[2]), + i32::from(px[3]), + i32::from(px[4]), + i32::from(px[5]), + i32::from(px[6]), + i32::from(px[7]), ]; - if !normal_threshold(&px, center_limit, interior) { + if !normal_threshold(&c, center_limit, interior) { continue; } - let [_, p2, p1, p0, q0, q1, q2, _] = px; + let [_, p2, p1, p0, q0, q1, q2, _] = c; if high_edge_variance(p1, p0, q0, q1, hev) { // dixie: filter_common with outer taps (p1/q1 unchanged). let f = filter_common(p1, p0, q0, q1, true); - plane[a - 2] = f[0] as u8; - plane[a - 1] = f[1] as u8; - plane[a] = f[2] as u8; - plane[a + 1] = f[3] as u8; + px[2] = f[0] as u8; + px[3] = f[1] as u8; + px[4] = f[2] as u8; + px[5] = f[3] as u8; } else { let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); - plane[a - 3] = m[0] as u8; - plane[a - 2] = m[1] as u8; - plane[a - 1] = m[2] as u8; - plane[a] = m[3] as u8; - plane[a + 1] = m[4] as u8; - plane[a + 2] = m[5] as u8; + px[1] = m[0] as u8; + px[2] = m[1] as u8; + px[3] = m[2] as u8; + px[4] = m[3] as u8; + px[5] = m[4] as u8; + px[6] = m[5] as u8; } + plane[a - 3..a + 3].copy_from_slice(&px[1..7]); } } @@ -450,19 +455,20 @@ fn filter_subblock_v_edge( for row in 0..8 * size { let a = anchor + row * stride; debug_assert!(a >= 4 && a + 3 < plane.len()); - let px = [ - i32::from(plane[a - 4]), - i32::from(plane[a - 3]), - i32::from(plane[a - 2]), - i32::from(plane[a - 1]), - i32::from(plane[a]), - i32::from(plane[a + 1]), - i32::from(plane[a + 2]), - i32::from(plane[a + 3]), + let px: [u8; 8] = plane[a - 4..a + 4].try_into().unwrap(); + let c = [ + i32::from(px[0]), + i32::from(px[1]), + i32::from(px[2]), + i32::from(px[3]), + i32::from(px[4]), + i32::from(px[5]), + i32::from(px[6]), + i32::from(px[7]), ]; - if normal_threshold(&px, center_limit, interior) { - let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); - let f = filter_common(px[2], px[3], px[4], px[5], outer); + if normal_threshold(&c, center_limit, interior) { + let outer = high_edge_variance(c[2], c[3], c[4], c[5], hev); + let f = filter_common(c[2], c[3], c[4], c[5], outer); plane[a - 2] = f[0] as u8; plane[a - 1] = f[1] as u8; plane[a] = f[2] as u8; @@ -481,37 +487,49 @@ fn filter_mb_h_edge( hev: i32, size: usize, ) { - for i in 0..8 * size { - let a = anchor + i; - debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); - let px = [ - i32::from(plane[a - 4 * stride]), - i32::from(plane[a - 3 * stride]), - i32::from(plane[a - 2 * stride]), - i32::from(plane[a - stride]), - i32::from(plane[a]), - i32::from(plane[a + stride]), - i32::from(plane[a + 2 * stride]), - i32::from(plane[a + 3 * stride]), + // Columns are contiguous (anchor + i), taps sit `stride` apart: the + // tap rows are pulled in with one bounds-checked slice each (most + // columns fail the threshold and need no store, so writes stay + // per-column). + let n = 8 * size; + let mut px = [[0u8; 64]; 8]; + debug_assert!(anchor >= 4 * stride && anchor + 3 * stride + n <= plane.len()); + for (k, r) in px.iter_mut().enumerate() { + // Add the row offset before backing up 4 rows: `anchor` is only + // guaranteed to sit >= 4 rows into the plane, and the subtracted + // form `anchor - (4 - k) * stride` underflows for k > 4. + let a = anchor + k * stride - 4 * stride; + r[..n].copy_from_slice(&plane[a..a + n]); + } + for i in 0..n { + let c = [ + i32::from(px[0][i]), + i32::from(px[1][i]), + i32::from(px[2][i]), + i32::from(px[3][i]), + i32::from(px[4][i]), + i32::from(px[5][i]), + i32::from(px[6][i]), + i32::from(px[7][i]), ]; - if !normal_threshold(&px, center_limit, interior) { + if !normal_threshold(&c, center_limit, interior) { continue; } - let [_, p2, p1, p0, q0, q1, q2, _] = px; + let [_, p2, p1, p0, q0, q1, q2, _] = c; if high_edge_variance(p1, p0, q0, q1, hev) { let f = filter_common(p1, p0, q0, q1, true); - plane[a - 2 * stride] = f[0] as u8; - plane[a - stride] = f[1] as u8; - plane[a] = f[2] as u8; - plane[a + stride] = f[3] as u8; + plane[anchor - 2 * stride + i] = f[0] as u8; + plane[anchor - stride + i] = f[1] as u8; + plane[anchor + i] = f[2] as u8; + plane[anchor + stride + i] = f[3] as u8; } else { let m = filter_mb_edge(p2, p1, p0, q0, q1, q2); - plane[a - 3 * stride] = m[0] as u8; - plane[a - 2 * stride] = m[1] as u8; - plane[a - stride] = m[2] as u8; - plane[a] = m[3] as u8; - plane[a + stride] = m[4] as u8; - plane[a + 2 * stride] = m[5] as u8; + plane[anchor - 3 * stride + i] = m[0] as u8; + plane[anchor - 2 * stride + i] = m[1] as u8; + plane[anchor - stride + i] = m[2] as u8; + plane[anchor + i] = m[3] as u8; + plane[anchor + stride + i] = m[4] as u8; + plane[anchor + 2 * stride + i] = m[5] as u8; } } } @@ -526,26 +544,33 @@ fn filter_subblock_h_edge( hev: i32, size: usize, ) { - for i in 0..8 * size { - let a = anchor + i; - debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len()); - let px = [ - i32::from(plane[a - 4 * stride]), - i32::from(plane[a - 3 * stride]), - i32::from(plane[a - 2 * stride]), - i32::from(plane[a - stride]), - i32::from(plane[a]), - i32::from(plane[a + stride]), - i32::from(plane[a + 2 * stride]), - i32::from(plane[a + 3 * stride]), + let n = 8 * size; + let mut px = [[0u8; 64]; 8]; + debug_assert!(anchor >= 4 * stride && anchor + 3 * stride + n <= plane.len()); + for (k, r) in px.iter_mut().enumerate() { + // Same add-first form as [`filter_mb_h_edge`]: the subtracted + // expression underflows for k > 4. + let a = anchor + k * stride - 4 * stride; + r[..n].copy_from_slice(&plane[a..a + n]); + } + for i in 0..n { + let c = [ + i32::from(px[0][i]), + i32::from(px[1][i]), + i32::from(px[2][i]), + i32::from(px[3][i]), + i32::from(px[4][i]), + i32::from(px[5][i]), + i32::from(px[6][i]), + i32::from(px[7][i]), ]; - if normal_threshold(&px, center_limit, interior) { - let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev); - let f = filter_common(px[2], px[3], px[4], px[5], outer); - plane[a - 2 * stride] = f[0] as u8; - plane[a - stride] = f[1] as u8; - plane[a] = f[2] as u8; - plane[a + stride] = f[3] as u8; + if normal_threshold(&c, center_limit, interior) { + let outer = high_edge_variance(c[2], c[3], c[4], c[5], hev); + let f = filter_common(c[2], c[3], c[4], c[5], outer); + plane[anchor - 2 * stride + i] = f[0] as u8; + plane[anchor - stride + i] = f[1] as u8; + plane[anchor + i] = f[2] as u8; + plane[anchor + stride + i] = f[3] as u8; } } } @@ -556,10 +581,11 @@ fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i for row in 0..16 { let a = anchor + row * stride; debug_assert!(a >= 2 && a + 1 < plane.len()); - let p1 = i32::from(plane[a - 2]); - let p0 = i32::from(plane[a - 1]); - let q0 = i32::from(plane[a]); - let q1 = i32::from(plane[a + 1]); + let px: [u8; 4] = plane[a - 2..a + 2].try_into().unwrap(); + let p1 = i32::from(px[0]); + let p0 = i32::from(px[1]); + let q0 = i32::from(px[2]); + let q1 = i32::from(px[3]); if simple_threshold(p1, p0, q0, q1, limit) { let f = filter_common(p1, p0, q0, q1, true); plane[a - 1] = f[1] as u8; @@ -570,17 +596,24 @@ fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i /// dixie `filter_h_edge_simple`: horizontal edge, simple filter. fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) { + // Contiguous columns, strided taps: chunked loads, conditional stores. + let mut px = [[0u8; 16]; 4]; + debug_assert!(anchor >= 2 * stride && anchor + stride + 16 <= plane.len()); + for (k, r) in px.iter_mut().enumerate() { + // Add-first form (see [`filter_mb_h_edge`]): the subtracted + // expression underflows for k > 2. + let a = anchor + k * stride - 2 * stride; + r.copy_from_slice(&plane[a..a + 16]); + } for i in 0..16 { - let a = anchor + i; - debug_assert!(a >= 2 * stride && a + stride < plane.len()); - let p1 = i32::from(plane[a - 2 * stride]); - let p0 = i32::from(plane[a - stride]); - let q0 = i32::from(plane[a]); - let q1 = i32::from(plane[a + stride]); + let p1 = i32::from(px[0][i]); + let p0 = i32::from(px[1][i]); + let q0 = i32::from(px[2][i]); + let q1 = i32::from(px[3][i]); if simple_threshold(p1, p0, q0, q1, limit) { let f = filter_common(p1, p0, q0, q1, true); - plane[a - stride] = f[1] as u8; - plane[a] = f[2] as u8; + plane[anchor - stride + i] = f[1] as u8; + plane[anchor + i] = f[2] as u8; } } } diff --git a/crates/ec-vp8/src/mc.rs b/crates/ec-vp8/src/mc.rs index 01d64181..e517cbdb 100644 --- a/crates/ec-vp8/src/mc.rs +++ b/crates/ec-vp8/src/mc.rs @@ -21,6 +21,7 @@ //! are reproduced exactly (`i32 >> 3` and `& 7` on negatives). //! //! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386 +use crate::avx2_supported; /// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes. const VP8_FILTER_WEIGHT: i32 = 128; @@ -154,6 +155,13 @@ pub(crate) fn predict_luma( /// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*, /// filter.c). `(sx, sy)` is the full-pel block origin in the bordered /// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy). +/// +/// Both passes share one clamped intermediate buffer: the first pass is +/// clamped to 0..=255 per pass (libvpx `clamp_pixel`), so it is stored as +/// `u8` at a fixed 16-lane stride. The AVX2 kernels always compute all 16 +/// lanes of an intermediate row (reads stay inside the 32-px border for +/// every block shape) and the vertical pass discards the tail lanes with +/// its `bw`-byte store; the scalar reference only fills the first `bw`. fn sixtap_block( src: &[u8], stride: usize, @@ -177,13 +185,44 @@ fn sixtap_block( let hf = &SUB_PEL_FILTERS[fx]; let vf = &SUB_PEL_FILTERS[fy]; + let rows = bh + 5; + let mut tmp = [0u8; 21 * 16]; // C: int FData[21 * 24], clamped to u8 + + #[cfg(target_arch = "x86_64")] + { + if avx2_supported() { + // SAFETY: AVX2 availability checked by `avx2_supported` just + // above; the border/bounds contracts of both kernels hold for + // every caller (`bw`/`bh` in 4..=16, bordered source plane). + #[allow(unsafe_code)] + unsafe { + simd::sixtap_h(src, stride, sx, sy, hf, &mut tmp, rows); + simd::sixtap_v(&tmp, vf, dst, dst_stride, bw, bh); + } + return; + } + } - // filter.c filter_block2d_first_pass on `src - 2*stride`: `bh + 5` - // horizontal lines (2 above the block, 3 below, for the vertical taps). - // Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the - // uniform loop reproduces the C for every phase combination. - let mut tmp = [0i32; 21 * 16]; // C: int FData[21 * 24] - for i in 0..bh + 5 { + sixtap_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows); + sixtap_v_scalar(&tmp, vf, dst, dst_stride, bw, bh); +} + +/// Scalar first pass of [`sixtap_block`] (filter.c +/// `filter_block2d_first_pass` on `src - 2*stride`): `rows` = `bh + 5` +/// horizontal lines, each sample `(dot + 64) >> 7` clamped to 0..=255. +/// Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the +/// uniform loop reproduces the C for every phase combination. +fn sixtap_h_scalar( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + hf: &[i32; 6], + tmp: &mut [u8; 21 * 16], + bw: usize, + rows: usize, +) { + for i in 0..rows { let row = (sy + i - 2) * stride + sx - 2; for j in 0..bw { let p = row + j; @@ -194,30 +233,269 @@ fn sixtap_block( + i32::from(src[p + 4]) * hf[4] + i32::from(src[p + 5]) * hf[5] + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ - tmp[i * bw + j] = clamp255(acc >> VP8_FILTER_SHIFT); + tmp[i * 16 + j] = clamp255(acc >> VP8_FILTER_SHIFT) as u8; } } +} - // filter.c filter_block2d_second_pass on `FData + 2*bw`: taps read the - // intermediate rows `r .. r + 5`. +/// Scalar second pass of [`sixtap_block`] (filter.c +/// `filter_block2d_second_pass` on `FData + 2*bw`): taps read the +/// intermediate rows `r .. r + 5` at the fixed 16-lane stride. +fn sixtap_v_scalar( + tmp: &[u8; 21 * 16], + vf: &[i32; 6], + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { for r in 0..bh { for c in 0..bw { - let acc = tmp[r * bw + c] * vf[0] - + tmp[(r + 1) * bw + c] * vf[1] - + tmp[(r + 2) * bw + c] * vf[2] - + tmp[(r + 3) * bw + c] * vf[3] - + tmp[(r + 4) * bw + c] * vf[4] - + tmp[(r + 5) * bw + c] * vf[5] + let acc = i32::from(tmp[r * 16 + c]) * vf[0] + + i32::from(tmp[(r + 1) * 16 + c]) * vf[1] + + i32::from(tmp[(r + 2) * 16 + c]) * vf[2] + + i32::from(tmp[(r + 3) * 16 + c]) * vf[3] + + i32::from(tmp[(r + 4) * 16 + c]) * vf[4] + + i32::from(tmp[(r + 5) * 16 + c]) * vf[5] + (VP8_FILTER_WEIGHT >> 1); /* Rounding */ dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8; } } } +/// Explicit `std::arch::x86_64` kernels for the six-tap and bilinear +/// passes (the 18% of a decode the profile pins on `sixtap_block` and its +/// chroma siblings). Nothing here is spec logic: each kernel is the scalar +/// function's arithmetic lane-parallel, with the same rounding, the same +/// truncation points and the same clamps -- the equivalence tests run +/// every kernel against its scalar reference over all shapes, phases and +/// worst-case input bytes. +/// +/// Exactness notes shared by the six-tap kernels: +/// - `_mm*_madd_epi16` multiplies *pairs of samples* by a packed tap pair +/// and accumulates in `i32`; every product is exact (widened samples +/// are 0..=255, `|byte * tap| <= 255 * 128 < 2^15`) and the six-product +/// sum is exact in `i32` (`|dot + 64| <= 255 * 160 + 64 < 2^23`). +/// - The even/odd column split exists because `madd` pairs *adjacent* +/// samples: the even accumulator's `madd` lane m is output `2m`, the +/// odd one output `2m+1` (load offset +1 shifts the sample window). +/// - `packs_epi32`'s `i32 -> i16` saturation can never fire: after +/// `(dot + 64) >> 7` the range is `[-76, 319]`. +/// - `packus_epi16`'s `u8` saturation *is* filter.c's `clamp_pixel`: +/// values below 0 saturate to 0, above 255 to 255, the rest unchanged. +#[cfg(target_arch = "x86_64")] +#[allow(unsafe_code)] +#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract +mod simd { + use super::{VP8_FILTER_SHIFT, VP8_FILTER_WEIGHT}; + use std::arch::x86_64::*; + + /// Tap pair `[t0, t1]` packed into one `i32`, the operand shape + /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` + /// is `s[2j] * t0 + s[2j+1] * t1` (ec-av1 `mc::simd::tap_pairs`). + #[inline] + fn tap_pair(a: i32, b: i32) -> i32 { + (b << 16) | (a as u16 as i32) + } + + /// Six-tap first pass, all 16 lanes of every intermediate row (see + /// [`sixtap_block`] for the layout). + /// + /// # Safety + /// Requires AVX2. `src` must be a bordered MC plane such that for + /// every `i < rows`, the 21 bytes starting at + /// `(sy + i - 2) * stride + sx - 2` are in bounds (`sx, sy >= 2`). + #[target_feature(enable = "avx2")] + pub(super) unsafe fn sixtap_h( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + hf: &[i32; 6], + tmp: &mut [u8; 21 * 16], + rows: usize, + ) { + debug_assert!(sx >= 2 && sy >= 2); + debug_assert!((sy + rows - 2) * stride + sx + 19 <= src.len()); + let tv = [ + _mm256_set1_epi32(tap_pair(hf[0], hf[1])), + _mm256_set1_epi32(tap_pair(hf[2], hf[3])), + _mm256_set1_epi32(tap_pair(hf[4], hf[5])), + ]; + let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1); + for i in 0..rows { + let sp = src.as_ptr().add((sy + i - 2) * stride + sx - 2); + // `cvtepu8_epi16` of the 16-byte window at byte offset `2k` + // puts each even output's tap pair in one `madd` lane pair: + // `e` accumulates outputs 0,2,..,14, `o` (window +1 byte) + // outputs 1,3,..,15. + let mut e = _mm256_setzero_si256(); + let mut o = _mm256_setzero_si256(); + for k in 0..3 { + let se = _mm256_cvtepu8_epi16(_mm_loadu_si128(sp.add(2 * k).cast())); + e = _mm256_add_epi32(e, _mm256_madd_epi16(se, tv[k])); + let so = _mm256_cvtepu8_epi16(_mm_loadu_si128(sp.add(2 * k + 1).cast())); + o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k])); + } + e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), VP8_FILTER_SHIFT); + o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), VP8_FILTER_SHIFT); + // `unpacklo/hi` + `packs` interleave even/odd outputs back in + // order (0..8 in the low 128-bit half, 8..16 in the high + // half), then `packus` narrows both halves in sequence -- its + // `u8` saturation is filter.c's `clamp_pixel` itself. + let lo = _mm256_unpacklo_epi32(e, o); + let hi = _mm256_unpackhi_epi32(e, o); + let i16 = _mm256_packs_epi32(lo, hi); + let u8 = _mm_packus_epi16( + _mm256_castsi256_si128(i16), + _mm256_extracti128_si256::<1>(i16), + ); + _mm_storeu_si128(tmp.as_mut_ptr().add(i * 16).cast(), u8); + } + } + + /// Six-tap second pass: `bh` output rows of `bw` (4/8/16) samples from + /// the 16-lane-strided intermediate. + /// + /// # Safety + /// Requires AVX2. `dst` must be writable for `bh` rows of `bw` bytes + /// at `dst_stride`; `bw` is 4, 8 or 16. + #[target_feature(enable = "avx2")] + pub(super) unsafe fn sixtap_v( + tmp: &[u8; 21 * 16], + vf: &[i32; 6], + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, + ) { + debug_assert!(matches!(bw, 4 | 8 | 16)); + debug_assert!(dst.len() >= (bh - 1) * dst_stride + bw); + let tv = [ + _mm256_set1_epi32(tap_pair(vf[0], vf[1])), + _mm256_set1_epi32(tap_pair(vf[2], vf[3])), + _mm256_set1_epi32(tap_pair(vf[4], vf[5])), + ]; + let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1); + for r in 0..bh { + let ip = tmp.as_ptr().add(r * 16); + // Rows `r + 2k` / `r + 2k + 1` widened to samples, interleaved + // by `unpack_epi16` so one `madd` covers two taps of every + // output; `lo` holds even columns, `hi` odd ones (one run per + // 128-bit lane). + let mut lo = _mm256_setzero_si256(); + let mut hi = _mm256_setzero_si256(); + for k in 0..3 { + let a = _mm256_cvtepu8_epi16(_mm_loadu_si128(ip.add(2 * k * 16).cast())); + let b = _mm256_cvtepu8_epi16(_mm_loadu_si128(ip.add((2 * k + 1) * 16).cast())); + lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv[k])); + hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv[k])); + } + lo = _mm256_srai_epi32(_mm256_add_epi32(lo, rnd), VP8_FILTER_SHIFT); + hi = _mm256_srai_epi32(_mm256_add_epi32(hi, rnd), VP8_FILTER_SHIFT); + // `packs` reorders to outputs 0..8 | 8..16 across the two + // 128-bit halves, in column order. + let i16 = _mm256_packs_epi32(lo, hi); + let u8 = _mm_packus_epi16( + _mm256_castsi256_si128(i16), + _mm256_extracti128_si256::<1>(i16), + ); + let dp = dst.as_mut_ptr().add(r * dst_stride); + match bw { + 16 => _mm_storeu_si128(dp.cast(), u8), + 8 => _mm_storel_epi64(dp.cast(), u8), + 4 => _mm_storeu_si32(dp.cast(), u8), + _ => unreachable!("bw is 4, 8 or 16"), + } + } + } + + /// Bilinear first pass, 8 output columns per step (`bw` is 4, 8 or + /// 16; `bw = 16` runs the loop twice). The `i16` accumulator is exact: + /// taps are non-negative and sum to 128, so every product and the sum + /// stay `<= 255 * 128 + 64 < 2^15` -- this *is* the C's `unsigned + /// short` intermediate, narrowed at a provably-in-range point. + /// + /// # Safety + /// Requires AVX2. For every `i < rows`, the 17 bytes starting at + /// `(sy + i) * stride + sx` must be in bounds of `src`. + #[target_feature(enable = "avx2")] + pub(super) unsafe fn bilinear_h( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + hf: &[i32; 2], + tmp: &mut [u8; 17 * 16], + rows: usize, + ) { + debug_assert!((sy + rows - 1) * stride + sx + 16 < src.len()); + let f0 = _mm_set1_epi16(hf[0] as i16); + let f1 = _mm_set1_epi16(hf[1] as i16); + let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16); + for i in 0..rows { + let sp = src.as_ptr().add((sy + i) * stride + sx); + for c in (0..16).step_by(8) { + // Lane j pairs the samples `j` and `j + 1` (tap `[0]` on + // the window at `c`, tap `[1]` shifted by one byte). + let a = _mm_cvtepu8_epi16(_mm_loadu_si128(sp.add(c).cast())); + let b = _mm_cvtepu8_epi16(_mm_loadu_si128(sp.add(c + 1).cast())); + let acc = _mm_add_epi16( + _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)), + rnd, + ); + let u8 = _mm_packus_epi16(_mm_srai_epi16::(acc), acc); + _mm_storel_epi64(tmp.as_mut_ptr().add(i * 16 + c).cast(), u8); + } + } + } + + /// Bilinear second pass: rows `r` / `r + 1` of the intermediate, same + /// exact-`i16` shape as [`bilinear_h`]. + /// + /// # Safety + /// Requires AVX2. `dst` must be writable for `bh` rows of `bw` bytes + /// at `dst_stride`; `bw` is 4, 8 or 16. + #[target_feature(enable = "avx2")] + pub(super) unsafe fn bilinear_v( + tmp: &[u8; 17 * 16], + vf: &[i32; 2], + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, + ) { + debug_assert!(matches!(bw, 4 | 8 | 16)); + debug_assert!(dst.len() >= (bh - 1) * dst_stride + bw); + let f0 = _mm_set1_epi16(vf[0] as i16); + let f1 = _mm_set1_epi16(vf[1] as i16); + let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16); + for r in 0..bh { + let ip = tmp.as_ptr().add(r * 16); + let dp = dst.as_mut_ptr().add(r * dst_stride); + for c in (0..bw).step_by(8) { + let a = _mm_cvtepu8_epi16(_mm_loadl_epi64(ip.add(c).cast())); + let b = _mm_cvtepu8_epi16(_mm_loadl_epi64(ip.add(16 + c).cast())); + let acc = _mm_add_epi16( + _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)), + rnd, + ); + let u8 = _mm_packus_epi16(_mm_srai_epi16::(acc), acc); + match bw - c { + 8 | 16 => _mm_storel_epi64(dp.add(c).cast(), u8), + _ => _mm_storeu_si32(dp.add(c).cast(), u8), + } + } + } + } +} + /// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*, /// filter.c). The dot products are provably in 0..=255 (taps are /// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's -/// bilinear passes store `unsigned short` intermediates and skip the clamp. +/// bilinear passes store `unsigned short` intermediates and skip the +/// clamp: the intermediate is stored as `u8` at a fixed 16-lane stride +/// (representation-only change, same argument as [`sixtap_block`]). fn bilinear_block( src: &[u8], stride: usize, @@ -240,26 +518,66 @@ fn bilinear_block( let hf = &BILINEAR_FILTERS[fx]; let vf = &BILINEAR_FILTERS[fy]; + let rows = bh + 1; + let mut tmp = [0u8; 17 * 16]; // C: unsigned short FData[17 * 16], <= 255 - // filter.c filter_block2d_bil_first_pass: `bh + 1` rows, horizontal - // taps [0] and [1]. Phase 0 is the exact identity, as above. - let mut tmp = [0u16; 17 * 16]; // C: unsigned short FData[17 * 16] - for i in 0..bh + 1 { + #[cfg(target_arch = "x86_64")] + { + if avx2_supported() { + // SAFETY: AVX2 checked by `avx2_supported`; border/bounds + // contracts hold for every caller (see [`sixtap_block`]). + #[allow(unsafe_code)] // SAFETY: avx2_supported() checked above + unsafe { + simd::bilinear_h(src, stride, sx, sy, hf, &mut tmp, rows); + simd::bilinear_v(&tmp, vf, dst, dst_stride, bw, bh); + } + return; + } + } + + bilinear_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows); + bilinear_v_scalar(&tmp, vf, dst, dst_stride, bw, bh); +} + +/// Scalar first pass of [`bilinear_block`] (filter.c +/// `filter_block2d_bil_first_pass`): `bh + 1` rows, taps `[0]` and `[1]`. +/// Phase 0 is the exact identity, as in [`sixtap_h_scalar`]. +fn bilinear_h_scalar( + src: &[u8], + stride: usize, + sx: usize, + sy: usize, + hf: &[i32; 2], + tmp: &mut [u8; 17 * 16], + bw: usize, + rows: usize, +) { + for i in 0..rows { let row = (sy + i) * stride + sx; for j in 0..bw { let p = row + j; let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1] + (VP8_FILTER_WEIGHT / 2); /* Rounding */ - tmp[i * bw + j] = (acc >> VP8_FILTER_SHIFT) as u16; + tmp[i * 16 + j] = (acc >> VP8_FILTER_SHIFT) as u8; } } +} - // filter.c filter_block2d_bil_second_pass: vertical taps [0] and - // `[width]` (the next intermediate row). +/// Scalar second pass of [`bilinear_block`] (filter.c +/// `filter_block2d_bil_second_pass`): taps `[0]` and `[1]` read rows +/// `r` / `r + 1` of the intermediate at the fixed 16-lane stride. +fn bilinear_v_scalar( + tmp: &[u8; 17 * 16], + vf: &[i32; 2], + dst: &mut [u8], + dst_stride: usize, + bw: usize, + bh: usize, +) { for r in 0..bh { for c in 0..bw { - let acc = i32::from(tmp[r * bw + c]) * vf[0] - + i32::from(tmp[(r + 1) * bw + c]) * vf[1] + let acc = i32::from(tmp[r * 16 + c]) * vf[0] + + i32::from(tmp[(r + 1) * 16 + c]) * vf[1] + (VP8_FILTER_WEIGHT / 2); /* Rounding */ dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8; } @@ -760,4 +1078,124 @@ mod tests { ); assert_eq!(a, b); } + + /// Fills a bordered plane with a 0x00/0xFF checkerboard: maximizes the + /// six-tap dot products' excursions in both directions (negative taps + /// over 0xFF while positive taps sit on 0x00 and vice versa), so the + /// clamp/saturation paths of both implementations are exercised. + fn checkerboard_plane() -> Vec { + let mut out = vec![0u8; STRIDE * ROWS]; + for r in 0..ROWS { + for c in 0..STRIDE { + out[r * STRIDE + c] = if (r + c) & 1 == 0 { 0xFF } else { 0x00 }; + } + } + out + } + + /// The AVX2 kernels must be lane-for-lane identical to the scalar + /// reference (the libvpx transcription) on every block shape, every + /// phase pair, at both a central and a right/bottom-edge origin where + /// the wide loads reach furthest into the border. + #[test] + #[cfg(target_arch = "x86_64")] + fn simd_sixtap_matches_the_scalar_reference_everywhere() { + if !avx2_supported() { + return; + } + let planes = [plane(), checkerboard_plane()]; + let origins = [ + (BORDER + 2, BORDER + 3), + (BORDER + VIS_W - 16, BORDER + VIS_H - 16), + ]; + for p in &planes { + for &(sx, sy) in &origins { + for bw in [4usize, 8, 16] { + for bh in [4usize, 8, 16] { + for fx in 0..8usize { + for fy in 0..8usize { + if fx == 0 && fy == 0 { + continue; // whole-pel copy, shared path + } + let mut want = [0u8; 16 * 16]; + let mut got = [0u8; 16 * 16]; + let mut tmp = [0u8; 21 * 16]; + sixtap_h_scalar( + p, STRIDE, sx, sy, &SUB_PEL_FILTERS[fx], &mut tmp, bw, bh + 5, + ); + sixtap_v_scalar(&tmp, &SUB_PEL_FILTERS[fy], &mut want, 16, bw, bh); + // SAFETY: avx2_supported() checked above. + #[allow(unsafe_code)] + unsafe { + let mut tmp2 = [0u8; 21 * 16]; + simd::sixtap_h( + p, STRIDE, sx, sy, &SUB_PEL_FILTERS[fx], &mut tmp2, bh + 5, + ); + simd::sixtap_v(&tmp2, &SUB_PEL_FILTERS[fy], &mut got, 16, bw, bh); + } + let n = bh * 16; + assert_eq!( + &got[..n], + &want[..n], + "sixtap bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy})" + ); + } + } + } + } + } + } + } + + /// Same gate for the bilinear kernels. + #[test] + #[cfg(target_arch = "x86_64")] + fn simd_bilinear_matches_the_scalar_reference_everywhere() { + if !avx2_supported() { + return; + } + let planes = [plane(), checkerboard_plane()]; + let origins = [ + (BORDER + 2, BORDER + 3), + (BORDER + VIS_W - 16, BORDER + VIS_H - 16), + ]; + for p in &planes { + for &(sx, sy) in &origins { + for bw in [4usize, 8, 16] { + for bh in [4usize, 8, 16] { + for fx in 0..8usize { + for fy in 0..8usize { + if fx == 0 && fy == 0 { + continue; + } + let mut want = [0u8; 16 * 16]; + let mut got = [0u8; 16 * 16]; + let mut tmp = [0u8; 17 * 16]; + bilinear_h_scalar( + p, STRIDE, sx, sy, &BILINEAR_FILTERS[fx], &mut tmp, bw, bh + 1, + ); + bilinear_v_scalar(&tmp, &BILINEAR_FILTERS[fy], &mut want, 16, bw, bh); + // SAFETY: avx2_supported() checked above. + #[allow(unsafe_code)] + unsafe { + let mut tmp2 = [0u8; 17 * 16]; + simd::bilinear_h( + p, STRIDE, sx, sy, &BILINEAR_FILTERS[fx], &mut tmp2, bh + 1, + ); + simd::bilinear_v(&tmp2, &BILINEAR_FILTERS[fy], &mut got, 16, bw, bh); + } + for r in 0..bh { + assert_eq!( + got[r * 16..r * 16 + bw], + want[r * 16..r * 16 + bw], + "bilinear bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy}) row={r}" + ); + } + } + } + } + } + } + } + } } 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;