forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mc_tests.rs1137 lines, 34.4 KiBHistoryRawDownload
1//! Tests of the motion compensation: hand-computed values for every fraction,
2//! edge clamping, weighted prediction, a per-sample reference model compared on
3//! random blocks, and a 1080p timing run.
4
5use crate::dec::cu_syntax::Motion;
6use crate::dec::mc::{
7 Block, McScratch, PlaneMut, PlaneRef, RefPicture, interp_chroma, interp_luma, predict_pu,
8};
9use crate::dec::weighted::{ExplicitWeights, Weight, store};
10use ec_h265_syntax::{PredWeightTable, WeightEntry};
11
12/// A plane of `w x h` samples from `f(x, y)`, stride `w`.
13fn plane_from(w: usize, h: usize, bd: u32, f: impl Fn(usize, usize) -> u16) -> Vec<u16> {
14 (0..h)
15 .flat_map(|y| (0..w).map(move |x| (x, y)))
16 .map(|(x, y)| f(x, y))
17 .map(|v| v.min((1 << bd) - 1))
18 .collect()
19}
20
21fn view(samples: &[u16], w: usize, h: usize, bd: u32) -> PlaneRef<'_> {
22 PlaneRef {
23 samples,
24 stride: w,
25 width: w,
26 height: h,
27 bit_depth: bd,
28 }
29}
30
31fn motion(pred_flags: [bool; 2], ref_idx: [i8; 2], mv: [[i32; 2]; 2]) -> Motion {
32 Motion {
33 pred_flags,
34 ref_idx,
35 mv,
36 }
37}
38
39/// A 16x16 luma plane that is zero except for `value` at (8, 8).
40fn impulse16(value: u16) -> Vec<u16> {
41 plane_from(16, 16, 10, |x, y| if (x, y) == (8, 8) { value } else { 0 })
42}
43
44#[test]
45fn luma_impulse_fractions_8bit_hand_values() {
46 // Impulse of 100 at column 8; the block starts at column 4 on row 8, so output
47 // j reads the impulse with tap index 7 - j. shift1 = 0 at 8 bits.
48 let p = impulse16(100);
49 let pl = view(&p, 16, 16, 8);
50 let blk = Block {
51 x: 4,
52 y: 8,
53 width: 4,
54 height: 1,
55 };
56 let mut scratch = McScratch::new();
57 let mut out = [0i32; 4];
58 let cases: [(i32, [i32; 4]); 3] = [
59 (1, [0, 100, -500, 1700]),
60 (2, [-100, 400, -1100, 4000]),
61 (3, [-100, 400, -1000, 5800]),
62 ];
63 for (frac, want) in cases {
64 interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap();
65 assert_eq!(out, want, "luma horizontal fraction {frac}");
66 }
67 // Full-sample position: the impulse shifted by shift3 = 14 - 8 = 6.
68 let full = Block {
69 x: 8,
70 y: 8,
71 width: 1,
72 height: 1,
73 };
74 interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap();
75 assert_eq!(out[0], 100 << 6);
76}
77
78#[test]
79fn luma_impulse_fractions_10bit_hand_values() {
80 // shift1 = 2 at 10 bits, so each tap sum is divided by 4 (exact here).
81 let p = impulse16(1000);
82 let pl = view(&p, 16, 16, 10);
83 let blk = Block {
84 x: 4,
85 y: 8,
86 width: 4,
87 height: 1,
88 };
89 let mut scratch = McScratch::new();
90 let mut out = [0i32; 4];
91 let cases: [(i32, [i32; 4]); 3] = [
92 (1, [0, 250, -1250, 4250]),
93 (2, [-250, 1000, -2750, 10000]),
94 (3, [-250, 1000, -2500, 14500]),
95 ];
96 for (frac, want) in cases {
97 interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap();
98 assert_eq!(out, want, "10-bit luma horizontal fraction {frac}");
99 }
100 let full = Block {
101 x: 8,
102 y: 8,
103 width: 1,
104 height: 1,
105 };
106 interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap();
107 assert_eq!(out[0], 1000 << 4, "10-bit full sample shift3 = 4");
108}
109
110#[test]
111fn luma_vertical_only_matches_horizontal_by_symmetry() {
112 let p = impulse16(100);
113 let pl = view(&p, 16, 16, 8);
114 // Block column 8, rows 4..8: output row k reads the impulse at tap 7 - k.
115 let blk = Block {
116 x: 8,
117 y: 4,
118 width: 1,
119 height: 4,
120 };
121 let mut scratch = McScratch::new();
122 let mut out = [0i32; 4];
123 interp_luma(&pl, blk, [0, 1], &mut scratch, &mut out).unwrap();
124 assert_eq!(out, [0, 100, -500, 1700]);
125 interp_luma(&pl, blk, [0, 3], &mut scratch, &mut out).unwrap();
126 assert_eq!(out, [-100, 400, -1000, 5800]);
127}
128
129#[test]
130fn luma_two_dimensional_hand_values() {
131 // 10 bits, impulse 4096 at (8, 8), block at (4, 4), fractions (2, 2).
132 // Horizontal pass on the impulse row gives tmp = [-1024, 4096, -11264, 40960]
133 // (shift1 = 2), and the vertical pass with shift2 = 6 yields the 4x4 block.
134 // Built raw: plane_from would clamp the impulse to the 10-bit range.
135 let mut p = vec![0u16; 16 * 16];
136 p[8 * 16 + 8] = 4096;
137 let pl = view(&p, 16, 16, 10);
138 let blk = Block {
139 x: 4,
140 y: 4,
141 width: 4,
142 height: 4,
143 };
144 let mut scratch = McScratch::new();
145 let mut out = [0i32; 16];
146 interp_luma(&pl, blk, [2, 2], &mut scratch, &mut out).unwrap();
147 assert_eq!(
148 out,
149 [
150 16, -64, 176, -640, //
151 -64, 256, -704, 2560, //
152 176, -704, 1936, -7040, //
153 -640, 2560, -7040, 25600,
154 ]
155 );
156}
157
158#[test]
159fn chroma_impulse_fractions_hand_values() {
160 // 8 bits, impulse 100 at (8, 8) in the chroma plane; block at column 5 (so
161 // output j reads tap 4 - j), the four taps that land in range being j = 1..=3.
162 let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 });
163 let pl = view(&p, 16, 16, 8);
164 let blk = Block {
165 x: 5,
166 y: 8,
167 width: 4,
168 height: 1,
169 };
170 let mut scratch = McScratch::new();
171 let mut out = [0i32; 4];
172 let cases: [(i32, [i32; 4]); 7] = [
173 (1, [0, -200, 1000, 5800]),
174 (2, [0, -200, 1600, 5400]),
175 (3, [0, -400, 2800, 4600]),
176 (4, [0, -400, 3600, 3600]),
177 (5, [0, -600, 4600, 2800]),
178 (6, [0, -400, 5400, 1600]),
179 (7, [0, -200, 5800, 1000]),
180 ];
181 for (frac, want) in cases {
182 interp_chroma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap();
183 assert_eq!(out, want, "chroma horizontal eighth {frac}");
184 }
185 let full = Block {
186 x: 8,
187 y: 8,
188 width: 1,
189 height: 1,
190 };
191 interp_chroma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap();
192 assert_eq!(out[0], 100 << 6);
193}
194
195#[test]
196fn chroma_motion_vector_splits_integer_and_eighth() {
197 // A chroma mv of 8 + 3 eighths moves one whole sample plus the eighth-3 filter.
198 let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 });
199 let pl = view(&p, 16, 16, 8);
200 let mut scratch = McScratch::new();
201 let mut a = [0i32; 4];
202 let mut b = [0i32; 4];
203 let start = Block {
204 x: 4,
205 y: 8,
206 width: 4,
207 height: 1,
208 };
209 interp_chroma(&pl, start, [11, 0], &mut scratch, &mut a).unwrap();
210 let shifted = Block {
211 x: 5,
212 y: 8,
213 width: 4,
214 height: 1,
215 };
216 interp_chroma(&pl, shifted, [3, 0], &mut scratch, &mut b).unwrap();
217 assert_eq!(a, b);
218}
219
220#[test]
221fn luma_edges_clamp_at_all_four_borders() {
222 // v(x, y) = 10 * y + x on an 8x8 plane: every border has distinct values.
223 let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16);
224 let pl = view(&p, 8, 8, 8);
225 let mut scratch = McScratch::new();
226 let mut out = [0i32; 16];
227 // Far left: every column reads column 0, so each row is v(0, y) << 6.
228 let blk = Block {
229 x: 0,
230 y: 0,
231 width: 4,
232 height: 4,
233 };
234 interp_luma(&pl, blk, [-4000, 0], &mut scratch, &mut out).unwrap();
235 for r in 0..4 {
236 for c in 0..4 {
237 assert_eq!(out[r * 4 + c], (10 * r as i32) << 6, "far left");
238 }
239 }
240 // Far right: every column reads column 7.
241 let blk = Block {
242 x: 4,
243 y: 0,
244 width: 4,
245 height: 4,
246 };
247 interp_luma(&pl, blk, [4000, 0], &mut scratch, &mut out).unwrap();
248 for r in 0..4 {
249 for c in 0..4 {
250 assert_eq!(out[r * 4 + c], (10 * r as i32 + 7) << 6, "far right");
251 }
252 }
253 // Far up: every row reads row 0, so each column is v(x, 0) = x.
254 let blk = Block {
255 x: 4,
256 y: 0,
257 width: 4,
258 height: 4,
259 };
260 interp_luma(&pl, blk, [0, -4000], &mut scratch, &mut out).unwrap();
261 for r in 0..4 {
262 for c in 0..4 {
263 assert_eq!(out[r * 4 + c], (4 + c as i32) << 6, "far up");
264 }
265 }
266 // Far down: every row reads row 7.
267 let blk = Block {
268 x: 4,
269 y: 4,
270 width: 4,
271 height: 4,
272 };
273 interp_luma(&pl, blk, [0, 4000], &mut scratch, &mut out).unwrap();
274 for r in 0..4 {
275 for c in 0..4 {
276 assert_eq!(out[r * 4 + c], ((70 + 4 + c) as i32) << 6, "far down");
277 }
278 }
279 // Far outside in both directions, to each corner.
280 let corners = [
281 (0, 0, -4000, -4000, 0),
282 (4, 0, 4000, -4000, 7),
283 (0, 4, -4000, 4000, 70),
284 (4, 4, 4000, 4000, 77),
285 ];
286 for (x, y, mx, my, want) in corners {
287 let blk = Block {
288 x,
289 y,
290 width: 4,
291 height: 4,
292 };
293 interp_luma(&pl, blk, [mx, my], &mut scratch, &mut out).unwrap();
294 assert!(out.iter().all(|&v| v == want << 6), "corner {want}");
295 }
296}
297
298#[test]
299fn luma_fractional_edges_clamp_to_the_border_sample() {
300 // A fractional mv far outside reads one border column (or row) only, so the
301 // filter sums to 64 times that border sample.
302 let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16);
303 let pl = view(&p, 8, 8, 8);
304 let mut scratch = McScratch::new();
305 let mut out = [0i32; 16];
306 let blk = Block {
307 x: 0,
308 y: 0,
309 width: 4,
310 height: 4,
311 };
312 // -4001 quarter samples: integer part -1001, fraction 3.
313 interp_luma(&pl, blk, [-4001, 0], &mut scratch, &mut out).unwrap();
314 for r in 0..4 {
315 assert!(
316 out[r * 4..r * 4 + 4]
317 .iter()
318 .all(|&v| v == 64 * 10 * r as i32)
319 );
320 }
321 interp_luma(&pl, blk, [0, -4001], &mut scratch, &mut out).unwrap();
322 for c in 0..4 {
323 assert!((0..4).all(|r| out[r * 4 + c] == 64 * c as i32));
324 }
325}
326
327#[test]
328fn chroma_edges_clamp_at_all_four_borders() {
329 let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16);
330 let pl = view(&p, 8, 8, 8);
331 let mut scratch = McScratch::new();
332 let mut out = [0i32; 4];
333 let blk = Block {
334 x: 0,
335 y: 0,
336 width: 2,
337 height: 2,
338 };
339 // Eighth-sample mv of -8001: integer part -1001, fraction 7.
340 interp_chroma(&pl, blk, [-8001, 0], &mut scratch, &mut out).unwrap();
341 assert_eq!(out, [0, 0, 640, 640]);
342 let blk = Block {
343 x: 6,
344 y: 6,
345 width: 2,
346 height: 2,
347 };
348 interp_chroma(&pl, blk, [8000, 8000], &mut scratch, &mut out).unwrap();
349 assert!(out.iter().all(|&v| v == 77 << 6));
350}
351
352#[test]
353fn default_uni_and_bi_hand_values() {
354 let mut buf = [0u16; 4];
355 let blk = Block {
356 x: 0,
357 y: 0,
358 width: 4,
359 height: 1,
360 };
361 // 8 bits: shift1 = 6 for uni, shift2 = 7 for bi.
362 let mut dst = PlaneMut {
363 samples: &mut buf,
364 stride: 4,
365 bit_depth: 8,
366 origin: 0,
367 };
368 store(
369 &mut dst,
370 blk,
371 [Some(&[6400, -100, 16320, 16384]), None],
372 None,
373 )
374 .unwrap();
375 assert_eq!(buf, [100, 0, 255, 255]);
376
377 let mut buf = [0u16; 2];
378 let blk2 = Block {
379 x: 0,
380 y: 0,
381 width: 2,
382 height: 1,
383 };
384 let mut dst = PlaneMut {
385 samples: &mut buf,
386 stride: 2,
387 bit_depth: 8,
388 origin: 0,
389 };
390 store(
391 &mut dst,
392 blk2,
393 [Some(&[6400, 6400]), Some(&[6400, 6464])],
394 None,
395 )
396 .unwrap();
397 assert_eq!(buf, [100, 101]);
398
399 // 10 bits: shift1 = 4 for uni, shift2 = 5 for bi.
400 let mut buf = [0u16; 3];
401 let blk3 = Block {
402 x: 0,
403 y: 0,
404 width: 3,
405 height: 1,
406 };
407 let mut dst = PlaneMut {
408 samples: &mut buf,
409 stride: 3,
410 bit_depth: 10,
411 origin: 0,
412 };
413 store(&mut dst, blk3, [Some(&[6400, 16368, 16384]), None], None).unwrap();
414 assert_eq!(buf, [400, 1023, 1023]);
415 let mut dst = PlaneMut {
416 samples: &mut buf,
417 stride: 3,
418 bit_depth: 10,
419 origin: 0,
420 };
421 store(
422 &mut dst,
423 blk3,
424 [Some(&[6400, 0, 0]), Some(&[12800, 0, 0])],
425 None,
426 )
427 .unwrap();
428 assert_eq!(buf[0], 600);
429}
430
431#[test]
432fn explicit_uni_and_bi_hand_values_8bit() {
433 let blk = Block {
434 x: 0,
435 y: 0,
436 width: 1,
437 height: 1,
438 };
439 let mut buf = [0u16; 1];
440 // denom 2, w = 3, o = 5: ((6400*3 + 128) >> 8) + 5 = 75 + 5.
441 let mut dst = PlaneMut {
442 samples: &mut buf,
443 stride: 1,
444 bit_depth: 8,
445 origin: 0,
446 };
447 let w = [Weight { w: 3, o: 5 }, Weight::default()];
448 store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap();
449 assert_eq!(buf[0], 80);
450
451 // Negative weight -1 and offset 200: ((-6400 + 128) >> 8) + 200 = -25 + 200.
452 let w = [Weight { w: -1, o: 200 }, Weight::default()];
453 let mut dst = PlaneMut {
454 samples: &mut buf,
455 stride: 1,
456 bit_depth: 8,
457 origin: 0,
458 };
459 store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap();
460 assert_eq!(buf[0], 175);
461
462 // Negative offset clipping at zero: w = -1, o = -200 gives -225 -> 0.
463 let w = [Weight { w: -1, o: -200 }, Weight::default()];
464 let mut dst = PlaneMut {
465 samples: &mut buf,
466 stride: 1,
467 bit_depth: 8,
468 origin: 0,
469 };
470 store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap();
471 assert_eq!(buf[0], 0);
472
473 // Bi: w0 = -2, o0 = -3 with p0 = 6400; w1 = 6, o1 = 7 with p1 = 12800.
474 // (-12800 + 76800 + ((-3 + 7 + 1) << 8)) >> 9 = 127.
475 let w = [Weight { w: -2, o: -3 }, Weight { w: 6, o: 7 }];
476 let mut dst = PlaneMut {
477 samples: &mut buf,
478 stride: 1,
479 bit_depth: 8,
480 origin: 0,
481 };
482 store(&mut dst, blk, [Some(&[6400]), Some(&[12800])], Some((2, w))).unwrap();
483 assert_eq!(buf[0], 127);
484}
485
486#[test]
487fn explicit_uni_hand_value_10bit_with_scaled_offset() {
488 // The caller scales offsets by 1 << (BitDepth - 8); 5 << 2 = 20.
489 // shift1 = 4 at 10 bits, log2WD = 2 + 4 = 6: ((6400*3 + 32) >> 6) + 20 = 300 + 20.
490 let blk = Block {
491 x: 0,
492 y: 0,
493 width: 1,
494 height: 1,
495 };
496 let mut buf = [0u16; 1];
497 let mut dst = PlaneMut {
498 samples: &mut buf,
499 stride: 1,
500 bit_depth: 10,
501 origin: 0,
502 };
503 let w = [Weight { w: 3, o: 20 }, Weight::default()];
504 store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap();
505 assert_eq!(buf[0], 320);
506}
507
508#[test]
509fn weight_table_derivation_with_chroma_offsets() {
510 // luma denom 2, chroma denom 3. Entry 0: luma delta -1 offset 5; chroma deltas
511 // 3 and -2 with the ChromaOffset values the parser already derived (-7, 9).
512 // Entry 1 has no flags, so every weight is the default and offsets are 0.
513 let table = PredWeightTable {
514 luma_log2_weight_denom: 2,
515 delta_chroma_log2_weight_denom: 1,
516 l0: vec![
517 WeightEntry {
518 luma: Some((-1, 5)),
519 chroma: Some([(3, -7), (-2, 9)]),
520 },
521 WeightEntry::default(),
522 ],
523 l1: vec![],
524 };
525 let ew = ExplicitWeights::from_table(&table, 8, 8, false).unwrap();
526 assert_eq!(ew.log2_denom, [2, 3, 3]);
527 assert_eq!(
528 ew.entries[0][0],
529 [
530 Weight { w: 3, o: 5 },
531 Weight { w: 11, o: -7 },
532 Weight { w: 6, o: 9 },
533 ]
534 );
535 assert_eq!(
536 ew.entries[0][1],
537 [
538 Weight { w: 4, o: 0 },
539 Weight { w: 8, o: 0 },
540 Weight { w: 8, o: 0 }
541 ]
542 );
543 // At 10 bits every offset is scaled by 4.
544 let ew10 = ExplicitWeights::from_table(&table, 10, 10, false).unwrap();
545 assert_eq!(ew10.entries[0][0][0], Weight { w: 3, o: 20 });
546 assert_eq!(ew10.entries[0][0][1].o, -28);
547 assert_eq!(ew10.entries[0][0][2].o, 36);
548 // A coded weight delta outside -128..=127 is corrupt.
549 let bad = PredWeightTable {
550 luma_log2_weight_denom: 0,
551 delta_chroma_log2_weight_denom: 0,
552 l0: vec![WeightEntry {
553 luma: Some((200, 0)),
554 chroma: None,
555 }],
556 l1: vec![],
557 };
558 assert!(ExplicitWeights::from_table(&bad, 8, 8, false).is_err());
559}
560
561#[test]
562fn predict_pu_constant_planes_recover_the_value() {
563 // A constant picture predicts itself for any motion and any weighting that is
564 // the identity: default bi of 100 and 100 gives 100.
565 let bd = 8;
566 let luma = plane_from(64, 64, bd, |_, _| 100);
567 let chroma = plane_from(32, 32, bd, |_, _| 100);
568 let pic: RefPicture<'_> = [
569 view(&luma, 64, 64, bd),
570 view(&chroma, 32, 32, bd),
571 view(&chroma, 32, 32, bd),
572 ];
573 let refs = [&[pic][..], &[pic][..]];
574 let mut oy = vec![0u16; 64 * 64];
575 let mut ou = vec![0u16; 32 * 32];
576 let mut ov = vec![0u16; 32 * 32];
577 let mut out = [
578 PlaneMut {
579 samples: &mut oy,
580 stride: 64,
581 bit_depth: bd,
582 origin: 0,
583 },
584 PlaneMut {
585 samples: &mut ou,
586 stride: 32,
587 bit_depth: bd,
588 origin: 0,
589 },
590 PlaneMut {
591 samples: &mut ov,
592 stride: 32,
593 bit_depth: bd,
594 origin: 0,
595 },
596 ];
597 let mut scratch = McScratch::new();
598 let pu = Block {
599 x: 16,
600 y: 8,
601 width: 8,
602 height: 4,
603 };
604 let m = motion([true, true], [0, 0], [[-13, 7], [22, -5]]);
605 predict_pu(refs, &m, None, pu, &mut out, &mut scratch).unwrap();
606 for (plane, stride, w, h, x, y) in [
607 (&oy, 64, 8, 4, 16, 8),
608 (&ou, 32, 4, 2, 8, 4),
609 (&ov, 32, 4, 2, 8, 4),
610 ] {
611 for r in 0..h {
612 for c in 0..w {
613 assert_eq!(plane[(y + r) * stride + x + c], 100);
614 }
615 }
616 }
617}
618
619#[test]
620fn predict_pu_rejects_bad_input() {
621 let bd = 8;
622 let luma = plane_from(16, 16, bd, |_, _| 1);
623 let chroma = plane_from(8, 8, bd, |_, _| 1);
624 let pic: RefPicture<'_> = [
625 view(&luma, 16, 16, bd),
626 view(&chroma, 8, 8, bd),
627 view(&chroma, 8, 8, bd),
628 ];
629 let refs = [&[pic][..], &[][..]];
630 let mut oy = vec![0u16; 16 * 16];
631 let mut ou = vec![0u16; 8 * 8];
632 let mut ov = vec![0u16; 8 * 8];
633 let mut out = [
634 PlaneMut {
635 samples: &mut oy,
636 stride: 16,
637 bit_depth: bd,
638 origin: 0,
639 },
640 PlaneMut {
641 samples: &mut ou,
642 stride: 8,
643 bit_depth: bd,
644 origin: 0,
645 },
646 PlaneMut {
647 samples: &mut ov,
648 stride: 8,
649 bit_depth: bd,
650 origin: 0,
651 },
652 ];
653 let mut scratch = McScratch::new();
654 let pu = Block {
655 x: 0,
656 y: 0,
657 width: 8,
658 height: 8,
659 };
660 // No list in use.
661 let none = motion([false, false], [0, 0], [[0; 2]; 2]);
662 assert!(predict_pu(refs, &none, None, pu, &mut out, &mut scratch).is_err());
663 // refIdxL1 names a picture list 1 does not have.
664 let l1 = motion([false, true], [0, 0], [[0; 2]; 2]);
665 assert!(predict_pu(refs, &l1, None, pu, &mut out, &mut scratch).is_err());
666 // A rectangle past the plane edge.
667 let off = Block {
668 x: 12,
669 y: 0,
670 width: 8,
671 height: 8,
672 };
673 let ok = motion([true, false], [0, 0], [[0; 2]; 2]);
674 assert!(predict_pu(refs, &ok, None, off, &mut out, &mut scratch).is_err());
675}
676
677// ---------------------------------------------------------------------------
678// Reference model: a deliberately naive transcription of 8.5.3.3 per sample.
679// It shares no code with the optimised path and copies the filter tables from
680// the spec again, so a transcription error in either shows up as a mismatch.
681// ---------------------------------------------------------------------------
682
683mod naive {
684 use crate::dec::cu_syntax::Motion;
685 use crate::dec::mc::{Block, PlaneRef, RefPicture};
686 use crate::dec::weighted::ExplicitWeights;
687
688 /// Table 8-11, luma. Row 0 is unused.
689 const LUMA: [[i64; 8]; 4] = [
690 [0, 0, 0, 64, 0, 0, 0, 0],
691 [-1, 4, -10, 58, 17, -5, 1, 0],
692 [-1, 4, -11, 40, 40, -11, 4, -1],
693 [0, 1, -5, 17, 58, -10, 4, -1],
694 ];
695 /// Table 8-12, chroma. Row 0 is unused.
696 const CHROMA: [[i64; 4]; 8] = [
697 [0, 64, 0, 0],
698 [-2, 58, 10, -2],
699 [-4, 54, 16, -2],
700 [-6, 46, 28, -4],
701 [-4, 36, 36, -4],
702 [-4, 28, 46, -6],
703 [-2, 16, 54, -4],
704 [-2, 10, 58, -2],
705 ];
706
707 /// `ref[Clip3(0, W-1, x)][Clip3(0, H-1, y)]`, one sample.
708 fn sample(p: &PlaneRef<'_>, x: i64, y: i64) -> i64 {
709 let cx = x.clamp(0, p.width as i64 - 1) as usize;
710 let cy = y.clamp(0, p.height as i64 - 1) as usize;
711 i64::from(p.samples[cy * p.stride + cx])
712 }
713
714 /// One predSampleLX at integer position (xi, yi) with fractions (fx, fy).
715 fn interp(p: &PlaneRef<'_>, xi: i64, yi: i64, fx: usize, fy: usize, luma: bool) -> i64 {
716 let bd = i64::from(p.bit_depth);
717 let shift1 = (bd - 8).min(4);
718 let shift2 = 6;
719 let shift3 = (14 - bd).max(2);
720 let taps: i64 = if luma { 8 } else { 4 };
721 let pad = taps / 2 - 1;
722 let coef = |frac: usize, i: i64| -> i64 {
723 if luma {
724 LUMA[frac][i as usize]
725 } else {
726 CHROMA[frac][i as usize]
727 }
728 };
729 if fx == 0 && fy == 0 {
730 return sample(p, xi, yi) << shift3;
731 }
732 if fy == 0 {
733 let mut s = 0;
734 for i in 0..taps {
735 s += coef(fx, i) * sample(p, xi + i - pad, yi);
736 }
737 return s >> shift1;
738 }
739 if fx == 0 {
740 let mut s = 0;
741 for i in 0..taps {
742 s += coef(fy, i) * sample(p, xi, yi + i - pad);
743 }
744 return s >> shift1;
745 }
746 let mut s = 0;
747 for n in 0..taps {
748 let mut temp = 0;
749 for i in 0..taps {
750 temp += coef(fx, i) * sample(p, xi + i - pad, yi + n - pad);
751 }
752 s += coef(fy, n) * (temp >> shift1);
753 }
754 s >> shift2
755 }
756
757 /// The weighted sample prediction of 8.5.3.3.4 for one sample.
758 /// `preds[list]` is `Some(predSamplesLX)` for each list in use.
759 fn weight(bd: i64, preds: [Option<i64>; 2], explicit: Option<(i64, [(i64, i64); 2])>) -> i64 {
760 let max = (1 << bd) - 1;
761 let shift1 = 14 - bd;
762 let clip = |v: i64| v.clamp(0, max);
763 match (preds, explicit) {
764 ([Some(p0), Some(p1)], None) => {
765 let shift2 = 15 - bd;
766 clip((p0 + p1 + (1 << (shift2 - 1))) >> shift2)
767 }
768 ([Some(p0), Some(p1)], Some((denom, [(w0, o0), (w1, o1)]))) => {
769 let log2wd = denom + shift1;
770 clip((p0 * w0 + p1 * w1 + ((o0 + o1 + 1) << log2wd)) >> (log2wd + 1))
771 }
772 ([Some(p), None], None) | ([None, Some(p)], None) => {
773 clip((p + (1 << (shift1 - 1))) >> shift1)
774 }
775 ([Some(p), None], Some((denom, [(w, o), _]))) => {
776 let log2wd = denom + shift1;
777 clip(if log2wd >= 1 {
778 ((p * w + (1 << (log2wd - 1))) >> log2wd) + o
779 } else {
780 p * w + o
781 })
782 }
783 ([None, Some(p)], Some((denom, [_, (w, o)]))) => {
784 let log2wd = denom + shift1;
785 clip(if log2wd >= 1 {
786 ((p * w + (1 << (log2wd - 1))) >> log2wd) + o
787 } else {
788 p * w + o
789 })
790 }
791 _ => panic!("naive model: no prediction"),
792 }
793 }
794
795 /// The final samples of one PU component, row-major `blk.width * blk.height`.
796 pub fn predict_component(
797 refs: [&[RefPicture<'_>]; 2],
798 motion: &Motion,
799 weights: Option<&ExplicitWeights>,
800 blk: Block,
801 comp: usize,
802 ) -> Vec<i64> {
803 let luma = comp == 0;
804 let bd = i64::from(
805 refs.iter()
806 .enumerate()
807 .find_map(|(l, r)| {
808 motion.pred_flags[l].then(|| r[motion.ref_idx[l] as usize][comp].bit_depth)
809 })
810 .unwrap(),
811 );
812 let mut out = Vec::with_capacity(blk.width * blk.height);
813 for r in 0..blk.height {
814 for c in 0..blk.width {
815 let mut preds = [None, None];
816 let mut wts = [(0i64, 0i64); 2];
817 for list in 0..2 {
818 if !motion.pred_flags[list] {
819 continue;
820 }
821 let pic = &refs[list][motion.ref_idx[list] as usize];
822 let p = &pic[comp];
823 let mv = motion.mv[list];
824 let (xi, yi, fx, fy) = if luma {
825 (
826 blk.x as i64 + i64::from(mv[0] >> 2) + c as i64,
827 blk.y as i64 + i64::from(mv[1] >> 2) + r as i64,
828 (mv[0] & 3) as usize,
829 (mv[1] & 3) as usize,
830 )
831 } else {
832 (
833 blk.x as i64 + i64::from(mv[0] >> 3) + c as i64,
834 blk.y as i64 + i64::from(mv[1] >> 3) + r as i64,
835 (mv[0] & 7) as usize,
836 (mv[1] & 7) as usize,
837 )
838 };
839 preds[list] = Some(interp(p, xi, yi, fx, fy, luma));
840 if let Some(ew) = weights {
841 let w = ew.entries[list][motion.ref_idx[list] as usize][comp];
842 wts[list] = (i64::from(w.w), i64::from(w.o));
843 }
844 }
845 let explicit = weights.map(|ew| (i64::from(ew.log2_denom[comp]), wts));
846 out.push(weight(bd, preds, explicit));
847 }
848 }
849 out
850 }
851}
852
853/// SplitMix64: a fixed-seed generator, so every run sees the same blocks.
854struct Rng(u64);
855
856impl Rng {
857 fn next_u64(&mut self) -> u64 {
858 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
859 let mut z = self.0;
860 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
861 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
862 z ^ (z >> 31)
863 }
864
865 fn below(&mut self, n: u64) -> u64 {
866 self.next_u64() % n
867 }
868
869 fn range(&mut self, lo: i64, hi: i64) -> i64 {
870 lo + (self.next_u64() % (hi - lo + 1) as u64) as i64
871 }
872}
873
874/// An owned picture: Y, Cb, Cr planes at the 4:2:0 sizes of a `w x h` luma picture.
875struct Pic {
876 planes: [Vec<u16>; 3],
877 w: usize,
878 h: usize,
879 bd: u32,
880}
881
882impl Pic {
883 fn random(rng: &mut Rng, w: usize, h: usize, bd: u32) -> Pic {
884 let max = (1u64 << bd) - 1;
885 let mut fill =
886 |n: usize| -> Vec<u16> { (0..n).map(|_| rng.below(max + 1) as u16).collect() };
887 let planes = [fill(w * h), fill(w * h / 4), fill(w * h / 4)];
888 Pic { planes, w, h, bd }
889 }
890
891 fn view(&self) -> RefPicture<'_> {
892 let dims = [
893 (self.w, self.h),
894 (self.w / 2, self.h / 2),
895 (self.w / 2, self.h / 2),
896 ];
897 std::array::from_fn(|c| PlaneRef {
898 samples: &self.planes[c],
899 stride: dims[c].0,
900 width: dims[c].0,
901 height: dims[c].1,
902 bit_depth: self.bd,
903 })
904 }
905}
906
907#[test]
908fn random_blocks_match_the_reference_model() {
909 let mut rng = Rng(0x5eed_1234_abcd_0001);
910 let mut scratch = McScratch::new();
911 let mut checked = 0usize;
912 let mut sizes_8x4_or_4x8 = 0usize;
913 let mut uni = 0usize;
914 let mut bi = 0usize;
915 let mut explicit = 0usize;
916 for case in 0..10_000 {
917 let bd = if rng.below(2) == 0 { 8 } else { 10 };
918 let pw = 8 * rng.range(8, 28) as usize;
919 let ph = 8 * rng.range(8, 28) as usize;
920 // Sizes 4..=64 in steps of 4; every eighth case is forced to 8x4 or 4x8.
921 let (w, h) = if case % 8 == 0 {
922 if rng.below(2) == 0 { (8, 4) } else { (4, 8) }
923 } else {
924 (4 * rng.range(1, 16) as usize, 4 * rng.range(1, 16) as usize)
925 };
926 if (w, h) == (8, 4) || (w, h) == (4, 8) {
927 sizes_8x4_or_4x8 += 1;
928 }
929 let x = 4 * rng.below(((pw - w) / 4 + 1) as u64) as usize;
930 let y = 4 * rng.below(((ph - h) / 4 + 1) as u64) as usize;
931
932 let lists: [Vec<Pic>; 2] = [
933 (0..rng.range(1, 3))
934 .map(|_| Pic::random(&mut rng, pw, ph, bd))
935 .collect(),
936 (0..rng.range(1, 3))
937 .map(|_| Pic::random(&mut rng, pw, ph, bd))
938 .collect(),
939 ];
940 let views: [Vec<RefPicture<'_>>; 2] = [
941 lists[0].iter().map(Pic::view).collect(),
942 lists[1].iter().map(Pic::view).collect(),
943 ];
944
945 let pred_flags = match rng.below(3) {
946 0 => [true, false],
947 1 => [false, true],
948 _ => [true, true],
949 };
950 if pred_flags[0] && pred_flags[1] {
951 bi += 1;
952 } else {
953 uni += 1;
954 }
955 let mut ref_idx = [0i8; 2];
956 let mut mv = [[0i32; 2]; 2];
957 let reach = 4 * (pw.max(ph) as i64 + 96);
958 for (list, mv_list) in mv.iter_mut().enumerate() {
959 ref_idx[list] = rng.below(lists[list].len() as u64) as i8;
960 *mv_list = std::array::from_fn(|_| {
961 if rng.below(2) == 0 {
962 rng.range(-reach, reach) as i32
963 } else {
964 rng.range(-40, 40) as i32
965 }
966 });
967 }
968 let m = Motion {
969 pred_flags,
970 ref_idx,
971 mv,
972 };
973
974 let weights = if rng.below(2) == 0 {
975 None
976 } else {
977 explicit += 1;
978 let shift = bd - 8;
979 let denom: [u32; 3] = [
980 rng.below(8) as u32,
981 rng.below(8) as u32,
982 rng.below(8) as u32,
983 ];
984 let mut entries: [Vec<[Weight; 3]>; 2] = [Vec::new(), Vec::new()];
985 for (list, slot) in entries.iter_mut().enumerate() {
986 *slot = (0..lists[list].len())
987 .map(|_| {
988 std::array::from_fn(|_| Weight {
989 w: rng.range(-128, 127) as i32,
990 o: (rng.range(-128, 127) as i32) << shift,
991 })
992 })
993 .collect();
994 }
995 Some(ExplicitWeights {
996 log2_denom: denom,
997 entries,
998 })
999 };
1000
1001 let pu = Block {
1002 x,
1003 y,
1004 width: w,
1005 height: h,
1006 };
1007 let mut planes = [
1008 vec![0u16; pw * ph],
1009 vec![0u16; pw * ph / 4],
1010 vec![0u16; pw * ph / 4],
1011 ];
1012 let dims = [(pw, ph), (pw / 2, ph / 2), (pw / 2, ph / 2)];
1013 {
1014 let [a, b, c] = &mut planes;
1015 let mut out = [
1016 PlaneMut {
1017 samples: a,
1018 stride: pw,
1019 bit_depth: bd,
1020 origin: 0,
1021 },
1022 PlaneMut {
1023 samples: b,
1024 stride: pw / 2,
1025 bit_depth: bd,
1026 origin: 0,
1027 },
1028 PlaneMut {
1029 samples: c,
1030 stride: pw / 2,
1031 bit_depth: bd,
1032 origin: 0,
1033 },
1034 ];
1035 let refs = [&views[0][..], &views[1][..]];
1036 predict_pu(refs, &m, weights.as_ref(), pu, &mut out, &mut scratch).unwrap();
1037 }
1038
1039 let refs = [&views[0][..], &views[1][..]];
1040 for comp in 0..3 {
1041 let blk = if comp == 0 {
1042 pu
1043 } else {
1044 Block {
1045 x: x / 2,
1046 y: y / 2,
1047 width: w / 2,
1048 height: h / 2,
1049 }
1050 };
1051 let want = naive::predict_component(refs, &m, weights.as_ref(), blk, comp);
1052 let stride = dims[comp].0;
1053 for r in 0..blk.height {
1054 for c in 0..blk.width {
1055 let got = i64::from(planes[comp][(blk.y + r) * stride + blk.x + c]);
1056 assert_eq!(
1057 got,
1058 want[r * blk.width + c],
1059 "case {case} bd {bd} comp {comp} pu {pu:?} mv {mv:?} refs {ref_idx:?} flags {pred_flags:?} r {r} c {c}"
1060 );
1061 }
1062 }
1063 }
1064 checked += 1;
1065 }
1066 assert_eq!(checked, 10_000);
1067 eprintln!(
1068 "mc reference model: {checked} random PUs agree ({uni} uni, {bi} bi, {explicit} explicit weighted, {sizes_8x4_or_4x8} of 8x4/4x8)"
1069 );
1070}
1071
1072/// One 1080p frame of 8x8 bi-predicted PUs, luma and 4:2:0 chroma. Timing only;
1073/// run with `--release --nocapture` to see the figure.
1074#[test]
1075fn bench_1080p_bipred_8x8_frame() {
1076 let (pw, ph, bd) = (1920usize, 1080usize, 10u32);
1077 let mut rng = Rng(42);
1078 let pic0 = Pic::random(&mut rng, pw, ph, bd);
1079 let pic1 = Pic::random(&mut rng, pw, ph, bd);
1080 let l0 = [pic0.view()];
1081 let l1 = [pic1.view()];
1082 let mut planes = [
1083 vec![0u16; pw * ph],
1084 vec![0u16; pw * ph / 4],
1085 vec![0u16; pw * ph / 4],
1086 ];
1087 let [a, b, c] = &mut planes;
1088 let mut out = [
1089 PlaneMut {
1090 samples: a,
1091 stride: pw,
1092 bit_depth: bd,
1093 origin: 0,
1094 },
1095 PlaneMut {
1096 samples: b,
1097 stride: pw / 2,
1098 bit_depth: bd,
1099 origin: 0,
1100 },
1101 PlaneMut {
1102 samples: c,
1103 stride: pw / 2,
1104 bit_depth: bd,
1105 origin: 0,
1106 },
1107 ];
1108 let mut scratch = McScratch::new();
1109 let start = std::time::Instant::now();
1110 for by in 0..ph / 8 {
1111 for bx in 0..pw / 8 {
1112 let m = Motion {
1113 pred_flags: [true, true],
1114 ref_idx: [0, 0],
1115 mv: [
1116 [(bx as i32 * 7 % 61) - 30, (by as i32 * 5 % 53) - 26],
1117 [(by as i32 * 3 % 47) - 23, (bx as i32 * 11 % 59) - 29],
1118 ],
1119 };
1120 let pu = Block {
1121 x: bx * 8,
1122 y: by * 8,
1123 width: 8,
1124 height: 8,
1125 };
1126 predict_pu([&l0, &l1], &m, None, pu, &mut out, &mut scratch).unwrap();
1127 }
1128 }
1129 let elapsed = start.elapsed();
1130 let checksum: u64 = planes.iter().flatten().map(|&v| u64::from(v)).sum();
1131 assert!(checksum > 0);
1132 eprintln!(
1133 "bench: 1080p frame, {} bi-pred 8x8 PUs (luma + 4:2:0 chroma): {:.2} ms (checksum {checksum})",
1134 (pw / 8) * (ph / 8),
1135 elapsed.as_secs_f64() * 1e3
1136 );
1137}