forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-perf8' (2e14ee56): AVX2 deblock over 16 edge lines with per-edge parameter sharing; Wiener restoration reuses the MC passes and resolves stripe substitution per row; byte-exact on four inputs, 4K 40.6 s to 35.7 s

Browse files at this commit

b83300d24ebcb775f82089f752eafb1a35eda9cfAhmet Kaan GümüşParent: d6ebc7791d30fe
crates/ec-av1/src/decode.rsmodified+552 -12
@@ -16541,6 +16541,389 @@ fn filter_edge(
16541 }16541 }
16542 }16542 }
16543 16543
16544+/// lane-perf8: [`filter_edge`]'s AVX2 kernel -- the scalar loop was 8.0% of a
16545+/// 4K decode's self time, spent almost entirely on the per-tap strided
16546+/// addressing (`perf annotate`'s hot lines are `leaq`/`movzwl` pairs, not the
16547+/// arithmetic). Nothing here is spec logic: the same masks, the same
16548+/// `filter4`/`filter6`/`filter8`/`filter14` weighted sums and the same
16549+/// rounding, done for 16 edge lines at once.
16550+///
16551+/// 16-bit lanes are exact for every value these filters see. Samples are in
16552+/// `[0, 4095]`, so a difference and the `blimit` term (`2 * |p0 - q0| +
16553+/// |p1 - q1| / 2 <= 10237`) fit `i16`; `filter4` works in the centred domain
16554+/// where every intermediate is clamped to `+-128 << (bit_depth - 8)`; and the
16555+/// wide kernels' weights each total 8 or 16, so their sums (at most
16556+/// `16 * 4095 + 8 = 65528`) fit `u16` -- hence `_mm256_srli_epi16` for their
16557+/// rounding shift, which is the unsigned shift the scalar's non-negative sum
16558+/// takes.
16559+#[cfg(target_arch = "x86_64")]
16560+#[allow(unsafe_code)]
16561+#[allow(unsafe_op_in_unsafe_fn)] // the kernel's whole body is its contract
16562+mod deblock_simd {
16563+ use std::arch::x86_64::*;
16564+
16565+ /// `a <= b` lane-wise, as a full-width mask.
16566+ ///
16567+ /// # Safety
16568+ /// Requires AVX2.
16569+ #[target_feature(enable = "avx2")]
16570+ #[inline]
16571+ unsafe fn le(a: __m256i, b: __m256i) -> __m256i {
16572+ _mm256_cmpeq_epi16(_mm256_max_epi16(a, b), b)
16573+ }
16574+
16575+ /// `|a - b|` lane-wise.
16576+ ///
16577+ /// # Safety
16578+ /// Requires AVX2.
16579+ #[target_feature(enable = "avx2")]
16580+ #[inline]
16581+ unsafe fn ad(a: __m256i, b: __m256i) -> __m256i {
16582+ _mm256_abs_epi16(_mm256_sub_epi16(a, b))
16583+ }
16584+
16585+ /// `signed_char_clamp_high`, lane-wise.
16586+ ///
16587+ /// # Safety
16588+ /// Requires AVX2.
16589+ #[target_feature(enable = "avx2")]
16590+ #[inline]
16591+ unsafe fn sclamp(v: __m256i, lo: __m256i, hi: __m256i) -> __m256i {
16592+ _mm256_min_epi16(_mm256_max_epi16(v, lo), hi)
16593+ }
16594+
16595+ /// 16 rows of 16 `i16` transposed in place (unpack ladder, then the
16596+ /// 128-bit lane swap AVX2's in-lane unpacks leave behind).
16597+ ///
16598+ /// # Safety
16599+ /// Requires AVX2.
16600+ #[target_feature(enable = "avx2")]
16601+ unsafe fn transpose16(t: &mut [__m256i; 16]) {
16602+ let mut a = [_mm256_setzero_si256(); 16];
16603+ for k in 0..8 {
16604+ a[2 * k] = _mm256_unpacklo_epi16(t[2 * k], t[2 * k + 1]);
16605+ a[2 * k + 1] = _mm256_unpackhi_epi16(t[2 * k], t[2 * k + 1]);
16606+ }
16607+ let mut b = [_mm256_setzero_si256(); 16];
16608+ for g in 0..4 {
16609+ let s = 4 * g;
16610+ b[s] = _mm256_unpacklo_epi32(a[s], a[s + 2]);
16611+ b[s + 1] = _mm256_unpackhi_epi32(a[s], a[s + 2]);
16612+ b[s + 2] = _mm256_unpacklo_epi32(a[s + 1], a[s + 3]);
16613+ b[s + 3] = _mm256_unpackhi_epi32(a[s + 1], a[s + 3]);
16614+ }
16615+ let mut c = [_mm256_setzero_si256(); 16];
16616+ for g in 0..2 {
16617+ let s = 8 * g;
16618+ for j in 0..4 {
16619+ c[s + 2 * j] = _mm256_unpacklo_epi64(b[s + j], b[s + j + 4]);
16620+ c[s + 2 * j + 1] = _mm256_unpackhi_epi64(b[s + j], b[s + j + 4]);
16621+ }
16622+ }
16623+ for i in 0..8 {
16624+ t[i] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x20);
16625+ t[i + 8] = _mm256_permute2x128_si256(c[i], c[i + 8], 0x31);
16626+ }
16627+ }
16628+
16629+ /// The wide kernels' tap weights, in tap order and with the spec's
16630+ /// rounding divisor as the row sum: `filter6` over `p2..q2`, `filter8`
16631+ /// over `p3..q3`, `filter14` over `p6..q6`.
16632+ const W6: [[i16; 6]; 4] = [
16633+ [3, 2, 2, 1, 0, 0],
16634+ [1, 2, 2, 2, 1, 0],
16635+ [0, 1, 2, 2, 2, 1],
16636+ [0, 0, 1, 2, 2, 3],
16637+ ];
16638+ const W8: [[i16; 8]; 6] = [
16639+ [3, 2, 1, 1, 1, 0, 0, 0],
16640+ [2, 1, 2, 1, 1, 1, 0, 0],
16641+ [1, 1, 1, 2, 1, 1, 1, 0],
16642+ [0, 1, 1, 1, 2, 1, 1, 1],
16643+ [0, 0, 1, 1, 1, 2, 1, 2],
16644+ [0, 0, 0, 1, 1, 1, 2, 3],
16645+ ];
16646+ const W14: [[i16; 14]; 12] = [
16647+ [7, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
16648+ [5, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0],
16649+ [4, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0],
16650+ [3, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0],
16651+ [2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0],
16652+ [1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 0],
16653+ [0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1],
16654+ [0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2],
16655+ [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 3],
16656+ [0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 1, 4],
16657+ [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 5],
16658+ [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 7],
16659+ ];
16660+
16661+ /// One weighted tap sum, rounded by `shift` (3 for the divide-by-8 rows,
16662+ /// 4 for `filter14`'s divide-by-16 ones). The sum is non-negative and
16663+ /// below `1 << 16`, so the logical shift is the arithmetic one.
16664+ ///
16665+ /// # Safety
16666+ /// Requires AVX2.
16667+ #[target_feature(enable = "avx2")]
16668+ #[inline]
16669+ unsafe fn wsum(taps: &[__m256i], w: &[i16], shift: i32) -> __m256i {
16670+ let mut s = _mm256_setzero_si256();
16671+ for (t, &k) in taps.iter().zip(w) {
16672+ match k {
16673+ 0 => {}
16674+ 1 => s = _mm256_add_epi16(s, *t),
16675+ 2 => s = _mm256_add_epi16(s, _mm256_add_epi16(*t, *t)),
16676+ _ => s = _mm256_add_epi16(s, _mm256_mullo_epi16(*t, _mm256_set1_epi16(k))),
16677+ }
16678+ }
16679+ let s = _mm256_add_epi16(s, _mm256_set1_epi16(1 << (shift - 1)));
16680+ if shift == 3 {
16681+ _mm256_srli_epi16(s, 3)
16682+ } else {
16683+ _mm256_srli_epi16(s, 4)
16684+ }
16685+ }
16686+
16687+ /// [`super::filter_edge`]'s body for 16 lines held as `t[0..16]`, `q0` in
16688+ /// `t[8]`; the filtered taps are written back in place.
16689+ ///
16690+ /// # Safety
16691+ /// Requires AVX2.
16692+ #[target_feature(enable = "avx2")]
16693+ #[allow(clippy::too_many_arguments)]
16694+ unsafe fn filter16(
16695+ t: &mut [__m256i; 16],
16696+ len: u8,
16697+ blimit: i32,
16698+ limit: i32,
16699+ hev_thr: i32,
16700+ flat_thresh: i32,
16701+ scale: i32,
16702+ smax: i32,
16703+ ) {
16704+ let lim = _mm256_set1_epi16(limit as i16);
16705+ let blim = _mm256_set1_epi16(blimit as i16);
16706+ let hthr = _mm256_set1_epi16(hev_thr as i16);
16707+ let fthr = _mm256_set1_epi16(flat_thresh as i16);
16708+ let zero = _mm256_setzero_si256();
16709+ let smaxv = _mm256_set1_epi16(smax as i16);
16710+ let (p6, p5, p4, p3, p2, p1, p0) = (t[1], t[2], t[3], t[4], t[5], t[6], t[7]);
16711+ let (q0, q1, q2, q3, q4, q5, q6) = (t[8], t[9], t[10], t[11], t[12], t[13], t[14]);
16712+
16713+ // `highbd_filter_mask`: the neighbour steps this kernel's length
16714+ // reaches, plus the shared `blimit` term.
16715+ let d1 = _mm256_max_epi16(ad(p1, p0), ad(q1, q0));
16716+ let mut md = d1;
16717+ if len >= 6 {
16718+ md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p2, p1), ad(q2, q1)));
16719+ }
16720+ if len >= 8 {
16721+ md = _mm256_max_epi16(md, _mm256_max_epi16(ad(p3, p2), ad(q3, q2)));
16722+ }
16723+ let bl = _mm256_add_epi16(
16724+ _mm256_slli_epi16(ad(p0, q0), 1),
16725+ _mm256_srli_epi16(ad(p1, q1), 1),
16726+ );
16727+ let mask = _mm256_and_si256(le(md, lim), le(bl, blim));
16728+ let hev = _mm256_cmpgt_epi16(d1, hthr);
16729+
16730+ // `filter4`, in the centred domain.
16731+ let centre = _mm256_set1_epi16((128 * scale) as i16);
16732+ let lo = _mm256_set1_epi16((-128 * scale) as i16);
16733+ let hi = _mm256_set1_epi16((128 * scale - 1) as i16);
16734+ let ps1 = _mm256_sub_epi16(p1, centre);
16735+ let ps0 = _mm256_sub_epi16(p0, centre);
16736+ let qs0 = _mm256_sub_epi16(q0, centre);
16737+ let qs1 = _mm256_sub_epi16(q1, centre);
16738+ let outer = _mm256_and_si256(hev, sclamp(_mm256_sub_epi16(ps1, qs1), lo, hi));
16739+ let f = sclamp(
16740+ _mm256_add_epi16(
16741+ outer,
16742+ _mm256_mullo_epi16(_mm256_set1_epi16(3), _mm256_sub_epi16(qs0, ps0)),
16743+ ),
16744+ lo,
16745+ hi,
16746+ );
16747+ let f1 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(4)), lo, hi), 3);
16748+ let f2 = _mm256_srai_epi16(sclamp(_mm256_add_epi16(f, _mm256_set1_epi16(3)), lo, hi), 3);
16749+ let tap = _mm256_andnot_si256(
16750+ hev,
16751+ _mm256_srai_epi16(_mm256_add_epi16(f1, _mm256_set1_epi16(1)), 1),
16752+ );
16753+ let n_p1 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps1, tap), lo, hi), centre);
16754+ let n_p0 = _mm256_add_epi16(sclamp(_mm256_add_epi16(ps0, f2), lo, hi), centre);
16755+ let n_q0 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs0, f1), lo, hi), centre);
16756+ let n_q1 = _mm256_add_epi16(sclamp(_mm256_sub_epi16(qs1, tap), lo, hi), centre);
16757+ let mut r = [
16758+ p5,
16759+ p4,
16760+ p3,
16761+ p2,
16762+ _mm256_blendv_epi8(p1, n_p1, mask),
16763+ _mm256_blendv_epi8(p0, n_p0, mask),
16764+ _mm256_blendv_epi8(q0, n_q0, mask),
16765+ _mm256_blendv_epi8(q1, n_q1, mask),
16766+ q2,
16767+ q3,
16768+ q4,
16769+ q5,
16770+ ];
16771+
16772+ if len >= 6 {
16773+ // `highbd_flat_mask4`, over the same reach as this length's mask.
16774+ let mut fl = _mm256_max_epi16(
16775+ _mm256_max_epi16(ad(p1, p0), ad(q1, q0)),
16776+ _mm256_max_epi16(ad(p2, p0), ad(q2, q0)),
16777+ );
16778+ if len >= 8 {
16779+ fl = _mm256_max_epi16(fl, _mm256_max_epi16(ad(p3, p0), ad(q3, q0)));
16780+ }
16781+ let flat = _mm256_and_si256(le(fl, fthr), mask);
16782+ if len == 6 {
16783+ let taps = [p2, p1, p0, q0, q1, q2];
16784+ for (j, w) in W6.iter().enumerate() {
16785+ r[4 + j] = _mm256_blendv_epi8(r[4 + j], wsum(&taps, w, 3), flat);
16786+ }
16787+ } else {
16788+ let taps = [p3, p2, p1, p0, q0, q1, q2, q3];
16789+ for (j, w) in W8.iter().enumerate() {
16790+ r[3 + j] = _mm256_blendv_epi8(r[3 + j], wsum(&taps, w, 3), flat);
16791+ }
16792+ if len > 8 {
16793+ let fl2 = _mm256_max_epi16(
16794+ _mm256_max_epi16(
16795+ _mm256_max_epi16(ad(p4, p0), ad(q4, q0)),
16796+ _mm256_max_epi16(ad(p5, p0), ad(q5, q0)),
16797+ ),
16798+ _mm256_max_epi16(ad(p6, p0), ad(q6, q0)),
16799+ );
16800+ let flat2 = _mm256_and_si256(le(fl2, fthr), flat);
16801+ let taps = [p6, p5, p4, p3, p2, p1, p0, q0, q1, q2, q3, q4, q5, q6];
16802+ for (j, w) in W14.iter().enumerate() {
16803+ r[j] = _mm256_blendv_epi8(r[j], wsum(&taps, w, 4), flat2);
16804+ }
16805+ }
16806+ }
16807+ }
16808+
16809+ // `r[j]` holds the sample at tap `j - 6`, i.e. `t[j + 2]`.
16810+ let (a, b) = match len {
16811+ 4 | 6 => (4, 8),
16812+ 8 => (3, 9),
16813+ _ => (0, 12),
16814+ };
16815+ for j in a..b {
16816+ t[j + 2] = _mm256_min_epi16(_mm256_max_epi16(r[j], zero), smaxv);
16817+ }
16818+ }
16819+
16820+ /// 16 edge lines at `base`. `vertical` names the edge: a vertical edge's
16821+ /// 16 lines are 16 consecutive rows and its taps are consecutive samples
16822+ /// (loaded as a 16x16 tile and transposed), a horizontal edge's are 16
16823+ /// consecutive columns with each tap a whole row segment.
16824+ ///
16825+ /// # Safety
16826+ /// Requires AVX2. For a vertical edge `base % stride >= 8`, `base %
16827+ /// stride + 8 <= stride` and 16 rows from `base` must be inside `data`;
16828+ /// for a horizontal edge `base >= 8 * stride` and `base + 8 * stride`
16829+ /// must be inside it.
16830+ #[target_feature(enable = "avx2")]
16831+ #[allow(clippy::too_many_arguments)]
16832+ pub unsafe fn edge16(
16833+ data: &mut [u16],
16834+ base: usize,
16835+ stride: usize,
16836+ vertical: bool,
16837+ len: u8,
16838+ blimit: i32,
16839+ limit: i32,
16840+ hev_thr: i32,
16841+ flat_thresh: i32,
16842+ scale: i32,
16843+ smax: i32,
16844+ ) {
16845+ let p = data.as_mut_ptr();
16846+ let mut t = [_mm256_setzero_si256(); 16];
16847+ // The taps this length reads, as `t` indices.
16848+ let (lo, hi) = match len {
16849+ 4 => (6, 10),
16850+ 6 => (5, 11),
16851+ 8 => (4, 12),
16852+ _ => (1, 15),
16853+ };
16854+ if vertical {
16855+ for j in 0..16 {
16856+ t[j] = _mm256_loadu_si256(p.add(base + j * stride - 8).cast());
16857+ }
16858+ transpose16(&mut t);
16859+ } else {
16860+ let top = base - 8 * stride;
16861+ for i in lo..hi {
16862+ t[i] = _mm256_loadu_si256(p.add(top + i * stride).cast());
16863+ }
16864+ }
16865+ filter16(&mut t, len, blimit, limit, hev_thr, flat_thresh, scale, smax);
16866+ if vertical {
16867+ transpose16(&mut t);
16868+ for j in 0..16 {
16869+ _mm256_storeu_si256(p.add(base + j * stride - 8).cast(), t[j]);
16870+ }
16871+ } else {
16872+ let top = base - 8 * stride;
16873+ let (a, b) = match len {
16874+ 4 | 6 => (6, 10),
16875+ 8 => (5, 11),
16876+ _ => (2, 14),
16877+ };
16878+ for i in a..b {
16879+ _mm256_storeu_si256(p.add(top + i * stride).cast(), t[i]);
16880+ }
16881+ }
16882+ }
16883+}
16884+
16885+/// [`filter_edge`] for 16 adjacent edge lines that share `edge_params`'
16886+/// output. Returns `false` when this build or CPU has no kernel, leaving the
16887+/// caller on the scalar path.
16888+#[allow(unused_variables)]
16889+fn filter_edge16(
16890+ data: &mut [u16],
16891+ base: usize,
16892+ stride: usize,
16893+ vertical: bool,
16894+ len: u8,
16895+ level: i32,
16896+ sharpness: u8,
16897+) -> bool {
16898+ #[cfg(target_arch = "x86_64")]
16899+ {
16900+ if crate::mc::simd_level() == crate::mc::SimdLevel::Avx2 {
16901+ let (blimit, limit, hev_thr) = deblock_thresholds(level, sharpness);
16902+ let shift = bit_depth() - 8;
16903+ // SAFETY: the avx2 arm is reached only when the CPU reports it,
16904+ // and `deblock_plane` checks the kernel's edge bounds.
16905+ #[allow(unsafe_code)]
16906+ unsafe {
16907+ deblock_simd::edge16(
16908+ data,
16909+ base,
16910+ stride,
16911+ vertical,
16912+ len,
16913+ blimit << shift,
16914+ limit << shift,
16915+ hev_thr << shift,
16916+ 1 << shift,
16917+ 1 << shift,
16918+ sample_max(),
16919+ )
16920+ };
16921+ return true;
16922+ }
16923+ }
16924+ false
16925+}
16926+
16544 /// One plane's worth of spec 7.14: every vertical edge across the plane,16927 /// One plane's worth of spec 7.14: every vertical edge across the plane,
16545 /// then every horizontal edge (the order the spec and libaom both use).16928 /// then every horizontal edge (the order the spec and libaom both use).
16546 fn deblock_plane(16929 fn deblock_plane(
@@ -16585,10 +16968,53 @@ fn deblock_plane(
16585 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {16968 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
16586 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);16969 eprintln!("DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}", plane.true_width, plane.true_height);
16587 }16970 }
16588- let mut y0 = 0usize;16971+ // lane-perf8: both passes iterate the edge's OWN direction innermost, so
16589- while y0 < th {16972+ // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
16590- let mut x0 = 4usize;16973+ // kernel. The swap is order-preserving: a filtered group overlaps only
16591- while x0 < tw {16974+ // groups along the edge it sits on -- the vertical pass's writes at
16975+ // `x0` reach columns `x0 - 7 ..= x0 + 5` of its own 4 rows, so the
16976+ // dependence is on ascending `x0` within a row, which stays the outer
16977+ // loop's order, and rows remain independent (horizontal pass mirrored).
16978+ let rows = plane.data.len() / stride.max(1);
16979+ let mut x0 = 4usize;
16980+ while x0 < tw {
16981+ let mut y0 = 0usize;
16982+ while y0 < th {
16983+ if y0 + 16 <= th && x0 >= 8 && x0 + 8 <= stride {
16984+ let ps: [Option<(u8, i32)>; 4] =
16985+ std::array::from_fn(|k| edge_params(lf, n, plane_idx, 0, chroma, x0, y0 + 4 * k));
16986+ if let Some((len, level)) = ps[0] {
16987+ if ps.iter().all(|p| *p == ps[0])
16988+ && filter_edge16(
16989+ &mut plane.data,
16990+ y0 * stride + x0,
16991+ stride,
16992+ true,
16993+ len,
16994+ level,
16995+ lf.sharpness,
16996+ )
16997+ {
16998+ y0 += 16;
16999+ continue;
17000+ }
17001+ }
17002+ for (k, p) in ps.iter().enumerate() {
17003+ if let Some((len, level)) = *p {
17004+ filter_edge(
17005+ &mut plane.data,
17006+ (y0 + 4 * k) * stride + x0,
17007+ stride as isize,
17008+ 1,
17009+ len,
17010+ level,
17011+ lf.sharpness,
17012+ );
17013+ }
17014+ }
17015+ y0 += 16;
17016+ continue;
17017+ }
16592 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {17018 if let Some((len, level)) = edge_params(lf, n, plane_idx, 0, chroma, x0, y0) {
16593 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {17019 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
16594 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");17020 eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
@@ -16603,14 +17029,49 @@ fn deblock_plane(
16603 lf.sharpness,17029 lf.sharpness,
16604 );17030 );
16605 }17031 }
16606- x0 += 4;17032+ y0 += 4;
16607 }17033 }
16608- y0 += 4;17034+ x0 += 4;
16609 }17035 }
16610- let mut x0 = 0usize;17036+ let mut y0 = 4usize;
16611- while x0 < tw {17037+ while y0 < th {
16612- let mut y0 = 4usize;17038+ let mut x0 = 0usize;
16613- while y0 < th {17039+ while x0 < tw {
17040+ if x0 + 16 <= tw && y0 >= 8 && y0 + 7 <= rows {
17041+ let ps: [Option<(u8, i32)>; 4] =
17042+ std::array::from_fn(|k| edge_params(lf, n, plane_idx, 1, chroma, x0 + 4 * k, y0));
17043+ if let Some((len, level)) = ps[0] {
17044+ if ps.iter().all(|p| *p == ps[0])
17045+ && filter_edge16(
17046+ &mut plane.data,
17047+ y0 * stride + x0,
17048+ stride,
17049+ false,
17050+ len,
17051+ level,
17052+ lf.sharpness,
17053+ )
17054+ {
17055+ x0 += 16;
17056+ continue;
17057+ }
17058+ }
17059+ for (k, p) in ps.iter().enumerate() {
17060+ if let Some((len, level)) = *p {
17061+ filter_edge(
17062+ &mut plane.data,
17063+ y0 * stride + x0 + 4 * k,
17064+ 1,
17065+ stride as isize,
17066+ len,
17067+ level,
17068+ lf.sharpness,
17069+ );
17070+ }
17071+ }
17072+ x0 += 16;
17073+ continue;
17074+ }
16614 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {17075 if let Some((len, level)) = edge_params(lf, n, plane_idx, 1, chroma, x0, y0) {
16615 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")17076 if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
16616 && plane_idx == 017077 && plane_idx == 0
@@ -16631,9 +17092,9 @@ fn deblock_plane(
16631 lf.sharpness,17092 lf.sharpness,
16632 );17093 );
16633 }17094 }
16634- y0 += 4;17095+ x0 += 4;
16635 }17096 }
16636- x0 += 4;17097+ y0 += 4;
16637 }17098 }
16638 }17099 }
16639 17100
@@ -31591,6 +32052,85 @@ mod tests {
31591 }32052 }
31592 }32053 }
31593 32054
32055+ /// lane-perf8: the AVX2 deblock kernel must be sample-identical to
32056+ /// [`super::filter_edge`] over the whole input domain -- every bit depth,
32057+ /// every filter length, every level and sharpness, and sample patterns
32058+ /// that put each of `mask`, `flat` and `flat2` on both sides of its
32059+ /// threshold (uniform, flat-with-step, small-noise and full-range
32060+ /// random), on both edge directions.
32061+ #[test]
32062+ #[cfg(target_arch = "x86_64")]
32063+ fn deblock_simd_kernel_matches_the_scalar_filter() {
32064+ if crate::mc::simd_level() != crate::mc::SimdLevel::Avx2 {
32065+ eprintln!("SKIP deblock simd: no avx2");
32066+ return;
32067+ }
32068+ let mut rng = 0x9e37_79b9_7f4a_7c15u64;
32069+ let mut next = move || {
32070+ rng ^= rng << 13;
32071+ rng ^= rng >> 7;
32072+ rng ^= rng << 17;
32073+ rng
32074+ };
32075+ let (stride, rows) = (64usize, 64usize);
32076+ for &bd in &[8u8, 10, 12] {
32077+ super::set_bit_depth(bd);
32078+ let smax = (1u64 << bd) - 1;
32079+ for pattern in 0..4u32 {
32080+ for trial in 0..8 {
32081+ let seed: Vec<u16> = (0..stride * rows)
32082+ .map(|k| {
32083+ let base = ((k / stride) as u64 * 7 + trial) % (smax + 1);
32084+ (match pattern {
32085+ // Uniform-ish: every mask and both flats pass.
32086+ 0 => base,
32087+ // A step across the edge column/row.
32088+ 1 => (base + if k % stride >= 32 { smax / 2 } else { 0 }) % (smax + 1),
32089+ // Small noise: flat passes at 8-bit, not always higher.
32090+ 2 => (base + next() % 4) % (smax + 1),
32091+ _ => next() % (smax + 1),
32092+ }) as u16
32093+ })
32094+ .collect();
32095+ for &len in &[4u8, 6, 8, 14] {
32096+ for &level in &[0i32, 1, 7, 23, 40, 63] {
32097+ for sharpness in 0..8u8 {
32098+ for &vertical in &[true, false] {
32099+ let (base, outer, tap) = if vertical {
32100+ (32 * stride + 32, stride as isize, 1isize)
32101+ } else {
32102+ (32 * stride + 32, 1isize, stride as isize)
32103+ };
32104+ let mut a = seed.clone();
32105+ for g in 0..4usize {
32106+ let b = if vertical {
32107+ base + 4 * g * stride
32108+ } else {
32109+ base + 4 * g
32110+ };
32111+ super::filter_edge(
32112+ &mut a, b, outer, tap, len, level, sharpness,
32113+ );
32114+ }
32115+ let mut b = seed.clone();
32116+ assert!(super::filter_edge16(
32117+ &mut b, base, stride, vertical, len, level, sharpness,
32118+ ));
32119+ assert_eq!(
32120+ a, b,
32121+ "bd={bd} pattern={pattern} trial={trial} len={len} \
32122+ level={level} sharp={sharpness} vert={vertical}"
32123+ );
32124+ }
32125+ }
32126+ }
32127+ }
32128+ }
32129+ }
32130+ }
32131+ super::set_bit_depth(8);
32132+ }
32133+
31594 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce32134 /// lane-golomb r7: [`reduce_inherited_chroma_tx_type`] must reproduce
31595 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`32135 /// `av1_ext_tx_used[av1_get_ext_tx_set_type(uv_tx, 1, reduced)]`
31596 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue32136 /// (libaom `av1/common/blockd.h:1036`/`1097`) exactly -- the g35 residue
crates/ec-av1/src/mc.rsmodified+2 -2
@@ -281,7 +281,7 @@ pub(crate) fn simd_level() -> SimdLevel {
281 /// the same `Round2(sum, InterRound0)`.281 /// the same `Round2(sum, InterRound0)`.
282 #[allow(unsafe_code)]282 #[allow(unsafe_code)]
283 #[inline]283 #[inline]
284-fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {284+pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
285 #[cfg(target_arch = "x86_64")]285 #[cfg(target_arch = "x86_64")]
286 {286 {
287 match simd_level() {287 match simd_level() {
@@ -586,7 +586,7 @@ fn horizontal_pass_unscaled(
586 /// eight slots. `acc` is left holding the unrounded sums.586 /// eight slots. `acc` is left holding the unrounded sums.
587 #[inline]587 #[inline]
588 #[allow(unsafe_code)]588 #[allow(unsafe_code)]
589-fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {589+pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
590 #[cfg(target_arch = "x86_64")]590 #[cfg(target_arch = "x86_64")]
591 {591 {
592 match simd_level() {592 match simd_level() {
crates/ec-av1/src/restoration.rsmodified+81 -42
@@ -494,11 +494,33 @@ fn lr_sample(
494 col: i64,494 col: i64,
495 ) -> i32 {495 ) -> i32 {
496 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;496 let col_c = col.clamp(0, plane_w as i64 - 1) as usize;
497- if row >= stripe_v_start as i64 && row < stripe_v_end as i64 {497+ i32::from(
498- i32::from(cdef[row as usize * stride + col_c])498+ lr_src_row(cdef, deblocked, stride, plane_w, plane_h, stripe_v_start, stripe_v_end, row)
499+ [col_c],
500+ )
501+}
502+
503+/// The plane row [`lr_sample`] reads, resolved once. Which buffer and which
504+/// row a sample comes from depends only on `row` -- the column only ever
505+/// clamps -- so a whole-row consumer (the Wiener horizontal pass) resolves
506+/// the substitution once per row instead of once per tap. [`lr_sample`] is
507+/// this function plus that clamp, so the rule has one statement.
508+#[allow(clippy::too_many_arguments)]
509+fn lr_src_row<'a>(
510+ cdef: &'a [u16],
511+ deblocked: &'a [u16],
512+ stride: usize,
513+ plane_w: usize,
514+ plane_h: usize,
515+ stripe_v_start: usize,
516+ stripe_v_end: usize,
517+ row: i64,
518+) -> &'a [u16] {
519+ let (buf, src_row) = if row >= stripe_v_start as i64 && row < stripe_v_end as i64 {
520+ (cdef, row as usize)
499 } else if row < stripe_v_start as i64 {521 } else if row < stripe_v_start as i64 {
500 if stripe_v_start == 0 {522 if stripe_v_start == 0 {
501- i32::from(cdef[col_c])523+ (cdef, 0)
502 } else {524 } else {
503 // libaom saves 2 deblocked context lines and duplicates the525 // libaom saves 2 deblocked context lines and duplicates the
504 // outer one to fill a 3-row border (`RESTORATION_BORDER`):526 // outer one to fill a 3-row border (`RESTORATION_BORDER`):
@@ -506,23 +528,21 @@ fn lr_sample(
506 // rows `stripe_v_start-2`/`-3` both read deblocked row528 // rows `stripe_v_start-2`/`-3` both read deblocked row
507 // `stripe_v_start-2`.529 // `stripe_v_start-2`.
508 let dist = stripe_v_start as i64 - 1 - row;530 let dist = stripe_v_start as i64 - 1 - row;
509- let src_row = if dist == 0 {531+ (
510- stripe_v_start - 1532+ deblocked,
511- } else {533+ if dist == 0 { stripe_v_start - 1 } else { stripe_v_start.saturating_sub(2) },
512- stripe_v_start.saturating_sub(2)534+ )
513- };
514- i32::from(deblocked[src_row * stride + col_c])
515 }535 }
516 } else if stripe_v_end == plane_h {536 } else if stripe_v_end == plane_h {
517- i32::from(cdef[(plane_h - 1) * stride + col_c])537+ (cdef, plane_h - 1)
518 } else {538 } else {
519 // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1`539 // Mirror image of the above: rows `stripe_v_end`/`stripe_v_end+1`
520 // read their own deblocked row, row `stripe_v_end+2` duplicates540 // read their own deblocked row, row `stripe_v_end+2` duplicates
521 // `stripe_v_end+1`.541 // `stripe_v_end+1`.
522 let dist = (row - stripe_v_end as i64).min(1) as usize;542 let dist = (row - stripe_v_end as i64).min(1) as usize;
523- let src_row = (stripe_v_end + dist).min(plane_h - 1);543+ (deblocked, (stripe_v_end + dist).min(plane_h - 1))
524- i32::from(deblocked[src_row * stride + col_c])544+ };
525- }545+ &buf[src_row * stride..src_row * stride + plane_w]
526 }546 }
527 547
528 /// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` ->548 /// Wiener pixel filter (spec 7.17.4, libaom `wiener_filter_stripe` ->
@@ -566,45 +586,58 @@ fn apply_wiener_stripe(
566 // this was a fresh allocation per stripe. Every entry is written below.586 // this was a fresh allocation per stripe. Every entry is written below.
567 let mut inter = WIENER_INTER_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));587 let mut inter = WIENER_INTER_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
568 inter.clear();588 inter.clear();
569- inter.resize(rows * w, 0i32);589+ // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the
590+ // last vertical output needs two rows of padding past the `h + 6` the
591+ // 7-tap kernel actually uses. Tap 7 is zero, so they never contribute.
592+ inter.resize((h + 8) * w, 0i32);
593+ // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16`
594+ // convolution over contiguous samples rounded by `Round2(_, 3)`, which
595+ // is `INTER_ROUND_0` -- so it runs on that module's kernels with the
596+ // eighth tap zeroed, instead of a scalar `lr_sample` call per tap. The
597+ // stripe substitution is resolved once per row by `lr_src_row`, and only
598+ // a unit touching the plane's left or right edge needs the clamped copy.
599+ let hf = &info.hfilter;
600+ let t16: [i16; 8] =
601+ [hf[0] as i16, hf[1] as i16, hf[2] as i16, hf[3] as i16, hf[4] as i16, hf[5] as i16, hf[6] as i16, 0];
602+ let (lo_bound, hi_bound) = (-wiener_bias as i32, (wiener_limit - 1 - wiener_bias) as i32);
603+ let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
570 for r in 0..rows {604 for r in 0..rows {
571 let row = v_start as i64 - 3 + r as i64;605 let row = v_start as i64 - 3 + r as i64;
572- for c in 0..w {606+ let src = lr_src_row(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row);
573- let col = h_start as i64 + c as i64;607+ let lo = h_start as i64 - 3;
574- let mut sum = 0i64;608+ let out = &mut inter[r * w..r * w + w];
575- for (t, &tap) in info.hfilter.iter().enumerate() {609+ if lo >= 0 && lo as usize + w + 7 <= plane_w {
576- let x = col - 3 + t as i64;610+ crate::mc::hpass_contig(&src[lo as usize..], &t16, out);
577- sum += tap as i64611+ } else {
578- * lr_sample(cdef, deblocked, stride, plane_w, plane_h, v_start, v_end, row, x) as i64;612+ hbuf.clear();
579- }613+ hbuf.extend(
580- // libaom's `highbd_convolve_add_src_horiz_hip` clamps its614+ (0..w + 7).map(|k| src[(lo + k as i64).clamp(0, plane_w as i64 - 1) as usize]),
581- // *biased* intermediate to `[0, WIENER_CLAMP_LIMIT(3, bd) - 1]`615+ );
582- // (`convolve.h:43`, `(1 << (bd + 1 + FILTER_BITS - round0))`).616+ crate::mc::hpass_contig(&hbuf, &t16, out);
583- // Its bias over this crate's unbiased sum is exactly617+ }
584- // `(1 << (bd + FILTER_BITS - 1)) >> round0 == 1 << (bd + 3)`618+ for v in out.iter_mut() {
585- // (the `rounding` term of that function, the rest cancelling619+ *v = (*v).clamp(lo_bound, hi_bound);
586- // against `WienerInfo`'s derived centre tap as the doc comment
587- // above derives), so the same clamp in *this* domain is the
588- // bound shifted down by that bias. At 8-bit neither end is ever
589- // reached by real content, which is why the old fixed `[0, 8191]`
590- // survived every 8-bit gate; at 10-bit the upper end is
591- // `128 * 1023 >> 3 == 16368`, well past `8191`, so a fixed
592- // 8-bit limit silently truncated most 10-bit Wiener pixels.
593- inter[r * w + c] = round2(sum, 3).clamp(-wiener_bias, wiener_limit - 1 - wiener_bias) as i32;
594 }620 }
595 }621 }
622+ WIENER_ROW_SCRATCH.with(|c| *c.borrow_mut() = hbuf);
596 // lane-perf7: the clamp bound is the frame's, so it is read once here623 // lane-perf7: the clamp bound is the frame's, so it is read once here
597 // instead of taking a thread-local read per output sample.624 // instead of taking a thread-local read per output sample.
598 let smax = i64::from(crate::decode::sample_max());625 let smax = i64::from(crate::decode::sample_max());
626+ // The vertical pass is `mc.rs`'s too, same 8th-tap-zero trick: it leaves
627+ // the accumulator unrounded, and `Round2(_, 11)` is `INTER_ROUND_1`.
628+ let vf = &info.vfilter;
629+ let taps: [i32; 8] = [vf[0], vf[1], vf[2], vf[3], vf[4], vf[5], vf[6], 0];
630+ let mut acc = WIENER_ACC_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
631+ acc.clear();
632+ acc.resize(w, 0i32);
599 for r in 0..h {633 for r in 0..h {
600- for c in 0..w {634+ crate::mc::vpass_row(&inter, w, r, &taps, &mut acc);
601- let mut sum = 0i64;635+ let dst = &mut out[(v_start + r) * stride + h_start..][..w];
602- for (t, &tap) in info.vfilter.iter().enumerate() {636+ for (o, &a) in dst.iter_mut().zip(acc.iter()) {
603- sum += tap as i64 * inter[(r + t) * w + c] as i64;637+ *o = round2(i64::from(a), 11).clamp(0, smax) as u16;
604- }
605- out[(v_start + r) * stride + h_start + c] = round2(sum, 11).clamp(0, smax) as u16;
606 }638 }
607 }639 }
640+ WIENER_ACC_SCRATCH.with(|c| *c.borrow_mut() = acc);
608 WIENER_INTER_SCRATCH.with(|c| *c.borrow_mut() = inter);641 WIENER_INTER_SCRATCH.with(|c| *c.borrow_mut() = inter);
609 }642 }
610 643
@@ -613,6 +646,12 @@ thread_local! {
613 /// calls so a stripe does not allocate (lane-perf7).646 /// calls so a stripe does not allocate (lane-perf7).
614 static WIENER_INTER_SCRATCH: std::cell::RefCell<Vec<i32>> =647 static WIENER_INTER_SCRATCH: std::cell::RefCell<Vec<i32>> =
615 const { std::cell::RefCell::new(Vec::new()) };648 const { std::cell::RefCell::new(Vec::new()) };
649+ /// The clamped-column copy the horizontal pass needs at a plane edge.
650+ static WIENER_ROW_SCRATCH: std::cell::RefCell<Vec<u16>> =
651+ const { std::cell::RefCell::new(Vec::new()) };
652+ /// The vertical pass's unrounded accumulator row.
653+ static WIENER_ACC_SCRATCH: std::cell::RefCell<Vec<i32>> =
654+ const { std::cell::RefCell::new(Vec::new()) };
616 /// [`compute_ab`]'s two `(A, B)` grids, likewise (lane-perf7).655 /// [`compute_ab`]'s two `(A, B)` grids, likewise (lane-perf7).
617 #[allow(clippy::type_complexity)]656 #[allow(clippy::type_complexity)]
618 static SGR_AB_SCRATCH: std::cell::RefCell<(Vec<(i32, i64)>, Vec<(i32, i64)>)> =657 static SGR_AB_SCRATCH: std::cell::RefCell<(Vec<(i32, i64)>, Vec<(i32, i64)>)> =