forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-mc' (9a1ae95e): MC intermediate narrowed to i16 (range proven from the filter tables at 8/10-bit, pinned by test), vertical pass on madd_epi16 row pairs with round+clamp+narrow fused, constant-length whole-pel copies; wiener shares the kernels and stays exact; byte-exact, -5.5% instructions on the 4K segment

Browse files at this commit

e27b2d582e56f1b9a339dd6e3e6ba4a83c3197b2Ahmet Kaan GümüşParent: 74e98d83a35e5f
crates/ec-av1/src/mc.rsmodified+420 -85
@@ -18,6 +18,16 @@ fn round2(value: i32, shift: u32) -> i32 {
1818 }
1919 }
2020
21+/// The kernels' intermediate is `i16` (lane-mc), and every SIMD store lands
22+/// through `packs_epi32`, which saturates -- so the scalar arms must too, or
23+/// the two would disagree on an out-of-range sum. Motion compensation never
24+/// produces one (`horizontal_intermediate_fits_i16` proves the bound from the
25+/// tap sums at 8/10-bit; 12-bit is refused in stream.rs), and restoration's
26+/// wiener pass clamps its own output into i16 immediately after.
27+fn sat16(value: i32) -> i16 {
28+ value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
29+}
30+
2131 /// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
2232 /// horizontal pass's sum is brought down by before it is stored as the
2333 /// intermediate.
@@ -285,7 +295,7 @@ pub(crate) fn simd_level() -> SimdLevel {
285295 /// the same `Round2(sum, InterRound0)`.
286296 #[allow(unsafe_code)]
287297 #[inline]
288-pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
298+pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
289299 #[cfg(target_arch = "x86_64")]
290300 {
291301 match simd_level() {
@@ -308,7 +318,7 @@ pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
308318 }
309319
310320 /// The scalar reference for [`hpass_contig`] (lane-perf2's loop).
311-fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
321+fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
312322 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
313323 // depth), so the products are exactly the i32 ones but the widening
314324 // multiply is one instruction per pair.
@@ -317,7 +327,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
317327 for t in 0..8 {
318328 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
319329 }
320- *o = round2(sum, INTER_ROUND_0);
330+ *o = sat16(round2(sum, INTER_ROUND_0));
321331 }
322332 }
323333
@@ -329,12 +339,20 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
329339 #[cfg(target_arch = "x86_64")]
330340 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
331341 mod simd {
332- use super::{round2, INTER_ROUND_0};
342+ use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};
333343 use std::arch::x86_64::*;
334344
335345 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
336346 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is
337347 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.
348+ #[inline]
349+ fn taps16(taps: &[i32; 8]) -> [i16; 8] {
350+ [
351+ taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
352+ taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
353+ ]
354+ }
355+
338356 #[inline]
339357 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
340358 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
@@ -350,7 +368,7 @@ mod simd {
350368 /// # Safety
351369 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.
352370 #[target_feature(enable = "avx2")]
353- pub unsafe fn hpass_avx2(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
371+ pub unsafe fn hpass_avx2(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
354372 debug_assert!(src.len() >= out.len() + 7);
355373 let n = out.len();
356374 let tp = tap_pairs(t16);
@@ -377,8 +395,11 @@ mod simd {
377395 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);
378396 let lo = _mm256_unpacklo_epi32(e, o);
379397 let hi = _mm256_unpackhi_epi32(e, o);
380- _mm256_storeu_si256(op.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
381- _mm256_storeu_si256(op.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));
398+ // `lo`/`hi` already hold the 16 outputs in order, four per
399+ // 128-bit lane; `packs_epi32` narrows lane-wise, so the store is
400+ // c..c+16 in order. Saturation never fires: see
401+ // `horizontal_intermediate_fits_i16`.
402+ _mm256_storeu_si256(op.add(c).cast(), _mm256_packs_epi32(lo, hi));
382403 c += 16;
383404 }
384405 if c < n {
@@ -386,79 +407,255 @@ mod simd {
386407 }
387408 }
388409
389- /// Vertical pass, AVX2: 8 output columns per iteration, one
390- /// `_mm256_mullo_epi32` + `_mm256_add_epi32` per non-zero tap. Exact:
391- /// an intermediate is at most ~2^17 and a tap at most 128, so the eight
392- /// products stay well inside `i32` and `mullo`'s low half is the whole
393- /// product. `acc` is left unrounded, as the scalar form leaves it.
410+ /// Vertical pass, AVX2: the intermediate is `i16` (lane-mc: it provably
411+ /// fits, see `horizontal_intermediate_fits_i16`), so a row PAIR
412+ /// interleaved by `unpack_epi16` is exactly `_mm256_madd_epi16`'s shape --
413+ /// two taps of 16 columns per instruction, where the old `i32` form spent
414+ /// one `mullo_epi32` per tap per 8 columns. `acc` is left unrounded, as
415+ /// the scalar form leaves it.
394416 ///
395417 /// # Safety
396418 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
397419 /// and `acc` at least `block_w`.
398420 #[target_feature(enable = "avx2")]
399421 pub unsafe fn vpass_avx2(
400- intermediate: &[i32],
422+ intermediate: &[i16],
401423 block_w: usize,
402424 row: usize,
403425 taps: &[i32; 8],
404426 acc: &mut [i32],
405427 ) {
406428 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
429+ let tp = tap_pairs(&taps16(taps));
407430 let ip = intermediate.as_ptr().add(row * block_w);
408431 let ap = acc.as_mut_ptr();
409432 let mut c = 0usize;
433+ while c + 16 <= block_w {
434+ // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
435+ // lane), `hi` the other two runs; the two `permute2x128`s put the
436+ // 16 sums back in column order.
437+ let mut lo = _mm256_setzero_si256();
438+ let mut hi = _mm256_setzero_si256();
439+ for k in 0..4 {
440+ if tp[k] == 0 {
441+ continue;
442+ }
443+ let tv = _mm256_set1_epi32(tp[k]);
444+ let a = _mm256_loadu_si256(ip.add(2 * k * block_w + c).cast());
445+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * block_w + c).cast());
446+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
447+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
448+ }
449+ _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
450+ _mm256_storeu_si256(ap.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));
451+ c += 16;
452+ }
453+ vpass_tail_sse(ip, block_w, &tp, taps, ap, c);
454+ }
455+
456+ /// [`vpass_avx2`]'s 8- and 4-column steps, 128-bit: every AV1 block width
457+ /// is a multiple of 4, and the 8x8 luma block (the most common inter
458+ /// shape on real 4K content) lands here whole.
459+ ///
460+ /// # Safety
461+ /// `ip` must be readable for `8 * block_w` elements from `row`'s start and
462+ /// `ap` writable for `block_w`; `c` is the column already done.
463+ #[inline]
464+ unsafe fn vpass_tail_sse(
465+ ip: *const i16,
466+ block_w: usize,
467+ tp: &[i32; 4],
468+ taps: &[i32; 8],
469+ ap: *mut i32,
470+ mut c: usize,
471+ ) {
410472 while c + 8 <= block_w {
411- let mut v = _mm256_setzero_si256();
412- for (t, &tap) in taps.iter().enumerate() {
413- if tap == 0 {
473+ let mut lo = _mm_setzero_si128();
474+ let mut hi = _mm_setzero_si128();
475+ for k in 0..4 {
476+ if tp[k] == 0 {
414477 continue;
415478 }
416- let s = _mm256_loadu_si256(ip.add(t * block_w + c).cast());
417- v = _mm256_add_epi32(v, _mm256_mullo_epi32(_mm256_set1_epi32(tap), s));
479+ let tv = _mm_set1_epi32(tp[k]);
480+ let a = _mm_loadu_si128(ip.add(2 * k * block_w + c).cast());
481+ let b = _mm_loadu_si128(ip.add((2 * k + 1) * block_w + c).cast());
482+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
483+ hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
418484 }
419- _mm256_storeu_si256(ap.add(c).cast(), v);
485+ _mm_storeu_si128(ap.add(c).cast(), lo);
486+ _mm_storeu_si128(ap.add(c + 4).cast(), hi);
420487 c += 8;
421488 }
422- // Widths are multiples of 4, so at most one 4-column tail is left.
423- for cc in c..block_w {
489+ while c + 4 <= block_w {
490+ let mut lo = _mm_setzero_si128();
491+ for k in 0..4 {
492+ if tp[k] == 0 {
493+ continue;
494+ }
495+ let tv = _mm_set1_epi32(tp[k]);
496+ let a = _mm_loadl_epi64(ip.add(2 * k * block_w + c).cast());
497+ let b = _mm_loadl_epi64(ip.add((2 * k + 1) * block_w + c).cast());
498+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
499+ }
500+ _mm_storeu_si128(ap.add(c).cast(), lo);
501+ c += 4;
502+ }
503+ // Every AV1 block width is a multiple of 4, but the encoder's own
504+ // motion search prices odd widths through `predict`, so the last
505+ // columns still need the scalar form.
506+ while c < block_w {
424507 let mut sum = 0i32;
425508 for (t, &tap) in taps.iter().enumerate() {
426- sum += tap * intermediate[(row + t) * block_w + cc];
509+ sum += tap * i32::from(*ip.add(t * block_w + c));
427510 }
428- acc[cc] = sum;
511+ *ap.add(c) = sum;
512+ c += 1;
429513 }
430514 }
431515
432- /// Vertical pass, SSE4.1 (`_mm_mullo_epi32` is SSE4.1, unlike the
433- /// horizontal pass's SSE2 `madd`): [`vpass_avx2`] at 4 columns.
516+ /// [`vpass_avx2`] with the output rounding fused in: the sums never reach
517+ /// memory as `i32`, they are rounded by `INTER_ROUND_1`, clamped and
518+ /// stored as the block's own `u16` samples. `packus_epi32` is the clamp's
519+ /// lower half (a negative sum saturates to 0) and `min_epu16` its upper,
520+ /// which is exactly `round2(sum, INTER_ROUND_1).clamp(0, max)`.
434521 ///
435522 /// # Safety
436- /// Requires SSE4.1; same slice contract as [`vpass_avx2`].
437- #[target_feature(enable = "sse4.1")]
438- pub unsafe fn vpass_sse41(
439- intermediate: &[i32],
523+ /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
524+ /// and `dst` at least `block_w`.
525+ #[target_feature(enable = "avx2")]
526+ pub unsafe fn vpass_row_u16_avx2(
527+ intermediate: &[i16],
440528 block_w: usize,
441529 row: usize,
442530 taps: &[i32; 8],
443- acc: &mut [i32],
531+ max: i32,
532+ dst: &mut [u16],
444533 ) {
445- debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
534+ debug_assert!(intermediate.len() >= (row + 8) * block_w && dst.len() >= block_w);
535+ let tp = tap_pairs(&taps16(taps));
446536 let ip = intermediate.as_ptr().add(row * block_w);
447- let ap = acc.as_mut_ptr();
537+ let dp = dst.as_mut_ptr();
538+ let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_1 - 1));
539+ let mx = _mm256_set1_epi16(max as i16);
448540 let mut c = 0usize;
541+ while c + 16 <= block_w {
542+ let mut lo = rnd;
543+ let mut hi = rnd;
544+ for k in 0..4 {
545+ if tp[k] == 0 {
546+ continue;
547+ }
548+ let tv = _mm256_set1_epi32(tp[k]);
549+ let a = _mm256_loadu_si256(ip.add(2 * k * block_w + c).cast());
550+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * block_w + c).cast());
551+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
552+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
553+ }
554+ lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32);
555+ hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32);
556+ // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
557+ // per lane in order, so this is c..c+16 in order.
558+ let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
559+ _mm256_storeu_si256(dp.add(c).cast(), v);
560+ c += 16;
561+ }
562+ vpass_u16_tail_sse(ip, block_w, &tp, taps, max, dp, c);
563+ }
564+
565+ /// [`vpass_row_u16_avx2`]'s 8- and 4-column steps (SSE4.1 for
566+ /// `packus_epi32`), and the scalar remainder.
567+ ///
568+ /// # Safety
569+ /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
570+ #[target_feature(enable = "sse4.1")]
571+ unsafe fn vpass_u16_tail_sse(
572+ ip: *const i16,
573+ block_w: usize,
574+ tp: &[i32; 4],
575+ taps: &[i32; 8],
576+ max: i32,
577+ dp: *mut u16,
578+ mut c: usize,
579+ ) {
580+ let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1));
581+ let mx = _mm_set1_epi16(max as i16);
449582 while c + 4 <= block_w {
450- let mut v = _mm_setzero_si128();
451- for (t, &tap) in taps.iter().enumerate() {
452- if tap == 0 {
583+ let wide = c + 8 <= block_w;
584+ let mut lo = rnd;
585+ let mut hi = rnd;
586+ for k in 0..4 {
587+ if tp[k] == 0 {
453588 continue;
454589 }
455- let s = _mm_loadu_si128(ip.add(t * block_w + c).cast());
456- v = _mm_add_epi32(v, _mm_mullo_epi32(_mm_set1_epi32(tap), s));
590+ let tv = _mm_set1_epi32(tp[k]);
591+ let (pa, pb) = (ip.add(2 * k * block_w + c), ip.add((2 * k + 1) * block_w + c));
592+ let (a, b) = if wide {
593+ (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))
594+ } else {
595+ (_mm_loadl_epi64(pa.cast()), _mm_loadl_epi64(pb.cast()))
596+ };
597+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
598+ if wide {
599+ hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
600+ }
457601 }
458- _mm_storeu_si128(ap.add(c).cast(), v);
459- c += 4;
602+ let v = _mm_min_epu16(
603+ _mm_packus_epi32(_mm_srai_epi32(lo, INTER_ROUND_1 as i32), _mm_srai_epi32(hi, INTER_ROUND_1 as i32)),
604+ mx,
605+ );
606+ if wide {
607+ _mm_storeu_si128(dp.add(c).cast(), v);
608+ c += 8;
609+ } else {
610+ _mm_storel_epi64(dp.add(c).cast(), v);
611+ c += 4;
612+ }
613+ }
614+ while c < block_w {
615+ let mut sum = 0i32;
616+ for (t, &tap) in taps.iter().enumerate() {
617+ sum += tap * i32::from(*ip.add(t * block_w + c));
618+ }
619+ *dp.add(c) = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
620+ c += 1;
460621 }
461- debug_assert_eq!(c, block_w, "every AV1 block width is a multiple of 4");
622+ }
623+
624+ /// [`vpass_row_u16_avx2`] without the 16-column step.
625+ ///
626+ /// # Safety
627+ /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
628+ #[target_feature(enable = "sse4.1")]
629+ pub unsafe fn vpass_row_u16_sse41(
630+ intermediate: &[i16],
631+ block_w: usize,
632+ row: usize,
633+ taps: &[i32; 8],
634+ max: i32,
635+ dst: &mut [u16],
636+ ) {
637+ debug_assert!(intermediate.len() >= (row + 8) * block_w && dst.len() >= block_w);
638+ let tp = tap_pairs(&taps16(taps));
639+ vpass_u16_tail_sse(
640+ intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, max,
641+ dst.as_mut_ptr(), 0,
642+ );
643+ }
644+
645+ /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.
646+ ///
647+ /// # Safety
648+ /// SSE2 is baseline x86_64; same slice contract as [`vpass_avx2`].
649+ pub unsafe fn vpass_sse41(
650+ intermediate: &[i16],
651+ block_w: usize,
652+ row: usize,
653+ taps: &[i32; 8],
654+ acc: &mut [i32],
655+ ) {
656+ debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
657+ let tp = tap_pairs(&taps16(taps));
658+ vpass_tail_sse(intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, acc.as_mut_ptr(), 0);
462659 }
463660
464661 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per
@@ -467,7 +664,7 @@ mod simd {
467664 ///
468665 /// # Safety
469666 /// `src.len()` must be at least `out.len() + 7`. SSE2 is baseline x86_64.
470- pub unsafe fn hpass_sse2(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
667+ pub unsafe fn hpass_sse2(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
471668 debug_assert!(src.len() >= out.len() + 7);
472669 let n = out.len();
473670 let tp = tap_pairs(t16);
@@ -492,8 +689,9 @@ mod simd {
492689 }
493690 e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);
494691 o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32);
495- _mm_storeu_si128(op.add(c).cast(), _mm_unpacklo_epi32(e, o));
496- _mm_storeu_si128(op.add(c + 4).cast(), _mm_unpackhi_epi32(e, o));
692+ let lo = _mm_unpacklo_epi32(e, o);
693+ let hi = _mm_unpackhi_epi32(e, o);
694+ _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
497695 c += 8;
498696 }
499697 for (o, w) in out[c..].iter_mut().zip(src[c..].windows(8)) {
@@ -501,7 +699,7 @@ mod simd {
501699 for t in 0..8 {
502700 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
503701 }
504- *o = round2(sum, INTER_ROUND_0);
702+ *o = sat16(round2(sum, INTER_ROUND_0));
505703 }
506704 }
507705 }
@@ -514,7 +712,7 @@ mod simd {
514712 /// loop and it auto-vectorises. The edge case keeps the exact spec form
515713 /// (`sample`'s clamp per tap); both arms compute the same sums.
516714 #[inline]
517-fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i32]) {
715+fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i16]) {
518716 let block_w = out.len();
519717 let start = x0 - 3;
520718 if start >= 0 && start as usize + block_w + 7 <= true_width {
@@ -537,7 +735,7 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap
537735 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
538736 sum += tap * i32::from(reference[row_base + x]);
539737 }
540- *o = round2(sum, INTER_ROUND_0);
738+ *o = sat16(round2(sum, INTER_ROUND_0));
541739 }
542740 }
543741
@@ -554,7 +752,7 @@ fn horizontal_pass_unscaled(
554752 taps: &[i32; 8],
555753 block_w: usize,
556754 rows: usize,
557- intermediate: &mut [i32],
755+ intermediate: &mut [i16],
558756 ) {
559757 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
560758 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
@@ -568,14 +766,14 @@ fn horizontal_pass_unscaled(
568766 if x0 >= 0 && x0 as usize + block_w <= true_width {
569767 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
570768 for (o, &s) in out.iter_mut().zip(src) {
571- *o = gain * i32::from(s);
769+ *o = (gain * i32::from(s)) as i16;
572770 }
573771 continue;
574772 }
575773 }
576774 for (c, o) in out.iter_mut().enumerate() {
577775 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;
578- *o = gain * i32::from(reference[y * stride + x]);
776+ *o = (gain * i32::from(reference[y * stride + x])) as i16;
579777 }
580778 continue;
581779 }
@@ -590,7 +788,7 @@ fn horizontal_pass_unscaled(
590788 /// eight slots. `acc` is left holding the unrounded sums.
591789 #[inline]
592790 #[allow(unsafe_code)]
593-pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
791+pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
594792 #[cfg(target_arch = "x86_64")]
595793 {
596794 match simd_level() {
@@ -612,8 +810,61 @@ pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps:
612810 vpass_row_scalar(intermediate, block_w, row, taps, acc);
613811 }
614812
813+/// lane-mc: [`vpass_row`] with the output rounding fused in, for the two
814+/// entry points whose destination is `u16` samples. The unrounded `i32` sums
815+/// used to be stored to a scratch row and read straight back by a rounding
816+/// loop; here they never leave the register.
817+#[inline]
818+#[allow(unsafe_code)]
819+fn vpass_row_u16(
820+ intermediate: &[i16],
821+ block_w: usize,
822+ row: usize,
823+ taps: &[i32; 8],
824+ max: i32,
825+ dst: &mut [u16],
826+) {
827+ #[cfg(target_arch = "x86_64")]
828+ {
829+ match simd_level() {
830+ // SAFETY: the arm is reached only when the CPU reports the
831+ // feature; the kernel reads `intermediate[(row+t)*block_w ..
832+ // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which
833+ // the debug asserts pin.
834+ SimdLevel::Avx2 => {
835+ unsafe { simd::vpass_row_u16_avx2(intermediate, block_w, row, taps, max, dst) };
836+ return;
837+ }
838+ SimdLevel::Sse41 => {
839+ unsafe { simd::vpass_row_u16_sse41(intermediate, block_w, row, taps, max, dst) };
840+ return;
841+ }
842+ SimdLevel::Scalar => {}
843+ }
844+ }
845+ vpass_row_u16_scalar(intermediate, block_w, row, taps, max, dst);
846+}
847+
848+/// The scalar reference for [`vpass_row_u16`].
849+fn vpass_row_u16_scalar(
850+ intermediate: &[i16],
851+ block_w: usize,
852+ row: usize,
853+ taps: &[i32; 8],
854+ max: i32,
855+ dst: &mut [u16],
856+) {
857+ for (c, d) in dst[..block_w].iter_mut().enumerate() {
858+ let mut sum = 0i32;
859+ for (t, &tap) in taps.iter().enumerate() {
860+ sum += tap * i32::from(intermediate[(row + t) * block_w + c]);
861+ }
862+ *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
863+ }
864+}
865+
615866 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).
616-fn vpass_row_scalar(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
867+fn vpass_row_scalar(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
617868 acc[..block_w].fill(0);
618869 for (t, &tap) in taps.iter().enumerate() {
619870 if tap == 0 {
@@ -621,7 +872,7 @@ fn vpass_row_scalar(intermediate: &[i32], block_w: usize, row: usize, taps: &[i3
621872 }
622873 let base = (row + t) * block_w;
623874 for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) {
624- *a += tap * s;
875+ *a += tap * i32::from(s);
625876 }
626877 }
627878 }
@@ -633,20 +884,24 @@ thread_local! {
633884 /// horizontal pass writes every element it later reads, so no clearing is
634885 /// needed; the tail `block_w` elements are the vertical pass's row
635886 /// accumulator.
636- static MC_SCRATCH: std::cell::RefCell<Vec<i32>> = const { std::cell::RefCell::new(Vec::new()) };
887+ static MC_SCRATCH: std::cell::RefCell<(Vec<i16>, Vec<i32>)> =
888+ const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
637889 }
638890
639891 /// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
640892 /// a `block_w` accumulator (see [`MC_SCRATCH`]).
641-fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i32], &mut [i32]) -> R) -> R {
893+fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i16], &mut [i32]) -> R) -> R {
642894 MC_SCRATCH.with(|s| {
643895 let mut buf = s.borrow_mut();
644- let need = rows * block_w + block_w;
645- if buf.len() < need {
646- buf.resize(need, 0);
896+ let (inter, acc) = &mut *buf;
897+ let need = rows * block_w;
898+ if inter.len() < need {
899+ inter.resize(need, 0);
900+ }
901+ if acc.len() < block_w {
902+ acc.resize(block_w, 0);
647903 }
648- let (inter, acc) = buf[..need].split_at_mut(rows * block_w);
649- f(inter, acc)
904+ f(&mut inter[..need], &mut acc[..block_w])
650905 })
651906 }
652907
@@ -808,7 +1063,16 @@ pub(crate) fn predict_with_filters_kern(
8081063 // lane-perf2: an interior row is one contiguous copy.
8091064 if x0 >= 0 && x0 as usize + block_w <= true_width {
8101065 if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {
811- out.copy_from_slice(src);
1066+ // The common widths get a constant-length copy: at 8
1067+ // samples a `memcpy` call costs more than the move it
1068+ // makes, and 8x8 is the most common inter block on real
1069+ // 4K content.
1070+ match block_w {
1071+ 4 => out[..4].copy_from_slice(&src[..4]),
1072+ 8 => out[..8].copy_from_slice(&src[..8]),
1073+ 16 => out[..16].copy_from_slice(&src[..16]),
1074+ _ => out.copy_from_slice(src),
1075+ }
8121076 continue;
8131077 }
8141078 }
@@ -844,7 +1108,7 @@ pub(crate) fn predict_with_filters_kern(
8441108 // block's own first row where the pass would have put the 4th.
8451109 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
8461110 let max = crate::decode::sample_max(fctx);
847- with_scratch(rows, block_w, |intermediate, acc| {
1111+ with_scratch(rows, block_w, |intermediate, _acc| {
8481112 horizontal_pass_unscaled(
8491113 reference, stride, true_width, true_height, x0,
8501114 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
@@ -852,15 +1116,15 @@ pub(crate) fn predict_with_filters_kern(
8521116 );
8531117 if yfrac == 0 {
8541118 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
855- *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
1119+ *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
8561120 }
8571121 return;
8581122 }
8591123 for row in 0..block_h {
860- vpass_row(intermediate, block_w, row, v_filter, acc);
861- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {
862- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;
863- }
1124+ vpass_row_u16(
1125+ intermediate, block_w, row, v_filter, max,
1126+ &mut dst[row * block_w..(row + 1) * block_w],
1127+ );
8641128 }
8651129 });
8661130
@@ -980,7 +1244,7 @@ fn horizontal_scaled_pass(
9801244 kern_w: usize,
9811245 rows: usize,
9821246 h_kind: InterpFilterKind,
983- intermediate: &mut [i32],
1247+ intermediate: &mut [i16],
9841248 ) {
9851249 let x_step_qn = round_pow2_64(x_scale_fp, 4);
9861250 let off = (x_scale_fp - REF_NO_SCALE) * 8;
@@ -1002,7 +1266,7 @@ fn horizontal_scaled_pass(
10021266 let x = int_pel + t as i32 - 3;
10031267 sum += tap * sample(reference, stride, true_width, true_height, x, y);
10041268 }
1005- intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
1269+ intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
10061270 }
10071271 }
10081272 }
@@ -1033,7 +1297,7 @@ fn horizontal_pass(
10331297 kern_w: usize,
10341298 rows: usize,
10351299 h_kind: InterpFilterKind,
1036- intermediate: &mut [i32],
1300+ intermediate: &mut [i16],
10371301 ) {
10381302 if x_scale_fp == REF_NO_SCALE {
10391303 let (h_wide, h_narrow) = h_kind.tables();
@@ -1134,7 +1398,7 @@ pub(crate) fn predict_scaled_kern(
11341398
11351399 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
11361400 let max = crate::decode::sample_max(fctx);
1137- with_scratch(rows, block_w, |intermediate, acc| {
1401+ with_scratch(rows, block_w, |intermediate, _acc| {
11381402 horizontal_pass(
11391403 reference, stride, true_width, true_height, x_q4,
11401404 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
@@ -1142,15 +1406,15 @@ pub(crate) fn predict_scaled_kern(
11421406 );
11431407 if yfrac == 0 {
11441408 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1145- *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
1409+ *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
11461410 }
11471411 return;
11481412 }
11491413 for row in 0..block_h {
1150- vpass_row(intermediate, block_w, row, v_filter, acc);
1151- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {
1152- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;
1153- }
1414+ vpass_row_u16(
1415+ intermediate, block_w, row, v_filter, max,
1416+ &mut dst[row * block_w..(row + 1) * block_w],
1417+ );
11541418 }
11551419 });
11561420 }
@@ -1290,7 +1554,9 @@ pub fn predict_compound_intermediate_kern(
12901554 );
12911555 if yfrac == 0 {
12921556 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
1293- dst.copy_from_slice(&intermediate[..dst.len()]);
1557+ for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1558+ *d = i32::from(a);
1559+ }
12941560 return;
12951561 }
12961562 for row in 0..block_h {
@@ -1848,18 +2114,18 @@ mod tests {
18482114 let src: Vec<u16> = (0..w + 7)
18492115 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
18502116 .collect();
1851- let mut want = vec![0i32; w];
2117+ let mut want = vec![0i16; w];
18522118 super::hpass_contig_scalar(&src, &t16, &mut want);
1853- let mut got = vec![0i32; w];
2119+ let mut got = vec![0i16; w];
18542120 super::hpass_contig(&src, &t16, &mut got);
18552121 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
18562122 #[cfg(target_arch = "x86_64")]
18572123 {
1858- let mut sse = vec![0i32; w];
2124+ let mut sse = vec![0i16; w];
18592125 unsafe { super::simd::hpass_sse2(&src, &t16, &mut sse) };
18602126 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
18612127 if std::arch::is_x86_feature_detected!("avx2") {
1862- let mut avx = vec![0i32; w];
2128+ let mut avx = vec![0i16; w];
18632129 unsafe { super::simd::hpass_avx2(&src, &t16, &mut avx) };
18642130 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
18652131 }
@@ -1873,6 +2139,42 @@ mod tests {
18732139 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
18742140 }
18752141
2142+ /// lane-mc: the intermediate the horizontal pass writes is `i16`, which
2143+ /// is a claim about the FILTER TABLES, not about a sample: every kernel's
2144+ /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
2145+ /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
2146+ /// value is that over `1 << INTER_ROUND_0`. This enumerates all four
2147+ /// filter kinds, both their wide and narrow tables and all 16 phases at
2148+ /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses
2149+ /// 12-bit by name) and pins the result inside `i16` -- so the SIMD
2150+ /// stores' `packs_epi32` never saturates on a motion-compensation path.
2151+ #[test]
2152+ fn horizontal_intermediate_fits_i16() {
2153+ let kinds = [
2154+ InterpFilterKind::Regular,
2155+ InterpFilterKind::Smooth,
2156+ InterpFilterKind::Sharp,
2157+ InterpFilterKind::Bilinear,
2158+ ];
2159+ let max_sample = 1023i32; // 10-bit
2160+ let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2161+ for &kind in &kinds {
2162+ let (wide, narrow) = kind.tables();
2163+ for table in [wide, narrow] {
2164+ for taps in table {
2165+ let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2166+ let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
2167+ worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0));
2168+ worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));
2169+ }
2170+ }
2171+ }
2172+ assert!(
2173+ worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
2174+ "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16"
2175+ );
2176+ }
2177+
18762178 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
18772179 /// reference, over the same domain as
18782180 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
@@ -1896,16 +2198,18 @@ mod tests {
18962198 InterpFilterKind::Bilinear,
18972199 ];
18982200 let mut checked = 0usize;
1899- for span in [255i32 * 16, 1023 * 16, 4095 * 22] {
2201+ // The horizontal pass's own range at 8- and 10-bit (12-bit is
2202+ // refused in stream.rs), plus the saturating store's extreme.
2203+ for span in [255i32 * 16, 1023 * 20, 32767] {
19002204 for &kind in &kinds {
19012205 let (wide, narrow) = kind.tables();
19022206 for table in [wide, narrow] {
19032207 for frac in 0..16usize {
19042208 let taps = &table[frac];
1905- for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
2209+ for w in [4usize, 5, 8, 12, 16, 20, 32, 64, 128] {
19062210 let rows = 12usize;
1907- let inter: Vec<i32> = (0..rows * w)
1908- .map(|_| (rng() % (2 * span as u64 + 1)) as i32 - span)
2211+ let inter: Vec<i16> = (0..rows * w)
2212+ .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
19092213 .collect();
19102214 for row in [0usize, 1, 4] {
19112215 let mut want = vec![0i32; w];
@@ -1926,6 +2230,37 @@ mod tests {
19262230 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
19272231 }
19282232 }
2233+ // lane-mc: the rounding-fused form, over both
2234+ // sample maxima this decoder accepts -- its
2235+ // `packus`/`min_epu16` pair must reproduce
2236+ // `round2(_, InterRound1).clamp(0, max)`.
2237+ for max in [255i32, 1023] {
2238+ let mut want_u16 = vec![0u16; w];
2239+ super::vpass_row_u16_scalar(&inter, w, row, taps, max, &mut want_u16);
2240+ for (d, &a) in want_u16.iter().zip(want.iter()) {
2241+ assert_eq!(
2242+ i32::from(*d),
2243+ super::round2(a, super::INTER_ROUND_1).clamp(0, max),
2244+ "the fused reference is the two-step one"
2245+ );
2246+ }
2247+ let mut got_u16 = vec![0u16; w];
2248+ super::vpass_row_u16(&inter, w, row, taps, max, &mut got_u16);
2249+ assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");
2250+ #[cfg(target_arch = "x86_64")]
2251+ {
2252+ if std::arch::is_x86_feature_detected!("sse4.1") {
2253+ let mut sse = vec![0u16; w];
2254+ unsafe { super::simd::vpass_row_u16_sse41(&inter, w, row, taps, max, &mut sse) };
2255+ assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");
2256+ }
2257+ if std::arch::is_x86_feature_detected!("avx2") {
2258+ let mut avx = vec![0u16; w];
2259+ unsafe { super::simd::vpass_row_u16_avx2(&inter, w, row, taps, max, &mut avx) };
2260+ assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");
2261+ }
2262+ }
2263+ }
19292264 checked += 1;
19302265 }
19312266 }
@@ -1933,6 +2268,6 @@ mod tests {
19332268 }
19342269 }
19352270 }
1936- assert_eq!(checked, 3 * 4 * 2 * 16 * 8 * 3);
2271+ assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3);
19372272 }
19382273 }
crates/ec-av1/src/restoration.rsmodified+7 -3
@@ -596,7 +596,7 @@ fn apply_wiener_stripe(
596596 // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the
597597 // last vertical output needs two rows of padding past the `h + 6` the
598598 // 7-tap kernel actually uses. Tap 7 is zero, so they never contribute.
599- inter.resize((h + 8) * w, 0i32);
599+ inter.resize((h + 8) * w, 0i16);
600600 // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16`
601601 // convolution over contiguous samples rounded by `Round2(_, 3)`, which
602602 // is `INTER_ROUND_0` -- so it runs on that module's kernels with the
@@ -606,7 +606,11 @@ fn apply_wiener_stripe(
606606 let hf = &info.hfilter;
607607 let t16: [i16; 8] =
608608 [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];
609- let (lo_bound, hi_bound) = (-wiener_bias as i32, (wiener_limit - 1 - wiener_bias) as i32);
609+ // lane-mc: the intermediate is `i16` now. Both bounds are inside that
610+ // range at 8- and 10-bit (12-bit is refused in stream.rs), so the
611+ // kernel's saturating store composes with this clamp instead of changing
612+ // it: `[-2048, 8191]` at 8-bit, `[-8192, 32767]` at 10.
613+ let (lo_bound, hi_bound) = (-wiener_bias as i16, (wiener_limit - 1 - wiener_bias) as i16);
610614 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
611615 for r in 0..rows {
612616 let row = v_start as i64 - 3 + r as i64;
@@ -651,7 +655,7 @@ fn apply_wiener_stripe(
651655 thread_local! {
652656 /// [`apply_wiener_stripe`]'s horizontal-pass intermediate, kept across
653657 /// calls so a stripe does not allocate (lane-perf7).
654- static WIENER_INTER_SCRATCH: std::cell::RefCell<Vec<i32>> =
658+ static WIENER_INTER_SCRATCH: std::cell::RefCell<Vec<i16>> =
655659 const { std::cell::RefCell::new(Vec::new()) };
656660 /// The clamped-column copy the horizontal pass needs at a plane edge.
657661 static WIENER_ROW_SCRATCH: std::cell::RefCell<Vec<u16>> =