forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

inter.rs1084 lines, 36.0 KiBHistoryRawDownload
1//! Inter prediction sample construction (spec 8.4.2): the quarter-sample luma
2//! interpolation of 8.4.2.2.1, the eighth-sample chroma interpolation of
3//! 8.4.2.2.2 and the weighted combination of 8.4.2.3.
4//!
5//! Reference planes are the same padded [`crate::decoder::Plane8`] the decoder
6//! writes into, with the borders replicated once per picture
7//! (`Plane8::extend_borders`). That turns the per-sample `Clip3` of Equations
8//! 8-239 and 8-240 into a single clamp of the block origin: any position the
9//! spec would clip to an edge sample lands on the replicated copy of that same
10//! edge sample, so the interpolation loop never bounds-checks and never
11//! branches per sample. The clamp bounds below are what makes that exact —
12//! see [`clamp_origin`].
13
14use wide::{i16x8, i16x16, i32x8};
15
16/// A reference picture plane for motion compensation.
17pub(crate) struct RefPlane<'a> {
18 /// The whole padded plane.
19 pub data: &'a [u8],
20 /// Row pitch.
21 pub stride: usize,
22 /// Index of picture sample (0, 0).
23 pub origin: usize,
24 /// Picture width in samples.
25 pub width: usize,
26 /// Picture height in samples.
27 pub height: usize,
28 /// Replicated border width on every side.
29 pub pad: usize,
30}
31
32impl RefPlane<'_> {
33 #[inline]
34 fn at(&self, x: i32, y: i32) -> usize {
35 (self.origin as isize + y as isize * self.stride as isize + x as isize) as usize
36 }
37}
38
39/// Clamp a block origin so that every tap the interpolator reads stays inside
40/// the replicated border while producing the samples Equations 8-239/8-240
41/// would have clipped to.
42///
43/// `left`/`right` are the tap reach on each side (2 and 3 for the 6-tap luma
44/// filter, 0 and 1 for the bilinear chroma filter) and `size` the block extent.
45/// Once the block is completely outside the picture every tap resolves to the
46/// same edge sample, so clamping the origin to the last position where that is
47/// still true is exact rather than approximate.
48#[inline]
49fn clamp_origin(v: i32, size: usize, extent: usize, pad: usize, left: i32, right: i32) -> i32 {
50 let lo = -(pad as i32) + left;
51 let hi = extent as i32 + pad as i32 - right - size as i32;
52 v.clamp(lo.min(hi), hi)
53}
54
55/// Sixteen samples as 16-bit lanes, zero past the end of the plane.
56///
57/// A partition is at most 16 samples wide, so one vector covers a whole row and
58/// the lanes past `w` are simply never stored. Every index the interpolator
59/// reaches is inside the replicated border (see [`clamp_origin`]), so the zero
60/// fill is reachable only by those discarded lanes.
61#[inline]
62fn load16(data: &[u8], at: usize) -> i16x16 {
63 let mut a = [0i16; 16];
64 // The fixed-length slice is what makes this one widening load: a zip
65 // against an open-ended slice leaves the trip count unknown and the
66 // compiler emits a byte loop instead.
67 match data.get(at..at + 16) {
68 Some(row) => {
69 for (o, &b) in a.iter_mut().zip(row) {
70 *o = i16::from(b);
71 }
72 }
73 None => {
74 for (o, &b) in a.iter_mut().zip(&data[at..]) {
75 *o = i16::from(b);
76 }
77 }
78 }
79 i16x16::from(a)
80}
81
82/// The same over eight lanes, for chroma blocks (at most eight wide).
83#[inline]
84fn load8(data: &[u8], at: usize) -> i16x8 {
85 let mut a = [0i16; 8];
86 match data.get(at..at + 8) {
87 Some(row) => {
88 for (o, &b) in a.iter_mut().zip(row) {
89 *o = i16::from(b);
90 }
91 }
92 None => {
93 for (o, &b) in a.iter_mut().zip(&data[at..]) {
94 *o = i16::from(b);
95 }
96 }
97 }
98 i16x8::from(a)
99}
100
101/// The same 6-tap filter over eight neighbouring positions.
102///
103/// Eight lanes is one SSE2 register, which is the widest vector this crate can
104/// assume without a target feature it is not allowed to require. A partition
105/// narrower than sixteen samples therefore costs half or a quarter as much
106/// here as it does in the sixteen-lane form, where the surplus lanes are
107/// computed and then discarded.
108#[inline]
109fn tap6_8(data: &[u8], at: usize, step: usize) -> i16x8 {
110 let l = |k: isize| load8(data, (at as isize + k * step as isize) as usize);
111 let five = i16x8::splat(5);
112 let twenty = i16x8::splat(20);
113 l(-2) - five * l(-1) + twenty * l(0) + twenty * l(1) - five * l(2) + l(3)
114}
115
116/// The same filter over sixteen positions, for a full-width partition.
117#[inline]
118fn tap6_16(data: &[u8], at: usize, step: usize) -> i16x16 {
119 let l = |k: isize| load16(data, (at as isize + k * step as isize) as usize);
120 let five = i16x16::splat(5);
121 let twenty = i16x16::splat(20);
122 l(-2) - five * l(-1) + twenty * l(0) + twenty * l(1) - five * l(2) + l(3)
123}
124
125/// `Clip1Y( ( v + 16 ) >> 5 )` over a row, storing the first `dst.len()` lanes.
126#[inline]
127fn store_half8(dst: &mut [u8], v: i16x8, put: Put) {
128 let c = ((v + i16x8::splat(16)) >> 5u32)
129 .max(i16x8::ZERO)
130 .min(i16x8::splat(255));
131 match put {
132 Put::Set => {
133 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
134 *o = s as u8;
135 }
136 }
137 Put::Avg => {
138 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
139 *o = avg(*o, s as u8);
140 }
141 }
142 Put::AvgW {
143 w0,
144 w1,
145 shift,
146 round,
147 off,
148 } => {
149 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
150 store_weighted(o, s as u8, w0, w1, shift, round, off);
151 }
152 }
153 }
154}
155
156/// The same over sixteen lanes.
157#[inline]
158fn store_half16(dst: &mut [u8], v: i16x16, put: Put) {
159 let c = ((v + i16x16::splat(16)) >> 5u32)
160 .max(i16x16::ZERO)
161 .min(i16x16::splat(255));
162 match put {
163 Put::Set => {
164 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
165 *o = s as u8;
166 }
167 }
168 Put::Avg => {
169 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
170 *o = avg(*o, s as u8);
171 }
172 }
173 Put::AvgW {
174 w0,
175 w1,
176 shift,
177 round,
178 off,
179 } => {
180 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
181 store_weighted(o, s as u8, w0, w1, shift, round, off);
182 }
183 }
184 }
185}
186/// One 6-tap half-sample pass over a `w` x `h` block whose top-left sample is
187/// `base`, into a `w`-pitch buffer. `step` is the tap spacing: 1 for the
188/// horizontal filter, the plane stride for the vertical one.
189///
190/// A partition is 16, 8 or 4 samples wide, so the narrow widths take a single
191/// eight-lane vector rather than a sixteen-lane one whose upper half is
192/// discarded.
193#[inline]
194fn half_block(
195 dst: &mut [u8],
196 data: &[u8],
197 base: usize,
198 stride: usize,
199 step: usize,
200 w: usize,
201 h: usize,
202) {
203 if w == 16 {
204 for row in 0..h {
205 store_half16(
206 &mut dst[row * 16..row * 16 + 16],
207 tap6_16(data, base + row * stride, step),
208 Put::Set,
209 );
210 }
211 } else {
212 for row in 0..h {
213 store_half8(
214 &mut dst[row * w..row * w + w],
215 tap6_8(data, base + row * stride, step),
216 Put::Set,
217 );
218 }
219 }
220}
221
222/// Eight intermediate values as 32-bit lanes, zero past the end.
223#[inline]
224fn load_inter8(v: &[i16], at: usize) -> i32x8 {
225 let mut a = [0i32; 8];
226 for (o, &s) in a.iter_mut().zip(&v[at..]) {
227 *o = i32::from(s);
228 }
229 i32x8::from(a)
230}
231
232/// The 6-tap filter over already-filtered intermediate values (Equation
233/// 8-246), eight columns at a time. Those sums reach 449820, so this pass is
234/// 32-bit where the first one was 16-bit.
235#[inline]
236fn tap6_inter8(v: &[i16], at: usize, step: usize) -> i32x8 {
237 let l = |k: isize| load_inter8(v, (at as isize + k * step as isize) as usize);
238 let five = i32x8::splat(5);
239 let twenty = i32x8::splat(20);
240 l(-2) - five * l(-1) + twenty * l(0) + twenty * l(1) - five * l(2) + l(3)
241}
242
243/// `Clip1Y( ( v + 512 ) >> 10 )` over eight lanes.
244#[inline]
245fn store_centre(dst: &mut [u8], v: i32x8, put: Put) {
246 let c = ((v + i32x8::splat(512)) >> 10u32)
247 .max(i32x8::ZERO)
248 .min(i32x8::splat(255));
249 match put {
250 Put::Set => {
251 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
252 *o = s as u8;
253 }
254 }
255 Put::Avg => {
256 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
257 *o = avg(*o, s as u8);
258 }
259 }
260 Put::AvgW {
261 w0,
262 w1,
263 shift,
264 round,
265 off,
266 } => {
267 for (o, &s) in dst.iter_mut().zip(c.as_array()) {
268 store_weighted(o, s as u8, w0, w1, shift, round, off);
269 }
270 }
271 }
272}
273
274/// The rounded average of Equation 8-247 over `n` samples, sixteen at a time.
275#[inline]
276fn avg_rows(out: &mut [u8], a: &[u8], b: &[u8], n: usize) {
277 // Written as a plain loop over equal-length slices: this is the rounded
278 // byte average, which the compiler turns into one `pavgb` per sixteen
279 // samples — half the work of widening to 16-bit lanes and narrowing back.
280 let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
281 for i in 0..n {
282 out[i] = avg(a[i], b[i]);
283 }
284}
285
286/// The same average, written into a destination of pitch `os` from two
287/// `w`-pitch sources.
288#[inline]
289fn avg_rows_to(out: &mut [u8], os: usize, a: &[u8], b: &[u8], w: usize, h: usize, put: Put) {
290 if os == w {
291 avg_rows_to_contig(out, a, b, w * h, put);
292 return;
293 }
294 for row in 0..h {
295 avg_rows_to_contig(
296 &mut out[row * os..row * os + w],
297 &a[row * w..],
298 &b[row * w..],
299 w,
300 put,
301 );
302 }
303}
304
305/// The average over contiguous equal-length slices, honouring `put`.
306#[inline]
307fn avg_rows_to_contig(out: &mut [u8], a: &[u8], b: &[u8], n: usize, put: Put) {
308 match put {
309 Put::Set => avg_rows(out, a, b, n),
310 Put::Avg => {
311 let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
312 for i in 0..n {
313 out[i] = avg(avg(a[i], b[i]), out[i]);
314 }
315 }
316 Put::AvgW {
317 w0,
318 w1,
319 shift,
320 round,
321 off,
322 } => avg_rows_weighted(out, a, b, n, w0, w1, shift, round, off),
323 }
324}
325
326/// Copy `w` x `h` samples from a `w`-pitch source into an `os`-pitch
327/// destination, honouring `put`.
328#[inline]
329fn copy_rows(out: &mut [u8], os: usize, src: &[u8], w: usize, h: usize, put: Put) {
330 for row in 0..h {
331 let dst = &mut out[row * os..row * os + w];
332 let src = &src[row * w..row * w + w];
333 match put {
334 Put::Set => dst.copy_from_slice(src),
335 Put::Avg => {
336 for (d, &s) in dst.iter_mut().zip(src) {
337 *d = avg(*d, s);
338 }
339 }
340 Put::AvgW {
341 w0,
342 w1,
343 shift,
344 round,
345 off,
346 } => copy_rows_weighted(dst, src, w0, w1, shift, round, off),
347 }
348 }
349}
350
351#[inline]
352fn clip8(v: i32) -> u8 {
353 v.clamp(0, 255) as u8
354}
355
356#[inline]
357fn avg(a: u8, b: u8) -> u8 {
358 ((u32::from(a) + u32::from(b) + 1) >> 1) as u8
359}
360
361/// Widest intermediate row the luma interpolator needs: a 16-wide partition
362/// plus the five taps of the horizontal filter.
363const TMP_W: usize = 16 + 5;
364
365/// Index of the top-left sample of a whole-sample block, clamped exactly as
366/// [`mc_luma`] clamps it.
367///
368/// A motion search spends most of its time on whole-sample positions, where
369/// prediction is a copy; this lets it read the reference plane in place
370/// instead of copying every candidate into a buffer first.
371#[inline]
372pub(crate) fn integer_origin(r: &RefPlane<'_>, x: i32, y: i32, w: usize, h: usize) -> usize {
373 let xi = clamp_origin(x, w, r.width, r.pad, 2, 3);
374 let yi = clamp_origin(y, h, r.height, r.pad, 2, 3);
375 r.at(xi, yi)
376}
377/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition
378/// whose full-sample origin is `(x, y)` and whose motion vector is `mv` in
379/// quarter samples. Writes `w` x `h` prediction samples into `out` at pitch
380/// `os`, honouring `put` (see [`Put`]).
381///
382/// The pitch is a parameter so that the single-list, default-weight case —
383/// which is most of a P slice — interpolates straight into the picture instead
384/// of into a temporary that is then copied there.
385#[allow(clippy::too_many_arguments)]
386pub(crate) fn mc_luma(
387 r: &RefPlane<'_>,
388 x: i32,
389 y: i32,
390 mv: [i16; 2],
391 w: usize,
392 h: usize,
393 os: usize,
394 out: &mut [u8],
395 put: Put,
396) {
397 let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
398 let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3);
399 let yi = clamp_origin(y + (mv[1] as i32 >> 2), h, r.height, r.pad, 2, 3);
400 let stride = r.stride;
401 let base = r.at(xi, yi);
402
403 // Full sample: a straight copy.
404 if fx == 0 && fy == 0 {
405 match put {
406 Put::Set => {
407 for row in 0..h {
408 let src = base + row * stride;
409 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
410 }
411 }
412 Put::Avg => {
413 for row in 0..h {
414 let src = base + row * stride;
415 let dst = &mut out[row * os..row * os + w];
416 for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) {
417 *d = avg(*d, v);
418 }
419 }
420 }
421 Put::AvgW {
422 w0,
423 w1,
424 shift,
425 round,
426 off,
427 } => copy_weighted(
428 out,
429 os,
430 &r.data[base..],
431 stride,
432 w,
433 h,
434 w0,
435 w1,
436 shift,
437 round,
438 off,
439 ),
440 }
441 return;
442 }
443
444 // Half-sample rows ("b" of Equation 8-243) for rows yi..yi+h, plus one more
445 // row when the quarter position also needs "s".
446 let need_b = fx != 0 && fy != 2;
447 let need_h = fy != 0 && fx != 2;
448 let need_j = (fx == 2 && fy != 0) || (fy == 2 && fx != 0);
449
450 let mut bb = [0u8; 16 * 17];
451 if need_b {
452 // "s" is the same filter one row down, so row fy>>1 selects b or s.
453 let row0 = yi + if fy == 3 { 1 } else { 0 };
454 half_block(&mut bb, r.data, r.at(xi, row0), stride, 1, w, h);
455 }
456 let mut hh = [0u8; 16 * 17];
457 if need_h {
458 // "m" is the same filter one column right, so column fx>>1 selects h or m.
459 let col0 = xi + if fx == 3 { 1 } else { 0 };
460 half_block(&mut hh, r.data, r.at(col0, yi), stride, stride, w, h);
461 }
462 let mut jj = [0u8; 16 * 16];
463 if need_j {
464 // Equation 8-246: filter horizontally into intermediates, then
465 // vertically over those. The horizontal pass needs two rows above and
466 // three below the partition.
467 let mut inter = [0i16; TMP_W * (16 + 5)];
468 for row in 0..h + 5 {
469 let src = r.at(xi, yi + row as i32 - 2);
470 let base = row * TMP_W;
471 if w == 16 {
472 let v = tap6_16(r.data, src, 1);
473 inter[base..base + 16].copy_from_slice(v.as_array());
474 } else {
475 let v = tap6_8(r.data, src, 1);
476 for (o, &t) in inter[base..base + w].iter_mut().zip(v.as_array()) {
477 *o = t;
478 }
479 }
480 }
481 for row in 0..h {
482 for col in (0..w).step_by(8) {
483 let v = tap6_inter8(&inter, (row + 2) * TMP_W + col, TMP_W);
484 let n = (w - col).min(8);
485 store_centre(&mut jj[row * w + col..row * w + col + n], v, Put::Set);
486 }
487 }
488 }
489
490 // Table 8-12: each quarter position is one of the half-sample arrays, or
491 // the average of two of them. Resolving it once per partition rather than
492 // once per sample is what keeps the copy loops straight.
493 match (fx, fy) {
494 (2, 0) => copy_rows(out, os, &bb, w, h, put),
495 (0, 2) => copy_rows(out, os, &hh, w, h, put),
496 (2, 2) => copy_rows(out, os, &jj, w, h, put),
497 (2, 1) | (2, 3) => avg_rows_to(out, os, &bb, &jj, w, h, put),
498 (1, 2) | (3, 2) => avg_rows_to(out, os, &hh, &jj, w, h, put),
499 (1, 0) | (3, 0) | (0, 1) | (0, 3) => {
500 // Averaged with an integer sample one row or column over.
501 let (dx, dy) = match (fx, fy) {
502 (3, 0) => (1, 0),
503 (0, 3) => (0, 1),
504 _ => (0, 0),
505 };
506 let half: &[u8] = if fy == 0 { &bb } else { &hh };
507 for row in 0..h {
508 let src = base + (row + dy) * stride + dx;
509 let s = &r.data[src..src + w];
510 let hl = &half[row * w..row * w + w];
511 let dst = &mut out[row * os..row * os + w];
512 match put {
513 Put::Set => {
514 for col in 0..w {
515 dst[col] = avg(s[col], hl[col]);
516 }
517 }
518 Put::Avg => {
519 for col in 0..w {
520 dst[col] = avg(dst[col], avg(s[col], hl[col]));
521 }
522 }
523 Put::AvgW {
524 w0,
525 w1,
526 shift,
527 round,
528 off,
529 } => {
530 for col in 0..w {
531 store_weighted(
532 &mut dst[col],
533 avg(s[col], hl[col]),
534 w0,
535 w1,
536 shift,
537 round,
538 off,
539 );
540 }
541 }
542 }
543 }
544 }
545 // Diagonal quarter positions: the two nearest half samples.
546 _ => avg_rows_to(out, os, &bb, &hh, w, h, put),
547 }
548}
549
550/// Equation 8-270 over a block of statically known width.
551///
552/// The width is a const parameter because a chroma block is 2, 4 or 8 samples
553/// wide and the 2x2 case dominates real streams: with `W` known the row slices
554/// have constant length, which drops the bounds checks and lets the smallest
555/// blocks compile to a handful of scalar multiplies instead of a vector setup
556/// whose lanes are then thrown away.
557#[inline]
558fn chroma_rows<const W: usize>(
559 data: &[u8],
560 base: usize,
561 stride: usize,
562 h: usize,
563 wt: [u16; 4],
564 os: usize,
565 out: &mut [u8],
566 put: Put,
567) {
568 for row in 0..h {
569 let src = base + row * stride;
570 let p = &data[src..src + W + 1];
571 let q = &data[src + stride..src + stride + W + 1];
572 let dst = &mut out[row * os..row * os + W];
573 for c in 0..W {
574 let v = u16::from(p[c]) * wt[0]
575 + u16::from(p[c + 1]) * wt[1]
576 + u16::from(q[c]) * wt[2]
577 + u16::from(q[c + 1]) * wt[3]
578 + 32;
579 match put {
580 Put::Set => dst[c] = (v >> 6) as u8,
581 Put::Avg => dst[c] = avg(dst[c], (v >> 6) as u8),
582 Put::AvgW {
583 w0,
584 w1,
585 shift,
586 round,
587 off,
588 } => store_weighted(&mut dst[c], (v >> 6) as u8, w0, w1, shift, round, off),
589 }
590 }
591 }
592}
593
594/// Chroma eighth-sample interpolation (Equation 8-270) of a `w` x `h` block.
595#[allow(clippy::too_many_arguments)]
596pub(crate) fn mc_chroma(
597 r: &RefPlane<'_>,
598 x: i32,
599 y: i32,
600 mv: [i16; 2],
601 w: usize,
602 h: usize,
603 os: usize,
604 out: &mut [u8],
605 put: Put,
606) {
607 let (fx, fy) = ((mv[0] & 7) as u16, (mv[1] & 7) as u16);
608 let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1);
609 let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1);
610 let stride = r.stride;
611 let base = r.at(xi, yi);
612
613 // Full sample: a straight copy. A zero motion vector is the most common
614 // vector in real content, and it lands here.
615 if fx == 0 && fy == 0 {
616 match put {
617 Put::Set => {
618 for row in 0..h {
619 let src = base + row * stride;
620 out[row * os..row * os + w].copy_from_slice(&r.data[src..src + w]);
621 }
622 }
623 Put::Avg => {
624 for row in 0..h {
625 let src = base + row * stride;
626 let dst = &mut out[row * os..row * os + w];
627 for (d, &v) in dst.iter_mut().zip(&r.data[src..src + w]) {
628 *d = avg(*d, v);
629 }
630 }
631 }
632 Put::AvgW {
633 w0,
634 w1,
635 shift,
636 round,
637 off,
638 } => copy_weighted(
639 out,
640 os,
641 &r.data[base..],
642 stride,
643 w,
644 h,
645 w0,
646 w1,
647 shift,
648 round,
649 off,
650 ),
651 }
652 return;
653 }
654 // The four weights sum to 64, so the weighted sum of Equation 8-270 never
655 // exceeds 64 * 255 and the whole bilinear fits in 16-bit lanes.
656 let wt = [(8 - fx) * (8 - fy), fx * (8 - fy), (8 - fx) * fy, fx * fy];
657 match w {
658 2 => chroma_rows::<2>(r.data, base, stride, h, wt, os, out, put),
659 4 => chroma_rows::<4>(r.data, base, stride, h, wt, os, out, put),
660 _ => chroma_rows::<8>(r.data, base, stride, h, wt, os, out, put),
661 }
662}
663
664/// Weights of one component for one partition (spec 8.4.3), already resolved
665/// to the explicit/implicit/default case.
666#[derive(Clone, Copy, Debug, PartialEq, Eq)]
667pub(crate) struct Weights {
668 /// `logWDC`.
669 pub log_wd: i32,
670 /// `w0C`, `w1C`.
671 pub w: [i32; 2],
672 /// `o0C`, `o1C`.
673 pub o: [i32; 2],
674}
675
676impl Weights {
677 /// The identity weighting, which reproduces 8.4.2.3.1 exactly.
678 pub(crate) const DEFAULT: Weights = Weights {
679 log_wd: 0,
680 w: [1, 1],
681 o: [0, 0],
682 };
683
684 /// True when 8.4.2.3.1 applies, so a single-list prediction is its own
685 /// final prediction and needs no combining pass at all.
686 pub(crate) fn is_default(&self) -> bool {
687 *self == Weights::DEFAULT
688 }
689}
690
691/// How an interpolation result lands in `out`: written outright, or rounded
692/// into what is already there.
693///
694/// The weighted second pass of 8.4.2.3.2 is a fusion mode as well: the first
695/// prediction sits in `out`, and the second list's sample `v` combines with
696/// it as `clip((out*w0 + v*w1 + round) >> shift) + off` — the same integer
697/// formula, on the same bytes, as running the combining pass over the two
698/// clipped predictions.
699#[derive(Clone, Copy, PartialEq, Eq)]
700pub(crate) enum Put {
701 /// Write the prediction.
702 Set,
703 /// Average the prediction into the bytes already in `out`.
704 Avg,
705 /// Weighted-average the prediction into the bytes already in `out`.
706 AvgW {
707 w0: i32,
708 w1: i32,
709 shift: u32,
710 round: i32,
711 off: i32,
712 },
713}
714
715/// The 8.4.2.3.2 combining step for one sample: list 0's prediction is the
716/// byte already in `dst`, list 1's is `v`.
717#[inline]
718fn store_weighted(dst: &mut u8, v: u8, w0: i32, w1: i32, shift: u32, round: i32, off: i32) {
719 let p0 = i32::from(*dst);
720 *dst = clip8((((p0 * w0 + i32::from(v) * w1 + round) >> shift) + off) as i32);
721}
722/// The weighted combining pass over a whole block: `h` rows of `w` samples
723/// from a `stride`-pitch source into an `os`-pitch destination.
724#[inline(never)]
725#[allow(clippy::too_many_arguments)]
726fn copy_weighted(
727 out: &mut [u8],
728 os: usize,
729 src: &[u8],
730 stride: usize,
731 w: usize,
732 h: usize,
733 w0: i32,
734 w1: i32,
735 shift: u32,
736 round: i32,
737 off: i32,
738) {
739 for row in 0..h {
740 let dst = &mut out[row * os..row * os + w];
741 let s = &src[row * stride..row * stride + w];
742 for (d, &v) in dst.iter_mut().zip(s) {
743 store_weighted(d, v, w0, w1, shift, round, off);
744 }
745 }
746}
747
748/// The weighted combining pass over contiguous equal-length slices, where
749/// list 1's sample is the rounded average of `a` and `b`.
750#[inline(never)]
751#[allow(clippy::too_many_arguments)]
752fn avg_rows_weighted(
753 out: &mut [u8],
754 a: &[u8],
755 b: &[u8],
756 n: usize,
757 w0: i32,
758 w1: i32,
759 shift: u32,
760 round: i32,
761 off: i32,
762) {
763 let (out, a, b) = (&mut out[..n], &a[..n], &b[..n]);
764 for i in 0..n {
765 store_weighted(&mut out[i], avg(a[i], b[i]), w0, w1, shift, round, off);
766 }
767}
768
769/// The weighted combining pass over a whole block from a `w`-pitch source.
770#[inline(never)]
771#[allow(clippy::too_many_arguments)]
772fn copy_rows_weighted(
773 out: &mut [u8],
774 src: &[u8],
775 w0: i32,
776 w1: i32,
777 shift: u32,
778 round: i32,
779 off: i32,
780) {
781 for (d, &s) in out.iter_mut().zip(src) {
782 store_weighted(d, s, w0, w1, shift, round, off);
783 }
784}
785
786/// Combine the list predictions of one partition into the final prediction
787/// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that
788/// is not used is ignored.
789///
790/// The result is contiguous rather than written at the picture's pitch: the
791/// bi-predictive average is the one case where the samples of several rows are
792/// adjacent, and vectors that span the row boundary measured 6 to 9 per cent
793/// fewer instructions on 1080p than a per-row average at picture pitch.
794pub(crate) fn combine(
795 out: &mut [u8],
796 p0: &[u8],
797 p1: &[u8],
798 use0: bool,
799 use1: bool,
800 wt: &Weights,
801 n: usize,
802) {
803 if wt.is_default() {
804 // 8.4.2.3.1.
805 match (use0, use1) {
806 (true, false) => out[..n].copy_from_slice(&p0[..n]),
807 (false, true) => out[..n].copy_from_slice(&p1[..n]),
808 _ => avg_rows(out, p0, p1, n),
809 }
810 return;
811 }
812 // 8.4.2.3.2.
813 if use0 && use1 {
814 let round = 1 << wt.log_wd;
815 let off = (wt.o[0] + wt.o[1] + 1) >> 1;
816 for i in 0..n {
817 let v = (i32::from(p0[i]) * wt.w[0] + i32::from(p1[i]) * wt.w[1] + round)
818 >> (wt.log_wd + 1);
819 out[i] = clip8(v + off);
820 }
821 return;
822 }
823 let (src, k) = if use0 { (p0, 0) } else { (p1, 1) };
824 if wt.log_wd >= 1 {
825 let round = 1 << (wt.log_wd - 1);
826 for i in 0..n {
827 out[i] = clip8(((i32::from(src[i]) * wt.w[k] + round) >> wt.log_wd) + wt.o[k]);
828 }
829 } else {
830 for i in 0..n {
831 out[i] = clip8(i32::from(src[i]) * wt.w[k] + wt.o[k]);
832 }
833 }
834}
835
836#[cfg(test)]
837mod tests {
838 use super::*;
839
840 /// A plane whose interior is a known ramp and whose borders are replicated,
841 /// the way `Plane8::extend_borders` leaves them.
842 fn ramp_plane(w: usize, h: usize, pad: usize) -> (Vec<u8>, usize, usize) {
843 let stride = w + 2 * pad;
844 let origin = pad * stride + pad;
845 let mut data = vec![0u8; stride * (h + 2 * pad)];
846 for y in 0..h {
847 for x in 0..w {
848 data[origin + y * stride + x] = ((x * 3 + y * 7) % 251) as u8;
849 }
850 }
851 for y in 0..h {
852 let row = origin + y * stride;
853 let (l, r) = (data[row], data[row + w - 1]);
854 data[row - pad..row].fill(l);
855 data[row + w..row + w + pad].fill(r);
856 }
857 for y in 0..pad {
858 let top = origin - (y + 1) * stride - pad;
859 let src = origin - pad;
860 let (a, b) = data.split_at_mut(src);
861 a[top..top + stride].copy_from_slice(&b[..stride]);
862 let bot = origin + (h + y) * stride - pad;
863 let src = origin + (h - 1) * stride - pad;
864 let (a, b) = data.split_at_mut(bot);
865 b[..stride].copy_from_slice(&a[src..src + stride]);
866 }
867 (data, stride, origin)
868 }
869
870 fn plane(
871 data: &[u8],
872 stride: usize,
873 origin: usize,
874 w: usize,
875 h: usize,
876 pad: usize,
877 ) -> RefPlane<'_> {
878 RefPlane {
879 data,
880 stride,
881 origin,
882 width: w,
883 height: h,
884 pad,
885 }
886 }
887
888 /// The spec's clipped, per-sample definition of the same interpolation,
889 /// written straight from Equations 8-239 to 8-261 with no padding tricks.
890 #[allow(clippy::too_many_arguments)]
891 fn spec_luma(
892 pic: &[u8],
893 stride: usize,
894 origin: usize,
895 w: usize,
896 h: usize,
897 x: i32,
898 y: i32,
899 mv: [i16; 2],
900 pw: usize,
901 ph: usize,
902 out: &mut [u8],
903 ) {
904 let s = |px: i32, py: i32| -> i32 {
905 let cx = px.clamp(0, w as i32 - 1) as usize;
906 let cy = py.clamp(0, h as i32 - 1) as usize;
907 i32::from(pic[origin + cy * stride + cx])
908 };
909 let hf = |px: i32, py: i32| {
910 s(px - 2, py) - 5 * s(px - 1, py) + 20 * s(px, py) + 20 * s(px + 1, py)
911 - 5 * s(px + 2, py)
912 + s(px + 3, py)
913 };
914 let vf = |px: i32, py: i32| {
915 s(px, py - 2) - 5 * s(px, py - 1) + 20 * s(px, py) + 20 * s(px, py + 1)
916 - 5 * s(px, py + 2)
917 + s(px, py + 3)
918 };
919 let j1 = |px: i32, py: i32| {
920 let t = |k: i32| hf(px, py + k);
921 t(-2) - 5 * t(-1) + 20 * t(0) + 20 * t(1) - 5 * t(2) + t(3)
922 };
923 let (fx, fy) = ((mv[0] & 3) as i32, (mv[1] & 3) as i32);
924 let (xi, yi) = (x + (mv[0] as i32 >> 2), y + (mv[1] as i32 >> 2));
925 for row in 0..ph {
926 for col in 0..pw {
927 let (px, py) = (xi + col as i32, yi + row as i32);
928 let g = |dx: i32, dy: i32| s(px + dx, py + dy) as u8;
929 let b = |dy: i32| clip8((hf(px, py + dy) + 16) >> 5);
930 let hs = |dx: i32| clip8((vf(px + dx, py) + 16) >> 5);
931 let j = clip8((j1(px, py) + 512) >> 10);
932 out[row * pw + col] = match (fx, fy) {
933 (0, 0) => g(0, 0),
934 (1, 0) => avg(g(0, 0), b(0)),
935 (2, 0) => b(0),
936 (3, 0) => avg(g(1, 0), b(0)),
937 (0, 1) => avg(g(0, 0), hs(0)),
938 (0, 2) => hs(0),
939 (0, 3) => avg(g(0, 1), hs(0)),
940 (1, 1) => avg(b(0), hs(0)),
941 (3, 1) => avg(b(0), hs(1)),
942 (1, 3) => avg(hs(0), b(1)),
943 (3, 3) => avg(hs(1), b(1)),
944 (2, 1) => avg(b(0), j),
945 (2, 3) => avg(b(1), j),
946 (1, 2) => avg(hs(0), j),
947 (3, 2) => avg(hs(1), j),
948 _ => j,
949 };
950 }
951 }
952 }
953
954 /// Every fractional position, at interior positions and far outside the
955 /// picture, agrees with the spec's clipped definition.
956 #[test]
957 fn luma_interpolation_matches_the_clipped_definition() {
958 let (w, h, pad) = (48usize, 32usize, 32usize);
959 let (data, stride, origin) = ramp_plane(w, h, pad);
960 let r = plane(&data, stride, origin, w, h, pad);
961 let mut ours = [0u8; 256];
962 let mut theirs = [0u8; 256];
963 for &(px, py) in &[
964 (8i32, 8i32),
965 (0, 0),
966 (32, 16),
967 (-40, -40),
968 (60, 44),
969 (44, 4),
970 ] {
971 for fy in 0..4i16 {
972 for fx in 0..4i16 {
973 for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] {
974 let mv = [fx - 20 * 4, fy + 12];
975 mc_luma(&r, px, py, mv, pw, ph, pw, &mut ours, Put::Set);
976 spec_luma(&data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs);
977 assert_eq!(
978 ours[..pw * ph],
979 theirs[..pw * ph],
980 "({px},{py}) frac ({fx},{fy}) {pw}x{ph}"
981 );
982 }
983 }
984 }
985 }
986 }
987
988 /// `Put::Avg` turns `mc_luma` into the second half of a default-weighted
989 /// bi-prediction: averaging into the first list's bytes is bit-exact with
990 /// running the combining pass over the two clipped predictions (8.4.2.3.1).
991 #[test]
992 fn avg_mode_matches_the_combining_pass() {
993 let (w, h, pad) = (48usize, 32usize, 32usize);
994 let (data, stride, origin) = ramp_plane(w, h, pad);
995 let r = plane(&data, stride, origin, w, h, pad);
996 let mut fused = [0u8; 256];
997 let mut p0 = [0u8; 256];
998 let mut p1 = [0u8; 256];
999 let mut out = [0u8; 256];
1000 for mv0 in [[0i16; 2], [7, -3], [-41, 22]] {
1001 for mv1 in [[2i16; 2], [5, 1], [-13, 9]] {
1002 for &(pw, ph) in &[(16usize, 16usize), (8, 8), (4, 4)] {
1003 mc_luma(&r, 4, 4, mv0, pw, ph, pw, &mut p0, Put::Set);
1004 mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut p1, Put::Set);
1005 combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, pw * ph);
1006 // The fused shape: first list into the picture, second
1007 // averaged on top of it.
1008 fused[..pw * ph].copy_from_slice(&p0[..pw * ph]);
1009 mc_luma(&r, 4, 4, mv1, pw, ph, pw, &mut fused, Put::Avg);
1010 assert_eq!(
1011 fused[..pw * ph],
1012 out[..pw * ph],
1013 "mv {mv0:?} + {mv1:?} {pw}x{ph}"
1014 );
1015 }
1016 }
1017 }
1018 }
1019
1020 #[test]
1021 fn chroma_interpolation_matches_equation_8_270() {
1022 let (w, h, pad) = (24usize, 16usize, 16usize);
1023 let (data, stride, origin) = ramp_plane(w, h, pad);
1024 let r = plane(&data, stride, origin, w, h, pad);
1025 let mut ours = [0u8; 64];
1026 for &(px, py) in &[(4i32, 4i32), (0, 0), (-30, -30), (30, 22)] {
1027 for fy in 0..8i16 {
1028 for fx in 0..8i16 {
1029 let mv = [fx, fy];
1030 mc_chroma(&r, px, py, mv, 8, 8, 8, &mut ours, Put::Set);
1031 for row in 0..8i32 {
1032 for col in 0..8i32 {
1033 let s = |dx: i32, dy: i32| -> i32 {
1034 let cx = (px + col + dx).clamp(0, w as i32 - 1) as usize;
1035 let cy = (py + row + dy).clamp(0, h as i32 - 1) as usize;
1036 i32::from(data[origin + cy * stride + cx])
1037 };
1038 let (fx, fy) = (i32::from(fx), i32::from(fy));
1039 let want = ((8 - fx) * (8 - fy) * s(0, 0)
1040 + fx * (8 - fy) * s(1, 0)
1041 + (8 - fx) * fy * s(0, 1)
1042 + fx * fy * s(1, 1)
1043 + 32)
1044 >> 6;
1045 assert_eq!(
1046 i32::from(ours[(row * 8 + col) as usize]),
1047 want,
1048 "({px},{py}) frac ({fx},{fy}) at ({col},{row})"
1049 );
1050 }
1051 }
1052 }
1053 }
1054 }
1055 }
1056
1057 #[test]
1058 fn weighted_combination_follows_8_4_2_3() {
1059 let p0 = [100u8; 4];
1060 let p1 = [200u8; 4];
1061 let mut out = [0u8; 4];
1062 combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, 4);
1063 assert_eq!(out, [150; 4]);
1064 // Explicit, single list: ((100 * 2 + 2) >> 2) + 5 = 55.
1065 let w = Weights {
1066 log_wd: 2,
1067 w: [2, 3],
1068 o: [5, -5],
1069 };
1070 combine(&mut out, &p0, &p1, true, false, &w, 4);
1071 assert_eq!(out, [55; 4]);
1072 // Explicit, both lists: ((100*2 + 200*3 + 4) >> 3) + ((5 - 5 + 1) >> 1).
1073 combine(&mut out, &p0, &p1, true, true, &w, 4);
1074 assert_eq!(out, [100; 4]);
1075 // logWD 0 skips the rounding term entirely.
1076 let w0 = Weights {
1077 log_wd: 0,
1078 w: [2, 1],
1079 o: [3, 0],
1080 };
1081 combine(&mut out, &p0, &p1, true, false, &w0, 4);
1082 assert_eq!(out, [203; 4]);
1083 }
1084}