forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli4 days ago4021 commits

merge.rs557 lines, 17.8 KiBHistoryRawDownload
1//! Merge mode motion (8.5.3.2.2 to 8.5.3.2.5): the spatial candidates A1, B1, B0,
2//! A0 and B2 with the parallel merge level and the second-partition exclusions, the
3//! temporal candidate, combined bi-predictive candidates for B slices, zero
4//! candidates, and the 8x4 / 4x8 restriction on bi-prediction.
5
6use super::cu_syntax::{CuGeometry, PartMode, PredictionUnit};
7use super::motion_field::{PbMotion, SliceMotion, to16};
8
9/// Table 8-7: `l0CandIdx` for `combIdx` 0 to 11.
10const COMB_L0: [usize; 12] = [0, 1, 0, 2, 1, 2, 0, 3, 1, 3, 2, 3];
11/// Table 8-7: `l1CandIdx` for `combIdx` 0 to 11.
12const COMB_L1: [usize; 12] = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2];
13
14/// The merge motion of one prediction unit: the candidate `merge_idx` selects from
15/// the merge candidate list (8.5.3.2.2).
16pub fn derive_merge(
17 src: &SliceMotion<'_>,
18 cu: &CuGeometry,
19 pu_index: usize,
20 pu: &PredictionUnit,
21) -> PbMotion {
22 let params = src.params;
23 // 8.5.3.2.2: with a parallel merge level above 4x4, every 8x8 coding unit shares
24 // one merge list, derived as if it were a single prediction unit.
25 let single_list = params.log2_par_mrg_level > 2 && cu.size == 8;
26 let (x, y, w, h, part_idx) = if single_list {
27 (cu.x, cu.y, cu.size, cu.size, 0)
28 } else {
29 (pu.x, pu.y, pu.width, pu.height, pu_index)
30 };
31
32 let mut cands = spatial_candidates(src, cu.part_mode, x, y, w, h, part_idx);
33 if let Some(col) = temporal_candidate(src, x, y, w, h) {
34 cands.push(col);
35 }
36 let num_orig = cands.len();
37 let max = params.max_merge_cand;
38 if params.is_b && num_orig > 1 && num_orig < max {
39 combined_candidates(src, &mut cands, num_orig, max);
40 }
41 // 8.5.3.2.5: zero candidates fill the list up to MaxNumMergeCand.
42 let num_ref_idx = if params.is_b {
43 src.lists.l0.len().min(src.lists.l1.len())
44 } else {
45 src.lists.l0.len()
46 };
47 let mut zero_idx = 0;
48 while cands.len() < max {
49 let ref_idx = if zero_idx < num_ref_idx { zero_idx } else { 0 };
50 cands.push(zero_candidate(params.is_b, ref_idx));
51 zero_idx += 1;
52 }
53 let mut chosen = cands
54 .get(usize::from(pu.merge_idx))
55 .copied()
56 .unwrap_or_else(|| zero_candidate(params.is_b, 0));
57
58 // 8.5.3.2.2: an 8x4 or 4x8 prediction unit is not bi-predicted (nOrigPbW + nOrigPbH == 12).
59 if chosen.pred[0] && chosen.pred[1] && pu.width + pu.height == 12 {
60 chosen = PbMotion::new(
61 [true, false],
62 [chosen.ref_idx[0], -1],
63 [chosen.mv[0], [0, 0]],
64 );
65 }
66 chosen
67}
68
69/// The spatial merge candidates (8.5.3.2.3), in list order. A candidate is dropped
70/// when it is unavailable, when it lies in the same parallel merge region as the
71/// block, or when it repeats an earlier candidate that the spec compares it with.
72fn spatial_candidates(
73 src: &SliceMotion<'_>,
74 part: PartMode,
75 x: usize,
76 y: usize,
77 w: usize,
78 h: usize,
79 part_idx: usize,
80) -> Vec<PbMotion> {
81 let (xp, yp) = (x as isize, y as isize);
82 let (wi, hi) = (w as isize, h as isize);
83 let level = src.params.log2_par_mrg_level;
84 // Neighbours in the same merge estimation region are not used.
85 let fetch = |xn: isize, yn: isize| -> Option<PbMotion> {
86 if xp >> level == xn >> level && yp >> level == yn >> level {
87 return None;
88 }
89 src.neighbour(xn, yn)
90 };
91 // The second prediction unit of a vertical split must not take the first one's
92 // motion as its A1 candidate; the horizontal split does the same for B1.
93 let second_vertical = part_idx == 1
94 && matches!(
95 part,
96 PartMode::PartNx2N | PartMode::PartnLx2N | PartMode::PartnRx2N
97 );
98 let second_horizontal = part_idx == 1
99 && matches!(
100 part,
101 PartMode::Part2NxN | PartMode::Part2NxnU | PartMode::Part2NxnD
102 );
103
104 let a1 = if second_vertical {
105 None
106 } else {
107 fetch(xp - 1, yp + hi - 1)
108 };
109 let b1 = if second_horizontal {
110 None
111 } else {
112 fetch(xp + wi - 1, yp - 1)
113 };
114 let b0 = fetch(xp + wi, yp - 1);
115 let a0 = fetch(xp - 1, yp + hi);
116 let b2 = fetch(xp - 1, yp - 1);
117
118 let mut out = Vec::with_capacity(5);
119 out.extend(a1);
120 out.extend(b1.filter(|m| a1 != Some(*m)));
121 out.extend(b0.filter(|m| b1 != Some(*m)));
122 out.extend(a0.filter(|m| a1 != Some(*m)));
123 // B2 is used only when the four candidates above are not all there.
124 if out.len() != 4 {
125 out.extend(b2.filter(|m| a1 != Some(*m) && b1 != Some(*m)));
126 }
127 out
128}
129
130/// The temporal merge candidate (8.5.3.2.2 step 4): reference index 0 in each list
131/// the slice uses. `None` when neither list has a collocated vector.
132fn temporal_candidate(
133 src: &SliceMotion<'_>,
134 x: usize,
135 y: usize,
136 w: usize,
137 h: usize,
138) -> Option<PbMotion> {
139 let mv0 = src.temporal_mv(x, y, w, h, 0, 0);
140 let mv1 = if src.params.is_b {
141 src.temporal_mv(x, y, w, h, 1, 0)
142 } else {
143 None
144 };
145 if mv0.is_none() && mv1.is_none() {
146 return None;
147 }
148 let conv = |mv: Option<[i32; 2]>| mv.map_or([0i16, 0], to16);
149 Some(PbMotion::new(
150 [mv0.is_some(), mv1.is_some()],
151 [0, 0],
152 [conv(mv0), conv(mv1)],
153 ))
154}
155
156/// Combined bi-predictive candidates (8.5.3.2.4): pairs an L0 motion of one
157/// candidate with an L1 motion of another, in the order of Table 8-7, when the two
158/// refer to different pictures or carry different vectors.
159fn combined_candidates(
160 src: &SliceMotion<'_>,
161 cands: &mut Vec<PbMotion>,
162 num_orig: usize,
163 max: usize,
164) {
165 let total = num_orig * (num_orig - 1);
166 let mut comb = 0;
167 while comb < total && comb < COMB_L0.len() && cands.len() < max {
168 let (Some(&l0c), Some(&l1c)) = (cands.get(COMB_L0[comb]), cands.get(COMB_L1[comb])) else {
169 break;
170 };
171 if l0c.pred[0]
172 && l1c.pred[1]
173 && (src.ref_poc(0, l0c.ref_idx[0]) != src.ref_poc(1, l1c.ref_idx[1])
174 || l0c.mv[0] != l1c.mv[1])
175 {
176 cands.push(PbMotion::new(
177 [true, true],
178 [l0c.ref_idx[0], l1c.ref_idx[1]],
179 [l0c.mv[0], l1c.mv[1]],
180 ));
181 }
182 comb += 1;
183 }
184}
185
186/// A zero-vector candidate with reference index `ref_idx` in list 0 (and list 1 for
187/// a B slice).
188fn zero_candidate(is_b: bool, ref_idx: usize) -> PbMotion {
189 let r = i8::try_from(ref_idx).unwrap_or(0);
190 if is_b {
191 PbMotion::new([true, true], [r, r], [[0, 0], [0, 0]])
192 } else {
193 PbMotion::new([true, false], [r, -1], [[0, 0], [0, 0]])
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::super::cu_syntax::InterPredIdc;
200 use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared};
201 use super::super::rps::{RefEntry, RefPicLists};
202 use super::super::shared::SharedPic;
203 use super::*;
204 use std::sync::Arc;
205
206 fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry {
207 RefEntry { id, poc, long_term }
208 }
209
210 fn params(is_b: bool, max: usize, par: u32) -> MotionParams {
211 MotionParams {
212 is_b,
213 max_merge_cand: max,
214 log2_par_mrg_level: par,
215 ctb_log2: 6,
216 collocated_from_l0: true,
217 temporal_mvp: false,
218 no_backward_pred: false,
219 }
220 }
221
222 fn uni(list: usize, ref_idx: i8, mv: [i16; 2]) -> PbMotion {
223 let mut pred = [false, false];
224 pred[list] = true;
225 let mut r = [-1, -1];
226 r[list] = ref_idx;
227 let mut m = [[0i16; 2]; 2];
228 m[list] = mv;
229 PbMotion::new(pred, r, m)
230 }
231
232 fn pu_at(x: usize, y: usize, w: usize, h: usize, merge_idx: u8) -> PredictionUnit {
233 PredictionUnit {
234 x,
235 y,
236 width: w,
237 height: h,
238 merge_flag: true,
239 merge_idx,
240 inter_pred_idc: InterPredIdc::PredL0,
241 ..PredictionUnit::default()
242 }
243 }
244
245 fn cu(x: usize, y: usize, size: usize, part: PartMode) -> CuGeometry {
246 CuGeometry {
247 x,
248 y,
249 size,
250 part_mode: part,
251 skip: false,
252 }
253 }
254
255 fn p_lists() -> RefPicLists {
256 RefPicLists {
257 l0: vec![entry(0, 0, false)],
258 l1: Vec::new(),
259 }
260 }
261
262 /// The merge result for one PU, in a 64x64 picture with `field` as the current
263 /// motion field and `col` as the collocated picture.
264 fn merge_with(
265 field: &mut MotionField,
266 lists: &RefPicLists,
267 p: MotionParams,
268 col: Option<Arc<SharedPic>>,
269 geom: CuGeometry,
270 pu: PredictionUnit,
271 pu_index: usize,
272 ) -> PbMotion {
273 let src = SliceMotion {
274 params: p,
275 lists,
276 cur_poc: 4,
277 field,
278 col,
279 publish: None,
280 slice: 0,
281 };
282 derive_merge(&src, &geom, pu_index, &pu)
283 }
284
285 #[test]
286 fn no_neighbours_gives_zero_candidate() {
287 let mut field = MotionField::new(64, 64);
288 let got = merge_with(
289 &mut field,
290 &p_lists(),
291 params(false, 5, 2),
292 None,
293 cu(16, 16, 16, PartMode::Part2Nx2N),
294 pu_at(16, 16, 16, 16, 0),
295 0,
296 );
297 assert_eq!(got, uni(0, 0, [0, 0]));
298 }
299
300 #[test]
301 fn a1_is_first_and_intra_or_missing_neighbour_is_skipped() {
302 let mut field = MotionField::new(64, 64);
303 // A1 of the 16x16 block at (16,16) is (15,31): store motion there.
304 let m = uni(0, 0, [12, -7]);
305 field.store(0, 16, 16, 16, 0, m);
306 // B1 (31,15) stays missing (intra or not decoded).
307 let got = merge_with(
308 &mut field,
309 &p_lists(),
310 params(false, 5, 2),
311 None,
312 cu(16, 16, 16, PartMode::Part2Nx2N),
313 pu_at(16, 16, 16, 16, 0),
314 0,
315 );
316 assert_eq!(got, m);
317 }
318
319 #[test]
320 fn neighbour_in_other_slice_is_unavailable() {
321 let mut field = MotionField::new(64, 64);
322 field.store(0, 16, 16, 16, 1, uni(0, 0, [12, -7]));
323 let got = merge_with(
324 &mut field,
325 &p_lists(),
326 params(false, 5, 2),
327 None,
328 cu(16, 16, 16, PartMode::Part2Nx2N),
329 pu_at(16, 16, 16, 16, 0),
330 0,
331 );
332 assert_eq!(got, uni(0, 0, [0, 0]));
333 }
334
335 #[test]
336 fn b1_identical_to_a1_is_pruned() {
337 let mut field = MotionField::new(64, 64);
338 let a = uni(0, 0, [1, 2]);
339 let n = uni(0, 0, [5, 6]);
340 field.store(0, 16, 16, 16, 0, a); // A1
341 field.store(16, 0, 16, 16, 0, a); // B1 (31,15): same as A1, pruned
342 field.store(32, 0, 16, 16, 0, n); // B0 (32,15)
343 // merge_idx 1 is B0, since B1 is pruned.
344 let got = merge_with(
345 &mut field,
346 &p_lists(),
347 params(false, 5, 2),
348 None,
349 cu(16, 16, 16, PartMode::Part2Nx2N),
350 pu_at(16, 16, 16, 16, 1),
351 0,
352 );
353 assert_eq!(got, n);
354 }
355
356 #[test]
357 fn parallel_merge_level_hides_neighbours_in_the_same_region() {
358 // Log2ParMrgLevel 4 (16x16 regions). The 8x8 CU at (8,8) shares one list
359 // (singleMCLFlag), so A1 (7,15) and B1 (15,7) are in its own region and gone.
360 let mut field = MotionField::new(64, 64);
361 field.store(0, 8, 8, 8, 0, uni(0, 0, [9, 9])); // A1 position, same region
362 field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8])); // B1 position, same region
363 let far = uni(0, 0, [-3, 4]);
364 field.store(16, 0, 8, 8, 0, far); // B0 (16,7), another region
365 let got = merge_with(
366 &mut field,
367 &p_lists(),
368 params(false, 5, 4),
369 None,
370 cu(8, 8, 8, PartMode::Part2Nx2N),
371 pu_at(8, 8, 8, 8, 0),
372 0,
373 );
374 assert_eq!(got, far);
375 }
376
377 #[test]
378 fn parallel_merge_level_two_uses_the_neighbour() {
379 // The same layout with Log2ParMrgLevel 2: nothing is in the same region, so A1 is used.
380 let mut field = MotionField::new(64, 64);
381 let a = uni(0, 0, [9, 9]);
382 field.store(0, 8, 8, 8, 0, a);
383 field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8]));
384 let got = merge_with(
385 &mut field,
386 &p_lists(),
387 params(false, 5, 2),
388 None,
389 cu(8, 8, 8, PartMode::Part2Nx2N),
390 pu_at(8, 8, 8, 8, 0),
391 0,
392 );
393 assert_eq!(got, a);
394 }
395
396 #[test]
397 fn second_vertical_partition_skips_a1() {
398 // Nx2N, partIdx 1 at (x+8,y): A1 is the first partition, so it is not a candidate.
399 let mut field = MotionField::new(64, 64);
400 field.store(16, 16, 8, 16, 0, uni(0, 0, [1, 1])); // the first partition
401 let got = merge_with(
402 &mut field,
403 &p_lists(),
404 params(false, 5, 2),
405 None,
406 cu(16, 16, 16, PartMode::PartNx2N),
407 pu_at(24, 16, 8, 16, 0),
408 1,
409 );
410 assert_eq!(got, uni(0, 0, [0, 0]));
411 }
412
413 #[test]
414 fn temporal_candidate_scales_with_negative_distance() {
415 // Current POC 2; the collocated picture is POC 8 and its vector points to POC 4.
416 // The current L0[0] is POC 6, after the current picture: tb = -4, td = 4.
417 // mv 64: tx = (16384 + 2) / 4 = 4096, dsf = (-4 * 4096 + 32) >> 6 = -256,
418 // mv' = Sign(-256 * 64) * ((16384 + 127) >> 8) = -64.
419 let mut col_field = MotionField::new(64, 64);
420 col_field.slices.push(SliceRefs {
421 poc: [vec![4], vec![]],
422 long_term: [vec![false], vec![]],
423 });
424 col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0]));
425 let col = test_shared(&col_field, 8);
426 let lists = RefPicLists {
427 l0: vec![entry(0, 6, false)],
428 l1: Vec::new(),
429 };
430 let mut field = MotionField::new(64, 64);
431 let mut p = params(false, 5, 2);
432 p.temporal_mvp = true;
433 let src = SliceMotion {
434 params: p,
435 lists: &lists,
436 cur_poc: 2,
437 field: &mut field,
438 col: Some(col),
439 publish: None,
440 slice: 0,
441 };
442 // A 16x16 block at (16,16): bottom-right (32,32) is inside the picture and CTB row.
443 let got = derive_merge(
444 &src,
445 &cu(16, 16, 16, PartMode::Part2Nx2N),
446 0,
447 &pu_at(16, 16, 16, 16, 0),
448 );
449 assert_eq!(got, uni(0, 0, [-64, 0]));
450 }
451
452 #[test]
453 fn temporal_candidate_with_long_term_mismatch_is_unavailable() {
454 // The current L0[0] is long-term, the collocated reference is short-term:
455 // the candidate is unavailable and the zero candidate is used.
456 let mut col_field = MotionField::new(64, 64);
457 col_field.slices.push(SliceRefs {
458 poc: [vec![4], vec![]],
459 long_term: [vec![false], vec![]],
460 });
461 col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0]));
462 let col = test_shared(&col_field, 8);
463 let lists = RefPicLists {
464 l0: vec![entry(0, 0, true)],
465 l1: Vec::new(),
466 };
467 let mut field = MotionField::new(64, 64);
468 let mut p = params(false, 5, 2);
469 p.temporal_mvp = true;
470 let src = SliceMotion {
471 params: p,
472 lists: &lists,
473 cur_poc: 4,
474 field: &mut field,
475 col: Some(col),
476 publish: None,
477 slice: 0,
478 };
479 let got = derive_merge(
480 &src,
481 &cu(16, 16, 16, PartMode::Part2Nx2N),
482 0,
483 &pu_at(16, 16, 16, 16, 0),
484 );
485 assert_eq!(got, uni(0, 0, [0, 0]));
486 }
487
488 #[test]
489 fn combined_bi_candidate_from_l0_and_l1_neighbours() {
490 // A1 is L0-only (POC 0), B1 is L1-only (POC 6): they pair into a bi candidate.
491 let lists = RefPicLists {
492 l0: vec![entry(0, 0, false)],
493 l1: vec![entry(1, 6, false)],
494 };
495 let mut field = MotionField::new(64, 64);
496 let m0 = uni(0, 0, [2, 2]);
497 let m1 = uni(1, 0, [-5, 9]);
498 field.store(0, 16, 16, 16, 0, m0); // A1
499 field.store(16, 0, 16, 16, 0, m1); // B1 (31,15)
500 let got = merge_with(
501 &mut field,
502 &lists,
503 params(true, 5, 2),
504 None,
505 cu(16, 16, 16, PartMode::Part2Nx2N),
506 pu_at(16, 16, 16, 16, 2),
507 0,
508 );
509 let expect = PbMotion::new([true, true], [0, 0], [[2, 2], [-5, 9]]);
510 assert_eq!(got, expect);
511 }
512
513 #[test]
514 fn bi_candidate_becomes_uni_for_an_8x4_block() {
515 // A B slice whose A1 is bi-predicted: an 8x4 block keeps only L0.
516 let lists = RefPicLists {
517 l0: vec![entry(0, 0, false)],
518 l1: vec![entry(1, 8, false)],
519 };
520 let mut field = MotionField::new(64, 64);
521 let bi = PbMotion::new([true, true], [0, 0], [[3, -3], [4, 4]]);
522 field.store(0, 16, 16, 16, 0, bi); // A1 of an 8x4 PU at (16,16)
523 let got = merge_with(
524 &mut field,
525 &lists,
526 params(true, 5, 2),
527 None,
528 cu(16, 16, 8, PartMode::Part2Nx2N),
529 pu_at(16, 16, 8, 4, 0),
530 0,
531 );
532 assert_eq!(
533 got,
534 PbMotion::new([true, false], [0, -1], [[3, -3], [0, 0]])
535 );
536 }
537
538 #[test]
539 fn zero_candidates_use_increasing_reference_indices() {
540 // Two L0 references and merge_idx 1 with no spatial candidates: zero ref 1.
541 let lists = RefPicLists {
542 l0: vec![entry(0, 0, false), entry(1, 2, false)],
543 l1: Vec::new(),
544 };
545 let mut field = MotionField::new(64, 64);
546 let got = merge_with(
547 &mut field,
548 &lists,
549 params(false, 5, 2),
550 None,
551 cu(16, 16, 16, PartMode::Part2Nx2N),
552 pu_at(16, 16, 16, 16, 1),
553 0,
554 );
555 assert_eq!(got, uni(0, 1, [0, 0]));
556 }
557}