From abc2cab8107de51ea838c6e4d668820587920473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 13 Sep 2026 00:37:06 +0300 Subject: [PATCH] ec-vp8 perf: idct_add_into -- fused strided reconstruct + AVX2 kernel idct_add_into (28% of the post-MC-decode profile) now runs through transform::idct_add_strided: the prediction gather, the transform, the clamp-add and the strided stores in one function, with an explicit std::arch::x86_64 AVX2 kernel dispatched off a shared LazyLock probe and the scalar path kept as the libvpx transcription and lane-for-lane oracle. The kernel preserves the module's precision contract in full: the butterflies are the scalar i32 arithmetic lane-parallel (products exact, |i16 * 35468| < 2^31), and the only narrowing points are the oracle's short stores -- pass one's tmp and pass two's residual -- implemented as low-16-bit truncations via shuffle_epi8, never saturation. Coefficients transpose to column groups (rows woven by unpack_epi16), pass one's store-pattern transpose hands row groups to pass two, and the final clamp is explicit max 0 / min 255 in i32 before a saturating pack that never fires beyond the clamp. The equivalence test pushes coefficients to the i16 rails precisely because the network is exact for every input. Witness suite: 58 lib (new: simd-vs-scalar equivalence over rails + random, four stride shapes) + 4 header_parse + 4 keyframe_exact + 3 stream_exact, byte-exact, debug and release. Zero warnings. --- crates/ec-vp8/src/decode.rs | 16 +- crates/ec-vp8/src/lib.rs | 13 +- crates/ec-vp8/src/transform.rs | 303 +++++++++++++++++++++++++++++++++ 3 files changed, 319 insertions(+), 13 deletions(-) diff --git a/crates/ec-vp8/src/decode.rs b/crates/ec-vp8/src/decode.rs index 49157cee..19467923 100644 --- a/crates/ec-vp8/src/decode.rs +++ b/crates/ec-vp8/src/decode.rs @@ -1305,7 +1305,9 @@ fn ymode_as_bmode(y: u8) -> u8 { /// Add one 4x4 block's dequantized-coefficient residual to its /// prediction: reads the prediction patch from `pred`, clamps, writes -/// into the strided plane (§14.4/§14.5). +/// into the strided plane (§14.4/§14.5). The transform, the add and the +/// strided store live in `transform::idct_add_strided` (scalar reference +/// + AVX2 kernel). fn idct_add_into( plane: &mut [u8], coeffs: &[i16; 16], @@ -1315,15 +1317,5 @@ fn idct_add_into( dst_off: usize, dst_stride: usize, ) { - let mut p = [0u8; 16]; - for i in 0..4 { - let s = pred_off + i * pred_stride; - p[i * 4..i * 4 + 4].copy_from_slice(&pred[s..s + 4]); - } - let mut out = [0u8; 16]; - transform::idct4x4_add(coeffs, &p, &mut out); - for i in 0..4 { - let d = dst_off + i * dst_stride; - plane[d..d + 4].copy_from_slice(&out[i * 4..i * 4 + 4]); - } + transform::idct_add_strided(plane, coeffs, pred, pred_stride, pred_off, dst_off, dst_stride); } diff --git a/crates/ec-vp8/src/lib.rs b/crates/ec-vp8/src/lib.rs index 30756bf3..c804118f 100644 --- a/crates/ec-vp8/src/lib.rs +++ b/crates/ec-vp8/src/lib.rs @@ -9,7 +9,10 @@ //! //! # Unsafe //! -//! This crate contains no `unsafe` code. +//! The decoder logic is safe Rust. The one exception is the explicit +//! `std::arch::x86_64` SIMD kernels in `mc` and `transform` (each confined +//! to its own `#[allow(unsafe_code)]` module, dispatch-gated at run time +//! and lane-for-lane tested against its scalar reference). #![deny(unsafe_code)] #![warn(missing_docs)] @@ -63,3 +66,11 @@ pub(crate) fn debug_enabled() -> bool { _ => true, } } + +/// Cached AVX2 availability for the explicit-SIMD kernels (`mc`, `transform`). +#[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 +} diff --git a/crates/ec-vp8/src/transform.rs b/crates/ec-vp8/src/transform.rs index 520d7982..b41a5617 100644 --- a/crates/ec-vp8/src/transform.rs +++ b/crates/ec-vp8/src/transform.rs @@ -242,6 +242,243 @@ pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) { } } +/// Fused per-block reconstruction with strided prediction and strided +/// store (the per-4x4 hot path of `decode::idct_add_into`): inverse- +/// transforms `coeffs`, adds the 4x4 prediction block at +/// `pred[pred_off..]` (`pred_stride` between rows), clamps to 0..=255 and +/// stores into `plane` at `dst_off` (`dst_stride` between rows). +/// +/// Dispatches to the AVX2 kernel when available; the scalar path is the +/// libvpx transcription and the lane-for-lane oracle. +pub(crate) fn idct_add_strided( + plane: &mut [u8], + coeffs: &[i16; 16], + pred: &[u8], + pred_stride: usize, + pred_off: usize, + dst_off: usize, + dst_stride: usize, +) { + debug_assert!(pred.len() >= pred_off + 3 * pred_stride + 4); + debug_assert!(plane.len() >= dst_off + 3 * dst_stride + 4); + + #[cfg(target_arch = "x86_64")] + { + if crate::avx2_supported() { + // SAFETY: AVX2 checked by `avx2_supported`; the bounds + // contracts are the debug_asserts above. + #[allow(unsafe_code)] + unsafe { + simd::idct_add_strided(coeffs, pred, pred_stride, pred_off, plane, dst_off, dst_stride); + } + return; + } + } + + let residual = idct4x4(coeffs); + for row in 0..4 { + let s = pred_off + row * pred_stride; + let d = dst_off + row * dst_stride; + for col in 0..4 { + plane[d + col] = (i32::from(residual[row * 4 + col]) + + i32::from(pred[s + col])) + .clamp(0, 255) as u8; + } + } +} + +/// Explicit `std::arch::x86_64` kernel for [`idct_add_strided`]. +/// +/// The butterflies are the scalar `i32` arithmetic lane-parallel -- the +/// precision contract of this module is kept in full: products are exact +/// (`|i16 * K| <= 32767 * 35468 < 2^31`), butterfly sums never truncate +/// mid-network, and the ONLY narrowing points are the oracle's `short` +/// stores (pass one's `tmp`, pass two's residual), each a low-16-bit +/// truncation (`shuffle_epi8` byte picks), never saturation. The final +/// clamp is explicit `max 0 / min 255` in `i32` before a saturating pack +/// that therefore never fires beyond the clamp. +/// +/// Lane layout through the two passes (one AVX2 register holds two 4-lane +/// groups; lane `4g + l` = group `g`, element `l`): +/// - coefficients are transposed to column groups (a column = a group); +/// the pass pairs lanes `(l0, l2)` / `(l1, l3)` = rows `(0, 2)` / +/// `(1, 3)` of that column, and its outputs land row-major +/// (the libvpx store-pattern transpose), +/// - a 3-unpack transpose hands pass two row groups, +/// - pass two pairs `(ip0, ip2)` / `(ip1, ip3)` of each row. +#[cfg(target_arch = "x86_64")] +#[allow(unsafe_code)] +#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract +mod simd { + use super::{COSPI8SQRT2MINUS1, SINPI8SQRT2}; + use std::arch::x86_64::*; + + /// `shuffle_epi8` mask: keep the low 16 bits of `i32` lane 0 of each + /// 128-bit half. + const TAKE0: [u8; 16] = [ + 0, 1, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0, 1, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + ]; + /// `shuffle_epi8` masks picking column `c`'s four `i16`s out of the + /// row-major 4x4 block held in one `ymm` (element `(r, c)` sits at + /// byte `8r + 2c`): the low 128-bit half gathers rows 0, 1, the high + /// half rows 2, 3. + const COLPAIR_MASKS: [[u8; 16]; 4] = [ + [0, 1, 8, 9, 0x80, 0x80, 0x80, 0x80, 0, 1, 8, 9, 0x80, 0x80, 0x80, 0x80], + [2, 3, 10, 11, 0x80, 0x80, 0x80, 0x80, 2, 3, 10, 11, 0x80, 0x80, 0x80, 0x80], + [4, 5, 12, 13, 0x80, 0x80, 0x80, 0x80, 4, 5, 12, 13, 0x80, 0x80, 0x80, 0x80], + [6, 7, 14, 15, 0x80, 0x80, 0x80, 0x80, 6, 7, 14, 15, 0x80, 0x80, 0x80, 0x80], + ]; + + #[inline] + fn shuffle_mask(m: &[u8; 16]) -> __m128i { + // SAFETY: reads a 16-byte constant. + unsafe { _mm_loadu_si128(m.as_ptr().cast()) } + } + + /// One 4-point inverse-DCT butterfly pass over the two 4-lane groups + /// of `x` (`i32` lanes), with the second pass's `(x + 4) >> 3` when + /// `SHIFT` is 3 (pass one runs with `SHIFT = 0`, `rnd = 0`). + /// + /// Returns `i16`-truncated values packed as eight `i16`s in one + /// `xmm`: groups `g_a`, `g_b` in the low/high 64 bits. + /// + /// # Safety + /// Requires AVX2. + #[target_feature(enable = "avx2")] + unsafe fn pass( + x: __m256i, + sin: __m256i, + cos: __m256i, + rnd: __m256i, + ) -> __m128i { + // Dup the butterfly partners per half: [l0,l0,l2,l2], [l2,l2,l0,l0], + // [l1,l1,l3,l3], [l3,l3,l1,l1]. + let x02 = _mm256_shuffle_epi32::<0xA0>(x); + let x20 = _mm256_shuffle_epi32::<0x0A>(x); + let x13 = _mm256_shuffle_epi32::<0xF5>(x); + let x31 = _mm256_shuffle_epi32::<0x5F>(x); + let a1 = _mm256_add_epi32(x02, x20); // l0 + l2, every lane + let b1 = _mm256_sub_epi32(x02, x20); // lanes 0,1 = l0 - l2 + // `(v * K) >> 16`, exact in `i32` for every `i16` `v`. + let ms = + |v: __m256i, k: __m256i| _mm256_srai_epi32::<16>(_mm256_mullo_epi32(v, k)); + let c1 = _mm256_sub_epi32(ms(x13, sin), _mm256_add_epi32(x31, ms(x31, cos))); + let d1 = _mm256_add_epi32(_mm256_add_epi32(x13, ms(x13, cos)), ms(x31, sin)); + let y = |v: __m256i| { + _mm256_srai_epi32::(_mm256_add_epi32(v, rnd)) + }; + let y0 = y(_mm256_add_epi32(a1, d1)); + let y1 = y(_mm256_add_epi32(b1, c1)); + let y2 = y(_mm256_sub_epi32(b1, c1)); + let y3 = y(_mm256_sub_epi32(a1, d1)); + // Truncate each output to `i16` (the oracle's store points) and + // assemble group lanes [y0, y1, y2, y3]. Only lane 0 of every y* + // holds the true value: `b1`'s lanes 2,3 hold the NEGATED + // butterfly (x20 puts l2 first there) and `d1`/`c1`'s lanes 2,3 + // hold the (l1, l3) pair swapped, so the lane-2 dups of TAKE02 + // would feed garbage into the assembly. + let take0 = _mm256_broadcastsi128_si256(shuffle_mask(&TAKE0)); + let z0 = _mm256_shuffle_epi8(y0, take0); + let z1 = _mm256_shuffle_epi8(y1, take0); + let z2 = _mm256_shuffle_epi8(y2, take0); + let z3 = _mm256_shuffle_epi8(y3, take0); + let w01 = _mm256_unpacklo_epi16(z0, z1); + let w23 = _mm256_unpacklo_epi16(z2, z3); + let packed = _mm256_unpacklo_epi32(w01, w23); + // Each half of `packed` is [group's y0..y3 | dup bytes]; weave the + // two halves' low 64 bits into [g_a 4 i16 | g_b 4 i16]. + let p128 = _mm256_castsi256_si128(packed); + let p128hi = _mm256_extracti128_si256::<1>(packed); + _mm_unpacklo_epi64(p128, p128hi) + } + + /// [`super::idct_add_strided`]'s AVX2 body: see the module docs for + /// the lane layout through the two passes. + /// + /// # Safety + /// Requires AVX2. `pred[pred_off..]` must hold `3 * pred_stride + 4` + /// bytes and `plane[dst_off..]` `3 * dst_stride + 4`. + pub(super) unsafe fn idct_add_strided( + coeffs: &[i16; 16], + pred: &[u8], + pred_stride: usize, + pred_off: usize, + plane: &mut [u8], + dst_off: usize, + dst_stride: usize, + ) { + debug_assert!(pred.len() >= pred_off + 3 * pred_stride + 4); + debug_assert!(plane.len() >= dst_off + 3 * dst_stride + 4); + let sin = _mm256_set1_epi32(SINPI8SQRT2); + let cos = _mm256_set1_epi32(COSPI8SQRT2MINUS1); + let zero = _mm256_setzero_si256(); + + // Coefficients -> column groups (a group = one column, rows 0..3), + // widened to the butterflies' `i32` lanes. The whole 32-byte block + // is one ymm; each gather pulls column c's rows 0,1 (low half) and + // 2,3 (high half) and the unpack weaves them into one `xmm`. + let cx = _mm256_loadu_si256(coeffs.as_ptr().cast()); + let col = |c: usize| { + // The pair mask is the same 8 useful bytes in both halves, so + // broadcasting the 128-bit mask covers both. + let pair = _mm256_shuffle_epi8(cx, _mm256_broadcastsi128_si256(shuffle_mask(&COLPAIR_MASKS[c]))); + // rows 0,1 sit in the low half's bytes 0-3, rows 2,3 in the + // high half's -- `unpacklo_epi32` concatenates exactly those. + _mm_cvtepi16_epi32(_mm_unpacklo_epi32( + _mm256_castsi256_si128(pair), + _mm256_extracti128_si256::<1>(pair), + )) + }; + let cx01 = _mm256_inserti128_si256(_mm256_castsi128_si256(col(0)), col(1), 1); + let cx23 = _mm256_inserti128_si256(_mm256_castsi128_si256(col(2)), col(3), 1); + + // Pass one: the row-major `short tmp` (the store-pattern + // transpose); each result xmm holds the tmp columns (c, c + 1) + // column-major. + let t01 = pass::<0>(cx01, sin, cos, zero); + let t23 = pass::<0>(cx23, sin, cos, zero); + + // Weave the column pairs into rows 0..4: `a` holds columns + // (0, 2) rows 0..4, `b` columns (1, 3); low/high interleave + // splits them into row-major rows (0, 1) / (2, 3). + let a = _mm_unpacklo_epi16(t01, t23); + let b = _mm_unpackhi_epi16(t01, t23); + let rows01 = _mm_unpacklo_epi16(a, b); + let rows23 = _mm_unpackhi_epi16(a, b); + + // Pass two on row groups, with the §14.4 rounding constant. + let r0 = _mm_cvtepi16_epi32(rows01); + let r1 = _mm_cvtepi16_epi32(_mm_srli_si128::<8>(rows01)); + let r2 = _mm_cvtepi16_epi32(rows23); + let r3 = _mm_cvtepi16_epi32(_mm_srli_si128::<8>(rows23)); + let rx01 = _mm256_inserti128_si256(_mm256_castsi128_si256(r0), r1, 1); + let rx23 = _mm256_inserti128_si256(_mm256_castsi128_si256(r2), r3, 1); + let rnd = _mm256_set1_epi32(4); + let y01 = pass::<3>(rx01, sin, cos, rnd); // rows 0, 1 + let y23 = pass::<3>(rx23, sin, cos, rnd); // rows 2, 3 + + // Residual (i16, truncated in `pass`) + prediction, clamp, store. + let mut add_store = |row16: __m128i, s_off: usize, d_off: usize| { + let mut q = [0u8; 4]; + q.copy_from_slice(&pred[s_off..s_off + 4]); + let pv = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(u32::from_le_bytes(q) as i32)); + let s = _mm_add_epi32(_mm_cvtepi16_epi32(row16), pv); + let c = _mm_min_epi32(_mm_max_epi32(s, _mm_setzero_si128()), _mm_set1_epi32(255)); + let u16 = _mm_packus_epi32(c, c); + let u8 = _mm_packus_epi16(u16, u16); + _mm_storeu_si32(plane.as_mut_ptr().add(d_off).cast(), u8); + }; + add_store(y01, pred_off, dst_off); + add_store(_mm_srli_si128::<8>(y01), pred_off + pred_stride, dst_off + dst_stride); + add_store(y23, pred_off + 2 * pred_stride, dst_off + 2 * dst_stride); + add_store( + _mm_srli_si128::<8>(y23), + pred_off + 3 * pred_stride, + dst_off + 3 * dst_stride, + ); + } +} + /// Dequantization factors for one macroblock, indexed by plane and /// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -637,4 +874,70 @@ mod tests { } } } + + /// AVX2 [`simd::idct_add_strided`] vs the scalar reference. The i32 + /// lane network is exact for EVERY `i16` coefficient (products < 2^31, + /// truncations only at the oracle's `short` stores), so the + /// equivalence test pushes coefficients to the rails on purpose: + /// magnitudes at ±32767 put `i16 * 35468` within a factor of two of + /// the `i32` limit and the butterflies at their wrapping boundary -- + /// exactly where a lane-order or precision slip would show. + #[test] + #[cfg(target_arch = "x86_64")] + fn simd_idct_add_strided_matches_the_scalar_reference() { + if !crate::avx2_supported() { + return; + } + let mut s = 0x9E37_79B9_7F4A_7C15u64; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + s + }; + for case in 0..4000u32 { + let mut coeffs = [0i16; 16]; + for c in coeffs.iter_mut() { + *c = match rnd() % 4 { + 0 => i16::MAX, + 1 => i16::MIN, + _ => rnd() as i16, + }; + } + let pred: Vec = (0..2048).map(|_| rnd() as u8).collect(); + let pred_stride = [4usize, 8, 16, 24][(rnd() % 4) as usize]; + let pred_off = (rnd() as usize) % 1024; + let dst_stride = [16usize, 32, 48][(rnd() % 3) as usize]; + let dst_off = (rnd() as usize) % 1024; + debug_assert!(pred_off + 3 * pred_stride + 4 <= 2048); + + // Scalar reference (the libvpx transcription). + let mut want = vec![7u8; 4096]; + let residual = idct4x4(&coeffs); + for row in 0..4 { + for col in 0..4 { + want[dst_off + row * dst_stride + col] = (i32::from( + residual[row * 4 + col], + ) + i32::from(pred[pred_off + row * pred_stride + col])) + .clamp(0, 255) as u8; + } + } + + let mut got = vec![7u8; 4096]; + // SAFETY: avx2_supported() checked above. + #[allow(unsafe_code)] + unsafe { + simd::idct_add_strided( + &coeffs, + &pred, + pred_stride, + pred_off, + &mut got, + dst_off, + dst_stride, + ); + } + assert_eq!(got, want, "case {case}"); + } + } }