forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mc.rs1001 lines, 33.7 KiBHistoryRawDownload
1//! Motion compensation: the decoder's inter predictor (`dec_build_inter_predictors`,
2//! libvpx `vp9/decoder/vp9_decodeframe.c:593`), the on-the-fly reference border
3//! extension (`build_mc_border`, :473), the UMV-border MV clamp
4//! (`clamp_mv_to_umv_border_sb`, `vp9/common/vp9_reconinter.c:88`), the
5//! switchable filter kernels (`vp9/common/vp9_filter.c`) and the sub-pixel
6//! convolve (`vpx_dsp/vpx_convolve.c`).
7//!
8//! The VP9 decoder does NOT extend the reference frame's borders in place: it
9//! builds a bordered copy of the block's reference window per prediction
10//! (`extend_and_predict`) whenever the window leaves the frame or the frame's
11//! dimensions are not a multiple of 8. A reference slot whose size differs
12//! from the current frame is SCALED: [`ScaleFactors`] carries
13//! `vp9_setup_scale_factors_for_frame`, the block/MV are mapped into the
14//! reference with `vp9_scale_mv`, and the convolve steps by `x_step_q4` /
15//! `y_step_q4` (`sf->predict`, `vpx_scaled_*`).
16//!
17//! Indexing note: libvpx's convolve helpers take a raw pointer and subtract
18//! `SUBPEL_TAPS / 2 - 1` from it, so they read taps *before* the block's first
19//! sample. Rust slices cannot go negative, so every helper here takes a buffer
20//! plus an `origin` (the block's first sample) and indexes with `isize`.
21
22/// `SUBPEL_BITS` / `SUBPEL_MASK` / `SUBPEL_SHIFTS` / `SUBPEL_TAPS`
23/// (`vpx_dsp/vpx_filter.h:23-26`).
24const SUBPEL_BITS: i32 = 4;
25const SUBPEL_MASK: i32 = (1 << SUBPEL_BITS) - 1;
26const SUBPEL_SHIFTS: i32 = 1 << SUBPEL_BITS;
27const TAPS: usize = 8;
28/// `FILTER_BITS` (`vpx_dsp/vpx_filter.h:21`).
29const FILTER_BITS: i32 = 7;
30/// `VP9_INTERP_EXTEND` (`vpx_scale/yv12config.h:25`).
31const INTERP_EXTEND: i32 = 4;
32
33/// `REF_SCALE_SHIFT` / `REF_NO_SCALE` / `REF_INVALID_SCALE`
34/// (`vp9/common/vp9_scale.h:21-23`): the fixed-point precision of a reference
35/// frame's scale factor.
36const REF_SCALE_SHIFT: i32 = 14;
37const REF_NO_SCALE: i32 = 1 << REF_SCALE_SHIFT;
38const REF_INVALID_SCALE: i32 = -1;
39
40/// `scaled_x` / `scaled_y` (`vp9_scale.c:22`).
41fn scale_value(val: i32, scale_fp: i32) -> i32 {
42 (((val as i64) * scale_fp as i64) >> REF_SCALE_SHIFT) as i32
43}
44
45/// `struct scale_factors` (`vp9/common/vp9_scale.h:27`) set up by
46/// `vp9_setup_scale_factors_for_frame` (`vp9_scale.c:44`): the scale from a
47/// reference frame's coded size to this frame's, its derived 1/16-pel step
48/// (`x_step_q4`/`y_step_q4`; 16 means "no scaling on that axis") and
49/// `vp9_scale_mv`.
50#[derive(Clone, Copy)]
51pub(crate) struct ScaleFactors {
52 x_scale_fp: i32,
53 y_scale_fp: i32,
54 x_step_q4: i32,
55 y_step_q4: i32,
56}
57
58impl ScaleFactors {
59 /// `vp9_setup_scale_factors_for_frame(other_w, other_h, this_w, this_h)`:
60 /// `other_*` is the REFERENCE's coded size, `this_*` the frame being
61 /// decoded. An out-of-range ratio leaves `REF_INVALID_SCALE`, which
62 /// libvpx turns into `Reference frame has invalid dimensions` when the
63 /// reference is actually predicted from.
64 pub(crate) fn setup(other_w: usize, other_h: usize, this_w: usize, this_h: usize) -> Self {
65 // `valid_ref_frame_size` (`vp9_scale.h:61`): at most 2x down, 16x up.
66 let valid = 2 * this_w >= other_w
67 && 2 * this_h >= other_h
68 && this_w <= 16 * other_w
69 && this_h <= 16 * other_h;
70 if !valid {
71 return ScaleFactors {
72 x_scale_fp: REF_INVALID_SCALE,
73 y_scale_fp: REF_INVALID_SCALE,
74 x_step_q4: 0,
75 y_step_q4: 0,
76 };
77 }
78 let x_scale_fp = (((other_w as i64) << REF_SCALE_SHIFT) / this_w as i64) as i32;
79 let y_scale_fp = (((other_h as i64) << REF_SCALE_SHIFT) / this_h as i64) as i32;
80 ScaleFactors {
81 x_scale_fp,
82 y_scale_fp,
83 x_step_q4: scale_value(SUBPEL_SHIFTS, x_scale_fp),
84 y_step_q4: scale_value(SUBPEL_SHIFTS, y_scale_fp),
85 }
86 }
87
88 /// `vp9_is_valid_scale`.
89 pub(crate) fn is_valid(&self) -> bool {
90 self.x_scale_fp != REF_INVALID_SCALE && self.y_scale_fp != REF_INVALID_SCALE
91 }
92
93 /// `vp9_is_scaled`.
94 pub(crate) fn is_scaled(&self) -> bool {
95 self.is_valid() && (self.x_scale_fp != REF_NO_SCALE || self.y_scale_fp != REF_NO_SCALE)
96 }
97
98 fn scale_x(&self, val: i32) -> i32 {
99 scale_value(val, self.x_scale_fp)
100 }
101
102 fn scale_y(&self, val: i32) -> i32 {
103 scale_value(val, self.y_scale_fp)
104 }
105
106 /// `vp9_scale_mv` (`vp9_scale.c:29`): the block MV scaled to the
107 /// reference's resolution plus the sub-pixel offset of the block's own
108 /// scaled position. Returns `(row, col)` in 1/16-pel units.
109 ///
110 /// `x`/`y` are the block's coordinates in the CURRENT frame (libvpx
111 /// passes `mi_x + x`, `mi_y + y` — luma units even for chroma planes; the
112 /// sub-8x8 chroma offsets are always 0, so the mismatch never bites).
113 pub(crate) fn scale_mv(&self, mv: (i32, i32), x: i32, y: i32) -> (i32, i32) {
114 let x_off_q4 = self.scale_x(x << SUBPEL_BITS) & SUBPEL_MASK;
115 let y_off_q4 = self.scale_y(y << SUBPEL_BITS) & SUBPEL_MASK;
116 (self.scale_y(mv.0) + y_off_q4, self.scale_x(mv.1) + x_off_q4)
117 }
118}
119
120/// `vp9_filter_kernels` (`vp9/common/vp9_filter.c:79`), in libvpx's filter
121/// numbering: 0 `EIGHTTAP`, 1 `EIGHTTAP_SMOOTH`, 2 `EIGHTTAP_SHARP`,
122/// 3 `BILINEAR` (the 4-tap index 4 is unreachable for profile 0).
123pub(crate) const FILTERS: [[[i16; TAPS]; SUBPEL_SHIFTS as usize]; 4] = [
124 // sub_pel_filters_8: Lagrangian interpolation filter.
125 [
126 [0, 0, 0, 128, 0, 0, 0, 0],
127 [0, 1, -5, 126, 8, -3, 1, 0],
128 [-1, 3, -10, 122, 18, -6, 2, 0],
129 [-1, 4, -13, 118, 27, -9, 3, -1],
130 [-1, 4, -16, 112, 37, -11, 4, -1],
131 [-1, 5, -18, 105, 48, -14, 4, -1],
132 [-1, 5, -19, 97, 58, -16, 5, -1],
133 [-1, 6, -19, 88, 68, -18, 5, -1],
134 [-1, 6, -19, 78, 78, -19, 6, -1],
135 [-1, 5, -18, 68, 88, -19, 6, -1],
136 [-1, 5, -16, 58, 97, -19, 5, -1],
137 [-1, 4, -14, 48, 105, -18, 5, -1],
138 [-1, 4, -11, 37, 112, -16, 4, -1],
139 [-1, 3, -9, 27, 118, -13, 4, -1],
140 [0, 2, -6, 18, 122, -10, 3, -1],
141 [0, 1, -3, 8, 126, -5, 1, 0],
142 ],
143 // sub_pel_filters_8lp: freqmultiplier = 0.5 (EIGHTTAP_SMOOTH).
144 [
145 [0, 0, 0, 128, 0, 0, 0, 0],
146 [-3, -1, 32, 64, 38, 1, -3, 0],
147 [-2, -2, 29, 63, 41, 2, -3, 0],
148 [-2, -2, 26, 63, 43, 4, -4, 0],
149 [-2, -3, 24, 62, 46, 5, -4, 0],
150 [-2, -3, 21, 60, 49, 7, -4, 0],
151 [-1, -4, 18, 59, 51, 9, -4, 0],
152 [-1, -4, 16, 57, 53, 12, -4, -1],
153 [-1, -4, 14, 55, 55, 14, -4, -1],
154 [-1, -4, 12, 53, 57, 16, -4, -1],
155 [0, -4, 9, 51, 59, 18, -4, -1],
156 [0, -4, 7, 49, 60, 21, -3, -2],
157 [0, -4, 5, 46, 62, 24, -3, -2],
158 [0, -4, 4, 43, 63, 26, -2, -2],
159 [0, -3, 2, 41, 63, 29, -2, -2],
160 [0, -3, 1, 38, 64, 32, -1, -3],
161 ],
162 // sub_pel_filters_8s: DCT based filter (EIGHTTAP_SHARP).
163 [
164 [0, 0, 0, 128, 0, 0, 0, 0],
165 [-1, 3, -7, 127, 8, -3, 1, 0],
166 [-2, 5, -13, 125, 17, -6, 3, -1],
167 [-3, 7, -17, 121, 27, -10, 5, -2],
168 [-4, 9, -20, 115, 37, -13, 6, -2],
169 [-4, 10, -23, 108, 48, -16, 8, -3],
170 [-4, 10, -24, 100, 59, -19, 9, -3],
171 [-4, 11, -24, 90, 70, -21, 10, -4],
172 [-4, 11, -23, 80, 80, -23, 11, -4],
173 [-4, 10, -21, 70, 90, -24, 11, -4],
174 [-3, 9, -19, 59, 100, -24, 10, -4],
175 [-3, 8, -16, 48, 108, -23, 10, -4],
176 [-2, 6, -13, 37, 115, -20, 9, -4],
177 [-2, 5, -10, 27, 121, -17, 7, -3],
178 [-1, 3, -6, 17, 125, -13, 5, -2],
179 [0, 1, -3, 8, 127, -7, 3, -1],
180 ],
181 // bilinear_filters.
182 [
183 [0, 0, 0, 128, 0, 0, 0, 0],
184 [0, 0, 0, 120, 8, 0, 0, 0],
185 [0, 0, 0, 112, 16, 0, 0, 0],
186 [0, 0, 0, 104, 24, 0, 0, 0],
187 [0, 0, 0, 96, 32, 0, 0, 0],
188 [0, 0, 0, 88, 40, 0, 0, 0],
189 [0, 0, 0, 80, 48, 0, 0, 0],
190 [0, 0, 0, 72, 56, 0, 0, 0],
191 [0, 0, 0, 64, 64, 0, 0, 0],
192 [0, 0, 0, 56, 72, 0, 0, 0],
193 [0, 0, 0, 48, 80, 0, 0, 0],
194 [0, 0, 0, 40, 88, 0, 0, 0],
195 [0, 0, 0, 32, 96, 0, 0, 0],
196 [0, 0, 0, 24, 104, 0, 0, 0],
197 [0, 0, 0, 16, 112, 0, 0, 0],
198 [0, 0, 0, 8, 120, 0, 0, 0],
199 ],
200];
201
202use crate::{Sample, clip_pixel_bd, round_pow2};
203
204/// Read `buf[i]` for a possibly negative `i`. Every caller keeps `i` inside
205/// the buffer (the border copy guarantees the tap margins exist).
206#[inline]
207fn at(buf: &[Sample], i: isize) -> Sample {
208 buf[i as usize]
209}
210
211/// `clamp_mv_to_umv_border_sb` (`vp9/common/vp9_reconinter.c:88`), returning
212/// the MV in 1/16-pel (`MV_PRECISION_Q4`) units.
213///
214/// `mb_*` are the block's distances to the frame edges in 1/8-pel units
215/// (`xd->mb_to_*_edge`, i.e. `±mi * 64`); `bw`/`bh` are the PLANE block's
216/// pixel dimensions. `clamp_mv(mv, min_col, max_col, min_row, max_row)`:
217/// columns are bounded by the left/right edges, rows by the top/bottom.
218pub(crate) fn clamp_mv_to_umv_border_sb(
219 mv: (i32, i32),
220 bw: i32,
221 bh: i32,
222 mb_left: i32,
223 mb_right: i32,
224 mb_top: i32,
225 mb_bottom: i32,
226 ss_x: usize,
227 ss_y: usize,
228) -> (i32, i32) {
229 let spel_left = (INTERP_EXTEND + bw) << SUBPEL_BITS;
230 let spel_right = spel_left - SUBPEL_SHIFTS;
231 let spel_top = (INTERP_EXTEND + bh) << SUBPEL_BITS;
232 let spel_bottom = spel_top - SUBPEL_SHIFTS;
233 let xs = 1 << (1 - ss_x);
234 let ys = 1 << (1 - ss_y);
235 let col = (mv.1 * xs).clamp(mb_left * xs - spel_left, mb_right * xs + spel_right);
236 let row = (mv.0 * ys).clamp(mb_top * ys - spel_top, mb_bottom * ys + spel_bottom);
237 (row, col)
238}
239
240/// `build_mc_border` (`vp9/decoder/vp9_decodeframe.c:473`): copy the
241/// `b_w` x `b_h` window whose top-left is frame pixel `(x, y)` into `dst`,
242/// replicating the frame's first/last row and column for reads outside
243/// `[0, w)` x `[0, h)`.
244#[allow(clippy::too_many_arguments)]
245fn build_mc_border(
246 src: &[Sample],
247 src_stride: usize,
248 dst: &mut [Sample],
249 dst_stride: usize,
250 x: i32,
251 mut y: i32,
252 b_w: usize,
253 mut b_h: usize,
254 w: i32,
255 h: i32,
256) {
257 // C computes `ref_row = src - x - y * src_stride`; for negative y the
258 // pointer arithmetic leaves the buffer and the row-index equivalent below
259 // is the same read.
260 let mut row = if y >= h {
261 (h - 1) as usize
262 } else if y > 0 {
263 y as usize
264 } else {
265 0
266 };
267 let mut out = 0usize;
268 loop {
269 let left = if x < 0 { (-x).min(b_w as i32) } else { 0 } as usize;
270 let right = if x + b_w as i32 > w {
271 (x + b_w as i32 - w).min(b_w as i32)
272 } else {
273 0
274 } as usize;
275 let copy = b_w - left - right;
276
277 let base = row * src_stride;
278 if left > 0 {
279 let v = src[base];
280 dst[out..out + left].fill(v);
281 }
282 if copy > 0 {
283 let from = (x + left as i32) as usize;
284 dst[out + left..out + left + copy]
285 .copy_from_slice(&src[base + from..base + from + copy]);
286 }
287 if right > 0 {
288 let v = src[base + (w - 1) as usize];
289 dst[out + left + copy..out + left + copy + right].fill(v);
290 }
291
292 out += dst_stride;
293 y += 1;
294 if y > 0 && y < h {
295 row += 1;
296 }
297 b_h -= 1;
298 if b_h == 0 {
299 break;
300 }
301 }
302}
303
304/// Largest block width or height the convolve kernels see (a 64-sample superblock).
305const MAX_W: usize = 64;
306
307/// Store one row of 8-tap sums: round, clip to `bd`, and average into `dst` when `avg`.
308#[inline]
309fn store_row(dst: &mut [Sample], acc: &[i32], avg: bool, maxv: i32) {
310 if avg {
311 for (d, &a) in dst.iter_mut().zip(acc) {
312 let v = ((a + 64) >> FILTER_BITS).clamp(0, maxv);
313 *d = ((*d as i32 + v + 1) >> 1) as Sample;
314 }
315 } else {
316 for (d, &a) in dst.iter_mut().zip(acc) {
317 *d = ((a + 64) >> FILTER_BITS).clamp(0, maxv) as Sample;
318 }
319 }
320}
321
322/// Unscaled horizontal 8-tap pass: `convolve_horiz` with `x_step == SUBPEL_SHIFTS`
323/// and one filter for the whole row. Written as one contiguous pass per tap so the
324/// compiler vectorises the inner loop; the sums equal the per-sample form exactly.
325// Same arguments as `convolve_horiz`, which callers already pass; a struct would be copied per call.
326#[allow(clippy::too_many_arguments)]
327fn conv_h_unscaled(
328 buf: &[Sample],
329 stride: usize,
330 origin: isize,
331 dst: &mut [Sample],
332 dst_stride: usize,
333 filt: &[i16; TAPS],
334 w: usize,
335 rows: usize,
336 avg: bool,
337 bd: u8,
338) {
339 let taps: [i32; TAPS] = filt.map(i32::from);
340 let maxv = (1i32 << bd) - 1;
341 let mut acc = [0i32; MAX_W];
342 let acc = &mut acc[..w];
343 for y in 0..rows {
344 // Output x reads samples x-3 ..= x+4 of this row.
345 let start = (origin + (y * stride) as isize - (TAPS as isize / 2 - 1)) as usize;
346 let src = &buf[start..start + w + TAPS - 1];
347 acc.fill(0);
348 for (k, &t) in taps.iter().enumerate() {
349 for (a, &s) in acc.iter_mut().zip(&src[k..k + w]) {
350 *a += s as i16 as i32 * t;
351 }
352 }
353 store_row(&mut dst[y * dst_stride..y * dst_stride + w], acc, avg, maxv);
354 }
355}
356
357/// Unscaled vertical 8-tap pass: `convolve_vert` with `y_step == SUBPEL_SHIFTS` and
358/// one filter for the whole block. Same sums as the per-sample form.
359// Same arguments as `convolve_vert`, which callers already pass; a struct would be copied per call.
360#[allow(clippy::too_many_arguments)]
361fn conv_v_unscaled(
362 buf: &[Sample],
363 stride: usize,
364 origin: isize,
365 dst: &mut [Sample],
366 dst_stride: usize,
367 filt: &[i16; TAPS],
368 w: usize,
369 h: usize,
370 avg: bool,
371 bd: u8,
372) {
373 let taps: [i32; TAPS] = filt.map(i32::from);
374 let maxv = (1i32 << bd) - 1;
375 let mut acc = [0i32; MAX_W];
376 let acc = &mut acc[..w];
377 for y in 0..h {
378 acc.fill(0);
379 for (k, &t) in taps.iter().enumerate() {
380 // Output row y reads rows y-3 ..= y+4 around the block origin.
381 let start = (origin + ((y + k) as isize - (TAPS as isize / 2 - 1)) * stride as isize) as usize;
382 for (a, &s) in acc.iter_mut().zip(&buf[start..start + w]) {
383 *a += s as i16 as i32 * t;
384 }
385 }
386 store_row(&mut dst[y * dst_stride..y * dst_stride + w], acc, avg, maxv);
387 }
388}
389
390/// `convolve_horiz` / `convolve_avg_horiz` (`vpx_dsp/vpx_convolve.c:22`).
391/// `origin` is the block's first sample in `buf`; taps are read from
392/// `origin + y*stride + (x_q4 >> SUBPEL_BITS) - (SUBPEL_TAPS / 2 - 1) + k`.
393/// `x_step` advances `x_q4` per output sample — `SUBPEL_SHIFTS` for an
394/// unscaled reference, `sf->x_step_q4` (the scaled sampler, also used by
395/// `vpx_scaled_horiz`) otherwise.
396#[allow(clippy::too_many_arguments)]
397fn convolve_horiz(
398 buf: &[Sample],
399 stride: usize,
400 origin: isize,
401 dst: &mut [Sample],
402 dst_stride: usize,
403 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
404 x0_q4: i32,
405 x_step: i32,
406 w: usize,
407 rows: usize,
408 avg: bool,
409 bd: u8,
410) {
411 if x_step == SUBPEL_SHIFTS && (0..SUBPEL_SHIFTS).contains(&x0_q4) {
412 // Unscaled: the filter is the same for every output sample.
413 let filt = &f[x0_q4 as usize];
414 conv_h_unscaled(buf, stride, origin, dst, dst_stride, filt, w, rows, avg, bd);
415 return;
416 }
417 for y in 0..rows {
418 let mut x_q4 = x0_q4;
419 for x in 0..w {
420 let base = origin + y as isize * stride as isize + (x_q4 >> SUBPEL_BITS) as isize
421 - (TAPS as isize / 2 - 1);
422 let filt = &f[(x_q4 & SUBPEL_MASK) as usize];
423 let mut sum = 0i32;
424 for k in 0..TAPS {
425 sum += at(buf, base + k as isize) as i32 * filt[k] as i32;
426 }
427 let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32;
428 let d = y * dst_stride + x;
429 dst[d] = if avg {
430 round_pow2(dst[d] as i32 + v, 1) as Sample
431 } else {
432 v as Sample
433 };
434 x_q4 += x_step;
435 }
436 }
437}
438
439/// `convolve_vert` / `convolve_avg_vert` (`vpx_dsp/vpx_convolve.c:80`).
440/// `y_step` advances `y_q4` per output sample (`SUBPEL_SHIFTS` unscaled,
441/// `sf->y_step_q4` for `vpx_scaled_vert`).
442#[allow(clippy::too_many_arguments)]
443fn convolve_vert(
444 buf: &[Sample],
445 stride: usize,
446 origin: isize,
447 dst: &mut [Sample],
448 dst_stride: usize,
449 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
450 y0_q4: i32,
451 y_step: i32,
452 w: usize,
453 h: usize,
454 avg: bool,
455 bd: u8,
456) {
457 if y_step == SUBPEL_SHIFTS && (0..SUBPEL_SHIFTS).contains(&y0_q4) {
458 // Unscaled: the filter is the same for every output row.
459 let filt = &f[y0_q4 as usize];
460 conv_v_unscaled(buf, stride, origin, dst, dst_stride, filt, w, h, avg, bd);
461 return;
462 }
463 for x in 0..w {
464 let mut y_q4 = y0_q4;
465 for y in 0..h {
466 let base = origin
467 + ((y_q4 >> SUBPEL_BITS) as isize - (TAPS as isize / 2 - 1)) * stride as isize
468 + x as isize;
469 let filt = &f[(y_q4 & SUBPEL_MASK) as usize];
470 let mut sum = 0i32;
471 for k in 0..TAPS {
472 sum += at(buf, base + k as isize * stride as isize) as i32 * filt[k] as i32;
473 }
474 let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32;
475 let d = y * dst_stride + x;
476 dst[d] = if avg {
477 round_pow2(dst[d] as i32 + v, 1) as Sample
478 } else {
479 v as Sample
480 };
481 y_q4 += y_step;
482 }
483 }
484}
485
486/// `inter_predictor` + `sf->predict` (`vp9/common/vp9_reconinter.h:23`,
487/// `vp9/common/vp9_scale.c:79`): the kernel is picked by
488/// `predict[subpel_x != 0][subpel_y != 0][avg]`. Unscaled that is
489/// copy/avg, the vertical, the horizontal and the 2D convolve; with a scaled
490/// reference the table collapses to the scaled variants (`vpx_scaled_horiz` /
491/// `vpx_scaled_vert` — the same walk with `x_step_q4` / `y_step_q4` — and
492/// `vpx_scaled_2d`), reproduced here by the step-aware convolve helpers.
493///
494/// `w` x `h` output samples written at `dst`; `buf`/`origin` locate the
495/// block's first reference sample. `temp` is the `vpx_convolve8` intermediate
496/// (stride-64 scratch of `64 * 135` bytes plus a `64 * 64` second scratch for
497/// the averaging variant).
498#[allow(clippy::too_many_arguments)]
499fn inter_predictor(
500 buf: &[Sample],
501 stride: usize,
502 origin: isize,
503 dst: &mut [Sample],
504 dst_stride: usize,
505 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
506 subpel_x: i32,
507 subpel_y: i32,
508 x_step: i32,
509 y_step: i32,
510 w: usize,
511 h: usize,
512 avg: bool,
513 temp: &mut [Sample],
514 bd: u8,
515) {
516 let scaled_x = x_step != SUBPEL_SHIFTS;
517 let scaled_y = y_step != SUBPEL_SHIFTS;
518 if scaled_x || scaled_y {
519 // sf->predict with a scaled axis (vp9_scale.c:79-110): an unscaled
520 // axis keeps its 1D kernel only when the other axis has no subpel
521 // offset; anything else is the 2D scaled convolve.
522 if !scaled_x && subpel_x == 0 {
523 convolve_vert(
524 buf, stride, origin, dst, dst_stride, f, subpel_y, y_step, w, h, avg, bd,
525 );
526 return;
527 }
528 if !scaled_y && subpel_y == 0 {
529 convolve_horiz(
530 buf, stride, origin, dst, dst_stride, f, subpel_x, x_step, w, h, avg, bd,
531 );
532 return;
533 }
534 convolve_2d(
535 buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg,
536 temp, bd,
537 );
538 return;
539 }
540 if subpel_x == 0 && subpel_y == 0 {
541 for y in 0..h {
542 for x in 0..w {
543 let s = at(buf, origin + (y * stride + x) as isize) as i32;
544 let d = y * dst_stride + x;
545 dst[d] = if avg {
546 round_pow2(dst[d] as i32 + s, 1) as Sample
547 } else {
548 s as Sample
549 };
550 }
551 }
552 return;
553 }
554 if subpel_y == 0 {
555 convolve_horiz(
556 buf,
557 stride,
558 origin,
559 dst,
560 dst_stride,
561 f,
562 subpel_x,
563 SUBPEL_SHIFTS,
564 w,
565 h,
566 avg,
567 bd,
568 );
569 return;
570 }
571 if subpel_x == 0 {
572 convolve_vert(
573 buf,
574 stride,
575 origin,
576 dst,
577 dst_stride,
578 f,
579 subpel_y,
580 SUBPEL_SHIFTS,
581 w,
582 h,
583 avg,
584 bd,
585 );
586 return;
587 }
588 convolve_2d(
589 buf, stride, origin, dst, dst_stride, f, subpel_x, subpel_y, x_step, y_step, w, h, avg,
590 temp, bd,
591 );
592}
593
594/// `vpx_convolve8_c` / `vpx_convolve8_avg_c` (`vpx_dsp/vpx_convolve.c:158`) =
595/// `vpx_scaled_2d` / `vpx_scaled_avg_2d`: horizontal pass into a stride-64
596/// intermediate with `intermediate_height = (((h - 1) * y_step_q4 + y0_q4) >>
597/// SUBPEL_BITS) + SUBPEL_TAPS`, then the vertical pass. The horizontal pass
598/// starts `SUBPEL_TAPS / 2 - 1` rows ABOVE the block (C passes
599/// `src - src_stride * (SUBPEL_TAPS / 2 - 1)`).
600#[allow(clippy::too_many_arguments)]
601fn convolve_2d(
602 buf: &[Sample],
603 stride: usize,
604 origin: isize,
605 dst: &mut [Sample],
606 dst_stride: usize,
607 f: &[[i16; TAPS]; SUBPEL_SHIFTS as usize],
608 subpel_x: i32,
609 subpel_y: i32,
610 x_step: i32,
611 y_step: i32,
612 w: usize,
613 h: usize,
614 avg: bool,
615 temp: &mut [Sample],
616 bd: u8,
617) {
618 let intermediate_height = (((h as i32 - 1) * y_step + subpel_y) >> SUBPEL_BITS) as usize + TAPS;
619 let temp_origin = (TAPS as isize / 2 - 1) * 64;
620 convolve_horiz(
621 buf,
622 stride,
623 origin - (TAPS as isize / 2 - 1) * stride as isize,
624 temp,
625 64,
626 f,
627 subpel_x,
628 x_step,
629 w,
630 intermediate_height,
631 false,
632 bd,
633 );
634 if avg {
635 // vpx_convolve8_avg_c: full 2D into a second scratch, then average
636 // with the destination (which holds the first reference's block).
637 // `temp[..64 * 135]` is the horizontal intermediate; the region after
638 // it is the 2D result.
639 let (horiz, mid2) = temp.split_at_mut(64 * 135);
640 convolve_vert(
641 horiz,
642 64,
643 temp_origin,
644 mid2,
645 w,
646 f,
647 subpel_y,
648 y_step,
649 w,
650 h,
651 false,
652 bd,
653 );
654 for y in 0..h {
655 for x in 0..w {
656 let d = y * dst_stride + x;
657 dst[d] = round_pow2(dst[d] as i32 + mid2[y * w + x] as i32, 1) as Sample;
658 }
659 }
660 return;
661 }
662 convolve_vert(
663 temp,
664 64,
665 temp_origin,
666 dst,
667 dst_stride,
668 f,
669 subpel_y,
670 y_step,
671 w,
672 h,
673 false,
674 bd,
675 );
676}
677
678/// One reference plane of a stored frame.
679pub(crate) struct RefPlane<'a> {
680 /// Plane base — the frame's first visible sample.
681 pub data: &'a [Sample],
682 /// Row pitch.
683 pub stride: usize,
684 /// `y_crop_width` / `uv_crop_width`: the coded extent, which is what
685 /// `build_mc_border` replicates past.
686 pub width: usize,
687 /// `y_crop_height` / `uv_crop_height`.
688 pub height: usize,
689 /// Bits per sample of the reference frame.
690 pub bd: u8,
691}
692
693/// `dec_build_inter_predictors` (`vp9/decoder/vp9_decodeframe.c:593`):
694/// predict one `w` x `h` plane block whose top-left is plane pixel `(x, y)`
695/// inside the block at MI `(mi_row, mi_col)`. `sf` is the reference's scale
696/// factors; when they scale, the block is mapped into the reference frame
697/// (`scale_value_x/y`), the MV is scaled with it (`vp9_scale_mv`) and the
698/// convolve steps by `x_step_q4` / `y_step_q4`.
699#[allow(clippy::too_many_arguments)]
700pub(crate) fn build_inter_predictors(
701 dst: &mut [Sample],
702 dst_stride: usize,
703 refp: &RefPlane<'_>,
704 mi_col: usize,
705 mi_row: usize,
706 x: usize,
707 y: usize,
708 w: usize,
709 h: usize,
710 bw: usize,
711 bh: usize,
712 mv: (i32, i32),
713 mb_left: i32,
714 mb_right: i32,
715 mb_top: i32,
716 mb_bottom: i32,
717 ss_x: usize,
718 ss_y: usize,
719 kernel: usize,
720 avg: bool,
721 sf: &ScaleFactors,
722 scratch: &mut Vec<Sample>,
723 temp: &mut Vec<Sample>,
724) {
725 let bd = refp.bd;
726 let is_scaled = sf.is_scaled();
727 // `dec_build_inter_predictors` clamps (against the WHOLE block's `bw` x
728 // `bh`, not the 4x4 sub-block) only on the scaled path; unscaled MVs are
729 // just widened to 1/16 pel and rely on the border copy below.
730 let mv_q4 = if is_scaled {
731 clamp_mv_to_umv_border_sb(
732 mv, bw as i32, bh as i32, mb_left, mb_right, mb_top, mb_bottom, ss_x, ss_y,
733 )
734 } else {
735 (mv.0 * (1 << (1 - ss_y)), mv.1 * (1 << (1 - ss_x)))
736 };
737
738 // Co-ordinate of the containing block, pixel precision, plus the
739 // block-relative offset (`x`, `y`).
740 let x_pre = (-mb_left >> (3 + ss_x)) + x as i32;
741 let y_pre = (-mb_top >> (3 + ss_y)) + y as i32;
742 let (x_step, y_step, scaled_mv);
743 let (x0_16, y0_16, x0_pre, y0_pre);
744 if is_scaled {
745 // The block is mapped into the reference frame at 1/16-pel (the
746 // `x0_16` used for the border extent) and at pixel precision (`x0`,
747 // which shifts by the scaled MV's integer part below).
748 let x0 = sf.scale_x(x_pre);
749 let y0 = sf.scale_y(y_pre);
750 scaled_mv = sf.scale_mv(
751 mv_q4,
752 mi_col as i32 * 8 + x as i32,
753 mi_row as i32 * 8 + y as i32,
754 );
755 x_step = sf.x_step_q4;
756 y_step = sf.y_step_q4;
757 x0_16 = sf.scale_x(x_pre << SUBPEL_BITS) + scaled_mv.1;
758 y0_16 = sf.scale_y(y_pre << SUBPEL_BITS) + scaled_mv.0;
759 x0_pre = x0;
760 y0_pre = y0;
761 } else {
762 scaled_mv = mv_q4;
763 x_step = SUBPEL_SHIFTS;
764 y_step = SUBPEL_SHIFTS;
765 x0_16 = (x_pre << SUBPEL_BITS) + scaled_mv.1;
766 y0_16 = (y_pre << SUBPEL_BITS) + scaled_mv.0;
767 x0_pre = x_pre;
768 y0_pre = y_pre;
769 }
770 let subpel_x = scaled_mv.1 & SUBPEL_MASK;
771 let subpel_y = scaled_mv.0 & SUBPEL_MASK;
772
773 let frame_width = refp.width as i32;
774 let frame_height = refp.height as i32;
775 // `buf_ptr = ref_frame + y0 * stride + x0` is taken AFTER the MV integer
776 // part but BEFORE the tap padding below, so the direct read keeps its own
777 // copy of the coordinates.
778 let x0_mv = x0_pre + (scaled_mv.1 >> SUBPEL_BITS);
779 let y0_mv = y0_pre + (scaled_mv.0 >> SUBPEL_BITS);
780 let mut x0 = x0_mv;
781 let mut y0 = y0_mv;
782
783 let f = &FILTERS[kernel];
784
785 // `is_scaled || scaled_mv.col || scaled_mv.row || (frame_width & 7) ||
786 // (frame_height & 7)`: the border copy is skipped only when the window is
787 // provably inside the frame.
788 if is_scaled
789 || scaled_mv.1 != 0
790 || scaled_mv.0 != 0
791 || (frame_width & 7) != 0
792 || (frame_height & 7) != 0
793 {
794 let mut x1 = ((x0_16 + (w as i32 - 1) * x_step) >> SUBPEL_BITS) + 1;
795 let mut y1 = ((y0_16 + (h as i32 - 1) * y_step) >> SUBPEL_BITS) + 1;
796 let mut x_pad = false;
797 let mut y_pad = false;
798 if subpel_x != 0 || x_step != SUBPEL_SHIFTS {
799 x0 -= INTERP_EXTEND - 1;
800 x1 += INTERP_EXTEND;
801 x_pad = true;
802 }
803 if subpel_y != 0 || y_step != SUBPEL_SHIFTS {
804 y0 -= INTERP_EXTEND - 1;
805 y1 += INTERP_EXTEND;
806 y_pad = true;
807 }
808 if x0 < 0
809 || x0 > frame_width - 1
810 || x1 < 0
811 || x1 > frame_width - 1
812 || y0 < 0
813 || y0 > frame_height - 1
814 || y1 < 0
815 || y1 > frame_height - 1
816 {
817 let b_w = (x1 - x0 + 1) as usize;
818 let b_h = (y1 - y0 + 1) as usize;
819 let border_offset = usize::from(y_pad) * 3 * b_w + usize::from(x_pad) * 3;
820 scratch.resize(b_w * b_h, 0);
821 build_mc_border(
822 refp.data,
823 refp.stride,
824 scratch,
825 b_w,
826 x0,
827 y0,
828 b_w,
829 b_h,
830 frame_width,
831 frame_height,
832 );
833 inter_predictor(
834 scratch,
835 b_w,
836 border_offset as isize,
837 dst,
838 dst_stride,
839 f,
840 subpel_x,
841 subpel_y,
842 x_step,
843 y_step,
844 w,
845 h,
846 avg,
847 temp,
848 bd,
849 );
850 return;
851 }
852 }
853 // Inside the frame: read directly. The `x0`/`y0` checks above guarantee
854 // the `SUBPEL_TAPS / 2 - 1` tap margin that `inter_predictor` reads
855 // backwards also lies inside the visible plane.
856 let origin = y0_mv as isize * refp.stride as isize + x0_mv as isize;
857 inter_predictor(
858 refp.data,
859 refp.stride,
860 origin,
861 dst,
862 dst_stride,
863 f,
864 subpel_x,
865 subpel_y,
866 x_step,
867 y_step,
868 w,
869 h,
870 avg,
871 temp,
872 bd,
873 );
874}
875
876/// `average_split_mvs` (`vp9/common/vp9_reconinter.c:113`): the per-sub-block
877/// MV of a sub-8x8 inter block, selected by the plane's subsampling.
878///
879/// `ss_idx` 0 (luma and 4:4:4 chroma): the sub-block's own MV; 1 (4:4:0): the
880/// q2-rounded average of the vertical pair (`block`, `block + 2`); 2 (4:2:2):
881/// the horizontal pair (`block`, `block + 1`); 3 (4:2:0): the q4-rounded
882/// average of all four.
883///
884/// `round_mv_comp_qN(v) = (v < 0 ? v - N/2 : v + N/2) / N` — C's truncating
885/// division, which Rust's `/` on integers reproduces.
886pub(crate) fn average_split_mvs(
887 bmi: &[[(i32, i32); 2]; 4],
888 ref_idx: usize,
889 block: usize,
890 ss_x: usize,
891 ss_y: usize,
892) -> (i32, i32) {
893 let q2 = |v: i32| if v < 0 { (v - 1) / 2 } else { (v + 1) / 2 };
894 let q4 = |v: i32| if v < 0 { (v - 2) / 4 } else { (v + 2) / 4 };
895 match (ss_x, ss_y) {
896 (0, 0) => bmi[block][ref_idx],
897 (0, 1) => {
898 let (a, b) = (bmi[block][ref_idx], bmi[block + 2][ref_idx]);
899 (q2(a.0 + b.0), q2(a.1 + b.1))
900 }
901 (1, 0) => {
902 let (a, b) = (bmi[block][ref_idx], bmi[block + 1][ref_idx]);
903 (q2(a.0 + b.0), q2(a.1 + b.1))
904 }
905 _ => {
906 let mut row = 0;
907 let mut col = 0;
908 for b in bmi.iter() {
909 row += b[ref_idx].0;
910 col += b[ref_idx].1;
911 }
912 (q4(row), q4(col))
913 }
914 }
915}
916
917#[cfg(test)]
918mod tests {
919 use super::*;
920
921 /// Per-sample reference: the `convolve_horiz` / `convolve_vert` loops before the
922 /// unscaled fast path, with the same tap positions and rounding.
923 #[allow(clippy::too_many_arguments)]
924 fn ref_conv(
925 buf: &[Sample],
926 stride: usize,
927 origin: isize,
928 dst: &mut [Sample],
929 dst_stride: usize,
930 f: &[i16; TAPS],
931 horiz: bool,
932 w: usize,
933 h: usize,
934 avg: bool,
935 bd: u8,
936 ) {
937 for y in 0..h {
938 for x in 0..w {
939 let mut sum = 0i32;
940 for k in 0..TAPS {
941 let idx = if horiz {
942 origin + (y * stride + x) as isize + k as isize - 3
943 } else {
944 origin + (y as isize + k as isize - 3) * stride as isize + x as isize
945 };
946 sum += buf[idx as usize] as i32 * f[k] as i32;
947 }
948 let v = clip_pixel_bd(round_pow2(sum, FILTER_BITS), bd) as i32;
949 let d = y * dst_stride + x;
950 dst[d] = if avg { round_pow2(dst[d] as i32 + v, 1) as Sample } else { v as Sample };
951 }
952 }
953 }
954
955 /// Deterministic pseudo-random samples in `[0, 2^bd)`.
956 fn samples(n: usize, bd: u8, seed: u32) -> Vec<Sample> {
957 let mut s = seed;
958 (0..n)
959 .map(|_| {
960 s = s.wrapping_mul(1_103_515_245).wrapping_add(12_345);
961 ((s >> 8) & ((1 << bd) - 1)) as Sample
962 })
963 .collect()
964 }
965
966 #[test]
967 fn unscaled_fast_path_matches_per_sample_reference() {
968 for kernel in 0..4 {
969 for bd in [8u8, 10, 12] {
970 for frac in 0..SUBPEL_SHIFTS as usize {
971 for &(w, h) in &[(4usize, 4usize), (8, 8), (16, 8), (32, 32), (64, 64)] {
972 for avg in [false, true] {
973 let stride = 80usize;
974 let buf = samples(stride * 80, bd, (kernel * 977 + frac * 31 + w) as u32);
975 let origin = (3 * stride + 3) as isize;
976 let f = &FILTERS[kernel][frac];
977 let init = samples(64 * 64, bd, 7);
978 let mut got = init.clone();
979 let mut want = init.clone();
980 convolve_horiz(
981 &buf, stride, origin, &mut got, 64, &FILTERS[kernel], frac as i32,
982 SUBPEL_SHIFTS, w, h, avg, bd,
983 );
984 ref_conv(&buf, stride, origin, &mut want, 64, f, true, w, h, avg, bd);
985 assert_eq!(got, want, "horiz kernel={kernel} bd={bd} frac={frac} {w}x{h} avg={avg}");
986
987 let mut got = init.clone();
988 let mut want = init.clone();
989 convolve_vert(
990 &buf, stride, origin, &mut got, 64, &FILTERS[kernel], frac as i32,
991 SUBPEL_SHIFTS, w, h, avg, bd,
992 );
993 ref_conv(&buf, stride, origin, &mut want, 64, f, false, w, h, avg, bd);
994 assert_eq!(got, want, "vert kernel={kernel} bd={bd} frac={frac} {w}x{h} avg={avg}");
995 }
996 }
997 }
998 }
999 }
1000 }
1001}