forge
Explore
Log in

Don't you dare go Hollow

AVX2 CDEF filter -- 4K decode 47.1 s -> 41.2 s

Browse files at this commit

e2f820ed4e4d262eb779404f18e6f208230ec3bfAhmet Kaan GümüşParent: fb5fc2e
  • perf
    • AVX2 CDEF filter -- 4K decode 47.1 s -> 41.2 s
Show full message
perf(av1): AVX2 CDEF filter -- 4K decode 47.1 s -> 41.2 s

`cdef_filter_block` was 13.1% of a 4K decode's self time: a scalar loop
doing ~17 bounds-checked window reads, four `constrain` calls and a
min/max clamp per output sample.

The kernel does the same arithmetic 16 samples (two rows) at a time in
16-bit AVX2 lanes -- the same primary/secondary taps, the same
`sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)` (one
`_mm256_sign_epi16` reproduces `signum`, zero included), the same
exclusion of the `CDEF_VERY_LARGE` out-of-frame sentinel from the max
clamp (masking it to 0 cannot win a max seeded with a non-negative
sample), and the same `x + ((8 + sum - (sum < 0)) >> 4)` rounding.
16-bit lanes are exact for every value the filter sees: window samples
are in [0, 0x4000], so a tap difference fits in `i16` and the
tap-weighted sum is bounded by 24 * the threshold (at most 15 << 4).

The scalar form stays the reference (`cdef_filter_block_scalar`, the
only path on non-x86_64 and pre-AVX2 CPUs) and
`cdef_simd_kernel_matches_the_scalar_filter` pins the pair over the
whole domain: both block shapes, all 8 directions, every enable pair,
the 8/10/12-bit strength/damping ranges and windows that mix real
samples with sentinel borders.

