forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

mv.rs483 lines, 15.0 KiBHistoryRawDownload
1//! Macroblock partitioning and motion vector derivation (spec 7.4.5, 8.4.1).
2//!
3//! Motion data lives in the picture's per-4x4-block arrays, written as each
4//! partition is derived. Neighbour derivation (8.4.1.3.2) then reads those same
5//! arrays, which is what makes "the partition inside this macroblock has not
6//! been decoded yet" expressible: a bitmask of the blocks written so far stands
7//! in for the availability rule of clause 6.4.11.7, exactly rather than
8//! approximately.
9
10use crate::dpb::{BLK_DIRECT, BLK_INTRA, BLK_SKIP, Picture};
11
12/// Prediction mode of a macroblock or sub-macroblock partition (Table 7-13,
13/// 7-14, 7-17, 7-18).
14#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15pub(crate) enum Pred {
16 /// Pred_L0.
17 L0,
18 /// Pred_L1.
19 L1,
20 /// BiPred.
21 Bi,
22 /// Direct (B_Skip, B_Direct_16x16, B_Direct_8x8).
23 Direct,
24}
25
26impl Pred {
27 /// `(predFlagL0, predFlagL1)`; direct mode resolves later.
28 #[inline]
29 pub(crate) fn uses(self, list: usize) -> bool {
30 match self {
31 Pred::L0 => list == 0,
32 Pred::L1 => list == 1,
33 Pred::Bi => true,
34 Pred::Direct => false,
35 }
36 }
37}
38
39/// The partitioning of one inter macroblock.
40#[derive(Clone, Copy, Debug)]
41pub(crate) struct MbShape {
42 /// `NumMbPart( mb_type )`.
43 pub parts: usize,
44 /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks.
45 pub w: usize,
46 pub h: usize,
47 /// `MbPartPredMode` of each partition.
48 pub pred: [Pred; 2],
49 /// mb_type is P_8x8/P_8x8ref0/B_8x8: sub-macroblock types follow.
50 pub sub: bool,
51}
52
53const fn shape(parts: usize, w: usize, h: usize, p0: Pred, p1: Pred) -> MbShape {
54 MbShape {
55 parts,
56 w,
57 h,
58 pred: [p0, p1],
59 sub: false,
60 }
61}
62
63const SUB8X8: MbShape = MbShape {
64 parts: 4,
65 w: 2,
66 h: 2,
67 pred: [Pred::L0, Pred::L0],
68 sub: true,
69};
70
71/// Table 7-13, mb_type 0..4 of a P or SP slice.
72pub(crate) const P_SHAPES: [MbShape; 5] = [
73 shape(1, 4, 4, Pred::L0, Pred::L0),
74 shape(2, 4, 2, Pred::L0, Pred::L0),
75 shape(2, 2, 4, Pred::L0, Pred::L0),
76 SUB8X8,
77 SUB8X8, // P_8x8ref0: same partitioning, ref_idx inferred 0.
78];
79
80/// Table 7-14, mb_type 0..22 of a B slice.
81pub(crate) const B_SHAPES: [MbShape; 23] = [
82 shape(1, 4, 4, Pred::Direct, Pred::Direct),
83 shape(1, 4, 4, Pred::L0, Pred::L0),
84 shape(1, 4, 4, Pred::L1, Pred::L1),
85 shape(1, 4, 4, Pred::Bi, Pred::Bi),
86 shape(2, 4, 2, Pred::L0, Pred::L0),
87 shape(2, 2, 4, Pred::L0, Pred::L0),
88 shape(2, 4, 2, Pred::L1, Pred::L1),
89 shape(2, 2, 4, Pred::L1, Pred::L1),
90 shape(2, 4, 2, Pred::L0, Pred::L1),
91 shape(2, 2, 4, Pred::L0, Pred::L1),
92 shape(2, 4, 2, Pred::L1, Pred::L0),
93 shape(2, 2, 4, Pred::L1, Pred::L0),
94 shape(2, 4, 2, Pred::L0, Pred::Bi),
95 shape(2, 2, 4, Pred::L0, Pred::Bi),
96 shape(2, 4, 2, Pred::L1, Pred::Bi),
97 shape(2, 2, 4, Pred::L1, Pred::Bi),
98 shape(2, 4, 2, Pred::Bi, Pred::L0),
99 shape(2, 2, 4, Pred::Bi, Pred::L0),
100 shape(2, 4, 2, Pred::Bi, Pred::L1),
101 shape(2, 2, 4, Pred::Bi, Pred::L1),
102 shape(2, 4, 2, Pred::Bi, Pred::Bi),
103 shape(2, 2, 4, Pred::Bi, Pred::Bi),
104 SUB8X8,
105];
106
107/// The partitioning of one 8x8 sub-macroblock.
108#[derive(Clone, Copy, Debug)]
109pub(crate) struct SubShape {
110 /// `NumSubMbPart( sub_mb_type )`.
111 pub parts: usize,
112 /// `SubMbPartWidth`/`SubMbPartHeight` in 4x4 blocks.
113 pub w: usize,
114 pub h: usize,
115 /// `SubMbPredMode`.
116 pub pred: Pred,
117}
118
119const fn sub(parts: usize, w: usize, h: usize, pred: Pred) -> SubShape {
120 SubShape { parts, w, h, pred }
121}
122
123/// Table 7-17, sub_mb_type of a P macroblock.
124pub(crate) const P_SUB: [SubShape; 4] = [
125 sub(1, 2, 2, Pred::L0),
126 sub(2, 2, 1, Pred::L0),
127 sub(2, 1, 2, Pred::L0),
128 sub(4, 1, 1, Pred::L0),
129];
130
131/// Table 7-18, sub_mb_type of a B macroblock.
132pub(crate) const B_SUB: [SubShape; 13] = [
133 sub(4, 1, 1, Pred::Direct),
134 sub(1, 2, 2, Pred::L0),
135 sub(1, 2, 2, Pred::L1),
136 sub(1, 2, 2, Pred::Bi),
137 sub(2, 2, 1, Pred::L0),
138 sub(2, 1, 2, Pred::L0),
139 sub(2, 2, 1, Pred::L1),
140 sub(2, 1, 2, Pred::L1),
141 sub(2, 2, 1, Pred::Bi),
142 sub(2, 1, 2, Pred::Bi),
143 sub(4, 1, 1, Pred::L0),
144 sub(4, 1, 1, Pred::L1),
145 sub(4, 1, 1, Pred::Bi),
146];
147
148/// Motion data of one neighbouring partition (8.4.1.3.2).
149#[derive(Clone, Copy, Debug)]
150pub(crate) struct Nb {
151 /// The partition exists and has been decoded (clause 6.4.11.7).
152 pub avail: bool,
153 pub mv: [i16; 2],
154 /// -1 when the neighbour does not use this list, or is intra.
155 pub ref_idx: i8,
156}
157
158impl Default for Nb {
159 /// An unavailable partition, which 8.4.1.3.2 gives reference index -1 —
160 /// *not* 0. A derived `Default` would make it look like a neighbour on
161 /// reference picture 0 and hand the median rules a phantom match.
162 fn default() -> Nb {
163 Nb {
164 avail: false,
165 mv: [0; 2],
166 ref_idx: -1,
167 }
168 }
169}
170
171/// Where the current macroblock's motion data is being written, and which of
172/// its 4x4 blocks already carry it.
173pub(crate) struct MvCtx {
174 pub mb_x: usize,
175 pub mb_y: usize,
176 pub slice_id: u16,
177 /// Bit `y * 4 + x` set once block (x, y) of this macroblock is derived.
178 pub written: u16,
179}
180
181impl MvCtx {
182 /// Motion data of the 4x4 block at picture block coordinates `(bx, by)`,
183 /// for list `list`.
184 pub(crate) fn at(&self, pic: &Picture, bx: i32, by: i32, list: usize) -> Nb {
185 let w4 = (pic.mb_w * 4) as i32;
186 let h4 = (pic.mb_h * 4) as i32;
187 if bx < 0 || by < 0 || bx >= w4 || by >= h4 {
188 return Nb::default();
189 }
190 let (mbx, mby) = (bx as usize / 4, by as usize / 4);
191 let addr = mby * pic.mb_w + mbx;
192 if mbx == self.mb_x && mby == self.mb_y {
193 let within = (by as usize % 4) * 4 + bx as usize % 4;
194 if self.written & (1 << within) == 0 {
195 return Nb::default();
196 }
197 } else if pic.mb_slice[addr] != self.slice_id {
198 return Nb::default();
199 }
200 let idx = by as usize * pic.mb_w * 4 + bx as usize;
201 if pic.blk[idx] & BLK_INTRA != 0 {
202 // Available as a partition, but contributes no motion (8.4.1.3.2).
203 return Nb {
204 avail: true,
205 mv: [0; 2],
206 ref_idx: -1,
207 };
208 }
209 Nb {
210 avail: true,
211 mv: pic.mv[idx][list],
212 ref_idx: pic.ref_idx[idx][list],
213 }
214 }
215
216 /// Neighbours A, B and C of a partition whose top-left 4x4 block is at
217 /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks
218 /// (clause 6.4.11.7, with the C-to-D substitution of 8-214).
219 pub(crate) fn neighbours(
220 &self,
221 pic: &Picture,
222 px: usize,
223 py: usize,
224 pw: usize,
225 list: usize,
226 ) -> [Nb; 3] {
227 let bx = (self.mb_x * 4 + px) as i32;
228 let by = (self.mb_y * 4 + py) as i32;
229 let a = self.at(pic, bx - 1, by, list);
230 let b = self.at(pic, bx, by - 1, list);
231 let mut c = self.at(pic, bx + pw as i32, by - 1, list);
232 if !c.avail {
233 c = self.at(pic, bx - 1, by - 1, list);
234 }
235 [a, b, c]
236 }
237}
238
239#[inline]
240fn median(a: i16, b: i16, c: i16) -> i16 {
241 a.max(b).min(a.min(b).max(c))
242}
243
244/// Motion vector prediction (clause 8.4.1.3), including the directional
245/// segmentation shortcuts of Equations 8-203 to 8-206.
246///
247/// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only
248/// select those shortcuts; `part` is the macroblock partition index.
249pub(crate) fn predict_mv(
250 n: &[Nb; 3],
251 ref_idx: i8,
252 part_w: usize,
253 part_h: usize,
254 part: usize,
255) -> [i16; 2] {
256 let [a, mut b, mut c] = *n;
257 match (part_w, part_h, part) {
258 (4, 2, 0) if b.ref_idx == ref_idx => return b.mv,
259 (4, 2, 1) if a.ref_idx == ref_idx => return a.mv,
260 (2, 4, 0) if a.ref_idx == ref_idx => return a.mv,
261 (2, 4, 1) if c.ref_idx == ref_idx => return c.mv,
262 _ => {}
263 }
264 // 8.4.1.3.1 step 1.
265 if !b.avail && !c.avail && a.avail {
266 b = a;
267 c = a;
268 }
269 let matches = u8::from(a.ref_idx == ref_idx)
270 + u8::from(b.ref_idx == ref_idx)
271 + u8::from(c.ref_idx == ref_idx);
272 if matches == 1 {
273 if a.ref_idx == ref_idx {
274 return a.mv;
275 }
276 if b.ref_idx == ref_idx {
277 return b.mv;
278 }
279 return c.mv;
280 }
281 [
282 median(a.mv[0], b.mv[0], c.mv[0]),
283 median(a.mv[1], b.mv[1], c.mv[1]),
284 ]
285}
286
287/// `MinPositive` (Equation 8-187).
288#[inline]
289pub(crate) fn min_positive(x: i8, y: i8) -> i8 {
290 if x >= 0 && y >= 0 { x.min(y) } else { x.max(y) }
291}
292
293/// Record one 4x4 block's motion data into the picture arrays.
294#[allow(clippy::too_many_arguments)]
295pub(crate) fn write_block(
296 pic: &mut Picture,
297 ctx: &mut MvCtx,
298 px: usize,
299 py: usize,
300 mv: [[i16; 2]; 2],
301 ref_idx: [i8; 2],
302 ref_id: [i32; 2],
303 flags: u8,
304) {
305 let bx = ctx.mb_x * 4 + px;
306 let by = ctx.mb_y * 4 + py;
307 let idx = by * pic.mb_w * 4 + bx;
308 pic.mv[idx] = mv;
309 pic.ref_idx[idx] = ref_idx;
310 pic.ref_id[idx] = ref_id;
311 pic.blk[idx] = flags;
312 ctx.written |= 1 << (py * 4 + px);
313}
314
315/// Mark every 4x4 block of the current macroblock as intra, clearing the motion
316/// data an inter neighbour would otherwise read (8.4.1.3.2, 9.3.3.1.1.7).
317pub(crate) fn write_intra_mb(pic: &mut Picture, mb_x: usize, mb_y: usize) {
318 let w4 = pic.mb_w * 4;
319 for py in 0..4 {
320 let base = (mb_y * 4 + py) * w4 + mb_x * 4;
321 for idx in base..base + 4 {
322 pic.mv[idx] = [[0; 2]; 2];
323 pic.ref_idx[idx] = [-1; 2];
324 pic.ref_id[idx] = [-1; 2];
325 pic.mvd_abs[idx] = [0; 4];
326 pic.blk[idx] = BLK_INTRA;
327 }
328 }
329}
330
331/// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the
332/// context thresholds of 9.3.3.1.1.7 can distinguish.
333#[inline]
334pub(crate) fn write_mvd(
335 pic: &mut Picture,
336 mb_x: usize,
337 mb_y: usize,
338 px: usize,
339 py: usize,
340 list: usize,
341 mvd: [i16; 2],
342) {
343 let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px;
344 let e = &mut pic.mvd_abs[idx];
345 e[list * 2] = mvd[0].unsigned_abs().min(127) as u8;
346 e[list * 2 + 1] = mvd[1].unsigned_abs().min(127) as u8;
347}
348
349/// `absMvdCompN` of the neighbouring partition at picture block coordinates
350/// `(bx, by)` (9.3.3.1.1.7): zero when the neighbour is unavailable, skipped,
351/// intra or direct coded.
352pub(crate) fn neighbour_mvd(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> [u32; 2] {
353 let w4 = (pic.mb_w * 4) as i32;
354 let h4 = (pic.mb_h * 4) as i32;
355 if bx < 0 || by < 0 || bx >= w4 || by >= h4 {
356 return [0; 2];
357 }
358 let (mbx, mby) = (bx as usize / 4, by as usize / 4);
359 if mbx == ctx.mb_x && mby == ctx.mb_y {
360 let within = (by as usize % 4) * 4 + bx as usize % 4;
361 if ctx.written & (1 << within) == 0 {
362 return [0; 2];
363 }
364 } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id {
365 return [0; 2];
366 }
367 let idx = by as usize * pic.mb_w * 4 + bx as usize;
368 if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 || pic.ref_idx[idx][list] < 0 {
369 return [0; 2];
370 }
371 let e = pic.mvd_abs[idx];
372 [u32::from(e[list * 2]), u32::from(e[list * 2 + 1])]
373}
374
375/// `condTermFlagN` for ref_idx_lX (9.3.3.1.1.6).
376pub(crate) fn ref_idx_cond(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> usize {
377 let w4 = (pic.mb_w * 4) as i32;
378 let h4 = (pic.mb_h * 4) as i32;
379 if bx < 0 || by < 0 || bx >= w4 || by >= h4 {
380 return 0;
381 }
382 let (mbx, mby) = (bx as usize / 4, by as usize / 4);
383 if mbx == ctx.mb_x && mby == ctx.mb_y {
384 let within = (by as usize % 4) * 4 + bx as usize % 4;
385 if ctx.written & (1 << within) == 0 {
386 return 0;
387 }
388 } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id {
389 return 0;
390 }
391 let idx = by as usize * pic.mb_w * 4 + bx as usize;
392 if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 {
393 return 0;
394 }
395 usize::from(pic.ref_idx[idx][list] > 0)
396}
397
398#[cfg(test)]
399mod tests {
400 use super::*;
401
402 fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb {
403 Nb { avail, mv, ref_idx }
404 }
405
406 /// With exactly one neighbour on the same reference picture, that
407 /// neighbour's vector is the prediction (Equation 8-211).
408 #[test]
409 fn single_matching_reference_wins() {
410 let n = [
411 nb(true, [4, 4], 1),
412 nb(true, [8, 8], 0),
413 nb(true, [12, 12], 2),
414 ];
415 assert_eq!(predict_mv(&n, 0, 4, 4, 0), [8, 8]);
416 }
417
418 /// Otherwise the prediction is the component-wise median (8-212, 8-213).
419 #[test]
420 fn median_of_three_when_several_match() {
421 let n = [
422 nb(true, [4, -8], 0),
423 nb(true, [8, 2], 0),
424 nb(true, [-2, 6], 1),
425 ];
426 assert_eq!(predict_mv(&n, 0, 4, 4, 0), [4, 2]);
427 }
428
429 /// B and C unavailable with A available copies A into both, which turns the
430 /// median into A (8-207 to 8-210).
431 #[test]
432 fn unavailable_b_and_c_fall_back_to_a() {
433 let n = [
434 nb(true, [6, -6], 3),
435 nb(false, [0, 0], -1),
436 nb(false, [0, 0], -1),
437 ];
438 assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]);
439 // With refIdx 3 the single-match rule fires first, same answer.
440 assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]);
441 }
442
443 /// The 16x8 and 8x16 shortcuts bypass the median entirely.
444 #[test]
445 fn directional_segmentation_shortcuts() {
446 let n = [
447 nb(true, [1, 1], 0),
448 nb(true, [2, 2], 0),
449 nb(true, [3, 3], 0),
450 ];
451 assert_eq!(predict_mv(&n, 0, 4, 2, 0), [2, 2], "16x8 part 0 takes B");
452 assert_eq!(predict_mv(&n, 0, 4, 2, 1), [1, 1], "16x8 part 1 takes A");
453 assert_eq!(predict_mv(&n, 0, 2, 4, 0), [1, 1], "8x16 part 0 takes A");
454 assert_eq!(predict_mv(&n, 0, 2, 4, 1), [3, 3], "8x16 part 1 takes C");
455 // A shortcut that does not match the reference index falls through.
456 assert_eq!(predict_mv(&n, 1, 4, 2, 0), [2, 2], "median of 1,2,3");
457 }
458
459 #[test]
460 fn min_positive_prefers_the_non_negative() {
461 assert_eq!(min_positive(2, 5), 2);
462 assert_eq!(min_positive(-1, 5), 5);
463 assert_eq!(min_positive(-1, -1), -1);
464 assert_eq!(min_positive(0, -1), 0);
465 }
466
467 /// Every B macroblock type maps to the partition shape Table 7-14 states.
468 #[test]
469 fn b_shapes_match_table_7_14() {
470 assert_eq!(B_SHAPES[0].pred[0], Pred::Direct);
471 assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi));
472 // The 16x8 / 8x16 pairs alternate, starting at mb_type 4.
473 #[allow(clippy::needless_range_loop)]
474 for t in 4..22 {
475 let s = B_SHAPES[t];
476 assert_eq!(s.parts, 2, "mb_type {t}");
477 let (w, h) = if t % 2 == 0 { (4, 2) } else { (2, 4) };
478 assert_eq!((s.w, s.h), (w, h), "mb_type {t}");
479 }
480 assert!(B_SHAPES[22].sub);
481 assert!(P_SHAPES[3].sub && P_SHAPES[4].sub);
482 }
483}