forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

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