forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

amvp.rs378 lines, 13.0 KiBHistoryRawDownload
1//! Luma motion vector prediction, AMVP (8.5.3.2.6, 8.5.3.2.7): the spatial
2//! candidates A (A0, A1) and B (B0, B1, B2) with the scaled variants and the
3//! `isScaledFlagLX` rule, the temporal candidate, duplicate removal, zero filling to
4//! two candidates, and `mvLX = mvpLX + MvdLX` with the 16-bit wrap (8-57 to 8-60).
5
6use super::cu_syntax::{InterPredIdc, PredictionUnit};
7use super::motion_field::{PbMotion, SliceMotion, scale_mv, to32};
8use super::rps::RefEntry;
9
10/// The AMVP motion of one prediction unit: each list the unit uses gets its
11/// predictor (selected by `mvp_lX_flag`) plus the decoded difference.
12pub fn derive_amvp(src: &SliceMotion<'_>, pu: &PredictionUnit) -> PbMotion {
13 let mut pred = [false; 2];
14 let mut ref_idx = [-1i8; 2];
15 let mut mv = [[0i16; 2]; 2];
16 for lx in 0..2 {
17 let used = match pu.inter_pred_idc {
18 InterPredIdc::PredL0 => lx == 0,
19 InterPredIdc::PredL1 => lx == 1,
20 InterPredIdc::PredBi => true,
21 };
22 if !used {
23 continue;
24 }
25 let r = pu.ref_idx[lx] as i8;
26 let mvp = predictor(src, pu, lx, r, usize::from(pu.mvp_flag[lx]));
27 pred[lx] = true;
28 ref_idx[lx] = r;
29 mv[lx] = [
30 wrap16(mvp[0] + pu.mvd[lx][0]),
31 wrap16(mvp[1] + pu.mvd[lx][1]),
32 ];
33 }
34 PbMotion::new(pred, ref_idx, mv)
35}
36
37/// `mvpLX` (8.5.3.2.6): the candidate `flag` of the list of up to two predictors.
38fn predictor(
39 src: &SliceMotion<'_>,
40 pu: &PredictionUnit,
41 lx: usize,
42 ref_idx: i8,
43 flag: usize,
44) -> [i32; 2] {
45 let (x, y) = (pu.x as isize, pu.y as isize);
46 let (w, h) = (pu.width as isize, pu.height as isize);
47 let target = src.ref_entry(lx, ref_idx);
48 let target_poc = target.map(|e| e.poc);
49
50 // A0 then A1 (8.5.3.2.7 steps 1 to 6).
51 let a = [src.neighbour(x - 1, y + h), src.neighbour(x - 1, y + h - 1)];
52 // B0, B1, B2.
53 let b = [
54 src.neighbour(x + w, y - 1),
55 src.neighbour(x + w - 1, y - 1),
56 src.neighbour(x - 1, y - 1),
57 ];
58 // isScaledFlagLX: some A neighbour is available.
59 let is_scaled = a.iter().any(Option::is_some);
60
61 let mv_a = if is_scaled {
62 first_pass(src, &a, lx, target_poc).or_else(|| second_pass(src, &a, lx, target))
63 } else {
64 // Without an A neighbour, the unscaled B candidate takes the A slot.
65 first_pass(src, &b, lx, target_poc)
66 };
67 let mv_b = if is_scaled {
68 first_pass(src, &b, lx, target_poc)
69 } else {
70 second_pass(src, &b, lx, target)
71 };
72
73 let mut list: Vec<[i32; 2]> = Vec::with_capacity(3);
74 if let Some(mv) = mv_a {
75 list.push(mv);
76 }
77 if let Some(mv) = mv_b {
78 // Equal A and B candidates collapse into one (8.5.3.2.6 step 3).
79 if mv_a != Some(mv) {
80 list.push(mv);
81 }
82 }
83 // The temporal candidate, when the spatial ones do not already fill the list.
84 if list.len() < 2 {
85 let (xp, yp) = (pu.x, pu.y);
86 if let Some(mv) = src.temporal_mv(xp, yp, pu.width, pu.height, lx, ref_idx) {
87 list.push(mv);
88 }
89 }
90 list.resize(2, [0, 0]);
91 list.get(flag).copied().unwrap_or([0, 0])
92}
93
94/// The first neighbour, in order, that refers to the target picture itself, in list
95/// `lx` or the other list. No scaling.
96fn first_pass(
97 src: &SliceMotion<'_>,
98 neighbours: &[Option<PbMotion>],
99 lx: usize,
100 target_poc: Option<i32>,
101) -> Option<[i32; 2]> {
102 let target_poc = target_poc?;
103 for m in neighbours.iter().flatten() {
104 for list in [lx, 1 - lx] {
105 if m.pred[list] && src.ref_poc(list, m.ref_idx[list]) == Some(target_poc) {
106 return Some(to32(m.mv[list]));
107 }
108 }
109 }
110 None
111}
112
113/// The first neighbour, in order, whose reference has the same long-term marking as
114/// the target. Its vector is scaled by the POC distances when both are short-term.
115fn second_pass(
116 src: &SliceMotion<'_>,
117 neighbours: &[Option<PbMotion>],
118 lx: usize,
119 target: Option<RefEntry>,
120) -> Option<[i32; 2]> {
121 let target = target?;
122 for m in neighbours.iter().flatten() {
123 for list in [lx, 1 - lx] {
124 if !m.pred[list] {
125 continue;
126 }
127 let Some(r) = src.ref_entry(list, m.ref_idx[list]) else {
128 continue;
129 };
130 if r.long_term != target.long_term {
131 continue;
132 }
133 let mv = to32(m.mv[list]);
134 if r.long_term || target.long_term {
135 return Some(mv);
136 }
137 return Some(scale_mv(mv, src.cur_poc - r.poc, src.cur_poc - target.poc));
138 }
139 }
140 None
141}
142
143/// `uLX = (mvpLX + mvdLX + 2^16) % 2^16`, read as a signed 16-bit value (8-57 to 8-60).
144fn wrap16(v: i32) -> i16 {
145 let u = v.rem_euclid(1 << 16);
146 let signed = if u >= 1 << 15 { u - (1 << 16) } else { u };
147 signed as i16
148}
149
150#[cfg(test)]
151mod tests {
152 use super::super::cu_syntax::InterPredIdc;
153 use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared};
154 use super::super::rps::{RefEntry, RefPicLists};
155 use super::super::shared::SharedPic;
156 use super::*;
157 use std::sync::Arc;
158
159 fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry {
160 RefEntry { id, poc, long_term }
161 }
162
163 fn params(temporal: bool) -> MotionParams {
164 MotionParams {
165 is_b: false,
166 max_merge_cand: 5,
167 log2_par_mrg_level: 2,
168 ctb_log2: 6,
169 collocated_from_l0: true,
170 temporal_mvp: temporal,
171 no_backward_pred: true,
172 }
173 }
174
175 fn l0(ref_idx: i8, mv: [i16; 2]) -> PbMotion {
176 PbMotion::new([true, false], [ref_idx, -1], [mv, [0, 0]])
177 }
178
179 /// An AMVP PU at (16,16) of size 16x16 with list 0, reference `ref_idx` and
180 /// difference `mvd`, using predictor `flag`.
181 fn pu(mvd: [i32; 2], flag: u8) -> PredictionUnit {
182 PredictionUnit {
183 x: 16,
184 y: 16,
185 width: 16,
186 height: 16,
187 inter_pred_idc: InterPredIdc::PredL0,
188 mvp_flag: [flag, 0],
189 mvd: [mvd, [0, 0]],
190 ..PredictionUnit::default()
191 }
192 }
193
194 /// Run the AMVP derivation for `pu` with `field` as the current motion field.
195 fn run(
196 field: &mut MotionField,
197 lists: &RefPicLists,
198 cur_poc: i32,
199 col: Option<Arc<SharedPic>>,
200 temporal: bool,
201 pu: &PredictionUnit,
202 ) -> PbMotion {
203 let src = SliceMotion {
204 params: params(temporal),
205 lists,
206 cur_poc,
207 field,
208 col,
209 publish: None,
210 slice: 0,
211 };
212 derive_amvp(&src, pu)
213 }
214
215 fn lists(poc: i32, long_term: bool) -> RefPicLists {
216 RefPicLists {
217 l0: vec![entry(0, poc, long_term)],
218 l1: Vec::new(),
219 }
220 }
221
222 #[test]
223 fn spatial_a_with_the_same_reference_is_used_unscaled() {
224 // A1 = (15,31) refers to POC 4, the target. Its vector is the predictor.
225 let mut field = MotionField::new(64, 64);
226 field.store(0, 16, 16, 16, 0, l0(0, [40, -12]));
227 let got = run(&mut field, &lists(4, false), 8, None, false, &pu([1, 1], 0));
228 assert_eq!(got, l0(0, [41, -11]));
229 }
230
231 #[test]
232 fn spatial_a_scales_by_distance() {
233 // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 0 (td = 8), mv 64:
234 // tx = (16384 + 4) / 8 = 2048, dsf = (4 * 2048 + 32) >> 6 = 128, mv' = 32.
235 // L0[0] is the target (POC 4); the neighbour uses L0[1] (POC 0).
236 let lists = RefPicLists {
237 l0: vec![entry(0, 4, false), entry(1, 0, false)],
238 l1: Vec::new(),
239 };
240 let mut field = MotionField::new(64, 64);
241 field.store(0, 16, 16, 16, 0, l0(1, [64, 0]));
242 let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0));
243 assert_eq!(got, l0(0, [32, 0]));
244 }
245
246 #[test]
247 fn spatial_a_scales_with_negative_distance() {
248 // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 12 (td = -4), mv 64:
249 // tx = (16384 + 2) / -4 = -4096, dsf = (4 * -4096 + 32) >> 6 = -256,
250 // mv' = -64.
251 let lists = RefPicLists {
252 l0: vec![entry(0, 4, false), entry(1, 12, false)],
253 l1: Vec::new(),
254 };
255 let mut field = MotionField::new(64, 64);
256 field.store(0, 16, 16, 16, 0, l0(1, [64, 0]));
257 let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0));
258 assert_eq!(got, l0(0, [-64, 0]));
259 }
260
261 #[test]
262 fn long_term_neighbour_is_not_scaled() {
263 // The target is long-term (POC 4) and so is the neighbour's reference (POC 0):
264 // the vector is used as it is.
265 let lists = RefPicLists {
266 l0: vec![entry(0, 4, true), entry(1, 0, true)],
267 l1: Vec::new(),
268 };
269 let mut field = MotionField::new(64, 64);
270 field.store(0, 16, 16, 16, 0, l0(1, [64, 0]));
271 let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0));
272 assert_eq!(got, l0(0, [64, 0]));
273 }
274
275 #[test]
276 fn long_term_mismatch_skips_the_neighbour() {
277 // The target is long-term but the neighbour's reference is short-term: the
278 // neighbour gives no predictor, and the list is zero-filled.
279 let lists = RefPicLists {
280 l0: vec![entry(0, 4, true), entry(1, 0, false)],
281 l1: Vec::new(),
282 };
283 let mut field = MotionField::new(64, 64);
284 field.store(0, 16, 16, 16, 0, l0(1, [64, 0]));
285 let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0));
286 assert_eq!(got, l0(0, [0, 0]));
287 }
288
289 #[test]
290 fn b_candidate_fills_the_a_slot_when_no_a_neighbour() {
291 // No A neighbour. B1 = (31,15) refers to the target POC 4: it fills the A slot,
292 // and the second B pass scales it back to itself (td = tb), so the list is
293 // [B, 0] and flag 0 picks B.
294 let mut field = MotionField::new(64, 64);
295 field.store(16, 0, 16, 16, 0, l0(0, [20, 6]));
296 let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0));
297 assert_eq!(got, l0(0, [20, 6]));
298 let other = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1));
299 assert_eq!(other, l0(0, [0, 0]));
300 }
301
302 #[test]
303 fn equal_a_and_b_collapse_to_one_predictor() {
304 // A1 and B1 carry the same vector toward the target: the list is [A, 0].
305 let mut field = MotionField::new(64, 64);
306 field.store(0, 16, 16, 16, 0, l0(0, [7, 7]));
307 field.store(16, 0, 16, 16, 0, l0(0, [7, 7]));
308 let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1));
309 assert_eq!(got, l0(0, [0, 0]));
310 let first = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0));
311 assert_eq!(first, l0(0, [7, 7]));
312 }
313
314 #[test]
315 fn temporal_fills_the_second_slot() {
316 // A1 gives one predictor, so the collocated vector is the second. The collocated
317 // picture is POC 8 with a vector toward POC 4 (td = 4), and the target is POC 4
318 // (tb = 4): no scaling.
319 let mut col_field = MotionField::new(64, 64);
320 col_field.slices.push(SliceRefs {
321 poc: [vec![4], vec![]],
322 long_term: [vec![false], vec![]],
323 });
324 col_field.store(32, 32, 16, 16, 0, l0(0, [-9, 5]));
325 let col = test_shared(&col_field, 8);
326 let mut field = MotionField::new(64, 64);
327 field.store(0, 16, 16, 16, 0, l0(0, [1, 1]));
328 let got = run(
329 &mut field,
330 &lists(4, false),
331 8,
332 Some(col),
333 true,
334 &pu([0, 0], 1),
335 );
336 assert_eq!(got, l0(0, [-9, 5]));
337 }
338
339 #[test]
340 fn mv_wraps_at_sixteen_bits() {
341 // mvp 32000 plus mvd 1000 is 33000, which wraps to 33000 - 65536 = -32536.
342 // mvp -32000 plus mvd -1000 is -33000, which wraps to 32536.
343 assert_eq!(wrap16(33000), -32536);
344 assert_eq!(wrap16(-33000), 32536);
345 // The boundaries: 32767 stays, 32768 becomes -32768.
346 assert_eq!(wrap16(32767), 32767);
347 assert_eq!(wrap16(32768), -32768);
348 assert_eq!(wrap16(-32768), -32768);
349 assert_eq!(wrap16(-32769), 32767);
350 }
351
352 #[test]
353 fn mvd_wrap_through_the_full_derivation() {
354 let mut field = MotionField::new(64, 64);
355 field.store(0, 16, 16, 16, 0, l0(0, [32000, -32000]));
356 let got = run(
357 &mut field,
358 &lists(4, false),
359 8,
360 None,
361 false,
362 &pu([1000, -1000], 0),
363 );
364 assert_eq!(got, l0(0, [-32536, 32536]));
365 }
366
367 #[test]
368 fn scale_mv_with_negative_and_positive_distances() {
369 // tb / td = 1/2 with td > 0: half the vector.
370 assert_eq!(scale_mv([64, 0], 4, 2), [32, 0]);
371 // td < 0, tb > 0: the vector flips.
372 assert_eq!(scale_mv([64, 0], -4, 4), [-64, 0]);
373 // Both negative, ratio 1: the vector is unchanged.
374 assert_eq!(scale_mv([-30, 7], -4, -4), [-30, 7]);
375 // The result is clipped to 16 bits.
376 assert_eq!(scale_mv([32767, 0], 1, 127), [32767, 0]);
377 }
378}