forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-vp8-perf' (292b7093): ec-vp8 decode is 2.5-3.5x faster -- per-bool env lookups (46% of profile) to a process-wide atomic, loop-filter chunked loads with conditional stores, AVX2 six-tap + bilinear MC passes (MC 18% -> 3%); big-obs clip class 72 fps and 720p 276 fps crate-level, clearing the seat swap's un-park lines with margin; idct AVX2 attempted and honestly reverted (exact-i32 ceiling ~1.3-1.5x kernel); byte-exact witness suite green per commit, debug AND release

Browse files at this commit

ff9aa0e711c78fc0c6e197622910bb11affa8b6cAhmet Kaan GümüşParent: d2a09ed1b64551
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+42 -0
@@ -29,3 +29,45 @@ 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+/// Cached AVX2 availability for the explicit-SIMD kernels (`mc`).
52+#[cfg(target_arch = "x86_64")]
53+pub(crate) fn avx2_supported() -> bool {
54+ static AVX2: std::sync::LazyLock<bool> =
55+ std::sync::LazyLock::new(|| std::arch::is_x86_feature_detected!("avx2"));
56+ *AVX2
57+}
58+
59+/// Whether `EC_VP8_DEBUG` per-macroblock dumps are enabled (same shape as
60+/// [`trace_enabled`]; the check sits in the per-MB reconstruct path).
61+pub(crate) fn debug_enabled() -> bool {
62+ use std::sync::atomic::{AtomicU8, Ordering};
63+ static STATE: AtomicU8 = AtomicU8::new(0);
64+ match STATE.load(Ordering::Relaxed) {
65+ 0 => {
66+ let on = std::env::var_os("EC_VP8_DEBUG").is_some();
67+ STATE.store(if on { 2 } else { 1 }, Ordering::Relaxed);
68+ on
69+ }
70+ 1 => false,
71+ _ => true,
72+ }
73+}
crates/ec-vp8/src/loopfilter.rsmodified+121 -88
@@ -401,39 +401,44 @@ fn filter_mb_v_edge(
401 hev: i32,401 hev: i32,
402 size: usize,402 size: usize,
403 ) {403 ) {
404+ // Taps are contiguous around each anchor: one slice read per pixel;
405+ // most pixels fail the threshold, so stores stay conditional.
404 for row in 0..8 * size {406 for row in 0..8 * size {
405 let a = anchor + row * stride;407 let a = anchor + row * stride;
406 debug_assert!(a >= 4 && a + 3 < plane.len());408 debug_assert!(a >= 4 && a + 3 < plane.len());
407- let px = [409+ let mut px = [0u8; 8];
408- i32::from(plane[a - 4]),410+ px.copy_from_slice(&plane[a - 4..a + 4]);
409- i32::from(plane[a - 3]),411+ let c = [
410- i32::from(plane[a - 2]),412+ i32::from(px[0]),
411- i32::from(plane[a - 1]),413+ i32::from(px[1]),
412- i32::from(plane[a]),414+ i32::from(px[2]),
413- i32::from(plane[a + 1]),415+ i32::from(px[3]),
414- i32::from(plane[a + 2]),416+ i32::from(px[4]),
415- i32::from(plane[a + 3]),417+ i32::from(px[5]),
418+ i32::from(px[6]),
419+ i32::from(px[7]),
416 ];420 ];
417- if !normal_threshold(&px, center_limit, interior) {421+ if !normal_threshold(&c, center_limit, interior) {
418 continue;422 continue;
419 }423 }
420- let [_, p2, p1, p0, q0, q1, q2, _] = px;424+ let [_, p2, p1, p0, q0, q1, q2, _] = c;
421 if high_edge_variance(p1, p0, q0, q1, hev) {425 if high_edge_variance(p1, p0, q0, q1, hev) {
422 // dixie: filter_common with outer taps (p1/q1 unchanged).426 // dixie: filter_common with outer taps (p1/q1 unchanged).
423 let f = filter_common(p1, p0, q0, q1, true);427 let f = filter_common(p1, p0, q0, q1, true);
424- plane[a - 2] = f[0] as u8;428+ px[2] = f[0] as u8;
425- plane[a - 1] = f[1] as u8;429+ px[3] = f[1] as u8;
426- plane[a] = f[2] as u8;430+ px[4] = f[2] as u8;
427- plane[a + 1] = f[3] as u8;431+ px[5] = f[3] as u8;
428 } else {432 } else {
429 let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);433 let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);
430- plane[a - 3] = m[0] as u8;434+ px[1] = m[0] as u8;
431- plane[a - 2] = m[1] as u8;435+ px[2] = m[1] as u8;
432- plane[a - 1] = m[2] as u8;436+ px[3] = m[2] as u8;
433- plane[a] = m[3] as u8;437+ px[4] = m[3] as u8;
434- plane[a + 1] = m[4] as u8;438+ px[5] = m[4] as u8;
435- plane[a + 2] = m[5] as u8;439+ px[6] = m[5] as u8;
436 }440 }
441+ plane[a - 3..a + 3].copy_from_slice(&px[1..7]);
437 }442 }
438 }443 }
439 444
@@ -450,19 +455,20 @@ fn filter_subblock_v_edge(
450 for row in 0..8 * size {455 for row in 0..8 * size {
451 let a = anchor + row * stride;456 let a = anchor + row * stride;
452 debug_assert!(a >= 4 && a + 3 < plane.len());457 debug_assert!(a >= 4 && a + 3 < plane.len());
453- let px = [458+ let px: [u8; 8] = plane[a - 4..a + 4].try_into().unwrap();
454- i32::from(plane[a - 4]),459+ let c = [
455- i32::from(plane[a - 3]),460+ i32::from(px[0]),
456- i32::from(plane[a - 2]),461+ i32::from(px[1]),
457- i32::from(plane[a - 1]),462+ i32::from(px[2]),
458- i32::from(plane[a]),463+ i32::from(px[3]),
459- i32::from(plane[a + 1]),464+ i32::from(px[4]),
460- i32::from(plane[a + 2]),465+ i32::from(px[5]),
461- i32::from(plane[a + 3]),466+ i32::from(px[6]),
467+ i32::from(px[7]),
462 ];468 ];
463- if normal_threshold(&px, center_limit, interior) {469+ if normal_threshold(&c, center_limit, interior) {
464- let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev);470+ let outer = high_edge_variance(c[2], c[3], c[4], c[5], hev);
465- let f = filter_common(px[2], px[3], px[4], px[5], outer);471+ let f = filter_common(c[2], c[3], c[4], c[5], outer);
466 plane[a - 2] = f[0] as u8;472 plane[a - 2] = f[0] as u8;
467 plane[a - 1] = f[1] as u8;473 plane[a - 1] = f[1] as u8;
468 plane[a] = f[2] as u8;474 plane[a] = f[2] as u8;
@@ -481,37 +487,49 @@ fn filter_mb_h_edge(
481 hev: i32,487 hev: i32,
482 size: usize,488 size: usize,
483 ) {489 ) {
484- for i in 0..8 * size {490+ // Columns are contiguous (anchor + i), taps sit `stride` apart: the
485- let a = anchor + i;491+ // tap rows are pulled in with one bounds-checked slice each (most
486- debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len());492+ // columns fail the threshold and need no store, so writes stay
487- let px = [493+ // per-column).
488- i32::from(plane[a - 4 * stride]),494+ let n = 8 * size;
489- i32::from(plane[a - 3 * stride]),495+ let mut px = [[0u8; 64]; 8];
490- i32::from(plane[a - 2 * stride]),496+ debug_assert!(anchor >= 4 * stride && anchor + 3 * stride + n <= plane.len());
491- i32::from(plane[a - stride]),497+ for (k, r) in px.iter_mut().enumerate() {
492- i32::from(plane[a]),498+ // Add the row offset before backing up 4 rows: `anchor` is only
493- i32::from(plane[a + stride]),499+ // guaranteed to sit >= 4 rows into the plane, and the subtracted
494- i32::from(plane[a + 2 * stride]),500+ // form `anchor - (4 - k) * stride` underflows for k > 4.
495- i32::from(plane[a + 3 * stride]),501+ let a = anchor + k * stride - 4 * stride;
502+ r[..n].copy_from_slice(&plane[a..a + n]);
503+ }
504+ for i in 0..n {
505+ let c = [
506+ i32::from(px[0][i]),
507+ i32::from(px[1][i]),
508+ i32::from(px[2][i]),
509+ i32::from(px[3][i]),
510+ i32::from(px[4][i]),
511+ i32::from(px[5][i]),
512+ i32::from(px[6][i]),
513+ i32::from(px[7][i]),
496 ];514 ];
497- if !normal_threshold(&px, center_limit, interior) {515+ if !normal_threshold(&c, center_limit, interior) {
498 continue;516 continue;
499 }517 }
500- let [_, p2, p1, p0, q0, q1, q2, _] = px;518+ let [_, p2, p1, p0, q0, q1, q2, _] = c;
501 if high_edge_variance(p1, p0, q0, q1, hev) {519 if high_edge_variance(p1, p0, q0, q1, hev) {
502 let f = filter_common(p1, p0, q0, q1, true);520 let f = filter_common(p1, p0, q0, q1, true);
503- plane[a - 2 * stride] = f[0] as u8;521+ plane[anchor - 2 * stride + i] = f[0] as u8;
504- plane[a - stride] = f[1] as u8;522+ plane[anchor - stride + i] = f[1] as u8;
505- plane[a] = f[2] as u8;523+ plane[anchor + i] = f[2] as u8;
506- plane[a + stride] = f[3] as u8;524+ plane[anchor + stride + i] = f[3] as u8;
507 } else {525 } else {
508 let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);526 let m = filter_mb_edge(p2, p1, p0, q0, q1, q2);
509- plane[a - 3 * stride] = m[0] as u8;527+ plane[anchor - 3 * stride + i] = m[0] as u8;
510- plane[a - 2 * stride] = m[1] as u8;528+ plane[anchor - 2 * stride + i] = m[1] as u8;
511- plane[a - stride] = m[2] as u8;529+ plane[anchor - stride + i] = m[2] as u8;
512- plane[a] = m[3] as u8;530+ plane[anchor + i] = m[3] as u8;
513- plane[a + stride] = m[4] as u8;531+ plane[anchor + stride + i] = m[4] as u8;
514- plane[a + 2 * stride] = m[5] as u8;532+ plane[anchor + 2 * stride + i] = m[5] as u8;
515 }533 }
516 }534 }
517 }535 }
@@ -526,26 +544,33 @@ fn filter_subblock_h_edge(
526 hev: i32,544 hev: i32,
527 size: usize,545 size: usize,
528 ) {546 ) {
529- for i in 0..8 * size {547+ let n = 8 * size;
530- let a = anchor + i;548+ let mut px = [[0u8; 64]; 8];
531- debug_assert!(a >= 4 * stride && a + 3 * stride < plane.len());549+ debug_assert!(anchor >= 4 * stride && anchor + 3 * stride + n <= plane.len());
532- let px = [550+ for (k, r) in px.iter_mut().enumerate() {
533- i32::from(plane[a - 4 * stride]),551+ // Same add-first form as [`filter_mb_h_edge`]: the subtracted
534- i32::from(plane[a - 3 * stride]),552+ // expression underflows for k > 4.
535- i32::from(plane[a - 2 * stride]),553+ let a = anchor + k * stride - 4 * stride;
536- i32::from(plane[a - stride]),554+ r[..n].copy_from_slice(&plane[a..a + n]);
537- i32::from(plane[a]),555+ }
538- i32::from(plane[a + stride]),556+ for i in 0..n {
539- i32::from(plane[a + 2 * stride]),557+ let c = [
540- i32::from(plane[a + 3 * stride]),558+ i32::from(px[0][i]),
559+ i32::from(px[1][i]),
560+ i32::from(px[2][i]),
561+ i32::from(px[3][i]),
562+ i32::from(px[4][i]),
563+ i32::from(px[5][i]),
564+ i32::from(px[6][i]),
565+ i32::from(px[7][i]),
541 ];566 ];
542- if normal_threshold(&px, center_limit, interior) {567+ if normal_threshold(&c, center_limit, interior) {
543- let outer = high_edge_variance(px[2], px[3], px[4], px[5], hev);568+ let outer = high_edge_variance(c[2], c[3], c[4], c[5], hev);
544- let f = filter_common(px[2], px[3], px[4], px[5], outer);569+ let f = filter_common(c[2], c[3], c[4], c[5], outer);
545- plane[a - 2 * stride] = f[0] as u8;570+ plane[anchor - 2 * stride + i] = f[0] as u8;
546- plane[a - stride] = f[1] as u8;571+ plane[anchor - stride + i] = f[1] as u8;
547- plane[a] = f[2] as u8;572+ plane[anchor + i] = f[2] as u8;
548- plane[a + stride] = f[3] as u8;573+ plane[anchor + stride + i] = f[3] as u8;
549 }574 }
550 }575 }
551 }576 }
@@ -556,10 +581,11 @@ fn filter_v_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i
556 for row in 0..16 {581 for row in 0..16 {
557 let a = anchor + row * stride;582 let a = anchor + row * stride;
558 debug_assert!(a >= 2 && a + 1 < plane.len());583 debug_assert!(a >= 2 && a + 1 < plane.len());
559- let p1 = i32::from(plane[a - 2]);584+ let px: [u8; 4] = plane[a - 2..a + 2].try_into().unwrap();
560- let p0 = i32::from(plane[a - 1]);585+ let p1 = i32::from(px[0]);
561- let q0 = i32::from(plane[a]);586+ let p0 = i32::from(px[1]);
562- let q1 = i32::from(plane[a + 1]);587+ let q0 = i32::from(px[2]);
588+ let q1 = i32::from(px[3]);
563 if simple_threshold(p1, p0, q0, q1, limit) {589 if simple_threshold(p1, p0, q0, q1, limit) {
564 let f = filter_common(p1, p0, q0, q1, true);590 let f = filter_common(p1, p0, q0, q1, true);
565 plane[a - 1] = f[1] as u8;591 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
570 596
571 /// dixie `filter_h_edge_simple`: horizontal edge, simple filter.597 /// dixie `filter_h_edge_simple`: horizontal edge, simple filter.
572 fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) {598 fn filter_h_edge_simple(plane: &mut [u8], stride: usize, anchor: usize, limit: i32) {
599+ // Contiguous columns, strided taps: chunked loads, conditional stores.
600+ let mut px = [[0u8; 16]; 4];
601+ debug_assert!(anchor >= 2 * stride && anchor + stride + 16 <= plane.len());
602+ for (k, r) in px.iter_mut().enumerate() {
603+ // Add-first form (see [`filter_mb_h_edge`]): the subtracted
604+ // expression underflows for k > 2.
605+ let a = anchor + k * stride - 2 * stride;
606+ r.copy_from_slice(&plane[a..a + 16]);
607+ }
573 for i in 0..16 {608 for i in 0..16 {
574- let a = anchor + i;609+ let p1 = i32::from(px[0][i]);
575- debug_assert!(a >= 2 * stride && a + stride < plane.len());610+ let p0 = i32::from(px[1][i]);
576- let p1 = i32::from(plane[a - 2 * stride]);611+ let q0 = i32::from(px[2][i]);
577- let p0 = i32::from(plane[a - stride]);612+ let q1 = i32::from(px[3][i]);
578- let q0 = i32::from(plane[a]);
579- let q1 = i32::from(plane[a + stride]);
580 if simple_threshold(p1, p0, q0, q1, limit) {613 if simple_threshold(p1, p0, q0, q1, limit) {
581 let f = filter_common(p1, p0, q0, q1, true);614 let f = filter_common(p1, p0, q0, q1, true);
582- plane[a - stride] = f[1] as u8;615+ plane[anchor - stride + i] = f[1] as u8;
583- plane[a] = f[2] as u8;616+ plane[anchor + i] = f[2] as u8;
584 }617 }
585 }618 }
586 }619 }
crates/ec-vp8/src/mc.rsmodified+463 -25
@@ -21,6 +21,7 @@
21 //! are reproduced exactly (`i32 >> 3` and `& 7` on negatives).21 //! are reproduced exactly (`i32 >> 3` and `& 7` on negatives).
22 //!22 //!
23 //! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc638623 //! [RFC 6386]: https://www.rfc-editor.org/rfc/rfc6386
24+use crate::avx2_supported;
24 25
25 /// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes.26 /// `VP8_FILTER_WEIGHT` (filter.c): tap weights sum to this, DC passes.
26 const VP8_FILTER_WEIGHT: i32 = 128;27 const VP8_FILTER_WEIGHT: i32 = 128;
@@ -154,6 +155,13 @@ pub(crate) fn predict_luma(
154 /// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*,155 /// Six-tap separable sub-pel predictor (libvpx vp8_sixtap_predict*,
155 /// filter.c). `(sx, sy)` is the full-pel block origin in the bordered156 /// filter.c). `(sx, sy)` is the full-pel block origin in the bordered
156 /// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy).157 /// reference, `(fx, fy)` the sub-pel phases 0..7 (0 = copy).
158+///
159+/// Both passes share one clamped intermediate buffer: the first pass is
160+/// clamped to 0..=255 per pass (libvpx `clamp_pixel`), so it is stored as
161+/// `u8` at a fixed 16-lane stride. The AVX2 kernels always compute all 16
162+/// lanes of an intermediate row (reads stay inside the 32-px border for
163+/// every block shape) and the vertical pass discards the tail lanes with
164+/// its `bw`-byte store; the scalar reference only fills the first `bw`.
157 fn sixtap_block(165 fn sixtap_block(
158 src: &[u8],166 src: &[u8],
159 stride: usize,167 stride: usize,
@@ -177,13 +185,44 @@ fn sixtap_block(
177 185
178 let hf = &SUB_PEL_FILTERS[fx];186 let hf = &SUB_PEL_FILTERS[fx];
179 let vf = &SUB_PEL_FILTERS[fy];187 let vf = &SUB_PEL_FILTERS[fy];
188+ let rows = bh + 5;
189+ let mut tmp = [0u8; 21 * 16]; // C: int FData[21 * 24], clamped to u8
190+
191+ #[cfg(target_arch = "x86_64")]
192+ {
193+ if avx2_supported() {
194+ // SAFETY: AVX2 availability checked by `avx2_supported` just
195+ // above; the border/bounds contracts of both kernels hold for
196+ // every caller (`bw`/`bh` in 4..=16, bordered source plane).
197+ #[allow(unsafe_code)]
198+ unsafe {
199+ simd::sixtap_h(src, stride, sx, sy, hf, &mut tmp, rows);
200+ simd::sixtap_v(&tmp, vf, dst, dst_stride, bw, bh);
201+ }
202+ return;
203+ }
204+ }
180 205
181- // filter.c filter_block2d_first_pass on `src - 2*stride`: `bh + 5`206+ sixtap_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows);
182- // horizontal lines (2 above the block, 3 below, for the vertical taps).207+ sixtap_v_scalar(&tmp, vf, dst, dst_stride, bw, bh);
183- // Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the208+}
184- // uniform loop reproduces the C for every phase combination.209+
185- let mut tmp = [0i32; 21 * 16]; // C: int FData[21 * 24]210+/// Scalar first pass of [`sixtap_block`] (filter.c
186- for i in 0..bh + 5 {211+/// `filter_block2d_first_pass` on `src - 2*stride`): `rows` = `bh + 5`
212+/// horizontal lines, each sample `(dot + 64) >> 7` clamped to 0..=255.
213+/// Phase 0 is the exact identity (`(p * 128 + 64) >> 7 == p`), so the
214+/// uniform loop reproduces the C for every phase combination.
215+fn sixtap_h_scalar(
216+ src: &[u8],
217+ stride: usize,
218+ sx: usize,
219+ sy: usize,
220+ hf: &[i32; 6],
221+ tmp: &mut [u8; 21 * 16],
222+ bw: usize,
223+ rows: usize,
224+) {
225+ for i in 0..rows {
187 let row = (sy + i - 2) * stride + sx - 2;226 let row = (sy + i - 2) * stride + sx - 2;
188 for j in 0..bw {227 for j in 0..bw {
189 let p = row + j;228 let p = row + j;
@@ -194,30 +233,269 @@ fn sixtap_block(
194 + i32::from(src[p + 4]) * hf[4]233 + i32::from(src[p + 4]) * hf[4]
195 + i32::from(src[p + 5]) * hf[5]234 + i32::from(src[p + 5]) * hf[5]
196 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */235 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
197- tmp[i * bw + j] = clamp255(acc >> VP8_FILTER_SHIFT);236+ tmp[i * 16 + j] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;
198 }237 }
199 }238 }
239+}
200 240
201- // filter.c filter_block2d_second_pass on `FData + 2*bw`: taps read the241+/// Scalar second pass of [`sixtap_block`] (filter.c
202- // intermediate rows `r .. r + 5`.242+/// `filter_block2d_second_pass` on `FData + 2*bw`): taps read the
243+/// intermediate rows `r .. r + 5` at the fixed 16-lane stride.
244+fn sixtap_v_scalar(
245+ tmp: &[u8; 21 * 16],
246+ vf: &[i32; 6],
247+ dst: &mut [u8],
248+ dst_stride: usize,
249+ bw: usize,
250+ bh: usize,
251+) {
203 for r in 0..bh {252 for r in 0..bh {
204 for c in 0..bw {253 for c in 0..bw {
205- let acc = tmp[r * bw + c] * vf[0]254+ let acc = i32::from(tmp[r * 16 + c]) * vf[0]
206- + tmp[(r + 1) * bw + c] * vf[1]255+ + i32::from(tmp[(r + 1) * 16 + c]) * vf[1]
207- + tmp[(r + 2) * bw + c] * vf[2]256+ + i32::from(tmp[(r + 2) * 16 + c]) * vf[2]
208- + tmp[(r + 3) * bw + c] * vf[3]257+ + i32::from(tmp[(r + 3) * 16 + c]) * vf[3]
209- + tmp[(r + 4) * bw + c] * vf[4]258+ + i32::from(tmp[(r + 4) * 16 + c]) * vf[4]
210- + tmp[(r + 5) * bw + c] * vf[5]259+ + i32::from(tmp[(r + 5) * 16 + c]) * vf[5]
211 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */260 + (VP8_FILTER_WEIGHT >> 1); /* Rounding */
212 dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;261 dst[r * dst_stride + c] = clamp255(acc >> VP8_FILTER_SHIFT) as u8;
213 }262 }
214 }263 }
215 }264 }
216 265
266+/// Explicit `std::arch::x86_64` kernels for the six-tap and bilinear
267+/// passes (the 18% of a decode the profile pins on `sixtap_block` and its
268+/// chroma siblings). Nothing here is spec logic: each kernel is the scalar
269+/// function's arithmetic lane-parallel, with the same rounding, the same
270+/// truncation points and the same clamps -- the equivalence tests run
271+/// every kernel against its scalar reference over all shapes, phases and
272+/// worst-case input bytes.
273+///
274+/// Exactness notes shared by the six-tap kernels:
275+/// - `_mm*_madd_epi16` multiplies *pairs of samples* by a packed tap pair
276+/// and accumulates in `i32`; every product is exact (widened samples
277+/// are 0..=255, `|byte * tap| <= 255 * 128 < 2^15`) and the six-product
278+/// sum is exact in `i32` (`|dot + 64| <= 255 * 160 + 64 < 2^23`).
279+/// - The even/odd column split exists because `madd` pairs *adjacent*
280+/// samples: the even accumulator's `madd` lane m is output `2m`, the
281+/// odd one output `2m+1` (load offset +1 shifts the sample window).
282+/// - `packs_epi32`'s `i32 -> i16` saturation can never fire: after
283+/// `(dot + 64) >> 7` the range is `[-76, 319]`.
284+/// - `packus_epi16`'s `u8` saturation *is* filter.c's `clamp_pixel`:
285+/// values below 0 saturate to 0, above 255 to 255, the rest unchanged.
286+#[cfg(target_arch = "x86_64")]
287+#[allow(unsafe_code)]
288+#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
289+mod simd {
290+ use super::{VP8_FILTER_SHIFT, VP8_FILTER_WEIGHT};
291+ use std::arch::x86_64::*;
292+
293+ /// Tap pair `[t0, t1]` packed into one `i32`, the operand shape
294+ /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))`
295+ /// is `s[2j] * t0 + s[2j+1] * t1` (ec-av1 `mc::simd::tap_pairs`).
296+ #[inline]
297+ fn tap_pair(a: i32, b: i32) -> i32 {
298+ (b << 16) | (a as u16 as i32)
299+ }
300+
301+ /// Six-tap first pass, all 16 lanes of every intermediate row (see
302+ /// [`sixtap_block`] for the layout).
303+ ///
304+ /// # Safety
305+ /// Requires AVX2. `src` must be a bordered MC plane such that for
306+ /// every `i < rows`, the 21 bytes starting at
307+ /// `(sy + i - 2) * stride + sx - 2` are in bounds (`sx, sy >= 2`).
308+ #[target_feature(enable = "avx2")]
309+ pub(super) unsafe fn sixtap_h(
310+ src: &[u8],
311+ stride: usize,
312+ sx: usize,
313+ sy: usize,
314+ hf: &[i32; 6],
315+ tmp: &mut [u8; 21 * 16],
316+ rows: usize,
317+ ) {
318+ debug_assert!(sx >= 2 && sy >= 2);
319+ debug_assert!((sy + rows - 2) * stride + sx + 19 <= src.len());
320+ let tv = [
321+ _mm256_set1_epi32(tap_pair(hf[0], hf[1])),
322+ _mm256_set1_epi32(tap_pair(hf[2], hf[3])),
323+ _mm256_set1_epi32(tap_pair(hf[4], hf[5])),
324+ ];
325+ let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1);
326+ for i in 0..rows {
327+ let sp = src.as_ptr().add((sy + i - 2) * stride + sx - 2);
328+ // `cvtepu8_epi16` of the 16-byte window at byte offset `2k`
329+ // puts each even output's tap pair in one `madd` lane pair:
330+ // `e` accumulates outputs 0,2,..,14, `o` (window +1 byte)
331+ // outputs 1,3,..,15.
332+ let mut e = _mm256_setzero_si256();
333+ let mut o = _mm256_setzero_si256();
334+ for k in 0..3 {
335+ let se = _mm256_cvtepu8_epi16(_mm_loadu_si128(sp.add(2 * k).cast()));
336+ e = _mm256_add_epi32(e, _mm256_madd_epi16(se, tv[k]));
337+ let so = _mm256_cvtepu8_epi16(_mm_loadu_si128(sp.add(2 * k + 1).cast()));
338+ o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
339+ }
340+ e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), VP8_FILTER_SHIFT);
341+ o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), VP8_FILTER_SHIFT);
342+ // `unpacklo/hi` + `packs` interleave even/odd outputs back in
343+ // order (0..8 in the low 128-bit half, 8..16 in the high
344+ // half), then `packus` narrows both halves in sequence -- its
345+ // `u8` saturation is filter.c's `clamp_pixel` itself.
346+ let lo = _mm256_unpacklo_epi32(e, o);
347+ let hi = _mm256_unpackhi_epi32(e, o);
348+ let i16 = _mm256_packs_epi32(lo, hi);
349+ let u8 = _mm_packus_epi16(
350+ _mm256_castsi256_si128(i16),
351+ _mm256_extracti128_si256::<1>(i16),
352+ );
353+ _mm_storeu_si128(tmp.as_mut_ptr().add(i * 16).cast(), u8);
354+ }
355+ }
356+
357+ /// Six-tap second pass: `bh` output rows of `bw` (4/8/16) samples from
358+ /// the 16-lane-strided intermediate.
359+ ///
360+ /// # Safety
361+ /// Requires AVX2. `dst` must be writable for `bh` rows of `bw` bytes
362+ /// at `dst_stride`; `bw` is 4, 8 or 16.
363+ #[target_feature(enable = "avx2")]
364+ pub(super) unsafe fn sixtap_v(
365+ tmp: &[u8; 21 * 16],
366+ vf: &[i32; 6],
367+ dst: &mut [u8],
368+ dst_stride: usize,
369+ bw: usize,
370+ bh: usize,
371+ ) {
372+ debug_assert!(matches!(bw, 4 | 8 | 16));
373+ debug_assert!(dst.len() >= (bh - 1) * dst_stride + bw);
374+ let tv = [
375+ _mm256_set1_epi32(tap_pair(vf[0], vf[1])),
376+ _mm256_set1_epi32(tap_pair(vf[2], vf[3])),
377+ _mm256_set1_epi32(tap_pair(vf[4], vf[5])),
378+ ];
379+ let rnd = _mm256_set1_epi32(VP8_FILTER_WEIGHT >> 1);
380+ for r in 0..bh {
381+ let ip = tmp.as_ptr().add(r * 16);
382+ // Rows `r + 2k` / `r + 2k + 1` widened to samples, interleaved
383+ // by `unpack_epi16` so one `madd` covers two taps of every
384+ // output; `lo` holds even columns, `hi` odd ones (one run per
385+ // 128-bit lane).
386+ let mut lo = _mm256_setzero_si256();
387+ let mut hi = _mm256_setzero_si256();
388+ for k in 0..3 {
389+ let a = _mm256_cvtepu8_epi16(_mm_loadu_si128(ip.add(2 * k * 16).cast()));
390+ let b = _mm256_cvtepu8_epi16(_mm_loadu_si128(ip.add((2 * k + 1) * 16).cast()));
391+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv[k]));
392+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv[k]));
393+ }
394+ lo = _mm256_srai_epi32(_mm256_add_epi32(lo, rnd), VP8_FILTER_SHIFT);
395+ hi = _mm256_srai_epi32(_mm256_add_epi32(hi, rnd), VP8_FILTER_SHIFT);
396+ // `packs` reorders to outputs 0..8 | 8..16 across the two
397+ // 128-bit halves, in column order.
398+ let i16 = _mm256_packs_epi32(lo, hi);
399+ let u8 = _mm_packus_epi16(
400+ _mm256_castsi256_si128(i16),
401+ _mm256_extracti128_si256::<1>(i16),
402+ );
403+ let dp = dst.as_mut_ptr().add(r * dst_stride);
404+ match bw {
405+ 16 => _mm_storeu_si128(dp.cast(), u8),
406+ 8 => _mm_storel_epi64(dp.cast(), u8),
407+ 4 => _mm_storeu_si32(dp.cast(), u8),
408+ _ => unreachable!("bw is 4, 8 or 16"),
409+ }
410+ }
411+ }
412+
413+ /// Bilinear first pass, 8 output columns per step (`bw` is 4, 8 or
414+ /// 16; `bw = 16` runs the loop twice). The `i16` accumulator is exact:
415+ /// taps are non-negative and sum to 128, so every product and the sum
416+ /// stay `<= 255 * 128 + 64 < 2^15` -- this *is* the C's `unsigned
417+ /// short` intermediate, narrowed at a provably-in-range point.
418+ ///
419+ /// # Safety
420+ /// Requires AVX2. For every `i < rows`, the 17 bytes starting at
421+ /// `(sy + i) * stride + sx` must be in bounds of `src`.
422+ #[target_feature(enable = "avx2")]
423+ pub(super) unsafe fn bilinear_h(
424+ src: &[u8],
425+ stride: usize,
426+ sx: usize,
427+ sy: usize,
428+ hf: &[i32; 2],
429+ tmp: &mut [u8; 17 * 16],
430+ rows: usize,
431+ ) {
432+ debug_assert!((sy + rows - 1) * stride + sx + 16 < src.len());
433+ let f0 = _mm_set1_epi16(hf[0] as i16);
434+ let f1 = _mm_set1_epi16(hf[1] as i16);
435+ let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16);
436+ for i in 0..rows {
437+ let sp = src.as_ptr().add((sy + i) * stride + sx);
438+ for c in (0..16).step_by(8) {
439+ // Lane j pairs the samples `j` and `j + 1` (tap `[0]` on
440+ // the window at `c`, tap `[1]` shifted by one byte).
441+ let a = _mm_cvtepu8_epi16(_mm_loadu_si128(sp.add(c).cast()));
442+ let b = _mm_cvtepu8_epi16(_mm_loadu_si128(sp.add(c + 1).cast()));
443+ let acc = _mm_add_epi16(
444+ _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)),
445+ rnd,
446+ );
447+ let u8 = _mm_packus_epi16(_mm_srai_epi16::<VP8_FILTER_SHIFT>(acc), acc);
448+ _mm_storel_epi64(tmp.as_mut_ptr().add(i * 16 + c).cast(), u8);
449+ }
450+ }
451+ }
452+
453+ /// Bilinear second pass: rows `r` / `r + 1` of the intermediate, same
454+ /// exact-`i16` shape as [`bilinear_h`].
455+ ///
456+ /// # Safety
457+ /// Requires AVX2. `dst` must be writable for `bh` rows of `bw` bytes
458+ /// at `dst_stride`; `bw` is 4, 8 or 16.
459+ #[target_feature(enable = "avx2")]
460+ pub(super) unsafe fn bilinear_v(
461+ tmp: &[u8; 17 * 16],
462+ vf: &[i32; 2],
463+ dst: &mut [u8],
464+ dst_stride: usize,
465+ bw: usize,
466+ bh: usize,
467+ ) {
468+ debug_assert!(matches!(bw, 4 | 8 | 16));
469+ debug_assert!(dst.len() >= (bh - 1) * dst_stride + bw);
470+ let f0 = _mm_set1_epi16(vf[0] as i16);
471+ let f1 = _mm_set1_epi16(vf[1] as i16);
472+ let rnd = _mm_set1_epi16((VP8_FILTER_WEIGHT / 2) as i16);
473+ for r in 0..bh {
474+ let ip = tmp.as_ptr().add(r * 16);
475+ let dp = dst.as_mut_ptr().add(r * dst_stride);
476+ for c in (0..bw).step_by(8) {
477+ let a = _mm_cvtepu8_epi16(_mm_loadl_epi64(ip.add(c).cast()));
478+ let b = _mm_cvtepu8_epi16(_mm_loadl_epi64(ip.add(16 + c).cast()));
479+ let acc = _mm_add_epi16(
480+ _mm_add_epi16(_mm_mullo_epi16(a, f0), _mm_mullo_epi16(b, f1)),
481+ rnd,
482+ );
483+ let u8 = _mm_packus_epi16(_mm_srai_epi16::<VP8_FILTER_SHIFT>(acc), acc);
484+ match bw - c {
485+ 8 | 16 => _mm_storel_epi64(dp.add(c).cast(), u8),
486+ _ => _mm_storeu_si32(dp.add(c).cast(), u8),
487+ }
488+ }
489+ }
490+ }
491+}
492+
217 /// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*,493 /// Two-tap bilinear separable predictor (libvpx vp8_bilinear_predict*,
218 /// filter.c). The dot products are provably in 0..=255 (taps are494 /// filter.c). The dot products are provably in 0..=255 (taps are
219 /// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's495 /// non-negative and sum to 128 over 0..=255 inputs), which is why libvpx's
220-/// bilinear passes store `unsigned short` intermediates and skip the clamp.496+/// bilinear passes store `unsigned short` intermediates and skip the
497+/// clamp: the intermediate is stored as `u8` at a fixed 16-lane stride
498+/// (representation-only change, same argument as [`sixtap_block`]).
221 fn bilinear_block(499 fn bilinear_block(
222 src: &[u8],500 src: &[u8],
223 stride: usize,501 stride: usize,
@@ -240,26 +518,66 @@ fn bilinear_block(
240 518
241 let hf = &BILINEAR_FILTERS[fx];519 let hf = &BILINEAR_FILTERS[fx];
242 let vf = &BILINEAR_FILTERS[fy];520 let vf = &BILINEAR_FILTERS[fy];
521+ let rows = bh + 1;
522+ let mut tmp = [0u8; 17 * 16]; // C: unsigned short FData[17 * 16], <= 255
243 523
244- // filter.c filter_block2d_bil_first_pass: `bh + 1` rows, horizontal524+ #[cfg(target_arch = "x86_64")]
245- // taps [0] and [1]. Phase 0 is the exact identity, as above.525+ {
246- let mut tmp = [0u16; 17 * 16]; // C: unsigned short FData[17 * 16]526+ if avx2_supported() {
247- for i in 0..bh + 1 {527+ // SAFETY: AVX2 checked by `avx2_supported`; border/bounds
528+ // contracts hold for every caller (see [`sixtap_block`]).
529+ #[allow(unsafe_code)] // SAFETY: avx2_supported() checked above
530+ unsafe {
531+ simd::bilinear_h(src, stride, sx, sy, hf, &mut tmp, rows);
532+ simd::bilinear_v(&tmp, vf, dst, dst_stride, bw, bh);
533+ }
534+ return;
535+ }
536+ }
537+
538+ bilinear_h_scalar(src, stride, sx, sy, hf, &mut tmp, bw, rows);
539+ bilinear_v_scalar(&tmp, vf, dst, dst_stride, bw, bh);
540+}
541+
542+/// Scalar first pass of [`bilinear_block`] (filter.c
543+/// `filter_block2d_bil_first_pass`): `bh + 1` rows, taps `[0]` and `[1]`.
544+/// Phase 0 is the exact identity, as in [`sixtap_h_scalar`].
545+fn bilinear_h_scalar(
546+ src: &[u8],
547+ stride: usize,
548+ sx: usize,
549+ sy: usize,
550+ hf: &[i32; 2],
551+ tmp: &mut [u8; 17 * 16],
552+ bw: usize,
553+ rows: usize,
554+) {
555+ for i in 0..rows {
248 let row = (sy + i) * stride + sx;556 let row = (sy + i) * stride + sx;
249 for j in 0..bw {557 for j in 0..bw {
250 let p = row + j;558 let p = row + j;
251 let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1]559 let acc = i32::from(src[p]) * hf[0] + i32::from(src[p + 1]) * hf[1]
252 + (VP8_FILTER_WEIGHT / 2); /* Rounding */560 + (VP8_FILTER_WEIGHT / 2); /* Rounding */
253- tmp[i * bw + j] = (acc >> VP8_FILTER_SHIFT) as u16;561+ tmp[i * 16 + j] = (acc >> VP8_FILTER_SHIFT) as u8;
254 }562 }
255 }563 }
564+}
256 565
257- // filter.c filter_block2d_bil_second_pass: vertical taps [0] and566+/// Scalar second pass of [`bilinear_block`] (filter.c
258- // `[width]` (the next intermediate row).567+/// `filter_block2d_bil_second_pass`): taps `[0]` and `[1]` read rows
568+/// `r` / `r + 1` of the intermediate at the fixed 16-lane stride.
569+fn bilinear_v_scalar(
570+ tmp: &[u8; 17 * 16],
571+ vf: &[i32; 2],
572+ dst: &mut [u8],
573+ dst_stride: usize,
574+ bw: usize,
575+ bh: usize,
576+) {
259 for r in 0..bh {577 for r in 0..bh {
260 for c in 0..bw {578 for c in 0..bw {
261- let acc = i32::from(tmp[r * bw + c]) * vf[0]579+ let acc = i32::from(tmp[r * 16 + c]) * vf[0]
262- + i32::from(tmp[(r + 1) * bw + c]) * vf[1]580+ + i32::from(tmp[(r + 1) * 16 + c]) * vf[1]
263 + (VP8_FILTER_WEIGHT / 2); /* Rounding */581 + (VP8_FILTER_WEIGHT / 2); /* Rounding */
264 dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8;582 dst[r * dst_stride + c] = (acc >> VP8_FILTER_SHIFT) as u8;
265 }583 }
@@ -760,4 +1078,124 @@ mod tests {
760 );1078 );
761 assert_eq!(a, b);1079 assert_eq!(a, b);
762 }1080 }
1081+
1082+ /// Fills a bordered plane with a 0x00/0xFF checkerboard: maximizes the
1083+ /// six-tap dot products' excursions in both directions (negative taps
1084+ /// over 0xFF while positive taps sit on 0x00 and vice versa), so the
1085+ /// clamp/saturation paths of both implementations are exercised.
1086+ fn checkerboard_plane() -> Vec<u8> {
1087+ let mut out = vec![0u8; STRIDE * ROWS];
1088+ for r in 0..ROWS {
1089+ for c in 0..STRIDE {
1090+ out[r * STRIDE + c] = if (r + c) & 1 == 0 { 0xFF } else { 0x00 };
1091+ }
1092+ }
1093+ out
1094+ }
1095+
1096+ /// The AVX2 kernels must be lane-for-lane identical to the scalar
1097+ /// reference (the libvpx transcription) on every block shape, every
1098+ /// phase pair, at both a central and a right/bottom-edge origin where
1099+ /// the wide loads reach furthest into the border.
1100+ #[test]
1101+ #[cfg(target_arch = "x86_64")]
1102+ fn simd_sixtap_matches_the_scalar_reference_everywhere() {
1103+ if !avx2_supported() {
1104+ return;
1105+ }
1106+ let planes = [plane(), checkerboard_plane()];
1107+ let origins = [
1108+ (BORDER + 2, BORDER + 3),
1109+ (BORDER + VIS_W - 16, BORDER + VIS_H - 16),
1110+ ];
1111+ for p in &planes {
1112+ for &(sx, sy) in &origins {
1113+ for bw in [4usize, 8, 16] {
1114+ for bh in [4usize, 8, 16] {
1115+ for fx in 0..8usize {
1116+ for fy in 0..8usize {
1117+ if fx == 0 && fy == 0 {
1118+ continue; // whole-pel copy, shared path
1119+ }
1120+ let mut want = [0u8; 16 * 16];
1121+ let mut got = [0u8; 16 * 16];
1122+ let mut tmp = [0u8; 21 * 16];
1123+ sixtap_h_scalar(
1124+ p, STRIDE, sx, sy, &SUB_PEL_FILTERS[fx], &mut tmp, bw, bh + 5,
1125+ );
1126+ sixtap_v_scalar(&tmp, &SUB_PEL_FILTERS[fy], &mut want, 16, bw, bh);
1127+ // SAFETY: avx2_supported() checked above.
1128+ #[allow(unsafe_code)]
1129+ unsafe {
1130+ let mut tmp2 = [0u8; 21 * 16];
1131+ simd::sixtap_h(
1132+ p, STRIDE, sx, sy, &SUB_PEL_FILTERS[fx], &mut tmp2, bh + 5,
1133+ );
1134+ simd::sixtap_v(&tmp2, &SUB_PEL_FILTERS[fy], &mut got, 16, bw, bh);
1135+ }
1136+ let n = bh * 16;
1137+ assert_eq!(
1138+ &got[..n],
1139+ &want[..n],
1140+ "sixtap bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy})"
1141+ );
1142+ }
1143+ }
1144+ }
1145+ }
1146+ }
1147+ }
1148+ }
1149+
1150+ /// Same gate for the bilinear kernels.
1151+ #[test]
1152+ #[cfg(target_arch = "x86_64")]
1153+ fn simd_bilinear_matches_the_scalar_reference_everywhere() {
1154+ if !avx2_supported() {
1155+ return;
1156+ }
1157+ let planes = [plane(), checkerboard_plane()];
1158+ let origins = [
1159+ (BORDER + 2, BORDER + 3),
1160+ (BORDER + VIS_W - 16, BORDER + VIS_H - 16),
1161+ ];
1162+ for p in &planes {
1163+ for &(sx, sy) in &origins {
1164+ for bw in [4usize, 8, 16] {
1165+ for bh in [4usize, 8, 16] {
1166+ for fx in 0..8usize {
1167+ for fy in 0..8usize {
1168+ if fx == 0 && fy == 0 {
1169+ continue;
1170+ }
1171+ let mut want = [0u8; 16 * 16];
1172+ let mut got = [0u8; 16 * 16];
1173+ let mut tmp = [0u8; 17 * 16];
1174+ bilinear_h_scalar(
1175+ p, STRIDE, sx, sy, &BILINEAR_FILTERS[fx], &mut tmp, bw, bh + 1,
1176+ );
1177+ bilinear_v_scalar(&tmp, &BILINEAR_FILTERS[fy], &mut want, 16, bw, bh);
1178+ // SAFETY: avx2_supported() checked above.
1179+ #[allow(unsafe_code)]
1180+ unsafe {
1181+ let mut tmp2 = [0u8; 17 * 16];
1182+ simd::bilinear_h(
1183+ p, STRIDE, sx, sy, &BILINEAR_FILTERS[fx], &mut tmp2, bh + 1,
1184+ );
1185+ simd::bilinear_v(&tmp2, &BILINEAR_FILTERS[fy], &mut got, 16, bw, bh);
1186+ }
1187+ for r in 0..bh {
1188+ assert_eq!(
1189+ got[r * 16..r * 16 + bw],
1190+ want[r * 16..r * 16 + bw],
1191+ "bilinear bw={bw} bh={bh} fx={fx} fy={fy} origin=({sx},{sy}) row={r}"
1192+ );
1193+ }
1194+ }
1195+ }
1196+ }
1197+ }
1198+ }
1199+ }
1200+ }
763 }1201 }
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;