Byte-exact on all four gate inputs (seg1080, seg4k, seg4k_lr, palette).
seg4k interleaved medians 3x: 47.08 s -> 41.23 s (-12.4%, 5.78 ->
6.60 fps); 1080p 11.00 -> 10.95 s.
crates/ec-av1/src/decode.rsmodified+363 -2
@@ -14234,6 +14234,7 @@ fn cdef_adjust_strength(strength: i32, var: i32) -> i32 {
14234 /// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a14234 /// chroma) in place, `sample(row, col)` reading the *unfiltered* frame (a
14235 /// previously-filtered neighbour must never feed this block's own sum).14235 /// previously-filtered neighbour must never feed this block's own sum).
14236 #[allow(clippy::too_many_arguments)]14236 #[allow(clippy::too_many_arguments)]
14237+#[allow(unsafe_code)]
14237 fn cdef_filter_block(14238 fn cdef_filter_block(
14238 src: &[i32],14239 src: &[i32],
14239 dst: &mut PlaneBuf,14240 dst: &mut PlaneBuf,
@@ -14249,6 +14250,77 @@ fn cdef_filter_block(
14249 enable_primary: bool,14250 enable_primary: bool,
14250 enable_secondary: bool,14251 enable_secondary: bool,
14251 coeff_shift: i32,14252 coeff_shift: i32,
14253+) {
14254+ let (stride, smax) = (dst.width, sample_max());
14255+ #[cfg(target_arch = "x86_64")]
14256+ if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 && (bw == 4 || bw == 8) && bh % 2 == 0
14257+ {
14258+ // SAFETY: reached only when the CPU reports avx2; the kernel reads
14259+ // `src`'s whole (bw + 4) x (bh + 4) window and writes exactly the
14260+ // `bh` runs of `bw` samples the scalar form writes.
14261+ unsafe {
14262+ cdef_simd::filter_block_avx2(
14263+ src,
14264+ &mut dst.data,
14265+ stride,
14266+ ox,
14267+ oy,
14268+ bw,
14269+ bh,
14270+ pri_strength,
14271+ sec_strength,
14272+ dir,
14273+ pri_damping,
14274+ sec_damping,
14275+ enable_primary,
14276+ enable_secondary,
14277+ coeff_shift,
14278+ smax,
14279+ )
14280+ };
14281+ return;
14282+ }
14283+ cdef_filter_block_scalar(
14284+ src,
14285+ &mut dst.data,
14286+ stride,
14287+ ox,
14288+ oy,
14289+ bw,
14290+ bh,
14291+ pri_strength,
14292+ sec_strength,
14293+ dir,
14294+ pri_damping,
14295+ sec_damping,
14296+ enable_primary,
14297+ enable_secondary,
14298+ coeff_shift,
14299+ smax,
14300+ );
14301+}
14302+
14303+/// [`cdef_filter_block`]'s scalar reference: spec 7.15.3 sample by sample,
14304+/// the form every non-AVX2 build decodes through and the one
14305+/// `cdef_simd_kernel_matches_the_scalar_filter` checks the kernel against.
14306+#[allow(clippy::too_many_arguments)]
14307+fn cdef_filter_block_scalar(
14308+ src: &[i32],
14309+ dst: &mut [u16],
14310+ stride: usize,
14311+ ox: usize,
14312+ oy: usize,
14313+ bw: usize,
14314+ bh: usize,
14315+ pri_strength: i32,
14316+ sec_strength: i32,
14317+ dir: usize,
14318+ pri_damping: i32,
14319+ sec_damping: i32,
14320+ enable_primary: bool,
14321+ enable_secondary: bool,
14322+ coeff_shift: i32,
14323+ smax: i32,
14252 ) {14324 ) {
14253 let clipping_required = enable_primary && enable_secondary;14325 let clipping_required = enable_primary && enable_secondary;
14254 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>14326 // libaom `cdef_filter_block_internal`: `cdef_pri_taps[(pri_strength >>
@@ -14261,7 +14333,6 @@ fn cdef_filter_block(
14261 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);14333 let pri_shift = cdef_constrain_shift(pri_strength.max(1), pri_damping);
14262 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);14334 let sec_shift = cdef_constrain_shift(sec_strength.max(1), sec_damping);
14263 let bstride = bw + 2 * CDEF_BORDER;14335 let bstride = bw + 2 * CDEF_BORDER;
14264- let smax = sample_max();
14265 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps14336 // `src` is [`cdef_gather`]'s window: (i, j) in block coordinates, taps
14266 // reaching +-CDEF_BORDER, so every index below is in range by construction.14337 // reaching +-CDEF_BORDER, so every index below is in range by construction.
14267 let at = |i: i32, j: i32| -> i32 {14338 let at = |i: i32, j: i32| -> i32 {
@@ -14319,7 +14390,213 @@ fn cdef_filter_block(
14319 if clipping_required {14390 if clipping_required {
14320 y = y.clamp(min, max);14391 y = y.clamp(min, max);
14321 }14392 }
14322- dst.data[(oy + i) * dst.width + (ox + j)] = y.clamp(0, smax) as u16;14393+ dst[(oy + i) * stride + (ox + j)] = y.clamp(0, smax) as u16;
14394+ }
14395+ }
14396+}
14397+
14398+/// lane-perf7 step 1: [`cdef_filter_block`]'s AVX2 kernel -- the scalar
14399+/// filter was 13.1% of a 4K decode's self time. Nothing here is spec logic:
14400+/// the same taps, the same `constrain`, the same `min`/`max` clamp with the
14401+/// `CDEF_VERY_LARGE` sentinel excluded from the max, the same
14402+/// `y + ((8 + sum - (sum < 0)) >> 4)` rounding, done 16 samples (two rows) at
14403+/// a time in 16-bit lanes.
14404+///
14405+/// 16-bit lanes are exact for every value this filter sees: window samples
14406+/// are in `[0, CDEF_VERY_LARGE]` (0x4000), so a tap difference fits in
14407+/// `i16`, a `constrain` result is bounded by the threshold (at most
14408+/// `15 << 4`), and the tap-weighted sum by `24 *` that.
14409+#[cfg(target_arch = "x86_64")]
14410+#[allow(unsafe_code)]
14411+#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
14412+mod cdef_simd {
14413+ use super::{
14414+ cdef_constrain_shift, CDEF_BORDER, CDEF_DIRECTIONS, CDEF_PRI_TAPS, CDEF_SEC_TAPS,
14415+ CDEF_VERY_LARGE,
14416+ };
14417+ use std::arch::x86_64::*;
14418+
14419+ /// The window's rows `i` and `i + 1` at one tap offset, as one 256-bit
14420+ /// register (low half = row `i`).
14421+ ///
14422+ /// # Safety
14423+ /// Requires AVX2; `off + bstride + 8` must be inside `w`.
14424+ #[target_feature(enable = "avx2")]
14425+ #[inline]
14426+ unsafe fn ld2(w: *const i16, off: isize, bstride: isize) -> __m256i {
14427+ let lo = _mm_loadu_si128(w.offset(off).cast());
14428+ let hi = _mm_loadu_si128(w.offset(off + bstride).cast());
14429+ _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1)
14430+ }
14431+
14432+ /// Spec 7.15.3's `constrain`, lane-parallel:
14433+ /// `sign(diff) * clamp(threshold - (|diff| >> shift), 0, |diff|)`.
14434+ /// `_mm256_sign_epi16` reproduces `signum` exactly, zero included (the
14435+ /// clamped magnitude is already 0 where `diff` is).
14436+ ///
14437+ /// # Safety
14438+ /// Requires AVX2.
14439+ #[target_feature(enable = "avx2")]
14440+ #[inline]
14441+ unsafe fn constrain(p: __m256i, x: __m256i, thr: __m256i, shift: __m128i) -> __m256i {
14442+ let diff = _mm256_sub_epi16(p, x);
14443+ let a = _mm256_abs_epi16(diff);
14444+ let t = _mm256_sub_epi16(thr, _mm256_sra_epi16(a, shift));
14445+ let t = _mm256_min_epi16(_mm256_max_epi16(t, _mm256_setzero_si256()), a);
14446+ _mm256_sign_epi16(t, diff)
14447+ }
14448+
14449+ /// [`super::cdef_filter_block_scalar`]'s arithmetic, two rows per
14450+ /// iteration. `bw` is 8 (luma) or 4 (4:2:0 chroma) and `bh` matches; for
14451+ /// `bw == 4` the upper four lanes of each half are window samples read
14452+ /// past the row (never past the buffer -- `w` is padded to 256 entries),
14453+ /// computed and then dropped by the 64-bit store.
14454+ ///
14455+ /// # Safety
14456+ /// Requires AVX2. `src` must hold the `(bw + 4) x (bh + 4)` window and
14457+ /// `dst` the `bh` rows of `bw` samples at `(ox, oy)`.
14458+ #[target_feature(enable = "avx2")]
14459+ #[allow(clippy::too_many_arguments)]
14460+ pub unsafe fn filter_block_avx2(
14461+ src: &[i32],
14462+ dst: &mut [u16],
14463+ stride: usize,
14464+ ox: usize,
14465+ oy: usize,
14466+ bw: usize,
14467+ bh: usize,
14468+ pri_strength: i32,
14469+ sec_strength: i32,
14470+ dir: usize,
14471+ pri_damping: i32,
14472+ sec_damping: i32,
14473+ enable_primary: bool,
14474+ enable_secondary: bool,
14475+ coeff_shift: i32,
14476+ smax: i32,
14477+ ) {
14478+ let bstride = bw + 2 * CDEF_BORDER;
14479+ // The window as `i16`, padded so every two-row tap load stays inside
14480+ // it (largest read: (bh + 3) * bstride + 8 <= 152 for the 8x8 luma
14481+ // block, 72 for the 4x4 chroma one).
14482+ let mut w = [0i16; 256];
14483+ let rows = bh + 2 * CDEF_BORDER;
14484+ for (d, &v) in w[..rows * bstride].iter_mut().zip(&src[..rows * bstride]) {
14485+ *d = v as i16;
14486+ }
14487+ let clipping_required = enable_primary && enable_secondary;
14488+ let pri_taps = CDEF_PRI_TAPS[((pri_strength >> coeff_shift) & 1) as usize];
14489+ let pri_shift = _mm_cvtsi32_si128(cdef_constrain_shift(pri_strength.max(1), pri_damping));
14490+ let sec_shift = _mm_cvtsi32_si128(cdef_constrain_shift(sec_strength.max(1), sec_damping));
14491+ let pri_thr = _mm256_set1_epi16(pri_strength as i16);
14492+ let sec_thr = _mm256_set1_epi16(sec_strength as i16);
14493+ let very_large = _mm256_set1_epi16(CDEF_VERY_LARGE as i16);
14494+ let zero = _mm256_setzero_si256();
14495+ let eight = _mm256_set1_epi16(8);
14496+ let smaxv = _mm256_set1_epi16(smax as i16);
14497+ let (pri_dir, sec_dir0, sec_dir1) =
14498+ (CDEF_DIRECTIONS[dir], CDEF_DIRECTIONS[(dir + 2) & 7], CDEF_DIRECTIONS[(dir + 6) & 7]);
14499+ let wp = w.as_ptr();
14500+ let bs = bstride as isize;
14501+ let dp = dst.as_mut_ptr();
14502+ let mut i = 0usize;
14503+ while i < bh {
14504+ let base = (i + CDEF_BORDER) as isize * bs + CDEF_BORDER as isize;
14505+ let x = ld2(wp, base, bs);
14506+ let mut sum = zero;
14507+ let mut max = x;
14508+ let mut min = x;
14509+ for k in 0..2usize {
14510+ if enable_primary {
14511+ let (tr, tc) = pri_dir[k];
14512+ let off = tr as isize * bs + tc as isize;
14513+ let p0 = ld2(wp, base + off, bs);
14514+ let p1 = ld2(wp, base - off, bs);
14515+ let tap = _mm256_set1_epi16(pri_taps[k] as i16);
14516+ sum = _mm256_add_epi16(
14517+ sum,
14518+ _mm256_mullo_epi16(tap, constrain(p0, x, pri_thr, pri_shift)),
14519+ );
14520+ sum = _mm256_add_epi16(
14521+ sum,
14522+ _mm256_mullo_epi16(tap, constrain(p1, x, pri_thr, pri_shift)),
14523+ );
14524+ if clipping_required {
14525+ // The sentinel is excluded from the max exactly as the
14526+ // scalar `if p != CDEF_VERY_LARGE` does: masking it to
14527+ // 0 cannot win a max whose seed `x` is non-negative.
14528+ max = _mm256_max_epi16(
14529+ max,
14530+ _mm256_andnot_si256(_mm256_cmpeq_epi16(p0, very_large), p0),
14531+ );
14532+ max = _mm256_max_epi16(
14533+ max,
14534+ _mm256_andnot_si256(_mm256_cmpeq_epi16(p1, very_large), p1),
14535+ );
14536+ min = _mm256_min_epi16(min, _mm256_min_epi16(p0, p1));
14537+ }
14538+ }
14539+ if enable_secondary {
14540+ let (tr0, tc0) = sec_dir0[k];
14541+ let (tr1, tc1) = sec_dir1[k];
14542+ let off0 = tr0 as isize * bs + tc0 as isize;
14543+ let off1 = tr1 as isize * bs + tc1 as isize;
14544+ let s0 = ld2(wp, base + off0, bs);
14545+ let s1 = ld2(wp, base - off0, bs);
14546+ let s2 = ld2(wp, base + off1, bs);
14547+ let s3 = ld2(wp, base - off1, bs);
14548+ if clipping_required {
14549+ for s in [s0, s1, s2, s3] {
14550+ max = _mm256_max_epi16(
14551+ max,
14552+ _mm256_andnot_si256(_mm256_cmpeq_epi16(s, very_large), s),
14553+ );
14554+ }
14555+ min = _mm256_min_epi16(
14556+ min,
14557+ _mm256_min_epi16(
14558+ _mm256_min_epi16(s0, s1),
14559+ _mm256_min_epi16(s2, s3),
14560+ ),
14561+ );
14562+ }
14563+ let c = _mm256_add_epi16(
14564+ _mm256_add_epi16(
14565+ constrain(s0, x, sec_thr, sec_shift),
14566+ constrain(s1, x, sec_thr, sec_shift),
14567+ ),
14568+ _mm256_add_epi16(
14569+ constrain(s2, x, sec_thr, sec_shift),
14570+ constrain(s3, x, sec_thr, sec_shift),
14571+ ),
14572+ );
14573+ sum = _mm256_add_epi16(
14574+ sum,
14575+ _mm256_mullo_epi16(_mm256_set1_epi16(CDEF_SEC_TAPS[k] as i16), c),
14576+ );
14577+ }
14578+ }
14579+ // `-1` where `sum < 0`, i.e. the scalar `- i32::from(sum < 0)`.
14580+ let neg = _mm256_cmpgt_epi16(zero, sum);
14581+ let mut y = _mm256_add_epi16(
14582+ x,
14583+ _mm256_srai_epi16(_mm256_add_epi16(_mm256_add_epi16(eight, sum), neg), 4),
14584+ );
14585+ if clipping_required {
14586+ y = _mm256_min_epi16(_mm256_max_epi16(y, min), max);
14587+ }
14588+ y = _mm256_min_epi16(_mm256_max_epi16(y, zero), smaxv);
14589+ let (lo, hi) = (_mm256_castsi256_si128(y), _mm256_extracti128_si256(y, 1));
14590+ let o0 = ((oy + i) * stride + ox) as isize;
14591+ let o1 = o0 + stride as isize;
14592+ if bw == 8 {
14593+ _mm_storeu_si128(dp.offset(o0).cast(), lo);
14594+ _mm_storeu_si128(dp.offset(o1).cast(), hi);
14595+ } else {
14596+ _mm_storel_epi64(dp.offset(o0).cast(), lo);
14597+ _mm_storel_epi64(dp.offset(o1).cast(), hi);
14598+ }
14599+ i += 2;
14323 }14600 }
14324 }14601 }
14325 }14602 }
@@ -31230,6 +31507,90 @@ mod tests {
31230 }31507 }
31231 }31508 }
31232 31509
31510+ /// lane-perf7 step 1: the AVX2 CDEF kernel must be value-identical to
31511+ /// [`super::cdef_filter_block_scalar`] over the whole input domain --
31512+ /// every direction, every enable pair, both block shapes, the 8/10/12-bit
31513+ /// strength and damping ranges, and windows that mix real samples with
31514+ /// the `CDEF_VERY_LARGE` out-of-frame sentinel (which must stay out of
31515+ /// the max clamp).
31516+ #[test]
31517+ #[cfg(target_arch = "x86_64")]
31518+ fn cdef_simd_kernel_matches_the_scalar_filter() {
31519+ if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 {
31520+ eprintln!("SKIP cdef simd: no avx2");
31521+ return;
31522+ }
31523+ let mut rng = 0x1234_5678_9abc_def0u64;
31524+ let mut next = move || {
31525+ rng ^= rng << 13;
31526+ rng ^= rng >> 7;
31527+ rng ^= rng << 17;
31528+ rng
31529+ };
31530+ for &(bit_depth, coeff_shift) in &[(8u8, 0i32), (10, 2), (12, 4)] {
31531+ let smax = (1i32 << bit_depth) - 1;
31532+ for &(bw, bh) in &[(8usize, 8usize), (4, 4)] {
31533+ let bstride = bw + 2 * super::CDEF_BORDER;
31534+ let rows = bh + 2 * super::CDEF_BORDER;
31535+ let stride = bw + 5;
31536+ for trial in 0..64 {
31537+ // Every fourth window seeds sentinels, in a growing
31538+ // border ring, so the straddling-block case is covered.
31539+ let sentinels = trial % 4;
31540+ let win: Vec<i32> = (0..rows * bstride)
31541+ .map(|k| {
31542+ let (r, c) = (k / bstride, k % bstride);
31543+ if sentinels > 0
31544+ && (r < sentinels
31545+ || c < sentinels
31546+ || r + sentinels >= rows
31547+ || c + sentinels >= bstride)
31548+ {
31549+ super::CDEF_VERY_LARGE
31550+ } else {
31551+ (next() % (smax as u64 + 1)) as i32
31552+ }
31553+ })
31554+ .collect();
31555+ for dir in 0..8usize {
31556+ for &pri in &[0i32, 1, 3, 15] {
31557+ for &sec in &[0i32, 1, 2, 4] {
31558+ for &damping in &[3i32, 5, 6, 9] {
31559+ let (pri, sec) = (pri << coeff_shift, sec << coeff_shift);
31560+ let (ep, es) = (pri != 0, sec != 0);
31561+ if !ep && !es {
31562+ continue;
31563+ }
31564+ let seed: Vec<u16> =
31565+ (0..stride * (bh + 2)).map(|k| (k % 97) as u16).collect();
31566+ let mut a = seed.clone();
31567+ let mut b = seed;
31568+ super::cdef_filter_block_scalar(
31569+ &win, &mut a, stride, 1, 1, bw, bh, pri, sec, dir,
31570+ damping, damping, ep, es, coeff_shift, smax,
31571+ );
31572+ // SAFETY: the avx2 arm was probed above.
31573+ #[allow(unsafe_code)]
31574+ unsafe {
31575+ super::cdef_simd::filter_block_avx2(
31576+ &win, &mut b, stride, 1, 1, bw, bh, pri, sec, dir,
31577+ damping, damping, ep, es, coeff_shift, smax,
31578+ )
31579+ };
31580+ assert_eq!(
31581+ a, b,
31582+ "bd={bit_depth} bw={bw} trial={trial} dir={dir} \
31583+ pri={pri} sec={sec} damping={damping}"
31584+ );
31585+ }
31586+ }
31587+ }
31588+ }
31589+ }
31590+ }
31591+ }
31592+ }
31593+
31233 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce31594 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce
31234 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`31595 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`
31235 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue31596 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue