forge
Explore
Log in

Don't you dare go Hollow

16-bit motion-compensation intermediate, vertical pass on madd

Browse files at this commit

ad664df4ff1885cc9e2fa675466cb7531790cf6bAhmet Kaan GümüşParent: 46b0c49
  • perf
    • 16-bit motion-compensation intermediate, vertical pass on madd
Show full message
perf(av1): 16-bit motion-compensation intermediate, vertical pass on madd

The separable inter filter kept its horizontal output in `i32`, so the
vertical pass spent one `mullo_epi32` per tap per 8 columns and moved
twice the bytes it had to. The intermediate provably fits `i16` at the
bit depths this decoder accepts -- a phase's positive taps sum to at
most 156, so `Round2(1023 * 156, 3)` is 19948, and 12-bit (where
`InterRound0` itself changes) is refused in stream.rs. With the buffer
narrowed, a row PAIR interleaved by `unpack_epi16` is exactly
`madd_epi16`'s shape: two taps of 16 columns per instruction.

The horizontal kernels store through `packs_epi32`, whose saturation is
unreachable on a motion-compensation path (the new
`horizontal_intermediate_fits_i16` enumerates every filter kind, table
and phase to prove it) and composes with the wiener clamp on the
restoration path, whose bounds are inside `i16` at 8- and 10-bit.

-3.7% instructions on the 4K segment (553.2 -> 532.7 G at one thread);
all four gate hashes unchanged.
crates/ec-av1/src/mc.rsmodified+189 -76
@@ -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,7 +339,7 @@ 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};
333343 use std::arch::x86_64::*;
334344
335345 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
@@ -350,7 +360,7 @@ mod simd {
350360 /// # Safety
351361 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.
352362 #[target_feature(enable = "avx2")]
353- pub unsafe fn hpass_avx2(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
363+ pub unsafe fn hpass_avx2(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
354364 debug_assert!(src.len() >= out.len() + 7);
355365 let n = out.len();
356366 let tp = tap_pairs(t16);
@@ -377,8 +387,11 @@ mod simd {
377387 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);
378388 let lo = _mm256_unpacklo_epi32(e, o);
379389 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));
390+ // `lo`/`hi` already hold the 16 outputs in order, four per
391+ // 128-bit lane; `packs_epi32` narrows lane-wise, so the store is
392+ // c..c+16 in order. Saturation never fires: see
393+ // `horizontal_intermediate_fits_i16`.
394+ _mm256_storeu_si256(op.add(c).cast(), _mm256_packs_epi32(lo, hi));
382395 c += 16;
383396 }
384397 if c < n {
@@ -386,79 +399,134 @@ mod simd {
386399 }
387400 }
388401
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.
402+ /// Vertical pass, AVX2: the intermediate is `i16` (lane-mc: it provably
403+ /// fits, see `horizontal_intermediate_fits_i16`), so a row PAIR
404+ /// interleaved by `unpack_epi16` is exactly `_mm256_madd_epi16`'s shape --
405+ /// two taps of 16 columns per instruction, where the old `i32` form spent
406+ /// one `mullo_epi32` per tap per 8 columns. `acc` is left unrounded, as
407+ /// the scalar form leaves it.
394408 ///
395409 /// # Safety
396410 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
397411 /// and `acc` at least `block_w`.
398412 #[target_feature(enable = "avx2")]
399413 pub unsafe fn vpass_avx2(
400- intermediate: &[i32],
414+ intermediate: &[i16],
401415 block_w: usize,
402416 row: usize,
403417 taps: &[i32; 8],
404418 acc: &mut [i32],
405419 ) {
406420 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
421+ let t16 = [
422+ taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
423+ taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
424+ ];
425+ let tp = tap_pairs(&t16);
407426 let ip = intermediate.as_ptr().add(row * block_w);
408427 let ap = acc.as_mut_ptr();
409428 let mut c = 0usize;
429+ while c + 16 <= block_w {
430+ // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
431+ // lane), `hi` the other two runs; the two `permute2x128`s put the
432+ // 16 sums back in column order.
433+ let mut lo = _mm256_setzero_si256();
434+ let mut hi = _mm256_setzero_si256();
435+ for k in 0..4 {
436+ if tp[k] == 0 {
437+ continue;
438+ }
439+ let tv = _mm256_set1_epi32(tp[k]);
440+ let a = _mm256_loadu_si256(ip.add(2 * k * block_w + c).cast());
441+ let b = _mm256_loadu_si256(ip.add((2 * k + 1) * block_w + c).cast());
442+ lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
443+ hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
444+ }
445+ _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
446+ _mm256_storeu_si256(ap.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));
447+ c += 16;
448+ }
449+ vpass_tail_sse(ip, block_w, &tp, taps, ap, c);
450+ }
451+
452+ /// [`vpass_avx2`]'s 8- and 4-column steps, 128-bit: every AV1 block width
453+ /// is a multiple of 4, and the 8x8 luma block (the most common inter
454+ /// shape on real 4K content) lands here whole.
455+ ///
456+ /// # Safety
457+ /// `ip` must be readable for `8 * block_w` elements from `row`'s start and
458+ /// `ap` writable for `block_w`; `c` is the column already done.
459+ #[inline]
460+ unsafe fn vpass_tail_sse(
461+ ip: *const i16,
462+ block_w: usize,
463+ tp: &[i32; 4],
464+ taps: &[i32; 8],
465+ ap: *mut i32,
466+ mut c: usize,
467+ ) {
410468 while c + 8 <= block_w {
411- let mut v = _mm256_setzero_si256();
412- for (t, &tap) in taps.iter().enumerate() {
413- if tap == 0 {
469+ let mut lo = _mm_setzero_si128();
470+ let mut hi = _mm_setzero_si128();
471+ for k in 0..4 {
472+ if tp[k] == 0 {
414473 continue;
415474 }
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));
475+ let tv = _mm_set1_epi32(tp[k]);
476+ let a = _mm_loadu_si128(ip.add(2 * k * block_w + c).cast());
477+ let b = _mm_loadu_si128(ip.add((2 * k + 1) * block_w + c).cast());
478+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
479+ hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
418480 }
419- _mm256_storeu_si256(ap.add(c).cast(), v);
481+ _mm_storeu_si128(ap.add(c).cast(), lo);
482+ _mm_storeu_si128(ap.add(c + 4).cast(), hi);
420483 c += 8;
421484 }
422- // Widths are multiples of 4, so at most one 4-column tail is left.
423- for cc in c..block_w {
485+ while c + 4 <= block_w {
486+ let mut lo = _mm_setzero_si128();
487+ for k in 0..4 {
488+ if tp[k] == 0 {
489+ continue;
490+ }
491+ let tv = _mm_set1_epi32(tp[k]);
492+ let a = _mm_loadl_epi64(ip.add(2 * k * block_w + c).cast());
493+ let b = _mm_loadl_epi64(ip.add((2 * k + 1) * block_w + c).cast());
494+ lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
495+ }
496+ _mm_storeu_si128(ap.add(c).cast(), lo);
497+ c += 4;
498+ }
499+ // Every AV1 block width is a multiple of 4, but the encoder's own
500+ // motion search prices odd widths through `predict`, so the last
501+ // columns still need the scalar form.
502+ while c < block_w {
424503 let mut sum = 0i32;
425504 for (t, &tap) in taps.iter().enumerate() {
426- sum += tap * intermediate[(row + t) * block_w + cc];
505+ sum += tap * i32::from(*ip.add(t * block_w + c));
427506 }
428- acc[cc] = sum;
507+ *ap.add(c) = sum;
508+ c += 1;
429509 }
430510 }
431511
432- /// Vertical pass, SSE4.1 (`_mm_mullo_epi32` is SSE4.1, unlike the
433- /// horizontal pass's SSE2 `madd`): [`vpass_avx2`] at 4 columns.
512+ /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.
434513 ///
435514 /// # Safety
436- /// Requires SSE4.1; same slice contract as [`vpass_avx2`].
437- #[target_feature(enable = "sse4.1")]
515+ /// SSE2 is baseline x86_64; same slice contract as [`vpass_avx2`].
438516 pub unsafe fn vpass_sse41(
439- intermediate: &[i32],
517+ intermediate: &[i16],
440518 block_w: usize,
441519 row: usize,
442520 taps: &[i32; 8],
443521 acc: &mut [i32],
444522 ) {
445523 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
446- let ip = intermediate.as_ptr().add(row * block_w);
447- let ap = acc.as_mut_ptr();
448- let mut c = 0usize;
449- while c + 4 <= block_w {
450- let mut v = _mm_setzero_si128();
451- for (t, &tap) in taps.iter().enumerate() {
452- if tap == 0 {
453- continue;
454- }
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));
457- }
458- _mm_storeu_si128(ap.add(c).cast(), v);
459- c += 4;
460- }
461- debug_assert_eq!(c, block_w, "every AV1 block width is a multiple of 4");
524+ let t16 = [
525+ taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
526+ taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
527+ ];
528+ let tp = tap_pairs(&t16);
529+ vpass_tail_sse(intermediate.as_ptr().add(row * block_w), block_w, &tp, taps, acc.as_mut_ptr(), 0);
462530 }
463531
464532 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per
@@ -467,7 +535,7 @@ mod simd {
467535 ///
468536 /// # Safety
469537 /// `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]) {
538+ pub unsafe fn hpass_sse2(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
471539 debug_assert!(src.len() >= out.len() + 7);
472540 let n = out.len();
473541 let tp = tap_pairs(t16);
@@ -492,8 +560,9 @@ mod simd {
492560 }
493561 e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);
494562 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));
563+ let lo = _mm_unpacklo_epi32(e, o);
564+ let hi = _mm_unpackhi_epi32(e, o);
565+ _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
497566 c += 8;
498567 }
499568 for (o, w) in out[c..].iter_mut().zip(src[c..].windows(8)) {
@@ -501,7 +570,7 @@ mod simd {
501570 for t in 0..8 {
502571 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
503572 }
504- *o = round2(sum, INTER_ROUND_0);
573+ *o = sat16(round2(sum, INTER_ROUND_0));
505574 }
506575 }
507576 }
@@ -514,7 +583,7 @@ mod simd {
514583 /// loop and it auto-vectorises. The edge case keeps the exact spec form
515584 /// (`sample`'s clamp per tap); both arms compute the same sums.
516585 #[inline]
517-fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i32]) {
586+fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i16]) {
518587 let block_w = out.len();
519588 let start = x0 - 3;
520589 if start >= 0 && start as usize + block_w + 7 <= true_width {
@@ -537,7 +606,7 @@ fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, tap
537606 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
538607 sum += tap * i32::from(reference[row_base + x]);
539608 }
540- *o = round2(sum, INTER_ROUND_0);
609+ *o = sat16(round2(sum, INTER_ROUND_0));
541610 }
542611 }
543612
@@ -554,7 +623,7 @@ fn horizontal_pass_unscaled(
554623 taps: &[i32; 8],
555624 block_w: usize,
556625 rows: usize,
557- intermediate: &mut [i32],
626+ intermediate: &mut [i16],
558627 ) {
559628 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
560629 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
@@ -568,14 +637,14 @@ fn horizontal_pass_unscaled(
568637 if x0 >= 0 && x0 as usize + block_w <= true_width {
569638 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
570639 for (o, &s) in out.iter_mut().zip(src) {
571- *o = gain * i32::from(s);
640+ *o = (gain * i32::from(s)) as i16;
572641 }
573642 continue;
574643 }
575644 }
576645 for (c, o) in out.iter_mut().enumerate() {
577646 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;
578- *o = gain * i32::from(reference[y * stride + x]);
647+ *o = (gain * i32::from(reference[y * stride + x])) as i16;
579648 }
580649 continue;
581650 }
@@ -590,7 +659,7 @@ fn horizontal_pass_unscaled(
590659 /// eight slots. `acc` is left holding the unrounded sums.
591660 #[inline]
592661 #[allow(unsafe_code)]
593-pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
662+pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
594663 #[cfg(target_arch = "x86_64")]
595664 {
596665 match simd_level() {
@@ -613,7 +682,7 @@ pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps:
613682 }
614683
615684 /// 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]) {
685+fn vpass_row_scalar(intermediate: &[i16], block_w: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
617686 acc[..block_w].fill(0);
618687 for (t, &tap) in taps.iter().enumerate() {
619688 if tap == 0 {
@@ -621,7 +690,7 @@ fn vpass_row_scalar(intermediate: &[i32], block_w: usize, row: usize, taps: &[i3
621690 }
622691 let base = (row + t) * block_w;
623692 for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) {
624- *a += tap * s;
693+ *a += tap * i32::from(s);
625694 }
626695 }
627696 }
@@ -633,20 +702,24 @@ thread_local! {
633702 /// horizontal pass writes every element it later reads, so no clearing is
634703 /// needed; the tail `block_w` elements are the vertical pass's row
635704 /// accumulator.
636- static MC_SCRATCH: std::cell::RefCell<Vec<i32>> = const { std::cell::RefCell::new(Vec::new()) };
705+ static MC_SCRATCH: std::cell::RefCell<(Vec<i16>, Vec<i32>)> =
706+ const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
637707 }
638708
639709 /// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
640710 /// 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 {
711+fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i16], &mut [i32]) -> R) -> R {
642712 MC_SCRATCH.with(|s| {
643713 let mut buf = s.borrow_mut();
644- let need = rows * block_w + block_w;
645- if buf.len() < need {
646- buf.resize(need, 0);
714+ let (inter, acc) = &mut *buf;
715+ let need = rows * block_w;
716+ if inter.len() < need {
717+ inter.resize(need, 0);
647718 }
648- let (inter, acc) = buf[..need].split_at_mut(rows * block_w);
649- f(inter, acc)
719+ if acc.len() < block_w {
720+ acc.resize(block_w, 0);
721+ }
722+ f(&mut inter[..need], &mut acc[..block_w])
650723 })
651724 }
652725
@@ -852,7 +925,7 @@ pub(crate) fn predict_with_filters_kern(
852925 );
853926 if yfrac == 0 {
854927 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
855- *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
928+ *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
856929 }
857930 return;
858931 }
@@ -980,7 +1053,7 @@ fn horizontal_scaled_pass(
9801053 kern_w: usize,
9811054 rows: usize,
9821055 h_kind: InterpFilterKind,
983- intermediate: &mut [i32],
1056+ intermediate: &mut [i16],
9841057 ) {
9851058 let x_step_qn = round_pow2_64(x_scale_fp, 4);
9861059 let off = (x_scale_fp - REF_NO_SCALE) * 8;
@@ -1002,7 +1075,7 @@ fn horizontal_scaled_pass(
10021075 let x = int_pel + t as i32 - 3;
10031076 sum += tap * sample(reference, stride, true_width, true_height, x, y);
10041077 }
1005- intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);
1078+ intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
10061079 }
10071080 }
10081081 }
@@ -1033,7 +1106,7 @@ fn horizontal_pass(
10331106 kern_w: usize,
10341107 rows: usize,
10351108 h_kind: InterpFilterKind,
1036- intermediate: &mut [i32],
1109+ intermediate: &mut [i16],
10371110 ) {
10381111 if x_scale_fp == REF_NO_SCALE {
10391112 let (h_wide, h_narrow) = h_kind.tables();
@@ -1142,7 +1215,7 @@ pub(crate) fn predict_scaled_kern(
11421215 );
11431216 if yfrac == 0 {
11441217 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1145- *d = round2(a, INTER_ROUND_1 - 7).clamp(0, max) as u16;
1218+ *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
11461219 }
11471220 return;
11481221 }
@@ -1290,7 +1363,9 @@ pub fn predict_compound_intermediate_kern(
12901363 );
12911364 if yfrac == 0 {
12921365 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
1293- dst.copy_from_slice(&intermediate[..dst.len()]);
1366+ for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1367+ *d = i32::from(a);
1368+ }
12941369 return;
12951370 }
12961371 for row in 0..block_h {
@@ -1848,18 +1923,18 @@ mod tests {
18481923 let src: Vec<u16> = (0..w + 7)
18491924 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
18501925 .collect();
1851- let mut want = vec![0i32; w];
1926+ let mut want = vec![0i16; w];
18521927 super::hpass_contig_scalar(&src, &t16, &mut want);
1853- let mut got = vec![0i32; w];
1928+ let mut got = vec![0i16; w];
18541929 super::hpass_contig(&src, &t16, &mut got);
18551930 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
18561931 #[cfg(target_arch = "x86_64")]
18571932 {
1858- let mut sse = vec![0i32; w];
1933+ let mut sse = vec![0i16; w];
18591934 unsafe { super::simd::hpass_sse2(&src, &t16, &mut sse) };
18601935 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
18611936 if std::arch::is_x86_feature_detected!("avx2") {
1862- let mut avx = vec![0i32; w];
1937+ let mut avx = vec![0i16; w];
18631938 unsafe { super::simd::hpass_avx2(&src, &t16, &mut avx) };
18641939 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
18651940 }
@@ -1873,6 +1948,42 @@ mod tests {
18731948 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
18741949 }
18751950
1951+ /// lane-mc: the intermediate the horizontal pass writes is `i16`, which
1952+ /// is a claim about the FILTER TABLES, not about a sample: every kernel's
1953+ /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
1954+ /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
1955+ /// value is that over `1 << INTER_ROUND_0`. This enumerates all four
1956+ /// filter kinds, both their wide and narrow tables and all 16 phases at
1957+ /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses
1958+ /// 12-bit by name) and pins the result inside `i16` -- so the SIMD
1959+ /// stores' `packs_epi32` never saturates on a motion-compensation path.
1960+ #[test]
1961+ fn horizontal_intermediate_fits_i16() {
1962+ let kinds = [
1963+ InterpFilterKind::Regular,
1964+ InterpFilterKind::Smooth,
1965+ InterpFilterKind::Sharp,
1966+ InterpFilterKind::Bilinear,
1967+ ];
1968+ let max_sample = 1023i32; // 10-bit
1969+ let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
1970+ for &kind in &kinds {
1971+ let (wide, narrow) = kind.tables();
1972+ for table in [wide, narrow] {
1973+ for taps in table {
1974+ let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
1975+ let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
1976+ worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0));
1977+ worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));
1978+ }
1979+ }
1980+ }
1981+ assert!(
1982+ worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
1983+ "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16"
1984+ );
1985+ }
1986+
18761987 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
18771988 /// reference, over the same domain as
18781989 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
@@ -1896,7 +2007,9 @@ mod tests {
18962007 InterpFilterKind::Bilinear,
18972008 ];
18982009 let mut checked = 0usize;
1899- for span in [255i32 * 16, 1023 * 16, 4095 * 22] {
2010+ // The horizontal pass's own range at 8- and 10-bit (12-bit is
2011+ // refused in stream.rs), plus the saturating store's extreme.
2012+ for span in [255i32 * 16, 1023 * 20, 32767] {
19002013 for &kind in &kinds {
19012014 let (wide, narrow) = kind.tables();
19022015 for table in [wide, narrow] {
@@ -1904,8 +2017,8 @@ mod tests {
19042017 let taps = &table[frac];
19052018 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
19062019 let rows = 12usize;
1907- let inter: Vec<i32> = (0..rows * w)
1908- .map(|_| (rng() % (2 * span as u64 + 1)) as i32 - span)
2020+ let inter: Vec<i16> = (0..rows * w)
2021+ .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
19092022 .collect();
19102023 for row in [0usize, 1, 4] {
19112024 let mut want = vec![0i32; w];
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>> =