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 {
18 }18 }
19 }19 }
20 20
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+
21 /// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the31 /// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
22 /// horizontal pass's sum is brought down by before it is stored as the32 /// horizontal pass's sum is brought down by before it is stored as the
23 /// intermediate.33 /// intermediate.
@@ -285,7 +295,7 @@ pub(crate) fn simd_level() -> SimdLevel {
285 /// the same `Round2(sum, InterRound0)`.295 /// the same `Round2(sum, InterRound0)`.
286 #[allow(unsafe_code)]296 #[allow(unsafe_code)]
287 #[inline]297 #[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]) {
289 #[cfg(target_arch = "x86_64")]299 #[cfg(target_arch = "x86_64")]
290 {300 {
291 match simd_level() {301 match simd_level() {
@@ -308,7 +318,7 @@ pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
308 }318 }
309 319
310 /// The scalar reference for [`hpass_contig`] (lane-perf2's loop).320 /// 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]) {
312 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit322 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
313 // depth), so the products are exactly the i32 ones but the widening323 // depth), so the products are exactly the i32 ones but the widening
314 // multiply is one instruction per pair.324 // multiply is one instruction per pair.
@@ -317,7 +327,7 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
317 for t in 0..8 {327 for t in 0..8 {
318 sum += i32::from(t16[t]) * i32::from(w[t] as i16);328 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
319 }329 }
320- *o = round2(sum, INTER_ROUND_0);330+ *o = sat16(round2(sum, INTER_ROUND_0));
321 }331 }
322 }332 }
323 333
@@ -329,12 +339,20 @@ fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i32]) {
329 #[cfg(target_arch = "x86_64")]339 #[cfg(target_arch = "x86_64")]
330 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract340 #[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
331 mod simd {341 mod simd {
332- use super::{round2, INTER_ROUND_0};342+ use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};
333 use std::arch::x86_64::*;343 use std::arch::x86_64::*;
334 344
335 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape345 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
336 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is346 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is
337 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.347 /// `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+
338 #[inline]356 #[inline]
339 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {357 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
340 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);358 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
@@ -350,7 +368,7 @@ mod simd {
350 /// # Safety368 /// # Safety
351 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.369 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.
352 #[target_feature(enable = "avx2")]370 #[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]) {
354 debug_assert!(src.len() >= out.len() + 7);372 debug_assert!(src.len() >= out.len() + 7);
355 let n = out.len();373 let n = out.len();
356 let tp = tap_pairs(t16);374 let tp = tap_pairs(t16);
@@ -377,8 +395,11 @@ mod simd {
377 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);395 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);
378 let lo = _mm256_unpacklo_epi32(e, o);396 let lo = _mm256_unpacklo_epi32(e, o);
379 let hi = _mm256_unpackhi_epi32(e, o);397 let hi = _mm256_unpackhi_epi32(e, o);
380- _mm256_storeu_si256(op.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));398+ // `lo`/`hi` already hold the 16 outputs in order, four per
381- _mm256_storeu_si256(op.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));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));
382 c += 16;403 c += 16;
383 }404 }
384 if c < n {405 if c < n {
@@ -386,79 +407,255 @@ mod simd {
386 }407 }
387 }408 }
388 409
389- /// Vertical pass, AVX2: 8 output columns per iteration, one410+ /// Vertical pass, AVX2: the intermediate is `i16` (lane-mc: it provably
390- /// `_mm256_mullo_epi32` + `_mm256_add_epi32` per non-zero tap. Exact:411+ /// fits, see `horizontal_intermediate_fits_i16`), so a row PAIR
391- /// an intermediate is at most ~2^17 and a tap at most 128, so the eight412+ /// interleaved by `unpack_epi16` is exactly `_mm256_madd_epi16`'s shape --
392- /// products stay well inside `i32` and `mullo`'s low half is the whole413+ /// two taps of 16 columns per instruction, where the old `i32` form spent
393- /// product. `acc` is left unrounded, as the scalar form leaves it.414+ /// one `mullo_epi32` per tap per 8 columns. `acc` is left unrounded, as
415+ /// the scalar form leaves it.
394 ///416 ///
395 /// # Safety417 /// # Safety
396 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements418 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
397 /// and `acc` at least `block_w`.419 /// and `acc` at least `block_w`.
398 #[target_feature(enable = "avx2")]420 #[target_feature(enable = "avx2")]
399 pub unsafe fn vpass_avx2(421 pub unsafe fn vpass_avx2(
400- intermediate: &[i32],422+ intermediate: &[i16],
401 block_w: usize,423 block_w: usize,
402 row: usize,424 row: usize,
403 taps: &[i32; 8],425 taps: &[i32; 8],
404 acc: &mut [i32],426 acc: &mut [i32],
405 ) {427 ) {
406 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);428 debug_assert!(intermediate.len() >= (row + 8) * block_w && acc.len() >= block_w);
429+ let tp = tap_pairs(&taps16(taps));
407 let ip = intermediate.as_ptr().add(row * block_w);430 let ip = intermediate.as_ptr().add(row * block_w);
408 let ap = acc.as_mut_ptr();431 let ap = acc.as_mut_ptr();
409 let mut c = 0usize;432 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+ ) {
410 while c + 8 <= block_w {472 while c + 8 <= block_w {
411- let mut v = _mm256_setzero_si256();473+ let mut lo = _mm_setzero_si128();
412- for (t, &tap) in taps.iter().enumerate() {474+ let mut hi = _mm_setzero_si128();
413- if tap == 0 {475+ for k in 0..4 {
476+ if tp[k] == 0 {
414 continue;477 continue;
415 }478 }
416- let s = _mm256_loadu_si256(ip.add(t * block_w + c).cast());479+ let tv = _mm_set1_epi32(tp[k]);
417- v = _mm256_add_epi32(v, _mm256_mullo_epi32(_mm256_set1_epi32(tap), s));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));
418 }484 }
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);
420 c += 8;487 c += 8;
421 }488 }
422- // Widths are multiples of 4, so at most one 4-column tail is left.489+ while c + 4 <= block_w {
423- for cc in c..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 {
424 let mut sum = 0i32;507 let mut sum = 0i32;
425 for (t, &tap) in taps.iter().enumerate() {508 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));
427 }510 }
428- acc[cc] = sum;511+ *ap.add(c) = sum;
512+ c += 1;
429 }513 }
430 }514 }
431 515
432- /// Vertical pass, SSE4.1 (`_mm_mullo_epi32` is SSE4.1, unlike the516+ /// [`vpass_avx2`] with the output rounding fused in: the sums never reach
433- /// horizontal pass's SSE2 `madd`): [`vpass_avx2`] at 4 columns.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)`.
434 ///521 ///
435 /// # Safety522 /// # Safety
436- /// Requires SSE4.1; same slice contract as [`vpass_avx2`].523+ /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
437- #[target_feature(enable = "sse4.1")]524+ /// and `dst` at least `block_w`.
438- pub unsafe fn vpass_sse41(525+ #[target_feature(enable = "avx2")]
439- intermediate: &[i32],526+ pub unsafe fn vpass_row_u16_avx2(
527+ intermediate: &[i16],
440 block_w: usize,528 block_w: usize,
441 row: usize,529 row: usize,
442 taps: &[i32; 8],530 taps: &[i32; 8],
443- acc: &mut [i32],531+ max: i32,
532+ dst: &mut [u16],
444 ) {533 ) {
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));
446 let ip = intermediate.as_ptr().add(row * block_w);536 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);
448 let mut c = 0usize;540 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);
449 while c + 4 <= block_w {582 while c + 4 <= block_w {
450- let mut v = _mm_setzero_si128();583+ let wide = c + 8 <= block_w;
451- for (t, &tap) in taps.iter().enumerate() {584+ let mut lo = rnd;
452- if tap == 0 {585+ let mut hi = rnd;
586+ for k in 0..4 {
587+ if tp[k] == 0 {
453 continue;588 continue;
454 }589 }
455- let s = _mm_loadu_si128(ip.add(t * block_w + c).cast());590+ let tv = _mm_set1_epi32(tp[k]);
456- v = _mm_add_epi32(v, _mm_mullo_epi32(_mm_set1_epi32(tap), s));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+ }
457 }601 }
458- _mm_storeu_si128(ap.add(c).cast(), v);602+ let v = _mm_min_epu16(
459- c += 4;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;
460 }621 }
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);
462 }659 }
463 660
464 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per661 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per
@@ -467,7 +664,7 @@ mod simd {
467 ///664 ///
468 /// # Safety665 /// # Safety
469 /// `src.len()` must be at least `out.len() + 7`. SSE2 is baseline x86_64.666 /// `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]) {
471 debug_assert!(src.len() >= out.len() + 7);668 debug_assert!(src.len() >= out.len() + 7);
472 let n = out.len();669 let n = out.len();
473 let tp = tap_pairs(t16);670 let tp = tap_pairs(t16);
@@ -492,8 +689,9 @@ mod simd {
492 }689 }
493 e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);690 e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);
494 o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32);691 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));692+ let lo = _mm_unpacklo_epi32(e, o);
496- _mm_storeu_si128(op.add(c + 4).cast(), _mm_unpackhi_epi32(e, o));693+ let hi = _mm_unpackhi_epi32(e, o);
694+ _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
497 c += 8;695 c += 8;
498 }696 }
499 for (o, w) in out[c..].iter_mut().zip(src[c..].windows(8)) {697 for (o, w) in out[c..].iter_mut().zip(src[c..].windows(8)) {
@@ -501,7 +699,7 @@ mod simd {
501 for t in 0..8 {699 for t in 0..8 {
502 sum += i32::from(t16[t]) * i32::from(w[t] as i16);700 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
503 }701 }
504- *o = round2(sum, INTER_ROUND_0);702+ *o = sat16(round2(sum, INTER_ROUND_0));
505 }703 }
506 }704 }
507 }705 }
@@ -514,7 +712,7 @@ mod simd {
514 /// loop and it auto-vectorises. The edge case keeps the exact spec form712 /// loop and it auto-vectorises. The edge case keeps the exact spec form
515 /// (`sample`'s clamp per tap); both arms compute the same sums.713 /// (`sample`'s clamp per tap); both arms compute the same sums.
516 #[inline]714 #[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]) {
518 let block_w = out.len();716 let block_w = out.len();
519 let start = x0 - 3;717 let start = x0 - 3;
520 if start >= 0 && start as usize + block_w + 7 <= true_width {718 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
537 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;735 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
538 sum += tap * i32::from(reference[row_base + x]);736 sum += tap * i32::from(reference[row_base + x]);
539 }737 }
540- *o = round2(sum, INTER_ROUND_0);738+ *o = sat16(round2(sum, INTER_ROUND_0));
541 }739 }
542 }740 }
543 741
@@ -554,7 +752,7 @@ fn horizontal_pass_unscaled(
554 taps: &[i32; 8],752 taps: &[i32; 8],
555 block_w: usize,753 block_w: usize,
556 rows: usize,754 rows: usize,
557- intermediate: &mut [i32],755+ intermediate: &mut [i16],
558 ) {756 ) {
559 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,757 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
560 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position758 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
@@ -568,14 +766,14 @@ fn horizontal_pass_unscaled(
568 if x0 >= 0 && x0 as usize + block_w <= true_width {766 if x0 >= 0 && x0 as usize + block_w <= true_width {
569 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {767 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
570 for (o, &s) in out.iter_mut().zip(src) {768 for (o, &s) in out.iter_mut().zip(src) {
571- *o = gain * i32::from(s);769+ *o = (gain * i32::from(s)) as i16;
572 }770 }
573 continue;771 continue;
574 }772 }
575 }773 }
576 for (c, o) in out.iter_mut().enumerate() {774 for (c, o) in out.iter_mut().enumerate() {
577 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;775 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;
579 }777 }
580 continue;778 continue;
581 }779 }
@@ -590,7 +788,7 @@ fn horizontal_pass_unscaled(
590 /// eight slots. `acc` is left holding the unrounded sums.788 /// eight slots. `acc` is left holding the unrounded sums.
591 #[inline]789 #[inline]
592 #[allow(unsafe_code)]790 #[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]) {
594 #[cfg(target_arch = "x86_64")]792 #[cfg(target_arch = "x86_64")]
595 {793 {
596 match simd_level() {794 match simd_level() {
@@ -612,8 +810,61 @@ pub(crate) fn vpass_row(intermediate: &[i32], block_w: usize, row: usize, taps:
612 vpass_row_scalar(intermediate, block_w, row, taps, acc);810 vpass_row_scalar(intermediate, block_w, row, taps, acc);
613 }811 }
614 812
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+
615 /// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).866 /// 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]) {
617 acc[..block_w].fill(0);868 acc[..block_w].fill(0);
618 for (t, &tap) in taps.iter().enumerate() {869 for (t, &tap) in taps.iter().enumerate() {
619 if tap == 0 {870 if tap == 0 {
@@ -621,7 +872,7 @@ fn vpass_row_scalar(intermediate: &[i32], block_w: usize, row: usize, taps: &[i3
621 }872 }
622 let base = (row + t) * block_w;873 let base = (row + t) * block_w;
623 for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) {874 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);
625 }876 }
626 }877 }
627 }878 }
@@ -633,20 +884,24 @@ thread_local! {
633 /// horizontal pass writes every element it later reads, so no clearing is884 /// horizontal pass writes every element it later reads, so no clearing is
634 /// needed; the tail `block_w` elements are the vertical pass's row885 /// needed; the tail `block_w` elements are the vertical pass's row
635 /// accumulator.886 /// 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())) };
637 }889 }
638 890
639 /// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus891 /// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
640 /// a `block_w` accumulator (see [`MC_SCRATCH`]).892 /// 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 {
642 MC_SCRATCH.with(|s| {894 MC_SCRATCH.with(|s| {
643 let mut buf = s.borrow_mut();895 let mut buf = s.borrow_mut();
644- let need = rows * block_w + block_w;896+ let (inter, acc) = &mut *buf;
645- if buf.len() < need {897+ let need = rows * block_w;
646- buf.resize(need, 0);898+ if inter.len() < need {
899+ inter.resize(need, 0);
900+ }
901+ if acc.len() < block_w {
902+ acc.resize(block_w, 0);
647 }903 }
648- let (inter, acc) = buf[..need].split_at_mut(rows * block_w);904+ f(&mut inter[..need], &mut acc[..block_w])
649- f(inter, acc)
650 })905 })
651 }906 }
652 907
@@ -808,7 +1063,16 @@ pub(crate) fn predict_with_filters_kern(
808 // lane-perf2: an interior row is one contiguous copy.1063 // lane-perf2: an interior row is one contiguous copy.
809 if x0 >= 0 && x0 as usize + block_w <= true_width {1064 if x0 >= 0 && x0 as usize + block_w <= true_width {
810 if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {1065 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+ }
812 continue;1076 continue;
813 }1077 }
814 }1078 }
@@ -844,7 +1108,7 @@ pub(crate) fn predict_with_filters_kern(
844 // block's own first row where the pass would have put the 4th.1108 // block's own first row where the pass would have put the 4th.
845 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1109 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
846 let max = crate::decode::sample_max(fctx);1110 let max = crate::decode::sample_max(fctx);
847- with_scratch(rows, block_w, |intermediate, acc| {1111+ with_scratch(rows, block_w, |intermediate, _acc| {
848 horizontal_pass_unscaled(1112 horizontal_pass_unscaled(
849 reference, stride, true_width, true_height, x0,1113 reference, stride, true_width, true_height, x0,
850 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,1114 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
@@ -852,15 +1116,15 @@ pub(crate) fn predict_with_filters_kern(
852 );1116 );
853 if yfrac == 0 {1117 if yfrac == 0 {
854 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {1118 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;
856 }1120 }
857 return;1121 return;
858 }1122 }
859 for row in 0..block_h {1123 for row in 0..block_h {
860- vpass_row(intermediate, block_w, row, v_filter, acc);1124+ vpass_row_u16(
861- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {1125+ intermediate, block_w, row, v_filter, max,
862- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;1126+ &mut dst[row * block_w..(row + 1) * block_w],
863- }1127+ );
864 }1128 }
865 });1129 });
866 1130
@@ -980,7 +1244,7 @@ fn horizontal_scaled_pass(
980 kern_w: usize,1244 kern_w: usize,
981 rows: usize,1245 rows: usize,
982 h_kind: InterpFilterKind,1246 h_kind: InterpFilterKind,
983- intermediate: &mut [i32],1247+ intermediate: &mut [i16],
984 ) {1248 ) {
985 let x_step_qn = round_pow2_64(x_scale_fp, 4);1249 let x_step_qn = round_pow2_64(x_scale_fp, 4);
986 let off = (x_scale_fp - REF_NO_SCALE) * 8;1250 let off = (x_scale_fp - REF_NO_SCALE) * 8;
@@ -1002,7 +1266,7 @@ fn horizontal_scaled_pass(
1002 let x = int_pel + t as i32 - 3;1266 let x = int_pel + t as i32 - 3;
1003 sum += tap * sample(reference, stride, true_width, true_height, x, y);1267 sum += tap * sample(reference, stride, true_width, true_height, x, y);
1004 }1268 }
1005- intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0);1269+ intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
1006 }1270 }
1007 }1271 }
1008 }1272 }
@@ -1033,7 +1297,7 @@ fn horizontal_pass(
1033 kern_w: usize,1297 kern_w: usize,
1034 rows: usize,1298 rows: usize,
1035 h_kind: InterpFilterKind,1299 h_kind: InterpFilterKind,
1036- intermediate: &mut [i32],1300+ intermediate: &mut [i16],
1037 ) {1301 ) {
1038 if x_scale_fp == REF_NO_SCALE {1302 if x_scale_fp == REF_NO_SCALE {
1039 let (h_wide, h_narrow) = h_kind.tables();1303 let (h_wide, h_narrow) = h_kind.tables();
@@ -1134,7 +1398,7 @@ pub(crate) fn predict_scaled_kern(
1134 1398
1135 let rows = if yfrac == 0 { block_h } else { block_h + 7 };1399 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1136 let max = crate::decode::sample_max(fctx);1400 let max = crate::decode::sample_max(fctx);
1137- with_scratch(rows, block_w, |intermediate, acc| {1401+ with_scratch(rows, block_w, |intermediate, _acc| {
1138 horizontal_pass(1402 horizontal_pass(
1139 reference, stride, true_width, true_height, x_q4,1403 reference, stride, true_width, true_height, x_q4,
1140 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,1404 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
@@ -1142,15 +1406,15 @@ pub(crate) fn predict_scaled_kern(
1142 );1406 );
1143 if yfrac == 0 {1407 if yfrac == 0 {
1144 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {1408 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;
1146 }1410 }
1147 return;1411 return;
1148 }1412 }
1149 for row in 0..block_h {1413 for row in 0..block_h {
1150- vpass_row(intermediate, block_w, row, v_filter, acc);1414+ vpass_row_u16(
1151- for (d, &a) in dst[row * block_w..(row + 1) * block_w].iter_mut().zip(acc.iter()) {1415+ intermediate, block_w, row, v_filter, max,
1152- *d = round2(a, INTER_ROUND_1).clamp(0, max) as u16;1416+ &mut dst[row * block_w..(row + 1) * block_w],
1153- }1417+ );
1154 }1418 }
1155 });1419 });
1156 }1420 }
@@ -1290,7 +1554,9 @@ pub fn predict_compound_intermediate_kern(
1290 );1554 );
1291 if yfrac == 0 {1555 if yfrac == 0 {
1292 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.1556 // `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+ }
1294 return;1560 return;
1295 }1561 }
1296 for row in 0..block_h {1562 for row in 0..block_h {
@@ -1848,18 +2114,18 @@ mod tests {
1848 let src: Vec<u16> = (0..w + 7)2114 let src: Vec<u16> = (0..w + 7)
1849 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)2115 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
1850 .collect();2116 .collect();
1851- let mut want = vec![0i32; w];2117+ let mut want = vec![0i16; w];
1852 super::hpass_contig_scalar(&src, &t16, &mut want);2118 super::hpass_contig_scalar(&src, &t16, &mut want);
1853- let mut got = vec![0i32; w];2119+ let mut got = vec![0i16; w];
1854 super::hpass_contig(&src, &t16, &mut got);2120 super::hpass_contig(&src, &t16, &mut got);
1855 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");2121 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
1856 #[cfg(target_arch = "x86_64")]2122 #[cfg(target_arch = "x86_64")]
1857 {2123 {
1858- let mut sse = vec![0i32; w];2124+ let mut sse = vec![0i16; w];
1859 unsafe { super::simd::hpass_sse2(&src, &t16, &mut sse) };2125 unsafe { super::simd::hpass_sse2(&src, &t16, &mut sse) };
1860 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");2126 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
1861 if std::arch::is_x86_feature_detected!("avx2") {2127 if std::arch::is_x86_feature_detected!("avx2") {
1862- let mut avx = vec![0i32; w];2128+ let mut avx = vec![0i16; w];
1863 unsafe { super::simd::hpass_avx2(&src, &t16, &mut avx) };2129 unsafe { super::simd::hpass_avx2(&src, &t16, &mut avx) };
1864 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");2130 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
1865 }2131 }
@@ -1873,6 +2139,42 @@ mod tests {
1873 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);2139 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
1874 }2140 }
1875 2141
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+
1876 /// lane-perf5: the vertical pass's SIMD kernels against the scalar2178 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
1877 /// reference, over the same domain as2179 /// reference, over the same domain as
1878 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,2180 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
@@ -1896,16 +2198,18 @@ mod tests {
1896 InterpFilterKind::Bilinear,2198 InterpFilterKind::Bilinear,
1897 ];2199 ];
1898 let mut checked = 0usize;2200 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] {
1900 for &kind in &kinds {2204 for &kind in &kinds {
1901 let (wide, narrow) = kind.tables();2205 let (wide, narrow) = kind.tables();
1902 for table in [wide, narrow] {2206 for table in [wide, narrow] {
1903 for frac in 0..16usize {2207 for frac in 0..16usize {
1904 let taps = &table[frac];2208 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] {
1906 let rows = 12usize;2210 let rows = 12usize;
1907- let inter: Vec<i32> = (0..rows * w)2211+ let inter: Vec<i16> = (0..rows * w)
1908- .map(|_| (rng() % (2 * span as u64 + 1)) as i32 - span)2212+ .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
1909 .collect();2213 .collect();
1910 for row in [0usize, 1, 4] {2214 for row in [0usize, 1, 4] {
1911 let mut want = vec![0i32; w];2215 let mut want = vec![0i32; w];
@@ -1926,6 +2230,37 @@ mod tests {
1926 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");2230 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
1927 }2231 }
1928 }2232 }
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+ }
1929 checked += 1;2264 checked += 1;
1930 }2265 }
1931 }2266 }
@@ -1933,6 +2268,6 @@ mod tests {
1933 }2268 }
1934 }2269 }
1935 }2270 }
1936- assert_eq!(checked, 3 * 4 * 2 * 16 * 8 * 3);2271+ assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3);
1937 }2272 }
1938 }2273 }
crates/ec-av1/src/restoration.rsmodified+7 -3
@@ -596,7 +596,7 @@ fn apply_wiener_stripe(
596 // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the596 // lane-perf8: `mc::vpass_row` reads a fixed 8 taps from `row`, so the
597 // last vertical output needs two rows of padding past the `h + 6` the597 // last vertical output needs two rows of padding past the `h + 6` the
598 // 7-tap kernel actually uses. Tap 7 is zero, so they never contribute.598 // 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);
600 // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16`600 // lane-perf8: this pass IS `mc.rs`'s horizontal one -- a 7-tap `i16`
601 // convolution over contiguous samples rounded by `Round2(_, 3)`, which601 // convolution over contiguous samples rounded by `Round2(_, 3)`, which
602 // is `INTER_ROUND_0` -- so it runs on that module's kernels with the602 // is `INTER_ROUND_0` -- so it runs on that module's kernels with the
@@ -606,7 +606,11 @@ fn apply_wiener_stripe(
606 let hf = &info.hfilter;606 let hf = &info.hfilter;
607 let t16: [i16; 8] =607 let t16: [i16; 8] =
608 [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];608 [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);
610 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));614 let mut hbuf = WIENER_ROW_SCRATCH.with(|c| std::mem::take(&mut *c.borrow_mut()));
611 for r in 0..rows {615 for r in 0..rows {
612 let row = v_start as i64 - 3 + r as i64;616 let row = v_start as i64 - 3 + r as i64;
@@ -651,7 +655,7 @@ fn apply_wiener_stripe(
651 thread_local! {655 thread_local! {
652 /// [`apply_wiener_stripe`]'s horizontal-pass intermediate, kept across656 /// [`apply_wiener_stripe`]'s horizontal-pass intermediate, kept across
653 /// calls so a stripe does not allocate (lane-perf7).657 /// 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>> =
655 const { std::cell::RefCell::new(Vec::new()) };659 const { std::cell::RefCell::new(Vec::new()) };
656 /// The clamped-column copy the horizontal pass needs at a plane edge.660 /// The clamped-column copy the horizontal pass needs at a plane edge.
657 static WIENER_ROW_SCRATCH: std::cell::RefCell<Vec<u16>> =661 static WIENER_ROW_SCRATCH: std::cell::RefCell<Vec<u16>> =