forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

mc.rs2492 lines, 101.7 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 InterpFilterKind::Regular,
1052 dst, fctx,
1053 );
1054}
1055
1056/// [`predict`], selecting the interpolation filter kernel explicitly (spec
1057/// 6.8.9's `interpolation_filter`) instead of always `Regular` -- the same
1058/// kernel both directions.
1059#[allow(clippy::too_many_arguments)]
1060pub(crate) fn predict_with_filter(
1061 reference: &[u16],
1062 stride: usize,
1063 true_width: usize,
1064 true_height: usize,
1065 x_q4: i32,
1066 y_q4: i32,
1067 block_w: usize,
1068 block_h: usize,
1069 filter_kind: InterpFilterKind,
1070 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1071) {
1072 predict_with_filters(
1073 reference,
1074 stride,
1075 true_width,
1076 true_height,
1077 x_q4,
1078 y_q4,
1079 block_w,
1080 block_h,
1081 filter_kind,
1082 filter_kind,
1083 dst, fctx,
1084 );
1085}
1086
1087/// [`predict_with_filter`], with the horizontal (`interp_filter[0]`) and
1088/// vertical (`interp_filter[1]`) kernels chosen independently -- spec
1089/// 5.11.20's per-block `SWITCHABLE` read is per-direction (`enable_dual_filter`),
1090/// so the two passes can genuinely differ.
1091#[allow(clippy::too_many_arguments)]
1092pub(crate) fn predict_with_filters(
1093 reference: &[u16],
1094 stride: usize,
1095 true_width: usize,
1096 true_height: usize,
1097 x_q4: i32,
1098 y_q4: i32,
1099 block_w: usize,
1100 block_h: usize,
1101 h_kind: InterpFilterKind,
1102 v_kind: InterpFilterKind,
1103 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1104) {
1105 predict_with_filters_kern(
1106 reference, stride, true_width, true_height, x_q4, y_q4, block_w,
1107 block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1108 );
1109}
1110
1111/// [`predict_with_filters`] with the 4-tap decision taken from the block's
1112/// TRUE width/height (`kern_w`/`kern_h`) rather than the destination buffer's.
1113/// libaom's `av1_get_interp_filter_params_with_block_size` (reconinter.h,
1114/// called per axis from `inter_predictor` with `w` then `h`) picks the narrow
1115/// kernel from the PREDICTION block's own dimensions; our inter path predicts
1116/// a rectangular block over its enclosing square buffer, so a rect block whose
1117/// chroma is 4 wide or 4 tall (luma 8x16 / 16x8 and taller kin) must still ask
1118/// for the 4-tap kernel on that axis -- lane-rectchroma2 r1.
1119#[allow(clippy::too_many_arguments)]
1120pub(crate) fn predict_with_filters_kern(
1121 reference: &[u16],
1122 stride: usize,
1123 true_width: usize,
1124 true_height: usize,
1125 x_q4: i32,
1126 y_q4: i32,
1127 block_w: usize,
1128 block_h: usize,
1129 kern_w: usize,
1130 kern_h: usize,
1131 h_kind: InterpFilterKind,
1132 v_kind: InterpFilterKind,
1133 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1134) {
1135 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1136 assert!(!reference.is_empty(), "a reference plane has samples");
1137 hit!(INTER_PRED_HITS);
1138
1139 #[cfg(test)]
1140 let stage_t = std::time::Instant::now();
1141
1142 let x0 = x_q4.div_euclid(16);
1143 let xfrac = x_q4.rem_euclid(16) as usize;
1144 let y0 = y_q4.div_euclid(16);
1145 let yfrac = y_q4.rem_euclid(16) as usize;
1146 if crate::envflags::env_flag!("EC_MC_TRACE") && block_w >= 4 {
1147 eprintln!(
1148 "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}"
1149 );
1150 }
1151
1152 // Whole-pel fast path: `SUBPEL_FILTERS[0]` is the identity tap (`128` at
1153 // its centre, everything else `0`), and both rounding shifts are exactly
1154 // that filter's own gain (see `INTER_ROUND_1`'s doc comment), so the two
1155 // 8-tap passes reproduce the reference sample byte-for-byte here --
1156 // `integer_mv_is_identity` below pins that. Skipping straight to a
1157 // clamped copy is bit-identical, not an approximation: it matters
1158 // because the motion search's own log/diamond stage (`motion.rs`) is
1159 // whole-pel-only and calls `predict` for every candidate it prices, so
1160 // this path is what most of a search's `predict` calls actually hit
1161 // (measured: `stage_timing_breakdown_inter` attributed 403 of a 720p
1162 // inter frame's 408ms motion-search bucket to `predict`, almost all of
1163 // it whole-pel candidates from stage 1).
1164 if xfrac == 0 && yfrac == 0 {
1165 for row in 0..block_h {
1166 let y = (y0 + row as i32).clamp(0, true_height as i32 - 1) as usize;
1167 let row_base = y * stride;
1168 let out = &mut dst[row * block_w..(row + 1) * block_w];
1169 // lane-perf2: an interior row is one contiguous copy.
1170 if x0 >= 0 && x0 as usize + block_w <= true_width {
1171 if let Some(src) = reference.get(row_base + x0 as usize..row_base + x0 as usize + block_w) {
1172 // The common widths get a constant-length copy: at 8
1173 // samples a `memcpy` call costs more than the move it
1174 // makes, and 8x8 is the most common inter block on real
1175 // 4K content.
1176 match block_w {
1177 4 => out[..4].copy_from_slice(&src[..4]),
1178 8 => out[..8].copy_from_slice(&src[..8]),
1179 16 => out[..16].copy_from_slice(&src[..16]),
1180 _ => out.copy_from_slice(src),
1181 }
1182 continue;
1183 }
1184 }
1185 for (col, o) in out.iter_mut().enumerate() {
1186 let x = (x0 + col as i32).clamp(0, true_width as i32 - 1) as usize;
1187 *o = reference[row_base + x];
1188 }
1189 }
1190 #[cfg(test)]
1191 crate::encode::stage_add(1, stage_t.elapsed());
1192 return;
1193 }
1194
1195 let (h_wide, h_narrow) = h_kind.tables();
1196 let (v_wide, v_narrow) = v_kind.tables();
1197 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1198 let h_filter = if kern_w <= 4 {
1199 &h_narrow[xfrac]
1200 } else {
1201 &h_wide[xfrac]
1202 };
1203 let v_filter = if kern_h <= 4 {
1204 &v_narrow[yfrac]
1205 } else {
1206 &v_wide[yfrac]
1207 };
1208
1209 // The vertical pass reads 3 rows above and 4 below the block, so the
1210 // horizontal pass must produce that many extra intermediate rows.
1211 // A whole-pel vertical position needs neither the 3 rows above nor the 4
1212 // below, and its vertical pass is the identity tap: `Round2(128 * a,
1213 // InterRound1) == Round2(a, InterRound1 - 7)`. Passing `y0 + 3` puts the
1214 // block's own first row where the pass would have put the 4th.
1215 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1216 let max = crate::decode::sample_max(fctx);
1217 // lane-mc2: a whole-pel horizontal position makes the horizontal pass the
1218 // identity tap, whose output is `s << 4` (`Round2(128 * s, InterRound0)`
1219 // with the tap 128). The vertical pass then computes
1220 // `Round2(sum(tap * (s << 4)), InterRound1)`, which is the same 8-tap sum
1221 // taken straight off the reference rows with every tap scaled by 16 --
1222 // bit-identical, and it skips materialising `block_h + 7` intermediate
1223 // rows. Interior blocks only; an edge block still needs the clamped read.
1224 if xfrac != 0 || yfrac == 0 {
1225 // fall through to the two-pass path
1226 } else {
1227 let top = y0 - 3;
1228 if top >= 0
1229 && x0 >= 0
1230 && x0 as usize + block_w <= true_width
1231 && top as usize + block_h + 7 <= true_height
1232 {
1233 let base = top as usize * stride + x0 as usize;
1234 if base + (block_h + 6) * stride + block_w <= reference.len() {
1235 let mut v16 = [0i32; 8];
1236 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1237 *o = t * 16;
1238 }
1239 // SAFETY: samples are below `2^15` at every supported bit
1240 // depth, so the same bytes read as `i16` are the same values;
1241 // the length is unchanged.
1242 #[allow(unsafe_code)]
1243 let src: &[i16] =
1244 unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
1245 vpass_row_u16(&src[base..], block_w, stride, block_h, &v16, max, dst);
1246 #[cfg(test)]
1247 crate::encode::stage_add(1, stage_t.elapsed());
1248 return;
1249 }
1250 }
1251 }
1252 with_scratch(rows, block_w, |intermediate, _acc| {
1253 horizontal_pass_unscaled(
1254 reference, stride, true_width, true_height, x0,
1255 if yfrac == 0 { y0 + 3 } else { y0 }, h_filter, block_w, rows,
1256 intermediate,
1257 );
1258 if yfrac == 0 {
1259 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1260 *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1261 }
1262 return;
1263 }
1264 vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1265 });
1266
1267 #[cfg(test)]
1268 crate::encode::stage_add(1, stage_t.elapsed());
1269}
1270
1271/// `REF_SCALE_SHIFT`'s "no scaling" value (spec 7.11.3.3, libaom `scale.h`
1272/// `REF_NO_SCALE`): `x_scale_fp == REF_NO_SCALE` means the stored reference's
1273/// luma width equals the current frame's, so [`predict_scaled`] reduces
1274/// exactly to [`predict_with_filters`] (verified in
1275/// `predict_scaled_at_no_scale_matches_predict_with_filters` below).
1276pub const REF_NO_SCALE: i64 = 1 << 14;
1277
1278/// The horizontal scale ratio spec 7.11.3.3 derives from luma widths only
1279/// (libaom `av1_setup_scale_factors_for_frame`, luma widths, `REF_SCALE_SHIFT
1280/// == 14`): `other_width` is the stored reference picture's own luma width,
1281/// `this_width` the current frame's coded luma width. AV1 superres never
1282/// scales height (r8's derivation), so there is no vertical counterpart.
1283pub fn scale_factor(other_width: usize, this_width: usize) -> i64 {
1284 (((other_width as i64) << 14) + this_width as i64 / 2) / this_width as i64
1285}
1286
1287thread_local! {
1288 /// lane-superres r10: firing count for the bypass gate (class
1289 /// `gate-blind-to-feature`) -- how many times [`predict_scaled`] itself
1290 /// ran, so the gate can hard-assert the scaled MC path actually fired
1291 /// rather than trust a pixel match alone (an unscaled reference would
1292 /// pass the pixels and prove nothing).
1293 static PREDICT_SCALED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1294}
1295
1296/// Current value of [`PREDICT_SCALED_HITS`].
1297pub fn predict_scaled_hits() -> usize {
1298 PREDICT_SCALED_HITS.with(|c| c.get())
1299}
1300
1301thread_local! {
1302 /// lane-hbdinter: how many inter predictions this thread has produced
1303 /// (single-reference, scaled, and the compound intermediate entry). The
1304 /// 10-bit inter gate hard-asserts this moved, so a stream that coded
1305 /// only intra blocks cannot pass it by construction (class
1306 /// `gate-blind-to-feature`).
1307 static INTER_PRED_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1308
1309 /// lane-rectchroma2 r1: how often the 4-tap decision came out DIFFERENT
1310 /// from what the destination buffer's own dimensions would have given --
1311 /// i.e. how often a rectangular block predicted over its enclosing square
1312 /// buffer asked for libaom's narrow kernel on an axis. Zero means a gate
1313 /// never exercised the rect-chroma shape at all.
1314 static RECT_NARROW_KERN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1315}
1316
1317/// Current value of [`RECT_NARROW_KERN_HITS`].
1318pub fn rect_narrow_kern_hits() -> usize {
1319 RECT_NARROW_KERN_HITS.with(|c| c.get())
1320}
1321
1322/// Resets [`RECT_NARROW_KERN_HITS`] (per-attempt counting, class
1323/// `counter-from-refused-stream`).
1324pub fn reset_rect_narrow_kern_hits() {
1325 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
1326}
1327
1328/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel
1329/// the destination buffer's dims would not have.
1330fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) {
1331 if (kern_w <= 4) != (block_w <= 4) || (kern_h <= 4) != (block_h <= 4) {
1332 hit!(RECT_NARROW_KERN_HITS);
1333 }
1334}
1335
1336/// Current value of [`INTER_PRED_HITS`].
1337pub fn inter_pred_hits() -> usize {
1338 INTER_PRED_HITS.with(|c| c.get())
1339}
1340
1341fn round_pow2_64(value: i64, shift: u32) -> i64 {
1342 if shift == 0 {
1343 value
1344 } else {
1345 (value + (1i64 << (shift - 1))) >> shift
1346 }
1347}
1348
1349/// `ROUND_POWER_OF_TWO_SIGNED` (libaom `common/common.h`): halves round away
1350/// from zero's *magnitude* -- negative inputs are rounded like their
1351/// negation, not truncated toward zero the way a plain arithmetic shift
1352/// would.
1353fn round_pow2_signed_64(value: i64, shift: u32) -> i64 {
1354 if value < 0 {
1355 -round_pow2_64(-value, shift)
1356 } else {
1357 round_pow2_64(value, shift)
1358 }
1359}
1360
1361/// Spec 7.11.3.3's horizontal pass on a (possibly) scaled reference, shared
1362/// by [`predict_scaled`] and [`predict_compound_intermediate`] -- the two
1363/// differ only in their VERTICAL rounding ([`INTER_ROUND_1`] vs
1364/// [`INTER_ROUND_1_COMPOUND`]), never here. Each output column walks the
1365/// reference by `x_step_qn` (the Q14 scale rounded down to the Q10
1366/// `SCALE_SUBPEL_BITS` grid) and picks its own filter phase from the low
1367/// bits, so `x_scale_fp == REF_NO_SCALE` reduces to the ordinary stride-1
1368/// whole-pel walk with one fixed phase (pinned by
1369/// `predict_scaled_at_no_scale_matches_predict_with_filters`).
1370#[allow(clippy::too_many_arguments)]
1371fn horizontal_scaled_pass(
1372 reference: &[u16],
1373 stride: usize,
1374 true_width: usize,
1375 true_height: usize,
1376 x_q4: i32,
1377 y0: i32,
1378 x_scale_fp: i64,
1379 block_w: usize,
1380 kern_w: usize,
1381 rows: usize,
1382 h_kind: InterpFilterKind,
1383 intermediate: &mut [i16],
1384) {
1385 let x_step_qn = round_pow2_64(x_scale_fp, 4);
1386 let off = (x_scale_fp - REF_NO_SCALE) * 8;
1387 let pos_x_q10 = round_pow2_signed_64(x_q4 as i64 * x_scale_fp + off, 8) + 32;
1388 let (h_wide, h_narrow) = h_kind.tables();
1389 for c in 0..block_w {
1390 let x_qn = pos_x_q10 + c as i64 * x_step_qn;
1391 let int_pel = (x_qn >> 10) as i32;
1392 let filter_idx = ((x_qn & 1023) >> 6) as usize;
1393 let h_filter = if kern_w <= 4 {
1394 &h_narrow[filter_idx]
1395 } else {
1396 &h_wide[filter_idx]
1397 };
1398 for r in 0..rows {
1399 let y = y0 - 3 + r as i32;
1400 let mut sum = 0;
1401 for (t, &tap) in h_filter.iter().enumerate() {
1402 let x = int_pel + t as i32 - 3;
1403 sum += tap * sample(reference, stride, true_width, true_height, x, y);
1404 }
1405 intermediate[r * block_w + c] = round2(sum, INTER_ROUND_0) as i16;
1406 }
1407 }
1408}
1409
1410/// lane-perf2: the horizontal pass every two-pass entry point takes.
1411/// `horizontal_scaled_pass` was carrying the UNSCALED work too (every
1412/// compound prediction goes through it whatever the reference's scale), and
1413/// its per-column walk re-derives an integer position and a filter phase
1414/// that are constant at `REF_NO_SCALE`, reads the reference column-major,
1415/// and clamps per tap -- 14% of decode self time. At `REF_NO_SCALE` the
1416/// scaled walk reduces algebraically to `x0 = x_q4 / 16`, phase `x_q4 % 16`
1417/// (`pos_x_q10 == x_q4 * 64 + 32`, so `int_pel == x0` and
1418/// `(x_qn & 1023) >> 6 == xfrac` for every column), which is exactly
1419/// [`horizontal_pass_unscaled`] -- and
1420/// `predict_scaled_at_no_scale_matches_predict_with_filters` pins that
1421/// equality end to end. A genuinely scaled reference (superres) still takes
1422/// the general path.
1423#[allow(clippy::too_many_arguments)]
1424fn horizontal_pass(
1425 reference: &[u16],
1426 stride: usize,
1427 true_width: usize,
1428 true_height: usize,
1429 x_q4: i32,
1430 y0: i32,
1431 x_scale_fp: i64,
1432 block_w: usize,
1433 kern_w: usize,
1434 rows: usize,
1435 h_kind: InterpFilterKind,
1436 intermediate: &mut [i16],
1437) {
1438 if x_scale_fp == REF_NO_SCALE {
1439 let (h_wide, h_narrow) = h_kind.tables();
1440 let xfrac = x_q4.rem_euclid(16) as usize;
1441 let taps = if kern_w <= 4 { &h_narrow[xfrac] } else { &h_wide[xfrac] };
1442 horizontal_pass_unscaled(
1443 reference,
1444 stride,
1445 true_width,
1446 true_height,
1447 x_q4.div_euclid(16),
1448 y0,
1449 taps,
1450 block_w,
1451 rows,
1452 intermediate,
1453 );
1454 return;
1455 }
1456 horizontal_scaled_pass(
1457 reference, stride, true_width, true_height, x_q4, y0, x_scale_fp, block_w, kern_w,
1458 rows, h_kind, intermediate,
1459 );
1460}
1461
1462/// [`predict_with_filters`]'s scaled-reference counterpart (spec 7.11.3.3):
1463/// used only when the stored reference's luma width differs from the current
1464/// frame's (`use_superres` on a non-key frame). `x_scale_fp` is
1465/// [`scale_factor`]'s ratio ([`REF_NO_SCALE`] reproduces
1466/// `predict_with_filters` bit-exact, pinned by
1467/// `predict_scaled_at_no_scale_matches_predict_with_filters`). Per r8's
1468/// derivation AV1 superres never scales height, so `y_q4`'s whole-sample /
1469/// fraction split and the vertical pass are untouched -- only the horizontal
1470/// pass's per-column integer position and filter phase come from a scaled
1471/// walk (`x_qn`) instead of a fixed stride-1 one.
1472///
1473/// # Panics
1474/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1475/// empty.
1476#[allow(clippy::too_many_arguments)]
1477pub(crate) fn predict_scaled(
1478 reference: &[u16],
1479 stride: usize,
1480 true_width: usize,
1481 true_height: usize,
1482 x_q4: i32,
1483 y_q4: i32,
1484 x_scale_fp: i64,
1485 block_w: usize,
1486 block_h: usize,
1487 h_kind: InterpFilterKind,
1488 v_kind: InterpFilterKind,
1489 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1490) {
1491 predict_scaled_kern(
1492 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1493 block_w, block_h, block_w, block_h, h_kind, v_kind, dst, fctx,
1494 );
1495}
1496
1497/// [`predict_scaled`] with the 4-tap decision from the block's true dims
1498/// (see [`predict_with_filters_kern`]).
1499#[allow(clippy::too_many_arguments)]
1500pub(crate) fn predict_scaled_kern(
1501 reference: &[u16],
1502 stride: usize,
1503 true_width: usize,
1504 true_height: usize,
1505 x_q4: i32,
1506 y_q4: i32,
1507 x_scale_fp: i64,
1508 block_w: usize,
1509 block_h: usize,
1510 kern_w: usize,
1511 kern_h: usize,
1512 h_kind: InterpFilterKind,
1513 v_kind: InterpFilterKind,
1514 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1515) {
1516 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1517 assert!(!reference.is_empty(), "a reference plane has samples");
1518 hit!(INTER_PRED_HITS);
1519 hit!(PREDICT_SCALED_HITS);
1520
1521 let y0 = y_q4.div_euclid(16);
1522 let yfrac = y_q4.rem_euclid(16) as usize;
1523
1524 // SCALE_SUBPEL_BITS == 10: x_step_qn is x_scale_fp (Q14) rounded down to
1525 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
1526 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
1527 let (v_wide, v_narrow) = v_kind.tables();
1528 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1529 let v_filter = if kern_h <= 4 {
1530 &v_narrow[yfrac]
1531 } else {
1532 &v_wide[yfrac]
1533 };
1534
1535 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1536 let max = crate::decode::sample_max(fctx);
1537 with_scratch(rows, block_w, |intermediate, _acc| {
1538 horizontal_pass(
1539 reference, stride, true_width, true_height, x_q4,
1540 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1541 kern_w, rows, h_kind, intermediate,
1542 );
1543 if yfrac == 0 {
1544 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1545 *d = round2(i32::from(a), INTER_ROUND_1 - 7).clamp(0, max) as u16;
1546 }
1547 return;
1548 }
1549 vpass_row_u16(intermediate, block_w, block_w, block_h, v_filter, max, dst);
1550 });
1551}
1552
1553/// [`predict_with_filters`] or [`predict_scaled`], on this reference's own
1554/// `x_scale_fp` -- the dispatch every inter path needs once a reference can be
1555/// scaled (superres). `REF_NO_SCALE` takes the ordinary stride-1 path, which
1556/// keeps [`predict_scaled_hits`] a true count of scaled predictions.
1557#[allow(clippy::too_many_arguments)]
1558pub(crate) fn predict_maybe_scaled(
1559 reference: &[u16],
1560 stride: usize,
1561 true_width: usize,
1562 true_height: usize,
1563 x_q4: i32,
1564 y_q4: i32,
1565 x_scale_fp: i64,
1566 block_w: usize,
1567 block_h: usize,
1568 h_kind: InterpFilterKind,
1569 v_kind: InterpFilterKind,
1570 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1571) {
1572 if x_scale_fp == REF_NO_SCALE {
1573 predict_with_filters(
1574 reference, stride, true_width, true_height, x_q4, y_q4, block_w, block_h, h_kind,
1575 v_kind, dst, fctx,
1576 );
1577 } else {
1578 predict_scaled(
1579 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp, block_w,
1580 block_h, h_kind, v_kind, dst, fctx,
1581 );
1582 }
1583}
1584
1585/// `InterRound1` for a compound ref (spec 7.11.3.2's `isCompound` branch,
1586/// `COMPOUND_ROUND1_BITS` in libaom's `convolve.h`): 4 bits shallower than
1587/// [`INTER_ROUND_1`] so the vertical pass lands in the `CONV_BUF` domain
1588/// (still above 8-bit pixel range) instead of a finished sample --
1589/// `predict_compound_intermediate` below stops there and leaves the final
1590/// clip to whichever combine step (simple/distance-weighted average, or a
1591/// future masked blend) runs on the pair of intermediates.
1592const INTER_ROUND_1_COMPOUND: u32 = 7;
1593
1594/// `InterPostRound` (spec 7.11.3.2): `2 * FILTER_BITS - (InterRound0 +
1595/// InterRound1)` with the *compound* `InterRound1` above -- `2*7 - (3+7) ==
1596/// 4`. [`combine_compound`] folds this together with `DIST_PRECISION_BITS`
1597/// (below) into one final shift.
1598const INTER_POST_ROUND: u32 = 4;
1599
1600/// `DIST_PRECISION_BITS` (spec 7.11.3.15 / libaom `enums.h`): the two
1601/// weights [`combine_compound`] takes always sum to `1 << 4 == 16`, whether
1602/// they are the simple-average split (8/8) or a distance-weighted split
1603/// from [`crate::compound::dist_wtd_comp_weight_assign`].
1604const DIST_PRECISION_BITS: u32 = 4;
1605
1606/// [`predict_with_filters`]'s compound counterpart: same two-pass separable
1607/// filter, but the vertical pass rounds by [`INTER_ROUND_1_COMPOUND`]
1608/// instead of [`INTER_ROUND_1`] and is never clipped to a pixel -- the
1609/// `CONV_BUF` intermediate domain spec 7.11.3.2 keeps a compound block's two
1610/// per-reference predictions in until [`combine_compound`] blends them.
1611/// `dst` receives one `i32` per sample, row-major, same shape as
1612/// [`predict_with_filters`]'s `u8` `dst`.
1613///
1614/// # Panics
1615/// Panics when `dst` is not `block_w * block_h` long, or the reference is
1616/// empty.
1617#[allow(clippy::too_many_arguments)]
1618pub fn predict_compound_intermediate(
1619 reference: &[u16],
1620 stride: usize,
1621 true_width: usize,
1622 true_height: usize,
1623 x_q4: i32,
1624 y_q4: i32,
1625 x_scale_fp: i64,
1626 block_w: usize,
1627 block_h: usize,
1628 h_kind: InterpFilterKind,
1629 v_kind: InterpFilterKind,
1630 dst: &mut [i32],
1631) {
1632 predict_compound_intermediate_kern(
1633 reference, stride, true_width, true_height, x_q4, y_q4, x_scale_fp,
1634 block_w, block_h, block_w, block_h, h_kind, v_kind, dst,
1635 );
1636}
1637
1638/// [`predict_compound_intermediate`] with the 4-tap decision from the block's
1639/// true dims (see [`predict_with_filters_kern`]).
1640#[allow(clippy::too_many_arguments)]
1641pub fn predict_compound_intermediate_kern(
1642 reference: &[u16],
1643 stride: usize,
1644 true_width: usize,
1645 true_height: usize,
1646 x_q4: i32,
1647 y_q4: i32,
1648 x_scale_fp: i64,
1649 block_w: usize,
1650 block_h: usize,
1651 kern_w: usize,
1652 kern_h: usize,
1653 h_kind: InterpFilterKind,
1654 v_kind: InterpFilterKind,
1655 dst: &mut [i32],
1656) {
1657 assert_eq!(dst.len(), block_w * block_h, "the destination is the block");
1658 assert!(!reference.is_empty(), "a reference plane has samples");
1659 hit!(INTER_PRED_HITS);
1660
1661 if x_scale_fp != REF_NO_SCALE {
1662 hit!(PREDICT_SCALED_HITS);
1663 }
1664
1665 let y0 = y_q4.div_euclid(16);
1666 let yfrac = y_q4.rem_euclid(16) as usize;
1667 if crate::envflags::env_flag!("EC_MC_TRACE") {
1668 eprintln!("EC_MC_COMP x_q4={x_q4} y_q4={y_q4} w={block_w} h={block_h} hk={h_kind:?} vk={v_kind:?}");
1669 }
1670
1671 let (v_wide, v_narrow) = v_kind.tables();
1672 note_narrow_kern(block_w, block_h, kern_w, kern_h);
1673 let v_filter = if kern_h <= 4 {
1674 &v_narrow[yfrac]
1675 } else {
1676 &v_wide[yfrac]
1677 };
1678
1679 let rows = if yfrac == 0 { block_h } else { block_h + 7 };
1680 // lane-mc2: the unscaled whole-pel horizontal position is the identity
1681 // tap, whose intermediate is `s << 4`, so the vertical pass is the same
1682 // 8-tap sum taken straight off the reference rows with the taps scaled by
1683 // 16 (see `predict_with_filters_kern`). Interior blocks only.
1684 let x0 = x_q4.div_euclid(16);
1685 if x_scale_fp == REF_NO_SCALE && x_q4.rem_euclid(16) == 0 && yfrac != 0 && block_w <= 128 {
1686 let top = y0 - 3;
1687 if top >= 0
1688 && x0 >= 0
1689 && x0 as usize + block_w <= true_width
1690 && top as usize + block_h + 7 <= true_height
1691 {
1692 let base = top as usize * stride + x0 as usize;
1693 if base + (block_h + 6) * stride + block_w <= reference.len() {
1694 let mut v16 = [0i32; 8];
1695 for (o, &t) in v16.iter_mut().zip(v_filter.iter()) {
1696 *o = t * 16;
1697 }
1698 // SAFETY: samples are below `2^15` at every supported bit
1699 // depth, so the same bytes read as `i16` are the same values.
1700 #[allow(unsafe_code)]
1701 let src: &[i16] =
1702 unsafe { std::slice::from_raw_parts(reference.as_ptr().cast::<i16>(), reference.len()) };
1703 vpass_row(&src[base..], block_w, stride, block_h, &v16, dst);
1704 for d in dst.iter_mut() {
1705 *d = round2(*d, INTER_ROUND_1_COMPOUND);
1706 }
1707 return;
1708 }
1709 }
1710 }
1711 with_scratch(rows, block_w, |intermediate, _acc| {
1712 horizontal_pass(
1713 reference, stride, true_width, true_height, x_q4,
1714 if yfrac == 0 { y0 + 3 } else { y0 }, x_scale_fp, block_w,
1715 kern_w, rows, h_kind, intermediate,
1716 );
1717 if yfrac == 0 {
1718 // `Round2(128 * a, INTER_ROUND_1_COMPOUND) == a`.
1719 for (d, &a) in dst.iter_mut().zip(intermediate.iter()) {
1720 *d = i32::from(a);
1721 }
1722 return;
1723 }
1724 vpass_row(intermediate, block_w, block_w, block_h, v_filter, dst);
1725 for d in dst.iter_mut() {
1726 *d = round2(*d, INTER_ROUND_1_COMPOUND);
1727 }
1728 });
1729}
1730
1731/// Blends two [`predict_compound_intermediate`] outputs into a finished
1732/// 8-bit block (spec 7.11.3.15's weighted-average combine, the
1733/// `comp_group_idx == 0` path -- `fwd_weight`/`bck_weight` are either the
1734/// simple-average split `(8, 8)` or [`crate::compound::dist_wtd_comp_weight_assign`]'s
1735/// output; both always sum to `1 << DIST_PRECISION_BITS`). Masked compound
1736/// (`comp_group_idx == 1`, wedge/diffwtd) is a different combine this
1737/// function does not cover -- decode.rs still refuses those by name.
1738pub(crate) fn combine_compound(
1739 pred0: &[i32],
1740 pred1: &[i32],
1741 fwd_weight: i32,
1742 bck_weight: i32,
1743 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1744) {
1745 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1746 assert_eq!(dst.len(), pred0.len(), "the destination is the block");
1747 for i in 0..dst.len() {
1748 // libaom (`av1_highbd_dist_wtd_convolve_2d_c`, and its lowbd twin)
1749 // applies the two shifts SEPARATELY: a truncating `>>
1750 // DIST_PRECISION_BITS` on the weighted sum, then `ROUND_POWER_OF_TWO`
1751 // by `round_bits == INTER_POST_ROUND`. Folding them into one
1752 // `Round2(sum, 8)` is NOT the same function -- it rounds up one LSB
1753 // whenever `(sum >> 4) + 8` is one below a multiple of 16 and the
1754 // dropped low 4 bits are non-zero.
1755 let sum = pred0[i] * fwd_weight + pred1[i] * bck_weight;
1756 dst[i] = round2(sum >> DIST_PRECISION_BITS, INTER_POST_ROUND)
1757 .clamp(0, crate::decode::sample_max(fctx)) as u16;
1758 }
1759}
1760
1761/// lane-maskcomp r2: `build_compound_diffwtd_mask` (reconinter.c) --
1762/// `DIFFWTD_38`/`DIFFWTD_38_INV` (`mask_type` bit: 0/1). Operates directly on
1763/// the two [`predict_compound_intermediate`] outputs: libaom's own
1764/// `av1_build_compound_diffwtd_mask_d16_c` runs on its CONV_BUF domain (which
1765/// carries a constant `round_offset` bias baked into every sample by its
1766/// convolve stage), but `abs(src0 - src1)` cancels an equal bias on both
1767/// sides exactly, so the unbiased `i32` intermediates this crate already
1768/// produces give the identical `diff` libaom computes. `round` is
1769/// `2*FILTER_BITS - round_0 - round_1 + (bd-8)` == [`INTER_POST_ROUND`] for
1770/// 8-bit content (`round_0=3`, compound `round_1=7`, `bd=8`).
1771pub(crate) fn diffwtd_mask(pred0: &[i32], pred1: &[i32], inv: bool, mask: &mut [u8], fctx: &crate::decode::FrameCtx) {
1772 assert_eq!(pred0.len(), pred1.len(), "both refs predict the same block");
1773 assert_eq!(mask.len(), pred0.len(), "one mask byte per pixel");
1774 // libaom `diffwtd_mask_d16` (`reconinter.c:307`): `round = 2*FILTER_BITS
1775 // - round_0 - round_1 + (bd - 8)`, i.e. INTER_POST_ROUND plus the
1776 // bit-depth headroom the CONV_BUF domain carries at 10/12-bit. `round_0`
1777 // and `round_1` themselves only move at 12-bit (`convolve.h:83`'s
1778 // `intbufrange > 16`), so the whole bit-depth dependence here is `bd - 8`.
1779 let round = INTER_POST_ROUND + u32::from(crate::decode::bit_depth(fctx)).saturating_sub(8);
1780 for i in 0..mask.len() {
1781 let diff = round2((pred0[i] - pred1[i]).abs(), round);
1782 let m = (38 + diff / 16).clamp(0, 64);
1783 mask[i] = if inv { (64 - m) as u8 } else { m as u8 };
1784 }
1785}
1786
1787/// lane-maskcomp r2: `aom_lowbd_blend_a64_d16_mask_c` (blend_a64_mask.c),
1788/// algebraically simplified to this crate's unbiased `i32` intermediate
1789/// domain the same way [`diffwtd_mask`]'s doc comment derives -- libaom's
1790/// `res -= round_offset` step cancels exactly against the bias `m + (64-m)
1791/// == 64` contributes equally from both inputs, leaving `(m*pred0 +
1792/// (64-m)*pred1) >> 6` (a plain, unrounded shift, matching the C `>>` on
1793/// `int32_t`) then one final [`round2`] by [`INTER_POST_ROUND`]. `mask` is
1794/// always the LUMA-resolution mask (`mask_stride` == luma block width);
1795/// `subsampled` selects the 2x2-average chroma read (spec 7.11.3.14 /
1796/// libaom's `subw == 1 && subh == 1` branch) vs. the direct luma read.
1797#[allow(clippy::too_many_arguments)]
1798pub(crate) fn blend_masked_compound(
1799 pred0: &[i32],
1800 pred1: &[i32],
1801 mask: &[u8],
1802 mask_stride: usize,
1803 w: usize,
1804 h: usize,
1805 subsampled: bool,
1806 dst: &mut [u16], fctx: &crate::decode::FrameCtx,
1807) {
1808 assert_eq!(pred0.len(), w * h, "pred0 is the destination-sized block");
1809 assert_eq!(pred1.len(), w * h, "pred1 is the destination-sized block");
1810 assert_eq!(dst.len(), w * h, "the destination is the block");
1811 for i in 0..h {
1812 for j in 0..w {
1813 let m = if subsampled {
1814 let idx = (2 * i) * mask_stride + 2 * j;
1815 round2(
1816 i32::from(mask[idx])
1817 + i32::from(mask[idx + 1])
1818 + i32::from(mask[idx + mask_stride])
1819 + i32::from(mask[idx + mask_stride + 1]),
1820 2,
1821 )
1822 } else {
1823 i32::from(mask[i * mask_stride + j])
1824 };
1825 let res = (m * pred0[i * w + j] + (64 - m) * pred1[i * w + j]) >> 6;
1826 dst[i * w + j] = round2(res, INTER_POST_ROUND).clamp(0, crate::decode::sample_max(fctx)) as u16;
1827 }
1828 }
1829}
1830
1831/// Whole-pel identity case: [`predict_compound_intermediate`]'s two-pass
1832/// filter reduces to `16 * source_sample` exactly (the fraction-0 row is a
1833/// single `128` tap both passes, and `128*128 == 1 << 14`, `14 - 7 == 7 ==
1834/// INTER_ROUND_1_COMPOUND`, so the extra `2^4` of gain the compound path
1835/// keeps over [`predict`]'s 11-bit round survives untouched) --
1836/// [`combine_compound`] then divides that back out exactly with an 8/8
1837/// simple-average weight split, so a compound block whose two references
1838/// (and MVs) happen to coincide reproduces the plain source sample, not an
1839/// off-by-one from double rounding.
1840#[test]
1841fn compound_intermediate_whole_pel_identity_round_trips_through_combine() {
1842 let fctx = &crate::decode::FrameCtx::new();
1843 let reference = vec![100u16; 16 * 16];
1844 let mut pred0 = vec![0i32; 16];
1845 predict_compound_intermediate(
1846 &reference,
1847 16,
1848 16,
1849 16,
1850 0,
1851 0,
1852 REF_NO_SCALE,
1853 4,
1854 4,
1855 InterpFilterKind::Regular,
1856 InterpFilterKind::Regular,
1857 &mut pred0,
1858 );
1859 assert!(pred0.iter().all(|&v| v == 1600), "{pred0:?}");
1860
1861 let pred1 = pred0.clone();
1862 let mut dst = vec![0u16; 16];
1863 combine_compound(&pred0, &pred1, 8, 8, &mut dst, fctx);
1864 assert!(dst.iter().all(|&v| v == 100), "{dst:?}");
1865}
1866
1867#[cfg(test)]
1868mod tests {
1869 use super::{
1870 InterpFilterKind, REF_NO_SCALE, predict, predict_scaled, predict_with_filter,
1871 predict_with_filters,
1872 };
1873
1874 /// Regression pin for the lane-av1flake ±1 defect: a real aomenc chroma
1875 /// inter block at the frame's top-left corner (mv q4 = (row 7, col 15),
1876 /// bw=bh=16) predicted the wrong value because this decoder always used
1877 /// the REGULAR filter table -- aomdec's own `av1_convolve_2d_sr_c` trace
1878 /// showed this block actually used `EIGHTTAP_SMOOTH`
1879 /// (`0 0 2 34 62 28 2 0` at xfrac=15, not REGULAR's `0 0 -2 8 126 -6 2
1880 /// 0`). Window and expected output dumped straight from an
1881 /// instrumented aomdec's `av1_convolve_2d_sr_c` on the pinned stream.
1882 #[test]
1883 fn smooth_filter_matches_aomdec_chroma_inter_block() {
1884 let fctx = &crate::decode::FrameCtx::new();
1885 #[rustfmt::skip]
1886 let window: [[u8; 24]; 24] = [
1887 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1888 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1889 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1890 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1891 [114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,117,117,117,116,115,115,114,114],
1892 [114,114,114,114,114,114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116,115,115,115],
1893 [114,114,114,114,114,114,114,114,114,114,115,115,115,115,116,116,116,116,116,116,115,115,115,115],
1894 [113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,116,116,116,116,115,115,115,115],
1895 [113,113,113,113,113,113,113,113,113,113,114,114,114,114,115,115,115,115,115,115,115,115,115,115],
1896 [112,112,112,112,112,112,112,112,112,113,113,113,113,114,114,114,114,114,115,115,115,115,115,115],
1897 [111,111,111,111,111,111,111,111,112,112,112,112,113,113,113,113,114,114,114,114,115,115,115,115],
1898 [110,110,110,110,110,110,110,110,111,111,111,111,112,112,112,113,113,113,113,113,114,114,114,115],
1899 [109,109,109,109,109,109,109,110,110,110,110,111,111,111,111,112,112,112,112,113,113,114,114,114],
1900 [108,108,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111,111,111,112,112,113,113,113],
1901 [108,108,108,108,108,108,108,108,108,108,109,109,109,110,110,110,110,110,111,111,112,112,112,112],
1902 [107,107,107,107,107,107,107,107,107,108,108,108,109,109,109,109,109,110,110,110,110,111,111,111],
1903 [106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,110,110,110],
1904 [106,106,106,106,106,106,106,106,106,107,107,107,107,108,108,108,108,109,109,109,109,109,109,109],
1905 [105,105,105,105,105,105,105,105,106,106,106,107,107,107,107,108,108,108,108,108,108,108,108,109],
1906 [104,104,104,104,104,104,104,104,104,105,105,106,106,106,107,107,107,107,107,107,107,108,108,108],
1907 [102,102,102,102,102,103,103,103,103,104,104,105,105,105,106,106,107,107,107,107,107,107,107,107],
1908 [101,101,101,101,101,101,101,102,102,103,103,104,104,104,105,105,106,106,106,106,106,107,107,107],
1909 [100,100,100,100,100,100,100,101,101,102,102,103,103,104,104,105,105,105,106,106,106,106,106,106],
1910 [99,99,99,99,99,99,100,100,100,101,101,102,103,103,104,104,105,105,105,105,105,105,105,106],
1911 ];
1912 // The dumped window spans real cols/rows -4..19; the block itself
1913 // starts at real (0, 0), so pad the reference plane so col/row 4 of
1914 // this buffer is real col/row 0, and hand `predict_with_filter` the
1915 // real (0, 0) coordinates -- clamping then reproduces the identical
1916 // extended border the dump already captured.
1917 let stride = 24;
1918 let mut reference = vec![0u16; stride * 24];
1919 for (r, row) in window.iter().enumerate() {
1920 for (c, &v) in row.iter().enumerate() {
1921 reference[r * stride + c] = u16::from(v);
1922 }
1923 }
1924 // predict()'s own edge clamp starts at true (0,0); shift so the
1925 // dumped window's row/col 4 lands there by biasing x_q4/y_q4's
1926 // whole-pel part by -4 and reading from a plane whose true origin
1927 // is the window's row/col 4 -- simplest is to pass true_width /
1928 // true_height covering the whole dumped window and offset the
1929 // whole-pel part of x_q4/y_q4 by +4 to land on real (0,0).
1930 let x_q4 = (4 + 0) * 16 + 15; // real block x0=0, xfrac=15
1931 let y_q4 = (4 + 0) * 16 + 7; // real block y0=0, yfrac=7
1932 let mut dst = vec![0u16; 16 * 16];
1933 predict_with_filter(
1934 &reference,
1935 stride,
1936 24,
1937 24,
1938 x_q4,
1939 y_q4,
1940 16,
1941 16,
1942 InterpFilterKind::Smooth,
1943 &mut dst, fctx,
1944 );
1945 #[rustfmt::skip]
1946 let expected_row0: [u16; 16] =
1947 [114,114,114,114,115,115,115,116,116,116,116,116,117,117,116,116];
1948 assert_eq!(
1949 &dst[0..16],
1950 &expected_row0,
1951 "row0 vs aomdec's real av1_convolve_2d_sr_c output"
1952 );
1953 #[rustfmt::skip]
1954 let expected_row15: [u16; 16] =
1955 [103,103,104,104,104,105,105,106,106,106,107,107,107,107,107,107];
1956 assert_eq!(
1957 &dst[15 * 16..15 * 16 + 16],
1958 &expected_row15,
1959 "row15 vs aomdec"
1960 );
1961 }
1962
1963 /// lane-gmaffine r5 root cause: a block 4 or fewer samples wide reads
1964 /// `Subpel_Filters[4]` -- the REGULAR narrow kernel -- for BOTH
1965 /// `EIGHTTAP` and `EIGHTTAP_SHARP` (spec 7.11.3.4's `filterIdx`, libaom
1966 /// `av1_interp_4tap[MULTITAP_SHARP] == av1_sub_pel_filters_4`,
1967 /// `filter.h:243`). We used the 8-tap sharp kernel there, which is
1968 /// invisible above 4 samples and so only ever bit the 4x4 chroma of an
1969 /// 8x8 (or smaller) luma leaf.
1970 #[test]
1971 fn a_narrow_block_reads_the_regular_four_tap_kernel_under_every_sharpness() {
1972 use crate::mc::{SUBPEL_FILTERS_4, SUBPEL_FILTERS_BILINEAR, SUBPEL_FILTERS_SMOOTH_4};
1973 for kind in [
1974 InterpFilterKind::Regular,
1975 InterpFilterKind::Smooth,
1976 InterpFilterKind::Sharp,
1977 InterpFilterKind::Bilinear,
1978 ] {
1979 let (wide, narrow) = kind.tables();
1980 let want: &[[i32; 8]; 16] = match kind {
1981 InterpFilterKind::Regular | InterpFilterKind::Sharp => &SUBPEL_FILTERS_4,
1982 InterpFilterKind::Smooth => &SUBPEL_FILTERS_SMOOTH_4,
1983 InterpFilterKind::Bilinear => &SUBPEL_FILTERS_BILINEAR,
1984 };
1985 assert_eq!(narrow, want, "{kind:?}: wrong narrow-block kernel");
1986 if kind == InterpFilterKind::Sharp {
1987 assert_ne!(wide, narrow, "sharp's wide kernel is not its narrow one");
1988 }
1989 }
1990 }
1991
1992 #[test]
1993 fn integer_mv_is_identity() {
1994 let fctx = &crate::decode::FrameCtx::new();
1995 let width = 12;
1996 let height = 12;
1997 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
1998 let mut dst = vec![0u16; 6 * 6];
1999 predict(
2000 &reference,
2001 width,
2002 width,
2003 height,
2004 3 * 16,
2005 4 * 16,
2006 6,
2007 6,
2008 &mut dst, fctx,
2009 );
2010 for row in 0..6 {
2011 for col in 0..6 {
2012 assert_eq!(
2013 dst[row * 6 + col],
2014 reference[(4 + row) * width + 3 + col],
2015 "integer MV must reproduce the reference block byte-for-byte"
2016 );
2017 }
2018 }
2019 }
2020
2021 #[test]
2022 fn half_pel_reproduces_the_ramp_midpoint() {
2023 let fctx = &crate::decode::FrameCtx::new();
2024 // Step 2 so every half-pel position lands on an exact integer.
2025 let width = 16;
2026 let height = 16;
2027 let reference: Vec<u16> = (0..width * height)
2028 .map(|i| (2 * (i % width)) as u16)
2029 .collect();
2030 let mut dst = vec![0u16; 4 * 4];
2031 // Half-pel in x only: fraction 8/16, integer part at column 5.
2032 predict(
2033 &reference,
2034 width,
2035 width,
2036 height,
2037 5 * 16 + 8,
2038 5 * 16,
2039 4,
2040 4,
2041 &mut dst, fctx,
2042 );
2043 for row in 0..4 {
2044 for col in 0..4 {
2045 let midpoint = 2 * (5 + col) + 1; // halfway between col and col+1
2046 assert_eq!(
2047 dst[row * 4 + col] as i32,
2048 midpoint as i32,
2049 "half-pel MV over a linear ramp must land exactly on the midpoint"
2050 );
2051 }
2052 }
2053 }
2054
2055 #[test]
2056 fn constant_plane_has_unit_dc_gain_at_every_subpel_position() {
2057 let fctx = &crate::decode::FrameCtx::new();
2058 let width = 20;
2059 let height = 20;
2060 let reference = vec![142u16; width * height];
2061 for yfrac in 0..16 {
2062 for xfrac in 0..16 {
2063 let mut dst = vec![0u16; 5 * 5];
2064 predict(
2065 &reference,
2066 width,
2067 width,
2068 height,
2069 5 * 16 + xfrac,
2070 5 * 16 + yfrac,
2071 5,
2072 5,
2073 &mut dst, fctx,
2074 );
2075 assert!(
2076 dst.iter().all(|&v| v == 142),
2077 "DC gain must be exactly 1 at fraction ({xfrac}, {yfrac}), got {dst:?}"
2078 );
2079 }
2080 }
2081 }
2082
2083 #[test]
2084 fn horizontal_and_vertical_only_filtering_differ() {
2085 let fctx = &crate::decode::FrameCtx::new();
2086 // A plane linear in both x and y with different, even coefficients so
2087 // each axis's half-pel interpolation lands on an exact integer: this
2088 // pins the actual value each pass produces, not just that the two
2089 // differ, so swapping which pass reads which axis is caught even if
2090 // it happened to produce two merely-different numbers.
2091 let width = 10;
2092 let height = 10;
2093 let reference: Vec<u16> = (0..height)
2094 .flat_map(|y| (0..width).map(move |x| (20 * x + 4 * y) as u16))
2095 .collect();
2096
2097 let mut horiz = vec![0u16; 4 * 4];
2098 predict(
2099 &reference,
2100 width,
2101 width,
2102 height,
2103 3 * 16 + 8,
2104 3 * 16,
2105 4,
2106 4,
2107 &mut horiz, fctx,
2108 );
2109 let mut vert = vec![0u16; 4 * 4];
2110 predict(
2111 &reference,
2112 width,
2113 width,
2114 height,
2115 3 * 16,
2116 3 * 16 + 8,
2117 4,
2118 4,
2119 &mut vert, fctx,
2120 );
2121
2122 for row in 0..4 {
2123 for col in 0..4 {
2124 // Horizontal half-pel: x interpolates to x0+col+0.5, y stays put.
2125 assert_eq!(
2126 horiz[row * 4 + col] as i32,
2127 20 * (3 + col as i32) + 10 + 4 * (3 + row as i32),
2128 "horizontal-only MV must interpolate along x only"
2129 );
2130 // Vertical half-pel: y interpolates to y0+row+0.5, x stays put.
2131 assert_eq!(
2132 vert[row * 4 + col] as i32,
2133 20 * (3 + col as i32) + 4 * (3 + row as i32) + 2,
2134 "vertical-only MV must interpolate along y only"
2135 );
2136 }
2137 }
2138 assert_ne!(
2139 horiz, vert,
2140 "horizontal-only and vertical-only sub-pel MVs must give different outputs"
2141 );
2142 }
2143
2144 #[test]
2145 fn mv_past_the_edge_clamps_instead_of_panicking() {
2146 let fctx = &crate::decode::FrameCtx::new();
2147 let width = 8;
2148 let height = 8;
2149 let reference: Vec<u16> = (0..width * height).map(|i| (i * 3 % 200) as u16).collect();
2150 let mut dst = vec![0u16; 4 * 4];
2151 // Whole-sample position far above and to the left of the plane, with
2152 // an odd fraction so both filter passes exercise the clamp.
2153 predict(
2154 &reference,
2155 width,
2156 width,
2157 height,
2158 -50 * 16 + 5,
2159 -50 * 16 + 5,
2160 4,
2161 4,
2162 &mut dst, fctx,
2163 );
2164 let expected = reference[0]; // the whole plane clamps to the top-left corner
2165 assert!(
2166 dst.iter().all(|&v| v == expected),
2167 "an MV past the top-left edge must clamp to the corner sample, got {dst:?}"
2168 );
2169
2170 let mut dst2 = vec![0u16; 4 * 4];
2171 predict(
2172 &reference,
2173 width,
2174 width,
2175 height,
2176 50 * 16 + 5,
2177 50 * 16 + 5,
2178 4,
2179 4,
2180 &mut dst2, fctx,
2181 );
2182 let expected2 = reference[height * width - 1]; // clamps to the bottom-right corner
2183 assert!(
2184 dst2.iter().all(|&v| v == expected2),
2185 "an MV past the bottom-right edge must clamp to the corner sample, got {dst2:?}"
2186 );
2187 }
2188
2189 #[test]
2190 fn predict_scaled_at_no_scale_matches_predict_with_filters() {
2191 let fctx = &crate::decode::FrameCtx::new();
2192 // Algebraic pin from the r8/r9 derivation: x_scale_fp == REF_NO_SCALE
2193 // must reduce predict_scaled's per-column scaled walk to the exact
2194 // same int_pel/filter_idx sequence predict_with_filters computes from
2195 // a fixed stride-1 walk -- every subpel fraction, every block width.
2196 let width = 24;
2197 let height = 24;
2198 let reference: Vec<u16> = (0..width * height).map(|i| (i * 7 % 251) as u16).collect();
2199 for block_w in [4usize, 8, 16] {
2200 for x_frac in 0..16i32 {
2201 let x_q4 = 3 * 16 + x_frac;
2202 let y_q4 = 2 * 16 + 5;
2203 let mut expected = vec![0u16; block_w * 8];
2204 predict_with_filters(
2205 &reference,
2206 width,
2207 width,
2208 height,
2209 x_q4,
2210 y_q4,
2211 block_w,
2212 8,
2213 InterpFilterKind::Regular,
2214 InterpFilterKind::Regular,
2215 &mut expected, fctx,
2216 );
2217 let mut got = vec![0u16; block_w * 8];
2218 predict_scaled(
2219 &reference,
2220 width,
2221 width,
2222 height,
2223 x_q4,
2224 y_q4,
2225 REF_NO_SCALE,
2226 block_w,
2227 8,
2228 InterpFilterKind::Regular,
2229 InterpFilterKind::Regular,
2230 &mut got, fctx,
2231 );
2232 assert_eq!(
2233 got, expected,
2234 "block_w={block_w} x_frac={x_frac}: REF_NO_SCALE must reproduce predict_with_filters exactly"
2235 );
2236 }
2237 }
2238 }
2239
2240 /// lane-perf5: every explicit-SIMD kernel is checked against the scalar
2241 /// reference it replaces, over the whole domain a decode can hand it --
2242 /// all block widths (4..=128), all 16 sub-pel phases, all four filter
2243 /// kinds with both their wide and narrow (4-tap) tables, and 8/10/12-bit
2244 /// sample ranges. The dispatch itself is exercised through
2245 /// [`super::hpass_contig`] (whatever this CPU selected).
2246 #[allow(unsafe_code)]
2247 #[test]
2248 fn simd_matches_scalar_horizontal_pass() {
2249 let mut state = 0x2545_f491_4f6c_dd1du64;
2250 let mut rng = move || {
2251 state ^= state << 13;
2252 state ^= state >> 7;
2253 state ^= state << 17;
2254 state
2255 };
2256 let kinds = [
2257 InterpFilterKind::Regular,
2258 InterpFilterKind::Smooth,
2259 InterpFilterKind::Sharp,
2260 InterpFilterKind::Bilinear,
2261 ];
2262 let mut checked = 0usize;
2263 for depth_max in [255u16, 1023, 4095] {
2264 for &kind in &kinds {
2265 let (wide, narrow) = kind.tables();
2266 for table in [wide, narrow] {
2267 for frac in 0..16usize {
2268 let taps = &table[frac];
2269 let t16 = [
2270 taps[0] as i16, taps[1] as i16, taps[2] as i16, taps[3] as i16,
2271 taps[4] as i16, taps[5] as i16, taps[6] as i16, taps[7] as i16,
2272 ];
2273 for w in [4usize, 8, 12, 16, 20, 32, 64, 128] {
2274 let src: Vec<u16> = (0..w + 7)
2275 .map(|_| (rng() % (u64::from(depth_max) + 1)) as u16)
2276 .collect();
2277 let mut want = vec![0i16; w];
2278 super::hpass_contig_scalar(&src, &t16, &mut want);
2279 let mut got = vec![0i16; w];
2280 super::hpass_contig(&src, &t16, &mut got);
2281 assert_eq!(got, want, "dispatch w={w} frac={frac} max={depth_max}");
2282 #[cfg(target_arch = "x86_64")]
2283 {
2284 let mut sse = vec![0i16; w];
2285 unsafe { super::simd::hpass_sse2(&src, 0, 1, sse.len(), &t16, &mut sse) };
2286 assert_eq!(sse, want, "sse w={w} frac={frac} max={depth_max}");
2287 if std::arch::is_x86_feature_detected!("avx2") {
2288 let mut avx = vec![0i16; w];
2289 unsafe { super::simd::hpass_avx2(&src, 0, 1, avx.len(), &t16, &mut avx) };
2290 assert_eq!(avx, want, "avx2 w={w} frac={frac} max={depth_max}");
2291 }
2292 }
2293 checked += 1;
2294 }
2295 }
2296 }
2297 }
2298 }
2299 assert_eq!(checked, 3 * 4 * 2 * 16 * 8);
2300 }
2301
2302 /// lane-mc: the intermediate the horizontal pass writes is `i16`, which
2303 /// is a claim about the FILTER TABLES, not about a sample: every kernel's
2304 /// positive taps sum to at most `S+` and its negative ones to `S-`, so a
2305 /// row's sum lies in `[max_sample * S-, max_sample * S+]` and the stored
2306 /// value is that over `1 << INTER_ROUND_0`. This enumerates all four
2307 /// filter kinds, both their wide and narrow tables and all 16 phases at
2308 /// the deepest sample this decoder accepts (10-bit; `stream.rs` refuses
2309 /// 12-bit by name) and pins the result inside `i16` -- so the SIMD
2310 /// stores' `packs_epi32` never saturates on a motion-compensation path.
2311 #[test]
2312 fn horizontal_intermediate_fits_i16() {
2313 let kinds = [
2314 InterpFilterKind::Regular,
2315 InterpFilterKind::Smooth,
2316 InterpFilterKind::Sharp,
2317 InterpFilterKind::Bilinear,
2318 ];
2319 let max_sample = 1023i32; // 10-bit
2320 let (mut worst_lo, mut worst_hi) = (0i32, 0i32);
2321 for &kind in &kinds {
2322 let (wide, narrow) = kind.tables();
2323 for table in [wide, narrow] {
2324 for taps in table {
2325 let pos: i32 = taps.iter().filter(|&&t| t > 0).sum();
2326 let neg: i32 = taps.iter().filter(|&&t| t < 0).sum();
2327 worst_hi = worst_hi.max(super::round2(max_sample * pos, super::INTER_ROUND_0));
2328 worst_lo = worst_lo.min(super::round2(max_sample * neg, super::INTER_ROUND_0));
2329 }
2330 }
2331 }
2332 assert!(
2333 worst_hi <= i32::from(i16::MAX) && worst_lo >= i32::from(i16::MIN),
2334 "the 10-bit intermediate range [{worst_lo}, {worst_hi}] must fit i16"
2335 );
2336 }
2337
2338 /// lane-perf5: the vertical pass's SIMD kernels against the scalar
2339 /// reference, over the same domain as
2340 /// [`simd_matches_scalar_horizontal_pass`] -- all widths, all phases,
2341 /// both wide and narrow (4-tap) tables of all four filter kinds, and
2342 /// intermediates spanning the 8/10/12-bit ranges the horizontal pass can
2343 /// produce (a 12-bit sample times the filter gain, both signs).
2344 #[allow(unsafe_code)]
2345 /// lane-mc2: with `xfrac == 0` the horizontal pass is the identity tap,
2346 /// so its intermediate is exactly `s << 4` and the vertical pass reads it
2347 /// with the taps scaled by 16. The fast path in
2348 /// [`predict_with_filters_kern`] skips the intermediate and reads the
2349 /// reference rows directly; this pins that it reproduces the two-pass
2350 /// form value-for-value at every vertical fraction and every block width
2351 /// (including the odd width the encoder's motion search prices).
2352 #[test]
2353 fn whole_pel_horizontal_matches_the_two_pass_form() {
2354 let fctx = &crate::decode::FrameCtx::new();
2355 let width = 160usize;
2356 let height = 48usize;
2357 let mut state = 0x2545_f491_4f6c_dd1du64;
2358 let mut rng = move || {
2359 state ^= state << 13;
2360 state ^= state >> 7;
2361 state ^= state << 17;
2362 state
2363 };
2364 let reference: Vec<u16> = (0..width * height).map(|_| (rng() % 256) as u16).collect();
2365 let mut checked = 0usize;
2366 for &kind in &[InterpFilterKind::Regular, InterpFilterKind::Smooth, InterpFilterKind::Sharp] {
2367 let (v_wide, v_narrow) = kind.tables();
2368 for (bw, bh) in [(4usize, 4usize), (5, 4), (8, 8), (16, 16), (12, 8), (32, 16)] {
2369 for yfrac in 1..16i32 {
2370 let (x0, y0) = (7i32, 9i32);
2371 let taps = if bh <= 4 { &v_narrow[yfrac as usize] } else { &v_wide[yfrac as usize] };
2372 let mut want = vec![0u16; bw * bh];
2373 for row in 0..bh {
2374 for col in 0..bw {
2375 let mut sum = 0i32;
2376 for (t, &tap) in taps.iter().enumerate() {
2377 let y = y0 - 3 + row as i32 + t as i32;
2378 let s = i32::from(reference[y as usize * width + x0 as usize + col]);
2379 // The identity horizontal tap's output.
2380 sum += tap * (s << 4);
2381 }
2382 want[row * bw + col] = super::round2(sum, super::INTER_ROUND_1).clamp(0, 255) as u16;
2383 }
2384 }
2385 let mut got = vec![0u16; bw * bh];
2386 super::predict_with_filters_kern(
2387 &reference, width, width, height, x0 * 16, y0 * 16 + yfrac,
2388 bw, bh, bw, bh, kind, kind, &mut got, fctx,
2389 );
2390 assert_eq!(got, want, "kind={kind:?} bw={bw} bh={bh} yfrac={yfrac}");
2391 checked += 1;
2392 }
2393 }
2394 }
2395 assert_eq!(checked, 3 * 6 * 15);
2396 }
2397
2398 #[allow(unsafe_code)]
2399 #[test]
2400 fn simd_matches_scalar_vertical_pass() {
2401 let mut state = 0x9e37_79b9_7f4a_7c15u64;
2402 let mut rng = move || {
2403 state ^= state << 13;
2404 state ^= state >> 7;
2405 state ^= state << 17;
2406 state
2407 };
2408 let kinds = [
2409 InterpFilterKind::Regular,
2410 InterpFilterKind::Smooth,
2411 InterpFilterKind::Sharp,
2412 InterpFilterKind::Bilinear,
2413 ];
2414 let mut checked = 0usize;
2415 // The horizontal pass's own range at 8- and 10-bit (12-bit is
2416 // refused in stream.rs), plus the saturating store's extreme.
2417 for span in [255i32 * 16, 1023 * 20, 32767] {
2418 for &kind in &kinds {
2419 let (wide, narrow) = kind.tables();
2420 for table in [wide, narrow] {
2421 for frac in 0..16usize {
2422 let taps = &table[frac];
2423 for w in [4usize, 5, 8, 12, 16, 20, 32, 64, 128] {
2424 let rows = 12usize;
2425 // lane-mc2: `st != w` is the fused whole-pel
2426 // horizontal path, which runs these kernels
2427 // straight over a reference plane's stride.
2428 for st in [w, w + 3] {
2429 let inter: Vec<i16> = (0..rows * st)
2430 .map(|_| ((rng() % (2 * span as u64 + 1)) as i32 - span) as i16)
2431 .collect();
2432 for row in [0usize, 1, 4] {
2433 let mut want = vec![0i32; w];
2434 super::vpass_row_scalar(&inter[row * st..], w, st, 0, taps, &mut want);
2435 let mut got = vec![0i32; w];
2436 super::vpass_row(&inter[row * st..], w, st, 1, taps, &mut got);
2437 assert_eq!(got, want, "dispatch w={w} frac={frac} row={row}");
2438 #[cfg(target_arch = "x86_64")]
2439 {
2440 if std::arch::is_x86_feature_detected!("sse4.1") {
2441 let mut sse = vec![0i32; w];
2442 unsafe { super::simd::vpass_sse41(&inter[row * st..], w, st, 1, taps, &mut sse) };
2443 assert_eq!(sse, want, "sse4.1 w={w} frac={frac} row={row}");
2444 }
2445 if std::arch::is_x86_feature_detected!("avx2") {
2446 let mut avx = vec![0i32; w];
2447 unsafe { super::simd::vpass_avx2(&inter[row * st..], w, st, 1, taps, &mut avx) };
2448 assert_eq!(avx, want, "avx2 w={w} frac={frac} row={row}");
2449 }
2450 }
2451 // lane-mc: the rounding-fused form, over both
2452 // sample maxima this decoder accepts -- its
2453 // `packus`/`min_epu16` pair must reproduce
2454 // `round2(_, InterRound1).clamp(0, max)`.
2455 for max in [255i32, 1023] {
2456 let mut want_u16 = vec![0u16; w];
2457 super::vpass_row_u16_scalar(&inter, w, st, row, taps, max, &mut want_u16);
2458 for (d, &a) in want_u16.iter().zip(want.iter()) {
2459 assert_eq!(
2460 i32::from(*d),
2461 super::round2(a, super::INTER_ROUND_1).clamp(0, max),
2462 "the fused reference is the two-step one"
2463 );
2464 }
2465 let mut got_u16 = vec![0u16; w];
2466 super::vpass_row_u16(&inter[row * st..], w, st, 1, taps, max, &mut got_u16);
2467 assert_eq!(got_u16, want_u16, "fused w={w} frac={frac} row={row} max={max}");
2468 #[cfg(target_arch = "x86_64")]
2469 {
2470 if std::arch::is_x86_feature_detected!("sse4.1") {
2471 let mut sse = vec![0u16; w];
2472 unsafe { super::simd::vpass_row_u16_sse41(&inter[row * st..], w, st, 1, taps, max, &mut sse) };
2473 assert_eq!(sse, want_u16, "fused sse4.1 w={w} max={max}");
2474 }
2475 if std::arch::is_x86_feature_detected!("avx2") {
2476 let mut avx = vec![0u16; w];
2477 unsafe { super::simd::vpass_row_u16_avx2(&inter[row * st..], w, st, 1, taps, max, &mut avx) };
2478 assert_eq!(avx, want_u16, "fused avx2 w={w} max={max}");
2479 }
2480 }
2481 }
2482 checked += 1;
2483 }
2484 }
2485 }
2486 }
2487 }
2488 }
2489 }
2490 assert_eq!(checked, 3 * 4 * 2 * 16 * 9 * 3 * 2);
2491 }
2492}