forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

mc.rs2497 lines, 102.0 KiBHistoryRawDownload
1//! Sub-pel motion compensation, spec 7.11.3 ("Motion vector scaling process"
2//! through "Block inter predictor process"), the REGULAR (`EIGHTTAP`) filter
3//! only, 8-bit samples only.
4//!
5//! A block's inter prediction is separable: an 8-tap horizontal pass over the
6//! reference, rounded down by `InterRound0`, feeds an 8-tap vertical pass
7//! over that intermediate, rounded down by `InterRound1`. Both fractions run
8//! in 1/16-pel steps -- luma motion vectors are stored at 1/8-pel and always
9//! land on an even step; chroma vectors, once scaled for subsampling, can
10//! land on any of the 16.
11use crate::hits::hit;
12
13/// `Round2` (spec 4.7): halves round up.
14fn round2(value: i32, shift: u32) -> i32 {
15 if shift == 0 {
16 value
17 } else {
18 (value + (1 << (shift - 1))) >> shift
19 }
20}
21
22/// The kernels' intermediate is `i16` (lane-mc), and every SIMD store lands
23/// through `packs_epi32`, which saturates -- so the scalar arms must too, or
24/// the two would disagree on an out-of-range sum. Motion compensation never
25/// produces one (`horizontal_intermediate_fits_i16` proves the bound from the
26/// tap sums at 8/10-bit; 12-bit is refused in stream.rs), and restoration's
27/// wiener pass clamps its own output into i16 immediately after.
28fn sat16(value: i32) -> i16 {
29 value.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
30}
31
32/// `InterRound0` (spec 7.11.3.2), 8-bit, non-compound: the shift the
33/// horizontal pass's sum is brought down by before it is stored as the
34/// intermediate.
35const INTER_ROUND_0: u32 = 3;
36/// `InterRound1` (spec 7.11.3.2), 8-bit, non-compound: the shift the vertical
37/// pass's sum is brought down by to land back on an 8-bit sample. Composed
38/// with `INTER_ROUND_0` the two shifts are the filter's own gain (each pass
39/// sums to 128, `128 * 128 == 1 << 14 == 1 << (INTER_ROUND_0 + INTER_ROUND_1)`)
40/// -- so an identity or DC input comes back exactly, by construction of the
41/// table rather than by a fitted constant.
42const INTER_ROUND_1: u32 = 11;
43
44/// `Subpel_Filters[EIGHTTAP]` (spec 7.11.3.3): 16 rows, one per 1/16-pel
45/// fraction, each an 8-tap kernel centred so tap index 3 lands on the integer
46/// sample (fraction 0 is the identity tap `[.., 128, ..]`).
47const SUBPEL_FILTERS: [[i32; 8]; 16] = [
48 [0, 0, 0, 128, 0, 0, 0, 0],
49 [0, 2, -6, 126, 8, -2, 0, 0],
50 [0, 2, -10, 122, 18, -4, 0, 0],
51 [0, 2, -12, 116, 28, -8, 2, 0],
52 [0, 2, -14, 110, 38, -10, 2, 0],
53 [0, 2, -14, 102, 48, -12, 2, 0],
54 [0, 2, -16, 94, 58, -12, 2, 0],
55 [0, 2, -14, 84, 66, -12, 2, 0],
56 [0, 2, -14, 76, 76, -14, 2, 0],
57 [0, 2, -12, 66, 84, -14, 2, 0],
58 [0, 2, -12, 58, 94, -16, 2, 0],
59 [0, 2, -12, 48, 102, -14, 2, 0],
60 [0, 2, -10, 38, 110, -14, 2, 0],
61 [0, 2, -8, 28, 116, -12, 2, 0],
62 [0, 0, -4, 18, 122, -10, 2, 0],
63 [0, 0, -2, 8, 126, -6, 2, 0],
64];
65
66/// `Subpel_Filters[EIGHTTAP]`'s narrow-block counterpart (spec 7.11.3.4's
67/// filter selection is per-axis: a `predict` axis whose output block
68/// dimension is 4 or less reads this table instead of [`SUBPEL_FILTERS`]),
69/// mirroring `av1_sub_pel_filters_4` (`filter.h`): the same 8-slot shape but
70/// zeroed at taps 0/1/6/7, so a 4-wide (or 4-tall) block's filter never
71/// reaches a full 3 samples past its own edge. Every 4:2:0 chroma block
72/// under an 8x8 (or smaller) luma leaf hits this on at least one axis --
73/// this is not an edge case, it is the common chroma shape.
74const SUBPEL_FILTERS_4: [[i32; 8]; 16] = [
75 [0, 0, 0, 128, 0, 0, 0, 0],
76 [0, 0, -4, 126, 8, -2, 0, 0],
77 [0, 0, -8, 122, 18, -4, 0, 0],
78 [0, 0, -10, 116, 28, -6, 0, 0],
79 [0, 0, -12, 110, 38, -8, 0, 0],
80 [0, 0, -12, 102, 48, -10, 0, 0],
81 [0, 0, -14, 94, 58, -10, 0, 0],
82 [0, 0, -12, 84, 66, -10, 0, 0],
83 [0, 0, -12, 76, 76, -12, 0, 0],
84 [0, 0, -10, 66, 84, -12, 0, 0],
85 [0, 0, -10, 58, 94, -14, 0, 0],
86 [0, 0, -10, 48, 102, -12, 0, 0],
87 [0, 0, -8, 38, 110, -12, 0, 0],
88 [0, 0, -6, 28, 116, -10, 0, 0],
89 [0, 0, -4, 18, 122, -8, 0, 0],
90 [0, 0, -2, 8, 126, -4, 0, 0],
91];
92
93/// `Subpel_Filters[EIGHTTAP_SMOOTH]` (`filter.h`'s `av1_sub_pel_filters_8smooth`).
94const SUBPEL_FILTERS_SMOOTH: [[i32; 8]; 16] = [
95 [0, 0, 0, 128, 0, 0, 0, 0],
96 [0, 2, 28, 62, 34, 2, 0, 0],
97 [0, 0, 26, 62, 36, 4, 0, 0],
98 [0, 0, 22, 62, 40, 4, 0, 0],
99 [0, 0, 20, 60, 42, 6, 0, 0],
100 [0, 0, 18, 58, 44, 8, 0, 0],
101 [0, 0, 16, 56, 46, 10, 0, 0],
102 [0, -2, 16, 54, 48, 12, 0, 0],
103 [0, -2, 14, 52, 52, 14, -2, 0],
104 [0, 0, 12, 48, 54, 16, -2, 0],
105 [0, 0, 10, 46, 56, 16, 0, 0],
106 [0, 0, 8, 44, 58, 18, 0, 0],
107 [0, 0, 6, 42, 60, 20, 0, 0],
108 [0, 0, 4, 40, 62, 22, 0, 0],
109 [0, 0, 4, 36, 62, 26, 0, 0],
110 [0, 0, 2, 34, 62, 28, 2, 0],
111];
112
113/// `SUBPEL_FILTERS_SMOOTH`'s narrow-block counterpart (`av1_sub_pel_filters_4smooth`).
114const SUBPEL_FILTERS_SMOOTH_4: [[i32; 8]; 16] = [
115 [0, 0, 0, 128, 0, 0, 0, 0],
116 [0, 0, 30, 62, 34, 2, 0, 0],
117 [0, 0, 26, 62, 36, 4, 0, 0],
118 [0, 0, 22, 62, 40, 4, 0, 0],
119 [0, 0, 20, 60, 42, 6, 0, 0],
120 [0, 0, 18, 58, 44, 8, 0, 0],
121 [0, 0, 16, 56, 46, 10, 0, 0],
122 [0, 0, 14, 54, 48, 12, 0, 0],
123 [0, 0, 12, 52, 52, 12, 0, 0],
124 [0, 0, 12, 48, 54, 14, 0, 0],
125 [0, 0, 10, 46, 56, 16, 0, 0],
126 [0, 0, 8, 44, 58, 18, 0, 0],
127 [0, 0, 6, 42, 60, 20, 0, 0],
128 [0, 0, 4, 40, 62, 22, 0, 0],
129 [0, 0, 4, 36, 62, 26, 0, 0],
130 [0, 0, 2, 34, 62, 30, 0, 0],
131];
132
133/// `Subpel_Filters[EIGHTTAP_SHARP]` (`av1_sub_pel_filters_8sharp`). A block
134/// whose dimension is 4 or less does NOT read this table: spec 7.11.3.4's
135/// `filterIdx` sends both EIGHTTAP and EIGHTTAP_SHARP to filter index 4, and
136/// libaom agrees -- `av1_interp_4tap[MULTITAP_SHARP]` is `av1_sub_pel_filters_4`,
137/// the REGULAR narrow kernel (`filter.h:243`), not a sharp one (lane-gmaffine r5).
138const SUBPEL_FILTERS_SHARP: [[i32; 8]; 16] = [
139 [0, 0, 0, 128, 0, 0, 0, 0],
140 [-2, 2, -6, 126, 8, -2, 2, 0],
141 [-2, 6, -12, 124, 16, -6, 4, -2],
142 [-2, 8, -18, 120, 26, -10, 6, -2],
143 [-4, 10, -22, 116, 38, -14, 6, -2],
144 [-4, 10, -22, 108, 48, -18, 8, -2],
145 [-4, 10, -24, 100, 60, -20, 8, -2],
146 [-4, 10, -24, 90, 70, -22, 10, -2],
147 [-4, 12, -24, 80, 80, -24, 12, -4],
148 [-2, 10, -22, 70, 90, -24, 10, -4],
149 [-2, 8, -20, 60, 100, -24, 10, -4],
150 [-2, 8, -18, 48, 108, -22, 10, -4],
151 [-2, 6, -14, 38, 116, -22, 10, -4],
152 [-2, 6, -10, 26, 120, -18, 8, -2],
153 [-2, 4, -6, 16, 124, -12, 6, -2],
154 [0, 2, -2, 8, 126, -6, 2, -2],
155];
156
157/// `Subpel_Filters[BILINEAR]` (`av1_bilinear_filters`) -- also never swapped
158/// for a narrow-block table (it is already only 2 non-zero taps).
159const SUBPEL_FILTERS_BILINEAR: [[i32; 8]; 16] = [
160 [0, 0, 0, 128, 0, 0, 0, 0],
161 [0, 0, 0, 120, 8, 0, 0, 0],
162 [0, 0, 0, 112, 16, 0, 0, 0],
163 [0, 0, 0, 104, 24, 0, 0, 0],
164 [0, 0, 0, 96, 32, 0, 0, 0],
165 [0, 0, 0, 88, 40, 0, 0, 0],
166 [0, 0, 0, 80, 48, 0, 0, 0],
167 [0, 0, 0, 72, 56, 0, 0, 0],
168 [0, 0, 0, 64, 64, 0, 0, 0],
169 [0, 0, 0, 56, 72, 0, 0, 0],
170 [0, 0, 0, 48, 80, 0, 0, 0],
171 [0, 0, 0, 40, 88, 0, 0, 0],
172 [0, 0, 0, 32, 96, 0, 0, 0],
173 [0, 0, 0, 24, 104, 0, 0, 0],
174 [0, 0, 0, 16, 112, 0, 0, 0],
175 [0, 0, 0, 8, 120, 0, 0, 0],
176];
177
178/// Which of the spec's four `interpolation_filter` kernels a block's motion
179/// compensation reads (spec 6.8.9 / `frame_header`'s `interpolation_filter`).
180/// A frame codes exactly one of these when not `Switchable`; a `Switchable`
181/// frame codes one per block per direction (spec 5.11.20's
182/// `read_interp_filter`, see `decode::decode_inter_block`), so `predict`'s
183/// callers resolve `Switchable` to a concrete pair of kinds themselves --
184/// this type only ever names the resolved kernel, never `Switchable` itself.
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub enum InterpFilterKind {
187 /// The `Regular` interpolation kernel.
188 Regular,
189 /// The `Smooth` interpolation kernel.
190 Smooth,
191 /// The `Sharp` interpolation kernel.
192 Sharp,
193 /// The `Bilinear` interpolation kernel.
194 Bilinear,
195}
196
197impl InterpFilterKind {
198 fn tables(self) -> (&'static [[i32; 8]; 16], &'static [[i32; 8]; 16]) {
199 match self {
200 InterpFilterKind::Regular => (&SUBPEL_FILTERS, &SUBPEL_FILTERS_4),
201 InterpFilterKind::Smooth => (&SUBPEL_FILTERS_SMOOTH, &SUBPEL_FILTERS_SMOOTH_4),
202 InterpFilterKind::Sharp => (&SUBPEL_FILTERS_SHARP, &SUBPEL_FILTERS_4),
203 InterpFilterKind::Bilinear => (&SUBPEL_FILTERS_BILINEAR, &SUBPEL_FILTERS_BILINEAR),
204 }
205 }
206
207 /// The three-symbol alphabet spec 5.11.20's `interp_filter[dir]` reads
208 /// under a `Switchable` frame decodes to (`EIGHTTAP`/`_SMOOTH`/`_SHARP`
209 /// in that order -- `BILINEAR` is never a `switchable_interp` outcome).
210 ///
211 /// # Panics
212 /// Panics when `symbol` is not `0..=2`.
213 pub fn from_switchable_symbol(symbol: usize) -> InterpFilterKind {
214 match symbol {
215 0 => InterpFilterKind::Regular,
216 1 => InterpFilterKind::Smooth,
217 2 => InterpFilterKind::Sharp,
218 _ => panic!("switchable_interp's alphabet is exactly 3 symbols"),
219 }
220 }
221
222 /// The frame header's own `interpolation_filter` (spec 6.8.9), for the
223 /// non-`Switchable` values a fixed-filter frame codes directly.
224 ///
225 /// # Panics
226 /// Panics on `Switchable`, which is not a concrete kernel -- callers
227 /// resolve it per block instead (spec 5.11.20).
228 pub fn from_header(filter: ec_av1_syntax::InterpolationFilter) -> InterpFilterKind {
229 match filter {
230 ec_av1_syntax::InterpolationFilter::Eighttap => InterpFilterKind::Regular,
231 ec_av1_syntax::InterpolationFilter::EighttapSmooth => InterpFilterKind::Smooth,
232 ec_av1_syntax::InterpolationFilter::EighttapSharp => InterpFilterKind::Sharp,
233 ec_av1_syntax::InterpolationFilter::Bilinear => InterpFilterKind::Bilinear,
234 ec_av1_syntax::InterpolationFilter::Switchable => {
235 panic!("Switchable is resolved per block, not as one frame-wide kernel")
236 }
237 }
238 }
239}
240
241/// A reference sample at `(x, y)`, clamped to the frame's true (unpadded)
242/// extent -- `true_width`/`true_height`, which can be narrower than
243/// `stride` -- rather than read out of range (spec 7.11.3.4's `Clip3`
244/// against the frame's edges): a motion vector that points past the true
245/// edge repeats the true edge's sample instead of panicking or picking up
246/// whatever this encoder's own uncoded padding columns/rows hold.
247#[allow(clippy::too_many_arguments)]
248fn sample(
249 reference: &[u16],
250 stride: usize,
251 true_width: usize,
252 true_height: usize,
253 x: i32,
254 y: i32,
255) -> i32 {
256 let cx = x.clamp(0, true_width as i32 - 1) as usize;
257 let cy = y.clamp(0, true_height as i32 - 1) as usize;
258 i32::from(reference[cy * stride + cx])
259}
260
261/// lane-perf5: which explicit-SIMD kernels this CPU can run. The scalar
262/// functions below stay the reference implementation -- every SIMD kernel is
263/// checked against them by `simd_matches_scalar_*` -- and every non-x86_64
264/// build, plus any x86_64 CPU without AVX2 or SSE4.1, decodes through them.
265#[derive(Clone, Copy, PartialEq, Eq, Debug)]
266#[allow(dead_code)] // every variant is constructed only on x86_64
267pub(crate) enum SimdLevel {
268 Scalar,
269 /// `_mm_madd_epi16` (SSE2) horizontal pass, `_mm_mullo_epi32` (SSE4.1)
270 /// vertical pass -- the pair is gated on SSE4.1, the later of the two.
271 Sse41,
272 Avx2,
273}
274
275/// The level, detected once per process (spec-irrelevant: pure dispatch).
276pub(crate) fn simd_level() -> SimdLevel {
277 static LEVEL: std::sync::OnceLock<SimdLevel> = std::sync::OnceLock::new();
278 *LEVEL.get_or_init(|| {
279 #[cfg(target_arch = "x86_64")]
280 {
281 if std::arch::is_x86_feature_detected!("avx2") {
282 return SimdLevel::Avx2;
283 }
284 if std::arch::is_x86_feature_detected!("sse4.1") {
285 return SimdLevel::Sse41;
286 }
287 }
288 SimdLevel::Scalar
289 })
290}
291
292/// The horizontal pass's inner loop over a contiguous window (`src` holds the
293/// row's whole footprint, `out.len() + 7` samples): SIMD where available,
294/// [`hpass_contig_scalar`] otherwise. Both produce the same `i32`s -- the
295/// SIMD form multiplies the same `i16` pairs, sums them in `i32` and applies
296/// the same `Round2(sum, InterRound0)`.
297#[allow(unsafe_code)]
298#[inline]
299pub(crate) fn hpass_contig(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
300 let n = out.len();
301 hpass_rows(src, 0, 1, n, t16, out);
302}
303
304/// lane-mc2: `rows` rows of [`hpass_contig`], `src_stride` apart in `src` and
305/// packed `block_w` apart in `out`. The tap vectors and the SIMD dispatch are
306/// set up once for the whole block instead of once per row.
307#[allow(unsafe_code)]
308#[inline]
309pub(crate) fn hpass_rows(
310 src: &[u16],
311 src_stride: usize,
312 rows: usize,
313 block_w: usize,
314 t16: &[i16; 8],
315 out: &mut [i16],
316) {
317 #[cfg(target_arch = "x86_64")]
318 {
319 match simd_level() {
320 SimdLevel::Avx2 => {
321 // SAFETY: the AVX2 arm is reached only when the CPU reports
322 // avx2; each row reads at most `block_w + 7` samples.
323 unsafe { simd::hpass_avx2(src, src_stride, rows, block_w, t16, out) };
324 return;
325 }
326 SimdLevel::Sse41 => {
327 // SAFETY: as above; the kernel needs only SSE2, which every
328 // x86_64 CPU has.
329 unsafe { simd::hpass_sse2(src, src_stride, rows, block_w, t16, out) };
330 return;
331 }
332 SimdLevel::Scalar => {}
333 }
334 }
335 for r in 0..rows {
336 hpass_contig_scalar(
337 &src[r * src_stride..],
338 t16,
339 &mut out[r * block_w..(r + 1) * block_w],
340 );
341 }
342}
343
344/// The scalar reference for [`hpass_contig`] (lane-perf2's loop).
345fn hpass_contig_scalar(src: &[u16], t16: &[i16; 8], out: &mut [i16]) {
346 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the bit
347 // depth), so the products are exactly the i32 ones but the widening
348 // multiply is one instruction per pair.
349 for (o, w) in out.iter_mut().zip(src.windows(8)) {
350 let mut sum = 0i32;
351 for t in 0..8 {
352 sum += i32::from(t16[t]) * i32::from(w[t] as i16);
353 }
354 *o = sat16(round2(sum, INTER_ROUND_0));
355 }
356}
357
358/// lane-perf5: explicit `std::arch::x86_64` kernels for the two motion
359/// compensation passes -- the 18.7% of a 1080p decode that lane-perf4 left in
360/// `hpass_row` + `vpass_row`. Nothing here is spec logic: each kernel is the
361/// scalar function's arithmetic, lane-parallel, with identical rounding.
362#[allow(unsafe_code)]
363#[cfg(target_arch = "x86_64")]
364#[allow(unsafe_op_in_unsafe_fn)] // each kernel's whole body is its contract
365mod simd {
366 use super::{round2, sat16, INTER_ROUND_0, INTER_ROUND_1};
367 use std::arch::x86_64::*;
368
369 /// `[t0,t1]`, `[t2,t3]`, `[t4,t5]`, `[t6,t7]` packed as `i32`s, the shape
370 /// `_mm*_madd_epi16` wants: lane `j` of `madd(samples, set1(pair))` is
371 /// `s[2j]*t_even + s[2j+1]*t_odd`, i.e. two taps of one output at once.
372 #[inline]
373 fn taps16(taps: &[i32; 8]) -> [i16; 8] {
374 [
375 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
376 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
377 ]
378 }
379
380 #[inline]
381 fn tap_pairs(t: &[i16; 8]) -> [i32; 4] {
382 let pack = |a: i16, b: i16| (a as u16 as i32) | ((b as i32) << 16);
383 [pack(t[0], t[1]), pack(t[2], t[3]), pack(t[4], t[5]), pack(t[6], t[7])]
384 }
385
386 /// Horizontal pass, AVX2: 16 outputs per iteration. Each 256-bit `madd`
387 /// covers 8 outputs two taps at a time, but only every other output (the
388 /// pairs are consecutive samples), so even and odd output columns are
389 /// accumulated in two registers and interleaved back into order by
390 /// `unpack` + `permute2x128`.
391 ///
392 /// # Safety
393 /// Requires AVX2. `src.len()` must be at least `out.len() + 7`.
394 #[target_feature(enable = "avx2")]
395 pub unsafe fn hpass_avx2(
396 src: &[u16],
397 src_stride: usize,
398 rows: usize,
399 block_w: usize,
400 t16: &[i16; 8],
401 out: &mut [i16],
402 ) {
403 debug_assert!(out.len() >= rows * block_w);
404 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
405 let tp = tap_pairs(t16);
406 let tv = [
407 _mm256_set1_epi32(tp[0]),
408 _mm256_set1_epi32(tp[1]),
409 _mm256_set1_epi32(tp[2]),
410 _mm256_set1_epi32(tp[3]),
411 ];
412 let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_0 - 1));
413 for r in 0..rows {
414 let sp = src.as_ptr().add(r * src_stride);
415 let op = out.as_mut_ptr().add(r * block_w);
416 let mut c = 0usize;
417 while c + 16 <= block_w {
418 let mut e = _mm256_setzero_si256();
419 let mut o = _mm256_setzero_si256();
420 for k in 0..4 {
421 let se = _mm256_loadu_si256(sp.add(c + 2 * k).cast());
422 e = _mm256_add_epi32(e, _mm256_madd_epi16(se, tv[k]));
423 let so = _mm256_loadu_si256(sp.add(c + 2 * k + 1).cast());
424 o = _mm256_add_epi32(o, _mm256_madd_epi16(so, tv[k]));
425 }
426 e = _mm256_srai_epi32(_mm256_add_epi32(e, rnd), INTER_ROUND_0 as i32);
427 o = _mm256_srai_epi32(_mm256_add_epi32(o, rnd), INTER_ROUND_0 as i32);
428 let lo = _mm256_unpacklo_epi32(e, o);
429 let hi = _mm256_unpackhi_epi32(e, o);
430 // `lo`/`hi` already hold the 16 outputs in order, four per
431 // 128-bit lane; `packs_epi32` narrows lane-wise, so the store
432 // is c..c+16 in order. Saturation never fires: see
433 // `horizontal_intermediate_fits_i16`.
434 _mm256_storeu_si256(op.add(c).cast(), _mm256_packs_epi32(lo, hi));
435 c += 16;
436 }
437 if c < block_w {
438 let s = r * src_stride + c;
439 let o = r * block_w + c;
440 hpass_sse2(&src[s..], 0, 1, block_w - c, t16, &mut out[o..o + block_w - c]);
441 }
442 }
443 }
444
445 /// Vertical pass, AVX2: the intermediate is `i16` (lane-mc: it provably
446 /// fits, see `horizontal_intermediate_fits_i16`), so a row PAIR
447 /// interleaved by `unpack_epi16` is exactly `_mm256_madd_epi16`'s shape --
448 /// two taps of 16 columns per instruction, where the old `i32` form spent
449 /// one `mullo_epi32` per tap per 8 columns. `acc` is left unrounded, as
450 /// the scalar form leaves it.
451 ///
452 /// # Safety
453 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
454 /// and `acc` at least `block_w`.
455 #[target_feature(enable = "avx2")]
456 pub unsafe fn vpass_avx2(
457 intermediate: &[i16],
458 block_w: usize,
459 src_stride: usize,
460 rows: usize,
461 taps: &[i32; 8],
462 acc: &mut [i32],
463 ) {
464 debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w);
465 let tp = tap_pairs(&taps16(taps));
466 for row in 0..rows {
467 let ip = intermediate.as_ptr().add(row * src_stride);
468 let ap = acc.as_mut_ptr().add(row * block_w);
469 let mut c = 0usize;
470 while c + 16 <= block_w {
471 // `lo` accumulates columns c+0..4 and c+8..12 (one per 128-bit
472 // lane), `hi` the other two runs; the two `permute2x128`s put the
473 // 16 sums back in column order.
474 let mut lo = _mm256_setzero_si256();
475 let mut hi = _mm256_setzero_si256();
476 for k in 0..4 {
477 if tp[k] == 0 {
478 continue;
479 }
480 let tv = _mm256_set1_epi32(tp[k]);
481 let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
482 let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
483 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
484 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
485 }
486 _mm256_storeu_si256(ap.add(c).cast(), _mm256_permute2x128_si256(lo, hi, 0x20));
487 _mm256_storeu_si256(ap.add(c + 8).cast(), _mm256_permute2x128_si256(lo, hi, 0x31));
488 c += 16;
489 }
490 vpass_tail_sse(ip, block_w, src_stride, &tp, taps, ap, c);
491 }
492 }
493
494 /// [`vpass_avx2`]'s 8- and 4-column steps, 128-bit: every AV1 block width
495 /// is a multiple of 4, and the 8x8 luma block (the most common inter
496 /// shape on real 4K content) lands here whole.
497 ///
498 /// # Safety
499 /// `ip` must be readable for `8 * block_w` elements from `row`'s start and
500 /// `ap` writable for `block_w`; `c` is the column already done.
501 #[inline]
502 unsafe fn vpass_tail_sse(
503 ip: *const i16,
504 block_w: usize,
505 src_stride: usize,
506 tp: &[i32; 4],
507 taps: &[i32; 8],
508 ap: *mut i32,
509 mut c: usize,
510 ) {
511 while c + 8 <= block_w {
512 let mut lo = _mm_setzero_si128();
513 let mut hi = _mm_setzero_si128();
514 for k in 0..4 {
515 if tp[k] == 0 {
516 continue;
517 }
518 let tv = _mm_set1_epi32(tp[k]);
519 let a = _mm_loadu_si128(ip.add(2 * k * src_stride + c).cast());
520 let b = _mm_loadu_si128(ip.add((2 * k + 1) * src_stride + c).cast());
521 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
522 hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
523 }
524 _mm_storeu_si128(ap.add(c).cast(), lo);
525 _mm_storeu_si128(ap.add(c + 4).cast(), hi);
526 c += 8;
527 }
528 while c + 4 <= block_w {
529 let mut lo = _mm_setzero_si128();
530 for k in 0..4 {
531 if tp[k] == 0 {
532 continue;
533 }
534 let tv = _mm_set1_epi32(tp[k]);
535 let a = _mm_loadl_epi64(ip.add(2 * k * src_stride + c).cast());
536 let b = _mm_loadl_epi64(ip.add((2 * k + 1) * src_stride + c).cast());
537 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
538 }
539 _mm_storeu_si128(ap.add(c).cast(), lo);
540 c += 4;
541 }
542 // Every AV1 block width is a multiple of 4, but the encoder's own
543 // motion search prices odd widths through `predict`, so the last
544 // columns still need the scalar form.
545 while c < block_w {
546 let mut sum = 0i32;
547 for (t, &tap) in taps.iter().enumerate() {
548 sum += tap * i32::from(*ip.add(t * src_stride + c));
549 }
550 *ap.add(c) = sum;
551 c += 1;
552 }
553 }
554
555 /// [`vpass_avx2`] with the output rounding fused in: the sums never reach
556 /// memory as `i32`, they are rounded by `INTER_ROUND_1`, clamped and
557 /// stored as the block's own `u16` samples. `packus_epi32` is the clamp's
558 /// lower half (a negative sum saturates to 0) and `min_epu16` its upper,
559 /// which is exactly `round2(sum, INTER_ROUND_1).clamp(0, max)`.
560 ///
561 /// # Safety
562 /// Requires AVX2. `intermediate` must hold `(row + 8) * block_w` elements
563 /// and `dst` at least `block_w`.
564 #[target_feature(enable = "avx2")]
565 pub unsafe fn vpass_row_u16_avx2(
566 intermediate: &[i16],
567 block_w: usize,
568 src_stride: usize,
569 rows: usize,
570 taps: &[i32; 8],
571 max: i32,
572 dst: &mut [u16],
573 ) {
574 debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w);
575 let tp = tap_pairs(&taps16(taps));
576 let rnd = _mm256_set1_epi32(1 << (INTER_ROUND_1 - 1));
577 let mx = _mm256_set1_epi16(max as i16);
578 for row in 0..rows {
579 let ip = intermediate.as_ptr().add(row * src_stride);
580 let dp = dst.as_mut_ptr().add(row * block_w);
581 let mut c = 0usize;
582 while c + 16 <= block_w {
583 let mut lo = rnd;
584 let mut hi = rnd;
585 for k in 0..4 {
586 if tp[k] == 0 {
587 continue;
588 }
589 let tv = _mm256_set1_epi32(tp[k]);
590 let a = _mm256_loadu_si256(ip.add(2 * k * src_stride + c).cast());
591 let b = _mm256_loadu_si256(ip.add((2 * k + 1) * src_stride + c).cast());
592 lo = _mm256_add_epi32(lo, _mm256_madd_epi16(_mm256_unpacklo_epi16(a, b), tv));
593 hi = _mm256_add_epi32(hi, _mm256_madd_epi16(_mm256_unpackhi_epi16(a, b), tv));
594 }
595 lo = _mm256_srai_epi32(lo, INTER_ROUND_1 as i32);
596 hi = _mm256_srai_epi32(hi, INTER_ROUND_1 as i32);
597 // `packus` narrows lane-wise, and `lo`/`hi` hold the columns four
598 // per lane in order, so this is c..c+16 in order.
599 let v = _mm256_min_epu16(_mm256_packus_epi32(lo, hi), mx);
600 _mm256_storeu_si256(dp.add(c).cast(), v);
601 c += 16;
602 }
603 vpass_u16_tail_sse(ip, block_w, src_stride, &tp, taps, max, dp, c);
604 }
605 }
606
607 /// [`vpass_row_u16_avx2`]'s 8- and 4-column steps (SSE4.1 for
608 /// `packus_epi32`), and the scalar remainder.
609 ///
610 /// # Safety
611 /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
612 #[target_feature(enable = "sse4.1")]
613 unsafe fn vpass_u16_tail_sse(
614 ip: *const i16,
615 block_w: usize,
616 src_stride: usize,
617 tp: &[i32; 4],
618 taps: &[i32; 8],
619 max: i32,
620 dp: *mut u16,
621 mut c: usize,
622 ) {
623 let rnd = _mm_set1_epi32(1 << (INTER_ROUND_1 - 1));
624 let mx = _mm_set1_epi16(max as i16);
625 while c + 4 <= block_w {
626 let wide = c + 8 <= block_w;
627 let mut lo = rnd;
628 let mut hi = rnd;
629 for k in 0..4 {
630 if tp[k] == 0 {
631 continue;
632 }
633 let tv = _mm_set1_epi32(tp[k]);
634 let (pa, pb) = (ip.add(2 * k * src_stride + c), ip.add((2 * k + 1) * src_stride + c));
635 let (a, b) = if wide {
636 (_mm_loadu_si128(pa.cast()), _mm_loadu_si128(pb.cast()))
637 } else {
638 (_mm_loadl_epi64(pa.cast()), _mm_loadl_epi64(pb.cast()))
639 };
640 lo = _mm_add_epi32(lo, _mm_madd_epi16(_mm_unpacklo_epi16(a, b), tv));
641 if wide {
642 hi = _mm_add_epi32(hi, _mm_madd_epi16(_mm_unpackhi_epi16(a, b), tv));
643 }
644 }
645 let v = _mm_min_epu16(
646 _mm_packus_epi32(_mm_srai_epi32(lo, INTER_ROUND_1 as i32), _mm_srai_epi32(hi, INTER_ROUND_1 as i32)),
647 mx,
648 );
649 if wide {
650 _mm_storeu_si128(dp.add(c).cast(), v);
651 c += 8;
652 } else {
653 _mm_storel_epi64(dp.add(c).cast(), v);
654 c += 4;
655 }
656 }
657 while c < block_w {
658 let mut sum = 0i32;
659 for (t, &tap) in taps.iter().enumerate() {
660 sum += tap * i32::from(*ip.add(t * src_stride + c));
661 }
662 *dp.add(c) = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
663 c += 1;
664 }
665 }
666
667 /// [`vpass_row_u16_avx2`] without the 16-column step.
668 ///
669 /// # Safety
670 /// Requires SSE4.1; same slice contract as [`vpass_row_u16_avx2`].
671 #[target_feature(enable = "sse4.1")]
672 pub unsafe fn vpass_row_u16_sse41(
673 intermediate: &[i16],
674 block_w: usize,
675 src_stride: usize,
676 rows: usize,
677 taps: &[i32; 8],
678 max: i32,
679 dst: &mut [u16],
680 ) {
681 debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && dst.len() >= rows * block_w);
682 let tp = tap_pairs(&taps16(taps));
683 for row in 0..rows {
684 vpass_u16_tail_sse(
685 intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps, max,
686 dst.as_mut_ptr().add(row * block_w), 0,
687 );
688 }
689 }
690
691 /// Vertical pass, SSE2: [`vpass_avx2`] without the 16-column step.
692 ///
693 /// # Safety
694 /// SSE2 is baseline x86_64; same slice contract as [`vpass_avx2`].
695 pub unsafe fn vpass_sse41(
696 intermediate: &[i16],
697 block_w: usize,
698 src_stride: usize,
699 rows: usize,
700 taps: &[i32; 8],
701 acc: &mut [i32],
702 ) {
703 debug_assert!(intermediate.len() >= (rows + 6) * src_stride + block_w && acc.len() >= rows * block_w);
704 let tp = tap_pairs(&taps16(taps));
705 for row in 0..rows {
706 vpass_tail_sse(
707 intermediate.as_ptr().add(row * src_stride), block_w, src_stride, &tp, taps,
708 acc.as_mut_ptr().add(row * block_w), 0,
709 );
710 }
711 }
712
713 /// Horizontal pass, SSE2: [`hpass_avx2`]'s scheme at 8 outputs per
714 /// iteration; the remainder (a width-4 block, or a 4-column tail) is the
715 /// scalar loop, which is where 4-tap kernels mostly land anyway.
716 ///
717 /// # Safety
718 /// `src.len()` must be at least `out.len() + 7`. SSE2 is baseline x86_64.
719 pub unsafe fn hpass_sse2(
720 src: &[u16],
721 src_stride: usize,
722 rows: usize,
723 block_w: usize,
724 t16: &[i16; 8],
725 out: &mut [i16],
726 ) {
727 debug_assert!(out.len() >= rows * block_w);
728 debug_assert!(src.len() >= (rows - 1) * src_stride + block_w + 7);
729 let tp = tap_pairs(t16);
730 let tv = [
731 _mm_set1_epi32(tp[0]),
732 _mm_set1_epi32(tp[1]),
733 _mm_set1_epi32(tp[2]),
734 _mm_set1_epi32(tp[3]),
735 ];
736 let rnd = _mm_set1_epi32(1 << (INTER_ROUND_0 - 1));
737 for r in 0..rows {
738 let sp = src.as_ptr().add(r * src_stride);
739 let op = out.as_mut_ptr().add(r * block_w);
740 let mut c = 0usize;
741 while c + 8 <= block_w {
742 let mut e = _mm_setzero_si128();
743 let mut o = _mm_setzero_si128();
744 for k in 0..4 {
745 let se = _mm_loadu_si128(sp.add(c + 2 * k).cast());
746 e = _mm_add_epi32(e, _mm_madd_epi16(se, tv[k]));
747 let so = _mm_loadu_si128(sp.add(c + 2 * k + 1).cast());
748 o = _mm_add_epi32(o, _mm_madd_epi16(so, tv[k]));
749 }
750 e = _mm_srai_epi32(_mm_add_epi32(e, rnd), INTER_ROUND_0 as i32);
751 o = _mm_srai_epi32(_mm_add_epi32(o, rnd), INTER_ROUND_0 as i32);
752 let lo = _mm_unpacklo_epi32(e, o);
753 let hi = _mm_unpackhi_epi32(e, o);
754 _mm_storeu_si128(op.add(c).cast(), _mm_packs_epi32(lo, hi));
755 c += 8;
756 }
757 while c < block_w {
758 let mut sum = 0i32;
759 for t in 0..8 {
760 sum += i32::from(t16[t]) * i32::from(*sp.add(c + t) as i16);
761 }
762 *op.add(c) = sat16(round2(sum, INTER_ROUND_0));
763 c += 1;
764 }
765 }
766 }
767}
768
769/// lane-perf2: one row of the separable filter's horizontal pass, dav1d
770/// style. When the row's whole 8-tap footprint (`x0-3 .. x0+block_w+4`) lies
771/// inside the reference's true extent -- the overwhelmingly common case --
772/// the row is one contiguous slice and the taps are a fixed `[i32; 8]`, so
773/// the per-sample `Clip3` and the per-tap table load both leave the inner
774/// loop and it auto-vectorises. The edge case keeps the exact spec form
775/// (`sample`'s clamp per tap); both arms compute the same sums.
776#[inline]
777fn hpass_row(reference: &[u16], row_base: usize, true_width: usize, x0: i32, taps: &[i32; 8], out: &mut [i16]) {
778 let block_w = out.len();
779 let start = x0 - 3;
780 if start >= 0 && start as usize + block_w + 7 <= true_width {
781 let s = row_base + start as usize;
782 if let Some(src) = reference.get(s..s + block_w + 7) {
783 // Both factors are 16-bit (a tap is |x| <= 128, a sample fits the
784 // bit depth), so the products are exactly the i32 ones above but
785 // the widening multiply is one instruction per pair.
786 let t16 = [
787 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
788 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
789 ];
790 hpass_contig(src, &t16, out);
791 return;
792 }
793 }
794 for (c, o) in out.iter_mut().enumerate() {
795 let mut sum = 0i32;
796 for (t, &tap) in taps.iter().enumerate() {
797 let x = (x0 + c as i32 + t as i32 - 3).clamp(0, true_width as i32 - 1) as usize;
798 sum += tap * i32::from(reference[row_base + x]);
799 }
800 *o = sat16(round2(sum, INTER_ROUND_0));
801 }
802}
803
804/// lane-perf2: the unscaled horizontal pass, `block_h + 7` rows of
805/// [`hpass_row`] with the vertical clamp hoisted out of the row.
806#[allow(clippy::too_many_arguments)]
807fn horizontal_pass_unscaled(
808 reference: &[u16],
809 stride: usize,
810 true_width: usize,
811 true_height: usize,
812 x0: i32,
813 y0: i32,
814 taps: &[i32; 8],
815 block_w: usize,
816 rows: usize,
817 intermediate: &mut [i16],
818) {
819 // Fraction 0 is the identity tap (`128` at slot 3), and `Round2(128 * s,
820 // InterRound0) == 16 * s` exactly, so a whole-pel horizontal position
821 // needs no filter at all -- one widened row read.
822 let identity = taps[3] == 128 && taps.iter().enumerate().all(|(i, &t)| i == 3 || t == 0);
823 // lane-mc2: when the whole `rows x (block_w+7)` footprint lies inside the
824 // reference -- the overwhelmingly common case -- every per-row test in
825 // the general loop below (the vertical clamp, the horizontal interior
826 // test, the slice bounds check, the tap narrowing and the SIMD dispatch)
827 // has the same answer for every row, so it is hoisted out and the loop
828 // becomes a walk of `stride`. Same sums, same order.
829 let start = x0 - 3;
830 let y_top = y0 - 3;
831 if !identity
832 && start >= 0
833 && y_top >= 0
834 && start as usize + block_w + 7 <= true_width
835 && y_top as usize + rows <= true_height
836 {
837 let base = y_top as usize * stride + start as usize;
838 let span = block_w + 7;
839 if base + (rows - 1) * stride + span <= reference.len() {
840 let t16 = [
841 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
842 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
843 ];
844 hpass_rows(
845 &reference[base..],
846 stride,
847 rows,
848 block_w,
849 &t16,
850 &mut intermediate[..rows * block_w],
851 );
852 return;
853 }
854 }
855 for r in 0..rows {
856 let y = (y0 - 3 + r as i32).clamp(0, true_height as i32 - 1) as usize;
857 let out = &mut intermediate[r * block_w..(r + 1) * block_w];
858 if identity {
859 let gain = 128 >> INTER_ROUND_0;
860 if x0 >= 0 && x0 as usize + block_w <= true_width {
861 if let Some(src) = reference.get(y * stride + x0 as usize..y * stride + x0 as usize + block_w) {
862 for (o, &s) in out.iter_mut().zip(src) {
863 *o = (gain * i32::from(s)) as i16;
864 }
865 continue;
866 }
867 }
868 for (c, o) in out.iter_mut().enumerate() {
869 let x = (x0 + c as i32).clamp(0, true_width as i32 - 1) as usize;
870 *o = (gain * i32::from(reference[y * stride + x])) as i16;
871 }
872 continue;
873 }
874 hpass_row(reference, y * stride, true_width, x0, taps, out);
875 }
876}
877
878/// lane-perf2: one output row of the vertical pass, accumulated tap-major so
879/// the inner loop walks two contiguous `i32` slices (vectorisable) instead of
880/// striding the intermediate by `block_w` per tap. A zero tap is skipped --
881/// adding `0 * x` is exactly nothing, and the 4-tap kernels zero four of the
882/// eight slots. `acc` is left holding the unrounded sums.
883#[inline]
884#[allow(unsafe_code)]
885pub(crate) fn vpass_row(intermediate: &[i16], block_w: usize, src_stride: usize, rows: usize, taps: &[i32; 8], acc: &mut [i32]) {
886 #[cfg(target_arch = "x86_64")]
887 {
888 match simd_level() {
889 // SAFETY: the arm is reached only when the CPU reports the
890 // feature; the kernel reads `intermediate[(row+t)*block_w ..
891 // + block_w]` for t in 0..8 and writes `acc[..block_w]`, which
892 // the debug asserts pin.
893 SimdLevel::Avx2 => {
894 unsafe { simd::vpass_avx2(intermediate, block_w, src_stride, rows, taps, acc) };
895 return;
896 }
897 SimdLevel::Sse41 => {
898 unsafe { simd::vpass_sse41(intermediate, block_w, src_stride, rows, taps, acc) };
899 return;
900 }
901 SimdLevel::Scalar => {}
902 }
903 }
904 for row in 0..rows {
905 vpass_row_scalar(
906 &intermediate[row * src_stride..], block_w, src_stride, 0, taps,
907 &mut acc[row * block_w..(row + 1) * block_w],
908 );
909 }
910}
911
912/// lane-mc: [`vpass_row`] with the output rounding fused in, for the two
913/// entry points whose destination is `u16` samples. The unrounded `i32` sums
914/// used to be stored to a scratch row and read straight back by a rounding
915/// loop; here they never leave the register.
916#[inline]
917#[allow(unsafe_code)]
918fn vpass_row_u16(
919 intermediate: &[i16],
920 block_w: usize,
921 src_stride: usize,
922 rows: usize,
923 taps: &[i32; 8],
924 max: i32,
925 dst: &mut [u16],
926) {
927 #[cfg(target_arch = "x86_64")]
928 {
929 match simd_level() {
930 // SAFETY: the arm is reached only when the CPU reports the
931 // feature; the kernel reads `intermediate[(row+t)*block_w ..
932 // + block_w]` for t in 0..8 and writes `dst[..block_w]`, which
933 // the debug asserts pin.
934 SimdLevel::Avx2 => {
935 unsafe { simd::vpass_row_u16_avx2(intermediate, block_w, src_stride, rows, taps, max, dst) };
936 return;
937 }
938 SimdLevel::Sse41 => {
939 unsafe { simd::vpass_row_u16_sse41(intermediate, block_w, src_stride, rows, taps, max, dst) };
940 return;
941 }
942 SimdLevel::Scalar => {}
943 }
944 }
945 for row in 0..rows {
946 vpass_row_u16_scalar(
947 &intermediate[row * src_stride..], block_w, src_stride, 0, taps, max,
948 &mut dst[row * block_w..(row + 1) * block_w],
949 );
950 }
951}
952
953/// The scalar reference for [`vpass_row_u16`].
954fn vpass_row_u16_scalar(
955 intermediate: &[i16],
956 block_w: usize,
957 src_stride: usize,
958 row: usize,
959 taps: &[i32; 8],
960 max: i32,
961 dst: &mut [u16],
962) {
963 for (c, d) in dst[..block_w].iter_mut().enumerate() {
964 let mut sum = 0i32;
965 for (t, &tap) in taps.iter().enumerate() {
966 sum += tap * i32::from(intermediate[(row + t) * src_stride + c]);
967 }
968 *d = round2(sum, INTER_ROUND_1).clamp(0, max) as u16;
969 }
970}
971
972/// The scalar reference for [`vpass_row`] (lane-perf2's tap-major loop).
973fn vpass_row_scalar(intermediate: &[i16], block_w: usize, src_stride: usize, row: usize, taps: &[i32; 8], acc: &mut [i32]) {
974 acc[..block_w].fill(0);
975 for (t, &tap) in taps.iter().enumerate() {
976 if tap == 0 {
977 continue;
978 }
979 let base = (row + t) * src_stride;
980 for (a, &s) in acc[..block_w].iter_mut().zip(&intermediate[base..base + block_w]) {
981 *a += tap * i32::from(s);
982 }
983 }
984}
985
986thread_local! {
987 /// lane-perf2: the separable filter's intermediate buffer, reused across
988 /// calls -- a 4K inter frame runs `predict*` hundreds of thousands of
989 /// times and each call used to `vec![0i32; (block_h+7) * block_w]`. The
990 /// horizontal pass writes every element it later reads, so no clearing is
991 /// needed; the tail `block_w` elements are the vertical pass's row
992 /// accumulator.
993 static MC_SCRATCH: std::cell::RefCell<(Vec<i16>, Vec<i32>)> =
994 const { std::cell::RefCell::new((Vec::new(), Vec::new())) };
995}
996
997/// Runs `f` on a scratch slice of `rows * block_w` intermediate elements plus
998/// a `block_w` accumulator (see [`MC_SCRATCH`]).
999fn with_scratch<R>(rows: usize, block_w: usize, f: impl FnOnce(&mut [i16], &mut [i32]) -> R) -> R {
1000 MC_SCRATCH.with(|s| {
1001 let mut buf = s.borrow_mut();
1002 let (inter, acc) = &mut *buf;
1003 let need = rows * block_w;
1004 if inter.len() < need {
1005 inter.resize(need, 0);
1006 }
1007 if acc.len() < block_w {
1008 acc.resize(block_w, 0);
1009 }
1010 f(&mut inter[..need], &mut acc[..block_w])
1011 })
1012}
1013
1014/// Predicts one `block_w * block_h` block into `dst`, row-major, from
1015/// `reference` (row-major, stride `stride`, true content
1016/// `true_width` x `true_height` -- a reference frame's decoded picture
1017/// buffer can be wider/taller than the true frame it holds, when this
1018/// encoder pads a picture to a whole number of superblocks; a spec decoder
1019/// never codes syntax for those extra columns/rows, so motion compensation
1020/// must clamp to the true extent, not the buffer's own stride).
1021///
1022/// `x_q4` / `y_q4` are the block's top-left position in the reference, in
1023/// 1/16-pel units (an integer MV has its low 4 bits zero); this function
1024/// splits each into its whole-sample part and its 0..16 fraction itself, so
1025/// the caller need not pre-split a motion vector.
1026///
1027/// # Panics
1028/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1029/// empty.
1030#[allow(clippy::too_many_arguments)] // one reference plane, one position, one block shape
1031pub(crate) fn predict(
1032 reference: &[u16],
1033 stride: usize,
1034 true_width: usize,
1035 true_height: usize,
1036 x_q4: i32,
1037 y_q4: i32,
1038 block_w: usize,
1039 block_h: usize,
1040 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1041) {
1042 predict_with_filter(
1043 reference,
1044 stride,
1045 true_width,
1046 true_height,
1047 x_q4,
1048 y_q4,
1049 block_w,
1050 block_h,
1051 // lane-refs: the FRAME's kernel (spec 6.8.9), not a hardwired
1052 // `Regular` -- `FrameCtx::interp_filter` is what the encoder set from
1053 // the header it is about to write, and every decode leaves it at
1054 // `Regular` (the decoder's own inter path calls
1055 // `predict_with_filters` with the kernels it parsed).
1056 fctx.interp_filter.get(),
1057 dst, fctx,
1058 );
1059}
1060
1061/// [`predict`], selecting the interpolation filter kernel explicitly (spec
1062/// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
1063/// kernel both directions.
1064#[allow(clippy::too_many_arguments)]
1065pub(crate) fn predict_with_filter(
1066 reference: &[u16],
1067 stride: usize,
1068 true_width: usize,
1069 true_height: usize,
1070 x_q4: i32,
1071 y_q4: i32,
1072 block_w: usize,
1073 block_h: usize,
1074 filter_kind: InterpFilterKind,
1075 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1076) {
1077 predict_with_filters(
1078 reference,
1079 stride,
1080 true_width,
1081 true_height,
1082 x_q4,
1083 y_q4,
1084 block_w,
1085 block_h,
1086 filter_kind,
1087 filter_kind,
1088 dst, fctx,
1089 );
1090}
1091
1092/// [`predict_with_filter`], with the horizontal (`interp_filter[0]`) and
1093/// vertical (`interp_filter[1]`) kernels chosen independently -- spec
1094/// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
1095/// so the two passes can genuinely differ.
1096#[allow(clippy::too_many_arguments)]
1097pub(crate) fn predict_with_filters(
1098 reference: &[u16],
1099 stride: usize,
1100 true_width: usize,
1101 true_height: usize,
1102 x_q4: i32,
1103 y_q4: i32,
1104 block_w: usize,
1105 block_h: usize,
1106 h_kind: InterpFilterKind,
1107 v_kind: InterpFilterKind,
1108 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1109) {
1110 predict_with_filters_kern(
1111 reference, stride, true_width, true_height, x_q4, y_q4, block_w,
1112 block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1113 );
1114}
1115
1116/// [`predict_with_filters`] with the 4-tap decision taken from the block's
1117/// TRUE width/height (`kern_w`/`kern_h`) rather than the destination buffer's.
1118/// libaom's `av1_get_interp_filter_params_with_block_size` (reconinter.h,
1119/// called per axis from `inter_predictor` with `w` then `h`) picks the narrow
1120/// kernel from the PREDICTION block's own dimensions; our inter path predicts
1121/// a rectangular block over its enclosing square buffer, so a rect block whose
1122/// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask
1123/// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.
1124#[allow(clippy::too_many_arguments)]
1125pub(crate) fn predict_with_filters_kern(
1126 reference: &[u16],
1127 stride: usize,
1128 true_width: usize,
1129 true_height: usize,
1130 x_q4: i32,
1131 y_q4: i32,
1132 block_w: usize,
1133 block_h: usize,
1134 kern_w: usize,
1135 kern_h: usize,
1136 h_kind: InterpFilterKind,
1137 v_kind: InterpFilterKind,
1138 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1139) {
1140 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1141 assert!(!reference.is_empty(), "a reference plane has samples");
1142 hit!(INTER_PRED_HITS);
1143
1144 #[cfg(test)]
1145 let stage_t = crate::encode::stage_start();
1146
1147 let x0 = x_q4.div_euclid(16);
1148 let xfrac = x_q4.rem_euclid(16) as usize;
1149 let y0 = y_q4.div_euclid(16);
1150 let yfrac = y_q4.rem_euclid(16) as usize;
1151 if crate::envflags::env_flag!("EC_MC_TRACE") && block_w >= 4 {
1152 eprintln!(
1153 "EC_MC_CALL x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} xfrac={xfrac} yfrac={yfrac} hk={h_kind:?} vk={v_kind:?} tw={true_width} th={true_height} stride={stride}"
1154 );
1155 }
1156
1157 // Whole-pel fast path: `SUBPEL_FILTERS[0]` is the identity tap (`128` at
1158 // its centre, everything else `0`), and both rounding shifts are exactly
1159 // that filter's own gain (see `INTER_ROUND_1`'s doc comment), so the two
1160 // 8-tap passes reproduce the reference sample byte-for-byte here --
1161 // `integer_mv_is_identity` below pins that. Skipping straight to a
1162 // clamped copy is bit-identical, not an approximation: it matters
1163 // because the motion search's own log/diamond stage (`motion.rs`) is
1164 // whole-pel-only and calls `predict` for every candidate it prices, so
1165 // this path is what most of a search's `predict` calls actually hit
1166 // (measured: `stage_timing_breakdown_inter` attributed 403 of a 720p
1167 // inter frame's 408ms motion-search bucket to `predict`, almost all of
1168 // it whole-pel candidates from stage 1).
1169 if xfrac == 0 && yfrac == 0 {
1170 for row in 0..block_h {
1171 let y = (y0 + row as i32).clamp(0, true_height as i32 - 1) as usize;
1172 let row_base = y * stride;
1173 let out = &mut dst[row * block_w..(row + 1) * block_w];
1174 // lane-perf2: an interior row is one contiguous copy.
1175 if x0 >= 0 && x0 as usize + block_w <= true_width {
1176 if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {
1177 // The common widths get a constant-length copy: at 8
1178 // samples a `memcpy` call costs more than the move it
1179 // makes, and 8x8 is the most common inter block on real
1180 // 4K content.
1181 match block_w {
1182 4 => out[..4].copy_from_slice(&src[..4]),
1183 8 => out[..8].copy_from_slice(&src[..8]),
1184 16 => out[..16].copy_from_slice(&src[..16]),
1185 _ => out.copy_from_slice(src),
1186 }
1187 continue;
1188 }
1189 }
1190 for (col, o) in out.iter_mut().enumerate() {
1191 let x = (x0 + col as i32).clamp(0, true_width as i32 - 1) as usize;
1192 *o = reference[row_base + x];
1193 }
1194 }
1195 #[cfg(test)]
1196 crate::encode::stage_since(1, stage_t);
1197 return;
1198 }
1199
1200 let (h_wide, h_narrow) = h_kind.tables();
1201 let (v_wide, v_narrow) = v_kind.tables();
1202 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1203 let h_filter = if kern_w <= 4 {
1204 &h_narrow[xfrac]
1205 } else {
1206 &h_wide[xfrac]
1207 };
1208 let v_filter = if kern_h <= 4 {
1209 &v_narrow[yfrac]
1210 } else {
1211 &v_wide[yfrac]
1212 };
1213
1214 // The vertical pass reads 3 rows above and 4 below the block, so the
1215 // horizontal pass must produce that many extra intermediate rows.
1216 // A whole-pel vertical position needs neither the 3 rows above nor the 4
1217 // below, and its vertical pass is the identity tap: `Round2(128 * a,
1218 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
1219 // block's own first row where the pass would have put the 4th.
1220 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1221 let max = crate::decode::sample_max(fctx);
1222 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the
1223 // identity tap, whose output is `s << 4` (`Round2(128 * s, InterRound0)`
1224 // with the tap 128). The vertical pass then computes
1225 // `Round2(sum(tap * (s << 4)), InterRound1)`, which is the same 8-tap sum
1226 // taken straight off the reference rows with every tap scaled by 16 --
1227 // bit-identical, and it skips materialising `block_h + 7` intermediate
1228 // rows. Interior blocks only; an edge block still needs the clamped read.
1229 if xfrac != 0 || yfrac == 0 {
1230 // fall through to the two-pass path
1231 } else {
1232 let top = y0 - 3;
1233 if top >= 0
1234 && x0 >= 0
1235 && x0 as usize + block_w <= true_width
1236 && top as usize + block_h + 7 <= true_height
1237 {
1238 let base = top as usize * stride + x0 as usize;
1239 if base + (block_h + 6) * stride + block_w <= reference.len() {
1240 let mut v16 = [0i32; 8];
1241 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1242 *o = t * 16;
1243 }
1244 // SAFETY: samples are below `2^15` at every supported bit
1245 // depth, so the same bytes read as `i16` are the same values;
1246 // the length is unchanged.
1247 #[allow(unsafe_code)]
1248 let src: &[i16] =
1249 unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
1250 vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst);
1251 #[cfg(test)]
1252 crate::encode::stage_since(1, stage_t);
1253 return;
1254 }
1255 }
1256 }
1257 with_scratch(rows, block_w, |intermediate, _acc| {
1258 horizontal_pass_unscaled(
1259 reference, stride, true_width, true_height, x0,
1260 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
1261 intermediate,
1262 );
1263 if yfrac == 0 {
1264 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1265 *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1266 }
1267 return;
1268 }
1269 vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1270 });
1271
1272 #[cfg(test)]
1273 crate::encode::stage_since(1, stage_t);
1274}
1275
1276/// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h`
1277/// `REF_NO_SCALE`): `x_scale_fp == REF_NO_SCALE` means the stored reference's
1278/// luma width equals the current frame's, so [`predict_scaled`] reduces
1279/// exactly to [`predict_with_filters`] (verified in
1280/// `predict_scaled_at_no_scale_matches_predict_with_filters` below).
1281pub const REF_NO_SCALE: i64 = 1 << 14;
1282
1283/// The horizontal scale ratio spec 7.11.3.3 derives from luma widths only
1284/// (libaom `av1_setup_scale_factors_for_frame`, luma widths, `REF_SCALE_SHIFT
1285/// == 14`): `other_width` is the stored reference picture's own luma width,
1286/// `this_width` the current frame's coded luma width. AV1 superres never
1287/// scales height (r8's derivation), so there is no vertical counterpart.
1288pub fn scale_factor(other_width: usize, this_width: usize) -> i64 {
1289 (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64
1290}
1291
1292thread_local! {
1293 /// lane-superres r10: firing count for the bypass gate (class
1294 /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself
1295 /// ran, so the gate can hard-assert the scaled MC path actually fired
1296 /// rather than trust a pixel match alone (an unscaled reference would
1297 /// pass the pixels and prove nothing).
1298 static PREDICT_SCALED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1299}
1300
1301/// Current value of [`PREDICT_SCALED_HITS`].
1302pub fn predict_scaled_hits() -> usize {
1303 PREDICT_SCALED_HITS.with(|c| c.get())
1304}
1305
1306thread_local! {
1307 /// lane-hbdinter: how many inter predictions this thread has produced
1308 /// (single-reference, scaled, and the compound intermediate entry). The
1309 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
1310 /// only intra blocks cannot pass it by construction (class
1311 /// `gate-blind-to-feature`).
1312 static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1313
1314 /// lane-rectchroma2 r1: how often the 4-tap decision came out DIFFERENT
1315 /// from what the destination buffer's own dimensions would have given --
1316 /// i.e. how often a rectangular block predicted over its enclosing square
1317 /// buffer asked for libaom's narrow kernel on an axis. Zero means a gate
1318 /// never exercised the rect-chroma shape at all.
1319 static RECT_NARROW_KERN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1320}
1321
1322/// Current value of [`RECT_NARROW_KERN_HITS`].
1323pub fn rect_narrow_kern_hits() -> usize {
1324 RECT_NARROW_KERN_HITS.with(|c| c.get())
1325}
1326
1327/// Resets [`RECT_NARROW_KERN_HITS`] (per-attempt counting, class
1328/// `counter-from-refused-stream`).
1329pub fn reset_rect_narrow_kern_hits() {
1330 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
1331}
1332
1333/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel
1334/// the destination buffer's dims would not have.
1335fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) {
1336 if (kern_w <= 4) != (block_w <= 4) || (kern_h <= 4) != (block_h <= 4) {
1337 hit!(RECT_NARROW_KERN_HITS);
1338 }
1339}
1340
1341/// Current value of [`INTER_PRED_HITS`].
1342pub fn inter_pred_hits() -> usize {
1343 INTER_PRED_HITS.with(|c| c.get())
1344}
1345
1346fn round_pow2_64(value: i64, shift: u32) -> i64 {
1347 if shift == 0 {
1348 value
1349 } else {
1350 (value + (1i64 << (shift - 1))) >> shift
1351 }
1352}
1353
1354/// `ROUND_POWER_OF_TWO_SIGNED` (libaom `common/common.h`): halves round away
1355/// from zero's *magnitude* -- negative inputs are rounded like their
1356/// negation, not truncated toward zero the way a plain arithmetic shift
1357/// would.
1358fn round_pow2_signed_64(value: i64, shift: u32) -> i64 {
1359 if value < 0 {
1360 -round_pow2_64(-value, shift)
1361 } else {
1362 round_pow2_64(value, shift)
1363 }
1364}
1365
1366/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared
1367/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two
1368/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs
1369/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the
1370/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10
1371/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low
1372/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1
1373/// whole-pel walk with one fixed phase (pinned by
1374/// `predict_scaled_at_no_scale_matches_predict_with_filters`).
1375#[allow(clippy::too_many_arguments)]
1376fn horizontal_scaled_pass(
1377 reference: &[u16],
1378 stride: usize,
1379 true_width: usize,
1380 true_height: usize,
1381 x_q4: i32,
1382 y0: i32,
1383 x_scale_fp: i64,
1384 block_w: usize,
1385 kern_w: usize,
1386 rows: usize,
1387 h_kind: InterpFilterKind,
1388 intermediate: &mut [i16],
1389) {
1390 let x_step_qn = round_pow2_64(x_scale_fp, 4);
1391 let off = (x_scale_fp - REF_NO_SCALE) * 8;
1392 let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32;
1393 let (h_wide, h_narrow) = h_kind.tables();
1394 for c in 0..block_w {
1395 let x_qn = pos_x_q10 + c as i64 * x_step_qn;
1396 let int_pel = (x_qn >> 10) as i32;
1397 let filter_idx = ((x_qn & 1023) >> 6) as usize;
1398 let h_filter = if kern_w <= 4 {
1399 &h_narrow[filter_idx]
1400 } else {
1401 &h_wide[filter_idx]
1402 };
1403 for r in 0..rows {
1404 let y = y0 - 3 + r as i32;
1405 let mut sum = 0;
1406 for (t, &tap) in h_filter.iter().enumerate() {
1407 let x = int_pel + t as i32 - 3;
1408 sum += tap * sample(reference, stride, true_width, true_height, x, y);
1409 }
1410 intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
1411 }
1412 }
1413}
1414
1415/// lane-perf2: the horizontal pass every two-pass entry point takes.
1416/// `horizontal_scaled_pass` was carrying the UNSCALED work too (every
1417/// compound prediction goes through it whatever the reference's scale), and
1418/// its per-column walk re-derives an integer position and a filter phase
1419/// that are constant at `REF_NO_SCALE`, reads the reference column-major,
1420/// and clamps per tap -- 14% of decode self time. At `REF_NO_SCALE` the
1421/// scaled walk reduces algebraically to `x0 = x_q4 / 16`, phase `x_q4 % 16`
1422/// (`pos_x_q10 == x_q4 * 64 + 32`, so `int_pel == x0` and
1423/// `(x_qn & 1023) >> 6 == xfrac` for every column), which is exactly
1424/// [`horizontal_pass_unscaled`] -- and
1425/// `predict_scaled_at_no_scale_matches_predict_with_filters` pins that
1426/// equality end to end. A genuinely scaled reference (superres) still takes
1427/// the general path.
1428#[allow(clippy::too_many_arguments)]
1429fn horizontal_pass(
1430 reference: &[u16],
1431 stride: usize,
1432 true_width: usize,
1433 true_height: usize,
1434 x_q4: i32,
1435 y0: i32,
1436 x_scale_fp: i64,
1437 block_w: usize,
1438 kern_w: usize,
1439 rows: usize,
1440 h_kind: InterpFilterKind,
1441 intermediate: &mut [i16],
1442) {
1443 if x_scale_fp == REF_NO_SCALE {
1444 let (h_wide, h_narrow) = h_kind.tables();
1445 let xfrac = x_q4.rem_euclid(16) as usize;
1446 let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] };
1447 horizontal_pass_unscaled(
1448 reference,
1449 stride,
1450 true_width,
1451 true_height,
1452 x_q4.div_euclid(16),
1453 y0,
1454 taps,
1455 block_w,
1456 rows,
1457 intermediate,
1458 );
1459 return;
1460 }
1461 horizontal_scaled_pass(
1462 reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w,
1463 rows, h_kind, intermediate,
1464 );
1465}
1466
1467/// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3):
1468/// used only when the stored reference's luma width differs from the current
1469/// frame's (`use_superres` on a non-key frame). `x_scale_fp` is
1470/// [`scale_factor`]'s ratio ([`REF_NO_SCALE`] reproduces
1471/// `predict_with_filters` bit-exact, pinned by
1472/// `predict_scaled_at_no_scale_matches_predict_with_filters`). Per r8's
1473/// derivation AV1 superres never scales height, so `y_q4`'s whole-sample /
1474/// fraction split and the vertical pass are untouched -- only the horizontal
1475/// pass's per-column integer position and filter phase come from a scaled
1476/// walk (`x_qn`) instead of a fixed stride-1 one.
1477///
1478/// # Panics
1479/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1480/// empty.
1481#[allow(clippy::too_many_arguments)]
1482pub(crate) fn predict_scaled(
1483 reference: &[u16],
1484 stride: usize,
1485 true_width: usize,
1486 true_height: usize,
1487 x_q4: i32,
1488 y_q4: i32,
1489 x_scale_fp: i64,
1490 block_w: usize,
1491 block_h: usize,
1492 h_kind: InterpFilterKind,
1493 v_kind: InterpFilterKind,
1494 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1495) {
1496 predict_scaled_kern(
1497 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1498 block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1499 );
1500}
1501
1502/// [`predict_scaled`] with the 4-tap decision from the block's true dims
1503/// (see [`predict_with_filters_kern`]).
1504#[allow(clippy::too_many_arguments)]
1505pub(crate) fn predict_scaled_kern(
1506 reference: &[u16],
1507 stride: usize,
1508 true_width: usize,
1509 true_height: usize,
1510 x_q4: i32,
1511 y_q4: i32,
1512 x_scale_fp: i64,
1513 block_w: usize,
1514 block_h: usize,
1515 kern_w: usize,
1516 kern_h: usize,
1517 h_kind: InterpFilterKind,
1518 v_kind: InterpFilterKind,
1519 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1520) {
1521 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1522 assert!(!reference.is_empty(), "a reference plane has samples");
1523 hit!(INTER_PRED_HITS);
1524 hit!(PREDICT_SCALED_HITS);
1525
1526 let y0 = y_q4.div_euclid(16);
1527 let yfrac = y_q4.rem_euclid(16) as usize;
1528
1529 // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to
1530 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
1531 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
1532 let (v_wide, v_narrow) = v_kind.tables();
1533 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1534 let v_filter = if kern_h <= 4 {
1535 &v_narrow[yfrac]
1536 } else {
1537 &v_wide[yfrac]
1538 };
1539
1540 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1541 let max = crate::decode::sample_max(fctx);
1542 with_scratch(rows, block_w, |intermediate, _acc| {
1543 horizontal_pass(
1544 reference, stride, true_width, true_height, x_q4,
1545 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1546 kern_w, rows, h_kind, intermediate,
1547 );
1548 if yfrac == 0 {
1549 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1550 *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1551 }
1552 return;
1553 }
1554 vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1555 });
1556}
1557
1558/// [`predict_with_filters`] or [`predict_scaled`], on this reference's own
1559/// `x_scale_fp` -- the dispatch every inter path needs once a reference can be
1560/// scaled (superres). `REF_NO_SCALE` takes the ordinary stride-1 path, which
1561/// keeps [`predict_scaled_hits`] a true count of scaled predictions.
1562#[allow(clippy::too_many_arguments)]
1563pub(crate) fn predict_maybe_scaled(
1564 reference: &[u16],
1565 stride: usize,
1566 true_width: usize,
1567 true_height: usize,
1568 x_q4: i32,
1569 y_q4: i32,
1570 x_scale_fp: i64,
1571 block_w: usize,
1572 block_h: usize,
1573 h_kind: InterpFilterKind,
1574 v_kind: InterpFilterKind,
1575 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1576) {
1577 if x_scale_fp == REF_NO_SCALE {
1578 predict_with_filters(
1579 reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,
1580 v_kind, dst, fctx,
1581 );
1582 } else {
1583 predict_scaled(
1584 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,
1585 block_h, h_kind, v_kind, dst, fctx,
1586 );
1587 }
1588}
1589
1590/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
1591/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
1592/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
1593/// (still above 8-bit pixel range) instead of a finished sample --
1594/// `predict_compound_intermediate` below stops there and leaves the final
1595/// clip to whichever combine step (simple/distance-weighted average, or a
1596/// future masked blend) runs on the pair of intermediates.
1597const INTER_ROUND_1_COMPOUND: u32 = 7;
1598
1599/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
1600/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
1601/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
1602/// (below) into one final shift.
1603const INTER_POST_ROUND: u32 = 4;
1604
1605/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
1606/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
1607/// they are the simple-average split (8/8) or a distance-weighted split
1608/// from [`crate::compound::dist_wtd_comp_weight_assign`].
1609const DIST_PRECISION_BITS: u32 = 4;
1610
1611/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
1612/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
1613/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
1614/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
1615/// per-reference predictions in until [`combine_compound`] blends them.
1616/// `dst` receives one `i32` per sample, row-major, same shape as
1617/// [`predict_with_filters`]'s `u8` `dst`.
1618///
1619/// # Panics
1620/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1621/// empty.
1622#[allow(clippy::too_many_arguments)]
1623pub fn predict_compound_intermediate(
1624 reference: &[u16],
1625 stride: usize,
1626 true_width: usize,
1627 true_height: usize,
1628 x_q4: i32,
1629 y_q4: i32,
1630 x_scale_fp: i64,
1631 block_w: usize,
1632 block_h: usize,
1633 h_kind: InterpFilterKind,
1634 v_kind: InterpFilterKind,
1635 dst: &mut [i32],
1636) {
1637 predict_compound_intermediate_kern(
1638 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1639 block_w, block_h, block_w, block_h, h_kind, v_kind, dst,
1640 );
1641}
1642
1643/// [`predict_compound_intermediate`] with the 4-tap decision from the block's
1644/// true dims (see [`predict_with_filters_kern`]).
1645#[allow(clippy::too_many_arguments)]
1646pub fn predict_compound_intermediate_kern(
1647 reference: &[u16],
1648 stride: usize,
1649 true_width: usize,
1650 true_height: usize,
1651 x_q4: i32,
1652 y_q4: i32,
1653 x_scale_fp: i64,
1654 block_w: usize,
1655 block_h: usize,
1656 kern_w: usize,
1657 kern_h: usize,
1658 h_kind: InterpFilterKind,
1659 v_kind: InterpFilterKind,
1660 dst: &mut [i32],
1661) {
1662 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1663 assert!(!reference.is_empty(), "a reference plane has samples");
1664 hit!(INTER_PRED_HITS);
1665
1666 if x_scale_fp != REF_NO_SCALE {
1667 hit!(PREDICT_SCALED_HITS);
1668 }
1669
1670 let y0 = y_q4.div_euclid(16);
1671 let yfrac = y_q4.rem_euclid(16) as usize;
1672 if crate::envflags::env_flag!("EC_MC_TRACE") {
1673 eprintln!("EC_MC_COMP x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} hk={h_kind:?} vk={v_kind:?}");
1674 }
1675
1676 let (v_wide, v_narrow) = v_kind.tables();
1677 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1678 let v_filter = if kern_h <= 4 {
1679 &v_narrow[yfrac]
1680 } else {
1681 &v_wide[yfrac]
1682 };
1683
1684 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1685 // lane-mc2: the unscaled whole-pel horizontal position is the identity
1686 // tap, whose intermediate is `s << 4`, so the vertical pass is the same
1687 // 8-tap sum taken straight off the reference rows with the taps scaled by
1688 // 16 (see `predict_with_filters_kern`). Interior blocks only.
1689 let x0 = x_q4.div_euclid(16);
1690 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {
1691 let top = y0 - 3;
1692 if top >= 0
1693 && x0 >= 0
1694 && x0 as usize + block_w <= true_width
1695 && top as usize + block_h + 7 <= true_height
1696 {
1697 let base = top as usize * stride + x0 as usize;
1698 if base + (block_h + 6) * stride + block_w <= reference.len() {
1699 let mut v16 = [0i32; 8];
1700 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1701 *o = t * 16;
1702 }
1703 // SAFETY: samples are below `2^15` at every supported bit
1704 // depth, so the same bytes read as `i16` are the same values.
1705 #[allow(unsafe_code)]
1706 let src: &[i16] =
1707 unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
1708 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);
1709 for d in dst.iter_mut() {
1710 *d = round2(*d, INTER_ROUND_1_COMPOUND);
1711 }
1712 return;
1713 }
1714 }
1715 }
1716 with_scratch(rows, block_w, |intermediate, _acc| {
1717 horizontal_pass(
1718 reference, stride, true_width, true_height, x_q4,
1719 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1720 kern_w, rows, h_kind, intermediate,
1721 );
1722 if yfrac == 0 {
1723 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
1724 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1725 *d = i32::from(a);
1726 }
1727 return;
1728 }
1729 vpass_row(intermediate, block_w, block_w, block_h, v_filter, dst);
1730 for d in dst.iter_mut() {
1731 *d = round2(*d, INTER_ROUND_1_COMPOUND);
1732 }
1733 });
1734}
1735
1736/// Blends two [`predict_compound_intermediate`] outputs into a finished
1737/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
1738/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
1739/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
1740/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
1741/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
1742/// function does not cover -- decode.rs still refuses those by name.
1743pub(crate) fn combine_compound(
1744 pred0: &[i32],
1745 pred1: &[i32],
1746 fwd_weight: i32,
1747 bck_weight: i32,
1748 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1749) {
1750 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1751 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
1752 for i in 0..dst.len() {
1753 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
1754 // applies the two shifts SEPARATELY: a truncating `>>
1755 // DIST_PRECISION_BITS` on the weighted sum, then `ROUND_POWER_OF_TWO`
1756 // by `round_bits == INTER_POST_ROUND`. Folding them into one
1757 // `Round2(sum, 8)` is NOT the same function -- it rounds up one LSB
1758 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
1759 // dropped low 4 bits are non-zero.
1760 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1761 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
1762 .clamp(0, crate::decode::sample_max(fctx)) as u16;
1763 }
1764}
1765
1766/// lane-maskcomp r2: `build_compound_diffwtd_mask` (reconinter.c) --
1767/// `DIFFWTD_38`/`DIFFWTD_38_INV` (`mask_type` bit: 0/1). Operates directly on
1768/// the two [`predict_compound_intermediate`] outputs: libaom's own
1769/// `av1_build_compound_diffwtd_mask_d16_c` runs on its CONV_BUF domain (which
1770/// carries a constant `round_offset` bias baked into every sample by its
1771/// convolve stage), but `abs(src0 - src1)` cancels an equal bias on both
1772/// sides exactly, so the unbiased `i32` intermediates this crate already
1773/// produces give the identical `diff` libaom computes. `round` is
1774/// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
1775/// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
1776pub(crate) fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) {
1777 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1778 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
1779 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
1780 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
1781 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
1782 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
1783 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
1784 let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
1785 for i in 0..mask.len() {
1786 let diff = round2((pred0[i] - pred1[i]).abs(), round);
1787 let m = (38 + diff / 16).clamp(0, 64);
1788 mask[i] = if inv { (64 - m) as u8 } else { m as u8 };
1789 }
1790}
1791
1792/// lane-maskcomp r2: `aom_lowbd_blend_a64_d16_mask_c` (blend_a64_mask.c),
1793/// algebraically simplified to this crate's unbiased `i32` intermediate
1794/// domain the same way [`diffwtd_mask`]'s doc comment derives -- libaom's
1795/// `res -= round_offset` step cancels exactly against the bias `m + (64-m)
1796/// == 64` contributes equally from both inputs, leaving `(m*pred0 +
1797/// (64-m)*pred1) >> 6` (a plain, unrounded shift, matching the C `>>` on
1798/// `int32_t`) then one final [`round2`] by [`INTER_POST_ROUND`]. `mask` is
1799/// always the LUMA-resolution mask (`mask_stride` == luma block width);
1800/// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /
1801/// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.
1802#[allow(clippy::too_many_arguments)]
1803pub(crate) fn blend_masked_compound(
1804 pred0: &[i32],
1805 pred1: &[i32],
1806 mask: &[u8],
1807 mask_stride: usize,
1808 w: usize,
1809 h: usize,
1810 subsampled: bool,
1811 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1812) {
1813 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
1814 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
1815 assert_eq!(dst.len(), w * h, "the destination is the block");
1816 for i in 0..h {
1817 for j in 0..w {
1818 let m = if subsampled {
1819 let idx = (2 * i) * mask_stride + 2 * j;
1820 round2(
1821 i32::from(mask[idx])
1822 + i32::from(mask[idx + 1])
1823 + i32::from(mask[idx + mask_stride])
1824 + i32::from(mask[idx + mask_stride + 1]),
1825 2,
1826 )
1827 } else {
1828 i32::from(mask[i * mask_stride + j])
1829 };
1830 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
1831 dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max(fctx)) as u16;
1832 }
1833 }
1834}
1835
1836/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
1837/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
1838/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
1839/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
1840/// keeps over [`predict`]'s 11-bit round survives untouched) --
1841/// [`combine_compound`] then divides that back out exactly with an 8/8
1842/// simple-average weight split, so a compound block whose two references
1843/// (and MVs) happen to coincide reproduces the plain source sample, not an
1844/// off-by-one from double rounding.
1845#[test]
1846fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1847 let fctx = &crate::decode::FrameCtx::new();
1848 let reference = vec![100u16; 16 * 16];
1849 let mut pred0 = vec![0i32; 16];
1850 predict_compound_intermediate(
1851 &reference,
1852 16,
1853 16,
1854 16,
1855 0,
1856 0,
1857 REF_NO_SCALE,
1858 4,
1859 4,
1860 InterpFilterKind::Regular,
1861 InterpFilterKind::Regular,
1862 &mut pred0,
1863 );
1864 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
1865
1866 let pred1 = pred0.clone();
1867 let mut dst = vec![0u16; 16];
1868 combine_compound(&pred0, &pred1, 8, 8, &mut dst, fctx);
1869 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
1870}
1871
1872#[cfg(test)]
1873mod tests {
1874 use super::{
1875 InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,
1876 predict_with_filters,
1877 };
1878
1879 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
1880 /// inter block at the frame's top-left corner (mv q4 = (row 7, col 15),
1881 /// bw=bh=16) predicted the wrong value because this decoder always used
1882 /// the REGULAR filter table -- aomdec's own `av1_convolve_2d_sr_c` trace
1883 /// showed this block actually used `EIGHTTAP_SMOOTH`
1884 /// (`0 0 2 34 62 28 2 0` at xfrac=15, not REGULAR's `0 0 -2 8 126 -6 2
1885 /// 0`). Window and expected output dumped straight from an
1886 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
1887 #[test]
1888 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1889 let fctx = &crate::decode::FrameCtx::new();
1890 #[rustfmt::skip]
1891 let window: [[u8; 24]; 24] = [
1892 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1893 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1894 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1895 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1896 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1897 [114,114,114,114,114,114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116,115,115,115],
1898 [114,114,114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,116,116,115,115,115,115],
1899 [113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,116,116,116,116,115,115,115,115],
1900 [113,113,113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,115,115,115,115,115,115],
1901 [112,112,112,112,112,112,112,112,112,113,113,113,113,114,114,114,114,114,115,115,115,115,115,115],
1902 [111,111,111,111,111,111,111,111,112,112,112,112,113,113,113,113,114,114,114,114,115,115,115,115],
1903 [110,110,110,110,110,110,110,110,111,111,111,111,112,112,112,113,113,113,113,113,114,114,114,115],
1904 [109,109,109,109,109,109,109,110,110,110,110,111,111,111,111,112,112,112,112,113,113,114,114,114],
1905 [108,108,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111,111,111,112,112,113,113,113],
1906 [108,108,108,108,108,108,108,108,108,108,109,109,109,110,110,110,110,110,111,111,112,112,112,112],
1907 [107,107,107,107,107,107,107,107,107,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111],
1908 [106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,110,110,110],
1909 [106,106,106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,109],
1910 [105,105,105,105,105,105,105,105,106,106,106,107,107,107,107,108,108,108,108,108,108,108,108,109],
1911 [104,104,104,104,104,104,104,104,104,105,105,106,106,106,107,107,107,107,107,107,107,108,108,108],
1912 [102,102,102,102,102,103,103,103,103,104,104,105,105,105,106,106,107,107,107,107,107,107,107,107],
1913 [101,101,101,101,101,101,101,102,102,103,103,104,104,104,105,105,106,106,106,106,106,107,107,107],
1914 [100,100,100,100,100,100,100,101,101,102,102,103,103,104,104,105,105,105,106,106,106,106,106,106],
1915 [99,99,99,99,99,99,100,100,100,101,101,102,103,103,104,104,105,105,105,105,105,105,105,106],
1916 ];
1917 // The dumped window spans real cols/rows -4..19; the block itself
1918 // starts at real (0, 0), so pad the reference plane so col/row 4 of
1919 // this buffer is real col/row 0, and hand `predict_with_filter` the
1920 // real (0, 0) coordinates -- clamping then reproduces the identical
1921 // extended border the dump already captured.
1922 let stride = 24;
1923 let mut reference = vec![0u16; stride * 24];
1924 for (r, row) in window.iter().enumerate() {
1925 for (c, &v) in row.iter().enumerate() {
1926 reference[r * stride + c] = u16::from(v);
1927 }
1928 }
1929 // predict()'s own edge clamp starts at true (0,0); shift so the
1930 // dumped window's row/col 4 lands there by biasing x_q4/y_q4's
1931 // whole-pel part by -4 and reading from a plane whose true origin
1932 // is the window's row/col 4 -- simplest is to pass true_width /
1933 // true_height covering the whole dumped window and offset the
1934 // whole-pel part of x_q4/y_q4 by +4 to land on real (0,0).
1935 let x_q4 = (4 + 0) * 16 + 15; // real block x0=0, xfrac=15
1936 let y_q4 = (4 + 0) * 16 + 7; // real block y0=0, yfrac=7
1937 let mut dst = vec![0u16; 16 * 16];
1938 predict_with_filter(
1939 &reference,
1940 stride,
1941 24,
1942 24,
1943 x_q4,
1944 y_q4,
1945 16,
1946 16,
1947 InterpFilterKind::Smooth,
1948 &mut dst, fctx,
1949 );
1950 #[rustfmt::skip]
1951 let expected_row0: [u16; 16] =
1952 [114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116];
1953 assert_eq!(
1954 &dst[0..16],
1955 &expected_row0,
1956 "row0 vs aomdec's real av1_convolve_2d_sr_c output"
1957 );
1958 #[rustfmt::skip]
1959 let expected_row15: [u16; 16] =
1960 [103,103,104,104,104,105,105,106,106,106,107,107,107,107,107,107];
1961 assert_eq!(
1962 &dst[15 * 16..15 * 16 + 16],
1963 &expected_row15,
1964 "row15 vs aomdec"
1965 );
1966 }
1967
1968 /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads
1969 /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH
1970 /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom
1971 /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`,
1972 /// `filter.h:243`). We used the 8-tap sharp kernel there, which is
1973 /// invisible above 4 samples and so only ever bit the 4x4 chroma of an
1974 /// 8x8 (or smaller) luma leaf.
1975 #[test]
1976 fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() {
1977 use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4};
1978 for kind in [
1979 InterpFilterKind::Regular,
1980 InterpFilterKind::Smooth,
1981 InterpFilterKind::Sharp,
1982 InterpFilterKind::Bilinear,
1983 ] {
1984 let (wide, narrow) = kind.tables();
1985 let want: &[[i32; 8]; 16] = match kind {
1986 InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4,
1987 InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4,
1988 InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR,
1989 };
1990 assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel");
1991 if kind == InterpFilterKind::Sharp {
1992 assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one");
1993 }
1994 }
1995 }
1996
1997 #[test]
1998 fn integer_mv_is_identity() {
1999 let fctx = &crate::decode::FrameCtx::new();
2000 let width = 12;
2001 let height = 12;
2002 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
2003 let mut dst = vec![0u16; 6 * 6];
2004 predict(
2005 &reference,
2006 width,
2007 width,
2008 height,
2009 3 * 16,
2010 4 * 16,
2011 6,
2012 6,
2013 &mut dst, fctx,
2014 );
2015 for row in 0..6 {
2016 for col in 0..6 {
2017 assert_eq!(
2018 dst[row * 6 + col],
2019 reference[(4 + row) * width + 3 + col],
2020 "integer MV must reproduce the reference block byte-for-byte"
2021 );
2022 }
2023 }
2024 }
2025
2026 #[test]
2027 fn half_pel_reproduces_the_ramp_midpoint() {
2028 let fctx = &crate::decode::FrameCtx::new();
2029 // Step 2 so every half-pel position lands on an exact integer.
2030 let width = 16;
2031 let height = 16;
2032 let reference: Vec<u16> = (0..width * height)
2033 .map(|i| (2 * (i % width)) as u16)
2034 .collect();
2035 let mut dst = vec![0u16; 4 * 4];
2036 // Half-pel in x only: fraction 8/16, integer part at column 5.
2037 predict(
2038 &reference,
2039 width,
2040 width,
2041 height,
2042 5 * 16 + 8,
2043 5 * 16,
2044 4,
2045 4,
2046 &mut dst, fctx,
2047 );
2048 for row in 0..4 {
2049 for col in 0..4 {
2050 let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
2051 assert_eq!(
2052 dst[row * 4 + col] as i32,
2053 midpoint as i32,
2054 "half-pel MV over a linear ramp must land exactly on the midpoint"
2055 );
2056 }
2057 }
2058 }
2059
2060 #[test]
2061 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
2062 let fctx = &crate::decode::FrameCtx::new();
2063 let width = 20;
2064 let height = 20;
2065 let reference = vec![142u16; width * height];
2066 for yfrac in 0..16 {
2067 for xfrac in 0..16 {
2068 let mut dst = vec![0u16; 5 * 5];
2069 predict(
2070 &reference,
2071 width,
2072 width,
2073 height,
2074 5 * 16 + xfrac,
2075 5 * 16 + yfrac,
2076 5,
2077 5,
2078 &mut dst, fctx,
2079 );
2080 assert!(
2081 dst.iter().all(|&v| v == 142),
2082 "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
2083 );
2084 }
2085 }
2086 }
2087
2088 #[test]
2089 fn horizontal_and_vertical_only_filtering_differ() {
2090 let fctx = &crate::decode::FrameCtx::new();
2091 // A plane linear in both x and y with different, even coefficients so
2092 // each axis's half-pel interpolation lands on an exact integer: this
2093 // pins the actual value each pass produces, not just that the two
2094 // differ, so swapping which pass reads which axis is caught even if
2095 // it happened to produce two merely-different numbers.
2096 let width = 10;
2097 let height = 10;
2098 let reference: Vec<u16> = (0..height)
2099 .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u16))
2100 .collect();
2101
2102 let mut horiz = vec![0u16; 4 * 4];
2103 predict(
2104 &reference,
2105 width,
2106 width,
2107 height,
2108 3 * 16 + 8,
2109 3 * 16,
2110 4,
2111 4,
2112 &mut horiz, fctx,
2113 );
2114 let mut vert = vec![0u16; 4 * 4];
2115 predict(
2116 &reference,
2117 width,
2118 width,
2119 height,
2120 3 * 16,
2121 3 * 16 + 8,
2122 4,
2123 4,
2124 &mut vert, fctx,
2125 );
2126
2127 for row in 0..4 {
2128 for col in 0..4 {
2129 // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
2130 assert_eq!(
2131 horiz[row * 4 + col] as i32,
2132 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
2133 "horizontal-only MV must interpolate along x only"
2134 );
2135 // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
2136 assert_eq!(
2137 vert[row * 4 + col] as i32,
2138 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
2139 "vertical-only MV must interpolate along y only"
2140 );
2141 }
2142 }
2143 assert_ne!(
2144 horiz, vert,
2145 "horizontal-only and vertical-only sub-pel MVs must give different outputs"
2146 );
2147 }
2148
2149 #[test]
2150 fn mv_past_the_edge_clamps_instead_of_panicking() {
2151 let fctx = &crate::decode::FrameCtx::new();
2152 let width = 8;
2153 let height = 8;
2154 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
2155 let mut dst = vec![0u16; 4 * 4];
2156 // Whole-sample position far above and to the left of the plane, with
2157 // an odd fraction so both filter passes exercise the clamp.
2158 predict(
2159 &reference,
2160 width,
2161 width,
2162 height,
2163 -50 * 16 + 5,
2164 -50 * 16 + 5,
2165 4,
2166 4,
2167 &mut dst, fctx,
2168 );
2169 let expected = reference[0]; // the whole plane clamps to the top-left corner
2170 assert!(
2171 dst.iter().all(|&v| v == expected),
2172 "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
2173 );
2174
2175 let mut dst2 = vec![0u16; 4 * 4];
2176 predict(
2177 &reference,
2178 width,
2179 width,
2180 height,
2181 50 * 16 + 5,
2182 50 * 16 + 5,
2183 4,
2184 4,
2185 &mut dst2, fctx,
2186 );
2187 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
2188 assert!(
2189 dst2.iter().all(|&v| v == expected2),
2190 "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
2191 );
2192 }
2193
2194 #[test]
2195 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
2196 let fctx = &crate::decode::FrameCtx::new();
2197 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
2198 // must reduce predict_scaled's per-column scaled walk to the exact
2199 // same int_pel/filter_idx sequence predict_with_filters computes from
2200 // a fixed stride-1 walk -- every subpel fraction, every block width.
2201 let width = 24;
2202 let height = 24;
2203 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
2204 for block_w in [4usize, 8, 16] {
2205 for x_frac in 0..16i32 {
2206 let x_q4 = 3 * 16 + x_frac;
2207 let y_q4 = 2 * 16 + 5;
2208 let mut expected = vec![0u16; block_w * 8];
2209 predict_with_filters(
2210 &reference,
2211 width,
2212 width,
2213 height,
2214 x_q4,
2215 y_q4,
2216 block_w,
2217 8,
2218 InterpFilterKind::Regular,
2219 InterpFilterKind::Regular,
2220 &mut expected, fctx,
2221 );
2222 let mut got = vec![0u16; block_w * 8];
2223 predict_scaled(
2224 &reference,
2225 width,
2226 width,
2227 height,
2228 x_q4,
2229 y_q4,
2230 REF_NO_SCALE,
2231 block_w,
2232 8,
2233 InterpFilterKind::Regular,
2234 InterpFilterKind::Regular,
2235 &mut got, fctx,
2236 );
2237 assert_eq!(
2238 got, expected,
2239 "block_w={block_w} x_frac={x_frac}: REF_NO_SCALE must reproduce predict_with_filters exactly"
2240 );
2241 }
2242 }
2243 }
2244
2245 /// lane-perf5: every explicit-SIMD kernel is checked against the scalar
2246 /// reference it replaces, over the whole domain a decode can hand it --
2247 /// all block widths (4..=128), all 16 sub-pel phases, all four filter
2248 /// kinds with both their wide and narrow (4-tap) tables, and 8/10/12-bit
2249 /// sample ranges. The dispatch itself is exercised through
2250 /// [`super::hpass_contig`] (whatever this CPU selected).
2251 #[allow(unsafe_code)]
2252 #[test]
2253 fn simd_matches_scalar_horizontal_pass() {
2254 let mut state = 0x2545_f491_4f6c_dd1du64;
2255 let mut rng = move || {
2256 state ^= state << 13;
2257 state ^= state >> 7;
2258 state ^= state << 17;
2259 state
2260 };
2261 let kinds = [
2262 InterpFilterKind::Regular,
2263 InterpFilterKind::Smooth,
2264 InterpFilterKind::Sharp,
2265 InterpFilterKind::Bilinear,
2266 ];
2267 let mut checked = 0usize;
2268 for depth_max in [255u16, 1023, 4095] {
2269 for &kind in &kinds {
2270 let (wide, narrow) = kind.tables();
2271 for table in [wide, narrow] {
2272 for frac in 0..16usize {
2273 let taps = &table[frac];
2274 let t16 = [
2275 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
2276 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
2277 ];
2278 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
2279 let src: Vec<u16> = (0..w + 7)
2280 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
2281 .collect();
2282 let mut want = vec![0i16; w];
2283 super::hpass_contig_scalar(&src, &t16, &mut want);
2284 let mut got = vec![0i16; w];
2285 super::hpass_contig(&src, &t16, &mut got);
2286 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
2287 #[cfg(target_arch = "x86_64")]
2288 {
2289 let mut sse = vec![0i16; w];
2290 unsafe { super::simd::hpass_sse2(&src, 0, 1, sse.len(), &t16, &mut sse) };
2291 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
2292 if std::arch::is_x86_feature_detected!("avx2") {
2293 let mut avx = vec![0i16; w];
2294 unsafe { super::simd::hpass_avx2(&src, 0, 1, avx.len(), &t16, &mut avx) };
2295 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
2296 }
2297 }
2298 checked += 1;
2299 }
2300 }
2301 }
2302 }
2303 }
2304 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
2305 }
2306
2307 /// lane-mc: the intermediate the horizontal pass writes is `i16`, which
2308 /// is a claim about the FILTER TABLES, not about a sample: every kernel's
2309 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
2310 /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
2311 /// value is that over `1 << INTER_ROUND_0`. This enumerates all four
2312 /// filter kinds, both their wide and narrow tables and all 16 phases at
2313 /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses
2314 /// 12-bit by name) and pins the result inside `i16` -- so the SIMD
2315 /// stores' `packs_epi32` never saturates on a motion-compensation path.
2316 #[test]
2317 fn horizontal_intermediate_fits_i16() {
2318 let kinds = [
2319 InterpFilterKind::Regular,
2320 InterpFilterKind::Smooth,
2321 InterpFilterKind::Sharp,
2322 InterpFilterKind::Bilinear,
2323 ];
2324 let max_sample = 1023i32; // 10-bit
2325 let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2326 for &kind in &kinds {
2327 let (wide, narrow) = kind.tables();
2328 for table in [wide, narrow] {
2329 for taps in table {
2330 let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2331 let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
2332 worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0));
2333 worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));
2334 }
2335 }
2336 }
2337 assert!(
2338 worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
2339 "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16"
2340 );
2341 }
2342
2343 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
2344 /// reference, over the same domain as
2345 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
2346 /// both wide and narrow (4-tap) tables of all four filter kinds, and
2347 /// intermediates spanning the 8/10/12-bit ranges the horizontal pass can
2348 /// produce (a 12-bit sample times the filter gain, both signs).
2349 #[allow(unsafe_code)]
2350 /// lane-mc2: with `xfrac == 0` the horizontal pass is the identity tap,
2351 /// so its intermediate is exactly `s << 4` and the vertical pass reads it
2352 /// with the taps scaled by 16. The fast path in
2353 /// [`predict_with_filters_kern`] skips the intermediate and reads the
2354 /// reference rows directly; this pins that it reproduces the two-pass
2355 /// form value-for-value at every vertical fraction and every block width
2356 /// (including the odd width the encoder's motion search prices).
2357 #[test]
2358 fn whole_pel_horizontal_matches_the_two_pass_form() {
2359 let fctx = &crate::decode::FrameCtx::new();
2360 let width = 160usize;
2361 let height = 48usize;
2362 let mut state = 0x2545_f491_4f6c_dd1du64;
2363 let mut rng = move || {
2364 state ^= state << 13;
2365 state ^= state >> 7;
2366 state ^= state << 17;
2367 state
2368 };
2369 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();
2370 let mut checked = 0usize;
2371 for &kind in &[InterpFilterKind::Regular, InterpFilterKind::Smooth, InterpFilterKind::Sharp] {
2372 let (v_wide, v_narrow) = kind.tables();
2373 for (bw, bh) in [(4usize, 4usize), (5, 4), (8, 8), (16, 16), (12, 8), (32, 16)] {
2374 for yfrac in 1..16i32 {
2375 let (x0, y0) = (7i32, 9i32);
2376 let taps = if bh <= 4 { &v_narrow[yfrac as usize] } else { &v_wide[yfrac as usize] };
2377 let mut want = vec![0u16; bw * bh];
2378 for row in 0..bh {
2379 for col in 0..bw {
2380 let mut sum = 0i32;
2381 for (t, &tap) in taps.iter().enumerate() {
2382 let y = y0 - 3 + row as i32 + t as i32;
2383 let s = i32::from(reference[y as usize * width + x0 as usize + col]);
2384 // The identity horizontal tap's output.
2385 sum += tap * (s << 4);
2386 }
2387 want[row * bw + col] = super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
2388 }
2389 }
2390 let mut got = vec![0u16; bw * bh];
2391 super::predict_with_filters_kern(
2392 &reference, width, width, height, x0 * 16, y0 * 16 + yfrac,
2393 bw, bh, bw, bh, kind, kind, &mut got, fctx,
2394 );
2395 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");
2396 checked += 1;
2397 }
2398 }
2399 }
2400 assert_eq!(checked, 3 * 6 * 15);
2401 }
2402
2403 #[allow(unsafe_code)]
2404 #[test]
2405 fn simd_matches_scalar_vertical_pass() {
2406 let mut state = 0x9e37_79b9_7f4a_7c15u64;
2407 let mut rng = move || {
2408 state ^= state << 13;
2409 state ^= state >> 7;
2410 state ^= state << 17;
2411 state
2412 };
2413 let kinds = [
2414 InterpFilterKind::Regular,
2415 InterpFilterKind::Smooth,
2416 InterpFilterKind::Sharp,
2417 InterpFilterKind::Bilinear,
2418 ];
2419 let mut checked = 0usize;
2420 // The horizontal pass's own range at 8- and 10-bit (12-bit is
2421 // refused in stream.rs), plus the saturating store's extreme.
2422 for span in [255i32 * 16, 1023 * 20, 32767] {
2423 for &kind in &kinds {
2424 let (wide, narrow) = kind.tables();
2425 for table in [wide, narrow] {
2426 for frac in 0..16usize {
2427 let taps = &table[frac];
2428 for w in [4usize, 5, 8, 12, 16, 20, 32, 64, 128] {
2429 let rows = 12usize;
2430 // lane-mc2: `st != w` is the fused whole-pel
2431 // horizontal path, which runs these kernels
2432 // straight over a reference plane's stride.
2433 for st in [w, w + 3] {
2434 let inter: Vec<i16> = (0..rows * st)
2435 .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
2436 .collect();
2437 for row in [0usize, 1, 4] {
2438 let mut want = vec![0i32; w];
2439 super::vpass_row_scalar(&inter[row * st..], w, st, 0, taps, &mut want);
2440 let mut got = vec![0i32; w];
2441 super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
2442 assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
2443 #[cfg(target_arch = "x86_64")]
2444 {
2445 if std::arch::is_x86_feature_detected!("sse4.1") {
2446 let mut sse = vec![0i32; w];
2447 unsafe { super::simd::vpass_sse41(&inter[row * st..], w, st, 1, taps, &mut sse) };
2448 assert_eq!(sse, want, "sse4.1 w={w} frac={frac} row={row}");
2449 }
2450 if std::arch::is_x86_feature_detected!("avx2") {
2451 let mut avx = vec![0i32; w];
2452 unsafe { super::simd::vpass_avx2(&inter[row * st..], w, st, 1, taps, &mut avx) };
2453 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
2454 }
2455 }
2456 // lane-mc: the rounding-fused form, over both
2457 // sample maxima this decoder accepts -- its
2458 // `packus`/`min_epu16` pair must reproduce
2459 // `round2(_, InterRound1).clamp(0, max)`.
2460 for max in [255i32, 1023] {
2461 let mut want_u16 = vec![0u16; w];
2462 super::vpass_row_u16_scalar(&inter, w, st, row, taps, max, &mut want_u16);
2463 for (d, &a) in want_u16.iter().zip(want.iter()) {
2464 assert_eq!(
2465 i32::from(*d),
2466 super::round2(a, super::INTER_ROUND_1).clamp(0, max),
2467 "the fused reference is the two-step one"
2468 );
2469 }
2470 let mut got_u16 = vec![0u16; w];
2471 super::vpass_row_u16(&inter[row * st..], w, st, 1, taps, max, &mut got_u16);
2472 assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");
2473 #[cfg(target_arch = "x86_64")]
2474 {
2475 if std::arch::is_x86_feature_detected!("sse4.1") {
2476 let mut sse = vec![0u16; w];
2477 unsafe { super::simd::vpass_row_u16_sse41(&inter[row * st..], w, st, 1, taps, max, &mut sse) };
2478 assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");
2479 }
2480 if std::arch::is_x86_feature_detected!("avx2") {
2481 let mut avx = vec![0u16; w];
2482 unsafe { super::simd::vpass_row_u16_avx2(&inter[row * st..], w, st, 1, taps, max, &mut avx) };
2483 assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");
2484 }
2485 }
2486 }
2487 checked += 1;
2488 }
2489 }
2490 }
2491 }
2492 }
2493 }
2494 }
2495 assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3 * 2);
2496 }
2497}