forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

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