forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

motion_field.rs712 lines, 26.0 KiBHistoryRawDownload
1//! The motion field of a picture, the collocated lookup of temporal motion vector
2//! prediction (8.5.3.2.8, 8.5.3.2.9) and the source that plugs the merge and AMVP
3//! derivations (8.5.3.2) into the CU parser.
4//!
5//! [`MotionField`] holds the motion of every 4x4 luma block of the picture being
6//! decoded. When the picture is finished, [`MotionField::compress`] keeps only the
7//! entry of the top-left 4x4 of each 16x16 block, which is all 8.5.3.2.8 reads, and
8//! attaches the slices' reference POCs and long-term flags. The result is a
9//! [`ColField`], stored with the picture in the DPB.
10//!
11//! A block has no entry (`None`) when it is intra coded or not decoded yet. Both
12//! make it unavailable as a spatial neighbour (6.4.2) and as a collocated block.
13//! Decoding order is z-scan order, so "stored already" is the same test as the
14//! z-scan availability of 6.4.1 for every neighbour that can be referenced.
15
16use std::sync::Arc;
17
18use super::cu_syntax::{CuGeometry, Motion, MotionSource, PredictionUnit};
19use super::dpb::Dpb;
20use super::pic::{PicState, PuMotion};
21use super::rps::{RefEntry, RefPicLists};
22use super::shared::SharedPic;
23use super::{amvp, merge};
24use ec_h265_syntax::slice::{SliceHeader, SliceType};
25use ec_h265_syntax::{Pps, Sps};
26
27const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
28const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
29
30/// The motion of one prediction block: `predFlagLX`, `refIdxLX` and `mvLX` for both
31/// lists. An unused list has reference index -1 and a zero vector, so two blocks
32/// with the same motion compare equal.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub struct PbMotion {
35 /// `predFlagL0` and `predFlagL1`.
36 pub pred: [bool; 2],
37 /// `refIdxL0` and `refIdxL1`, -1 for an unused list.
38 pub ref_idx: [i8; 2],
39 /// `mvL0` and `mvL1` (horizontal, vertical), quarter-sample units.
40 pub mv: [[i16; 2]; 2],
41}
42
43impl PbMotion {
44 /// Motion with the unused-list convention applied.
45 pub fn new(pred: [bool; 2], ref_idx: [i8; 2], mv: [[i16; 2]; 2]) -> PbMotion {
46 let mut m = PbMotion { pred, ref_idx, mv };
47 for (list, &used) in pred.iter().enumerate() {
48 if !used {
49 m.ref_idx[list] = -1;
50 m.mv[list] = [0, 0];
51 }
52 }
53 m
54 }
55
56 /// The stored form of a derived [`Motion`]. Vectors are already 16-bit in value.
57 pub fn from_motion(m: &Motion) -> PbMotion {
58 PbMotion::new(m.pred_flags, m.ref_idx, [to16(m.mv[0]), to16(m.mv[1])])
59 }
60
61 /// The [`Motion`] a [`MotionSource`] returns for this block.
62 pub fn to_motion(self) -> Motion {
63 Motion {
64 pred_flags: self.pred,
65 ref_idx: self.ref_idx,
66 mv: [to32(self.mv[0]), to32(self.mv[1])],
67 }
68 }
69}
70
71/// One stored entry: the motion of a block and the slice it was decoded in (the
72/// index into that picture's [`SliceRefs`]).
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub struct FieldCell {
75 /// The motion.
76 pub motion: PbMotion,
77 /// Index of the slice in the picture's slice list.
78 pub slice: u16,
79}
80
81/// The reference lists of one slice, as the collocated lookup needs them later: the
82/// POC and long-term marking of each entry at the time the slice was decoded.
83#[derive(Clone, Debug, Default, PartialEq, Eq)]
84pub struct SliceRefs {
85 /// `PicOrderCntVal` of each entry of `RefPicList0` and `RefPicList1`.
86 pub poc: [Vec<i32>; 2],
87 /// Whether each entry was a long-term reference.
88 pub long_term: [Vec<bool>; 2],
89}
90
91impl SliceRefs {
92 /// The POCs and long-term flags of a slice's lists.
93 pub fn from_lists(lists: &RefPicLists) -> SliceRefs {
94 let split = |list: &Vec<RefEntry>| {
95 (
96 list.iter().map(|e| e.poc).collect::<Vec<i32>>(),
97 list.iter().map(|e| e.long_term).collect::<Vec<bool>>(),
98 )
99 };
100 let (poc0, lt0) = split(&lists.l0);
101 let (poc1, lt1) = split(&lists.l1);
102 SliceRefs {
103 poc: [poc0, poc1],
104 long_term: [lt0, lt1],
105 }
106 }
107}
108
109/// The motion of every 4x4 luma block of the picture being decoded.
110#[derive(Clone, Debug)]
111pub struct MotionField {
112 width: usize,
113 height: usize,
114 /// Cells per row (4x4 units).
115 width4: usize,
116 cells: Vec<Option<FieldCell>>,
117 /// The reference lists of each slice of the picture, indexed by `FieldCell::slice`.
118 pub slices: Vec<SliceRefs>,
119 checksum: u64,
120 /// `TileId` of each CTB, raster order; empty when the picture has one tile.
121 tiles: Vec<u16>,
122 /// `CtbLog2SizeY` and the CTBs per row, for the tile lookup.
123 ctb_log2: u32,
124 ctb_cols: usize,
125 /// The tile of the prediction unit being derived (set by its [`SliceMotion`]).
126 cur_tile: u16,
127 /// The 4x4 unit row of `cells[0..width4]`: zero for a whole picture, and the row above
128 /// the band for a wavefront row band (see [`MotionField::band`]).
129 origin4: usize,
130 /// A wavefront band: its stores are kept in `words` for the picture's checksum, which
131 /// folds them in decoding order once the band is merged.
132 band: bool,
133 words: Vec<u64>,
134}
135
136/// The collocated view of a finished test field, as a picture of its own.
137#[cfg(test)]
138pub fn test_shared(field: &MotionField, poc: i32) -> Arc<SharedPic> {
139 let shared = SharedPic::new(poc, field.width(), field.height(), (8, 8), false, 1);
140 shared.publish_col(field, field.height());
141 Arc::new(shared)
142}
143
144impl MotionField {
145 /// An empty field for a picture of `width` by `height` luma samples.
146 pub fn new(width: usize, height: usize) -> MotionField {
147 let width4 = width.div_ceil(4);
148 let height4 = height.div_ceil(4);
149 MotionField {
150 width,
151 height,
152 width4,
153 cells: vec![None; width4 * height4],
154 slices: Vec::new(),
155 checksum: FNV_OFFSET,
156 tiles: Vec::new(),
157 ctb_log2: 0,
158 ctb_cols: 0,
159 cur_tile: 0,
160 origin4: 0,
161 band: false,
162 words: Vec::new(),
163 }
164 }
165
166 /// An empty band of this field for a wavefront row: `unit_rows` 4x4 unit rows starting
167 /// at unit row `origin4`, sharing this field's tile map. The band's first row is the row
168 /// above the CTB row, which the caller fills (see [`MotionField::cell_row_mut`]).
169 pub fn band(&self, origin4: usize, unit_rows: usize) -> MotionField {
170 MotionField {
171 width: self.width,
172 height: self.height,
173 width4: self.width4,
174 cells: vec![None; unit_rows * self.width4],
175 slices: Vec::new(),
176 checksum: FNV_OFFSET,
177 tiles: self.tiles.clone(),
178 ctb_log2: self.ctb_log2,
179 ctb_cols: self.ctb_cols,
180 cur_tile: 0,
181 origin4,
182 band: true,
183 words: Vec::new(),
184 }
185 }
186
187 /// The cells of the 4x4 unit row `unit_row` (a row this field stores).
188 pub fn cell_row(&self, unit_row: usize) -> &[Option<FieldCell>] {
189 let i = (unit_row - self.origin4) * self.width4;
190 &self.cells[i..i + self.width4]
191 }
192
193 /// The cells split into bands of `unit_rows` 4x4 unit rows each (the last band may be
194 /// shorter), for a wavefront to fill one band per CTB row. Only for a whole-picture field.
195 pub(crate) fn bands_mut(
196 &mut self,
197 unit_rows: usize,
198 ) -> std::slice::ChunksMut<'_, Option<FieldCell>> {
199 self.cells.chunks_mut(unit_rows * self.width4)
200 }
201
202 /// Mutable form of [`MotionField::cell_row`].
203 pub fn cell_row_mut(&mut self, unit_row: usize) -> &mut [Option<FieldCell>] {
204 let i = (unit_row - self.origin4) * self.width4;
205 &mut self.cells[i..i + self.width4]
206 }
207
208 /// Merge a finished band into this field: its cells from unit row `first_unit_row` on
209 /// are copied, and its stores are folded into the checksum in decoding order. Bands
210 /// merged in decoding order give the checksum a whole-picture decode would give.
211 pub fn merge_band(&mut self, band: &MotionField, first_unit_row: usize) {
212 let from = (first_unit_row - band.origin4) * self.width4;
213 let to = first_unit_row - self.origin4;
214 let n = band.cells.len() - from;
215 self.cells[to * self.width4..to * self.width4 + n].copy_from_slice(&band.cells[from..]);
216 for words in band.words.as_chunks::<8>().0 {
217 for &word in words {
218 self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME);
219 }
220 }
221 }
222
223 /// The tile of each CTB (raster order), so that a neighbour in another tile is
224 /// unavailable (6.4.1).
225 pub fn set_tiles(&mut self, tile_of_rs: Vec<u16>, ctb_log2: u32, ctb_cols: usize) {
226 self.tiles = tile_of_rs;
227 self.ctb_log2 = ctb_log2;
228 self.ctb_cols = ctb_cols;
229 }
230
231 /// The tile of the luma position `(x, y)`.
232 fn tile_at(&self, x: usize, y: usize) -> u16 {
233 if self.tiles.is_empty() {
234 return 0;
235 }
236 let rs = (y >> self.ctb_log2) * self.ctb_cols + (x >> self.ctb_log2);
237 self.tiles.get(rs).copied().unwrap_or(0)
238 }
239
240 /// Picture width in luma samples.
241 pub fn width(&self) -> usize {
242 self.width
243 }
244
245 /// Picture height in luma samples.
246 pub fn height(&self) -> usize {
247 self.height
248 }
249
250 /// The entry covering luma sample `(x, y)`; `None` outside the picture, for intra
251 /// blocks, and for blocks not decoded yet.
252 pub fn at(&self, x: isize, y: isize) -> Option<FieldCell> {
253 let x = usize::try_from(x).ok()?;
254 let y = usize::try_from(y).ok()?;
255 if x >= self.width || y >= self.height {
256 return None;
257 }
258 let i = (y / 4).checked_sub(self.origin4)? * self.width4 + x / 4;
259 self.cells.get(i).copied().flatten()
260 }
261
262 /// Forget the motion of the `w` by `h` block at `(x, y)`, so it reads as it did
263 /// before anything was stored there (an intra block has no entry).
264 pub fn clear(&mut self, x: usize, y: usize, w: usize, h: usize) {
265 let x_end = (x + w).min(self.width);
266 let y_end = (y + h).min(self.height);
267 for yy in (y..y_end).step_by(4) {
268 for xx in (x..x_end).step_by(4) {
269 self.cells[(yy / 4 - self.origin4) * self.width4 + xx / 4] = None;
270 }
271 }
272 }
273
274 /// The cells of the `w` by `h` luma area at `(x, y)` in raster order of 4x4
275 /// units, for a wavefront row to hand a finished CTB to the row below.
276 /// `x`, `y`, `w` and `h` are multiples of 4 inside the picture.
277 pub(crate) fn export_cells(
278 &self,
279 x: usize,
280 y: usize,
281 w: usize,
282 h: usize,
283 ) -> Vec<Option<FieldCell>> {
284 let mut out = Vec::with_capacity((w / 4) * (h / 4));
285 for yy in (y..y + h).step_by(4) {
286 let row = (yy / 4) * self.width4;
287 for xx in (x..x + w).step_by(4) {
288 out.push(self.cells[row + xx / 4]);
289 }
290 }
291 out
292 }
293
294 /// The inverse of [`MotionField::export_cells`].
295 pub(crate) fn import_cells(
296 &mut self,
297 x: usize,
298 y: usize,
299 w: usize,
300 h: usize,
301 cells: &[Option<FieldCell>],
302 ) {
303 let mut src = cells.iter();
304 for yy in (y..y + h).step_by(4) {
305 let row = (yy / 4) * self.width4;
306 for xx in (x..x + w).step_by(4) {
307 if let Some(cell) = src.next() {
308 self.cells[row + xx / 4] = *cell;
309 }
310 }
311 }
312 }
313
314 /// Store the motion of the `w` by `h` block at `(x, y)`, decoded in `slice`.
315 pub fn store(&mut self, x: usize, y: usize, w: usize, h: usize, slice: u16, motion: PbMotion) {
316 let x_end = (x + w).min(self.width);
317 let y_end = (y + h).min(self.height);
318 for yy in (y..y_end).step_by(4) {
319 for xx in (x..x_end).step_by(4) {
320 self.cells[(yy / 4 - self.origin4) * self.width4 + xx / 4] =
321 Some(FieldCell { motion, slice });
322 }
323 }
324 let mut words = [0u64; 8];
325 words[0] = x as u64;
326 words[1] = y as u64;
327 words[2] = w as u64;
328 words[3] = h as u64;
329 words[4] = u64::from(slice);
330 words[5] = u64::from(motion.pred[0]) | (u64::from(motion.pred[1]) << 1);
331 words[6] = (motion.ref_idx[0] as u8 as u64) | ((motion.ref_idx[1] as u8 as u64) << 8);
332 words[7] = (motion.mv[0][0] as u16 as u64)
333 | ((motion.mv[0][1] as u16 as u64) << 16)
334 | ((motion.mv[1][0] as u16 as u64) << 32)
335 | ((motion.mv[1][1] as u16 as u64) << 48);
336 if self.band {
337 self.words.extend_from_slice(&words);
338 return;
339 }
340 for word in words {
341 self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME);
342 }
343 }
344
345 /// A hash of every stored block, in decoding order. Equal for equal derivations.
346 pub fn checksum(&self) -> u64 {
347 self.checksum
348 }
349
350 /// The motion of every 4x4 unit in the form the deblocking filter reads (8.7.2.4).
351 /// A list's reference picture is named by its POC, which identifies a picture
352 /// among those one slice refers to; intra and undecoded units stay at the default.
353 pub fn deblock_units(&self) -> Vec<PuMotion> {
354 (0..self.cells.len())
355 .map(|i| self.deblock_unit(i))
356 .collect()
357 }
358
359 /// The deblocking motion of the 4x4 unit `i` (see [`MotionField::deblock_units`]).
360 fn deblock_unit(&self, i: usize) -> PuMotion {
361 let Some(cell) = self.cells[i] else {
362 return PuMotion::default();
363 };
364 let refs = self.slices.get(usize::from(cell.slice));
365 let mut ref_pic = [-1i32; 2];
366 for (list, slot) in ref_pic.iter_mut().enumerate() {
367 if cell.motion.pred[list] {
368 let idx = usize::try_from(cell.motion.ref_idx[list]).unwrap_or(0);
369 *slot = refs
370 .and_then(|r| r.poc[list].get(idx))
371 .copied()
372 .unwrap_or(-1);
373 }
374 }
375 PuMotion {
376 pred: cell.motion.pred,
377 ref_pic,
378 mv: cell.motion.mv.map(|v| [i32::from(v[0]), i32::from(v[1])]),
379 }
380 }
381
382 /// The motion of the luma rows `y0..y1` in the form the deblocking filter reads
383 /// (see [`MotionField::deblock_units`]), written to `out` (one entry per 4x4
384 /// unit of the picture, row-major). `y0` and `y1` are multiples of 4.
385 pub fn deblock_rows(&self, out: &mut [PuMotion], y0: usize, y1: usize) {
386 let (u0, u1) = ((y0 / 4) * self.width4, (y1 / 4) * self.width4);
387 for (i, slot) in out.iter_mut().enumerate().take(u1).skip(u0) {
388 *slot = self.deblock_unit(i);
389 }
390 }
391}
392
393/// The collocated picture's motion, kept with the picture in the DPB.
394#[derive(Clone, Debug, PartialEq, Eq)]
395pub struct ColField {
396 /// `PicOrderCntVal` of the picture.
397 pub poc: i32,
398 width: usize,
399 height: usize,
400 width16: usize,
401 cells: Vec<Option<FieldCell>>,
402 slices: Vec<SliceRefs>,
403}
404
405impl ColField {
406 /// The collocated view of a picture of `width` by `height` luma samples, with no
407 /// motion yet: [`ColField::fill_rows`] adds it as the rows are decoded.
408 pub fn new(poc: i32, width: usize, height: usize) -> ColField {
409 let width16 = width.div_ceil(16);
410 ColField {
411 poc,
412 width,
413 height,
414 width16,
415 cells: vec![None; width16 * height.div_ceil(16)],
416 slices: Vec::new(),
417 }
418 }
419
420 /// Take the top-left 4x4 of each 16x16 block whose top row lies in the luma rows
421 /// `y0..y1` from `field` (8.5.3.2.8), and the slices' reference lists. `y0` is a
422 /// multiple of 16, and the rows must be final in `field`.
423 pub fn fill_rows(&mut self, field: &MotionField, y0: usize, y1: usize) {
424 self.slices.clone_from(&field.slices);
425 let (b0, b1) = (y0 / 16, y1.div_ceil(16).min(self.height.div_ceil(16)));
426 for by in b0..b1 {
427 for bx in 0..self.width16 {
428 self.cells[by * self.width16 + bx] =
429 field.at((bx * 16) as isize, (by * 16) as isize);
430 }
431 }
432 }
433
434 /// The entry of the 16x16 block containing `(x, y)`, with its slice's reference
435 /// lists. `None` outside the picture, and for intra blocks.
436 fn at(&self, x: usize, y: usize) -> Option<(FieldCell, &SliceRefs)> {
437 if x >= self.width || y >= self.height {
438 return None;
439 }
440 let cell = self.cells[(y >> 4) * self.width16 + (x >> 4)]?;
441 let refs = self.slices.get(usize::from(cell.slice))?;
442 Some((cell, refs))
443 }
444}
445
446/// The collocated picture of a slice (8.5.3.2.8): `RefPicList1[collocated_ref_idx]`
447/// for a B slice with `collocated_from_l0_flag` 0, else `RefPicList0[...]`. `None`
448/// when temporal motion prediction is off, for I slices, and when the picture kept
449/// no motion.
450pub fn collocated(dpb: &Dpb, header: &SliceHeader, lists: &RefPicLists) -> Option<Arc<SharedPic>> {
451 if !header.temporal_mvp_enabled || header.slice_type == SliceType::I {
452 return None;
453 }
454 let list = if header.slice_type == SliceType::B && !header.collocated_from_l0 {
455 &lists.l1
456 } else {
457 &lists.l0
458 };
459 let entry = list.get(usize::try_from(header.collocated_ref_idx).ok()?)?;
460 Some(Arc::clone(&dpb.get(entry.id)?.picture))
461}
462
463/// The slice-level parameters the merge and AMVP derivations read.
464#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465pub struct MotionParams {
466 /// The slice is a B slice.
467 pub is_b: bool,
468 /// `MaxNumMergeCand`.
469 pub max_merge_cand: usize,
470 /// `Log2ParMrgLevel`.
471 pub log2_par_mrg_level: u32,
472 /// `CtbLog2SizeY`.
473 pub ctb_log2: u32,
474 /// `collocated_from_l0_flag`.
475 pub collocated_from_l0: bool,
476 /// `slice_temporal_mvp_enabled_flag`.
477 pub temporal_mvp: bool,
478 /// `NoBackwardPredFlag`: no reference picture follows the current one in output order.
479 pub no_backward_pred: bool,
480}
481
482/// The [`MotionSource`] of the decoder: derives each prediction unit's motion with
483/// the merge or AMVP process and stores it in the picture's motion field.
484pub struct SliceMotion<'a> {
485 /// Slice parameters.
486 pub params: MotionParams,
487 /// The slice's reference picture lists.
488 pub lists: &'a RefPicLists,
489 /// `PicOrderCntVal` of the current picture.
490 pub cur_poc: i32,
491 /// The motion field of the current picture.
492 pub field: &'a mut MotionField,
493 /// The collocated picture, if temporal prediction applies.
494 pub col: Option<Arc<SharedPic>>,
495 /// The picture this slice belongs to, when its rows are published as they are
496 /// decoded (see [`MotionSource::row_done`]).
497 pub publish: Option<Arc<SharedPic>>,
498 /// Index of this slice in the picture's slice list.
499 pub slice: u16,
500}
501
502impl<'a> SliceMotion<'a> {
503 /// The source for one slice of the current picture.
504 #[allow(clippy::too_many_arguments)] // the slice's parameters are all needed here
505 pub fn new(
506 sps: &Sps,
507 pps: &Pps,
508 header: &SliceHeader,
509 lists: &'a RefPicLists,
510 cur_poc: i32,
511 field: &'a mut MotionField,
512 col: Option<Arc<SharedPic>>,
513 slice: u16,
514 ) -> SliceMotion<'a> {
515 let ctb_log2 = sps.log2_min_cb_size_minus3 + 3 + sps.log2_diff_max_min_cb_size;
516 let no_backward_pred = lists
517 .l0
518 .iter()
519 .chain(lists.l1.iter())
520 .all(|e| e.poc <= cur_poc);
521 SliceMotion {
522 params: MotionParams {
523 is_b: header.slice_type == SliceType::B,
524 max_merge_cand: 5 - header.five_minus_max_num_merge_cand.min(4) as usize,
525 log2_par_mrg_level: pps.log2_parallel_merge_level_minus2 + 2,
526 ctb_log2,
527 collocated_from_l0: header.collocated_from_l0,
528 temporal_mvp: header.temporal_mvp_enabled,
529 no_backward_pred,
530 },
531 lists,
532 cur_poc,
533 field,
534 col,
535 publish: None,
536 slice,
537 }
538 }
539
540 /// The stored motion of the neighbouring block covering `(x, y)` when it is
541 /// available: decoded, inter coded and in this slice (6.4.1, 6.4.2).
542 pub fn neighbour(&self, x: isize, y: isize) -> Option<PbMotion> {
543 let cell = self.field.at(x, y)?;
544 let in_tile = self.field.tile_at(x as usize, y as usize) == self.field.cur_tile;
545 (cell.slice == self.slice && in_tile).then_some(cell.motion)
546 }
547
548 /// `RefPicListX[idx]` of the current slice.
549 pub fn ref_entry(&self, list: usize, idx: i8) -> Option<RefEntry> {
550 let entries = if list == 0 {
551 &self.lists.l0
552 } else {
553 &self.lists.l1
554 };
555 usize::try_from(idx)
556 .ok()
557 .and_then(|i| entries.get(i))
558 .copied()
559 }
560
561 /// `PicOrderCntVal` of `RefPicListX[idx]`.
562 pub fn ref_poc(&self, list: usize, idx: i8) -> Option<i32> {
563 self.ref_entry(list, idx).map(|e| e.poc)
564 }
565
566 /// Whether `RefPicListX[idx]` is a long-term reference.
567 pub fn ref_long_term(&self, list: usize, idx: i8) -> Option<bool> {
568 self.ref_entry(list, idx).map(|e| e.long_term)
569 }
570
571 /// The temporal luma vector predictor for the block `(x, y, w, h)` in list `lx`
572 /// with reference index `ref_idx` (8.5.3.2.8): the bottom-right collocated block
573 /// when it is inside the same CTB row and the picture, else the centre block.
574 pub fn temporal_mv(
575 &self,
576 x: usize,
577 y: usize,
578 w: usize,
579 h: usize,
580 lx: usize,
581 ref_idx: i8,
582 ) -> Option<[i32; 2]> {
583 let shared = self.col.as_deref()?;
584 let (xbr, ybr) = (x + w, y + h);
585 let ctb = self.params.ctb_log2;
586 // Both candidates lie in the CTB row of `y` (the bottom-right one only when it
587 // stays in that row), so the collocated rows up to the end of that row suffice.
588 let need = (((y >> ctb) + 1) << ctb).min(self.field.height());
589 let t = super::trace::now();
590 let waited = shared.wait_col_rows(need);
591 super::trace::since(super::trace::Phase::WaitCol, t);
592 waited.ok()?;
593 let col = shared.read_col();
594 if (y >> ctb) == (ybr >> ctb) && ybr < self.field.height() && xbr < self.field.width() {
595 let found = self.col_mv(&col, (xbr >> 4) << 4, (ybr >> 4) << 4, lx, ref_idx);
596 if found.is_some() {
597 return found;
598 }
599 }
600 let (xc, yc) = (x + (w >> 1), y + (h >> 1));
601 self.col_mv(&col, (xc >> 4) << 4, (yc >> 4) << 4, lx, ref_idx)
602 }
603
604 /// The collocated motion vector of the block at `(x, y)` (8.5.3.2.9), scaled to
605 /// the current reference (8.5.3.2.8 with the distance scaling).
606 fn col_mv(
607 &self,
608 col: &ColField,
609 x: usize,
610 y: usize,
611 lx: usize,
612 ref_idx: i8,
613 ) -> Option<[i32; 2]> {
614 let (cell, refs) = col.at(x, y)?;
615 let m = cell.motion;
616 let list_col = match (m.pred[0], m.pred[1]) {
617 (false, false) => return None,
618 (false, true) => 1,
619 (true, false) => 0,
620 (true, true) => {
621 if self.params.no_backward_pred {
622 lx
623 } else {
624 usize::from(self.params.collocated_from_l0)
625 }
626 }
627 };
628 let ref_col = usize::try_from(m.ref_idx[list_col]).ok()?;
629 let col_ref_poc = *refs.poc[list_col].get(ref_col)?;
630 let col_ref_lt = *refs.long_term[list_col].get(ref_col)?;
631 let cur = self.ref_entry(lx, ref_idx)?;
632 if cur.long_term != col_ref_lt {
633 return None;
634 }
635 let mv = to32(m.mv[list_col]);
636 let col_diff = col.poc - col_ref_poc;
637 let cur_diff = self.cur_poc - cur.poc;
638 if cur.long_term || col_diff == cur_diff {
639 Some(mv)
640 } else {
641 Some(scale_mv(mv, col_diff, cur_diff))
642 }
643 }
644}
645
646impl MotionSource for SliceMotion<'_> {
647 fn row_done(&mut self, pic: &mut PicState, row_end: usize) {
648 // The CTB row that ended is `row_end - ctb`; its motion is final.
649 let ctb = 1usize << self.params.ctb_log2;
650 let y0 = row_end.saturating_sub(ctb);
651 if pic.has_pixels() {
652 let (u0, u1) = (y0, row_end.min(self.field.height()));
653 self.field.deblock_rows(&mut pic.motion, u0, u1);
654 }
655 if let Some(shared) = &self.publish {
656 shared.publish_col(self.field, row_end);
657 }
658 }
659
660 fn band_cells(&mut self) -> Option<&mut MotionField> {
661 Some(&mut *self.field)
662 }
663
664 fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion {
665 self.field.cur_tile = self.field.tile_at(cu.x, cu.y);
666 let derived = if pu.merge_flag {
667 merge::derive_merge(self, cu, pu_index, pu)
668 } else {
669 amvp::derive_amvp(self, pu)
670 };
671 self.field
672 .store(pu.x, pu.y, pu.width, pu.height, self.slice, derived);
673 derived.to_motion()
674 }
675}
676
677/// `mvLX` scaled by the POC distances (8-180 to 8-183): `td` is the distance of the
678/// reference the vector points to, `tb` the distance of the target reference, both
679/// as `DiffPicOrderCnt` values before clipping. A zero `td` leaves the vector as it is.
680pub fn scale_mv(mv: [i32; 2], td: i32, tb: i32) -> [i32; 2] {
681 let td = td.clamp(-128, 127);
682 let tb = tb.clamp(-128, 127);
683 if td == 0 {
684 return mv;
685 }
686 let tx = (16384 + (td.abs() >> 1)) / td;
687 let dist_scale = ((tb * tx + 32) >> 6).clamp(-4096, 4095);
688 mv.map(|c| {
689 let p = dist_scale * c;
690 let sign = if p < 0 { -1 } else { 1 };
691 (sign * ((p.abs() + 127) >> 8)).clamp(-32768, 32767)
692 })
693}
694
695/// The chroma vector of 4:2:0 content, in 1/8 chroma sample units (8.5.3.2.10):
696/// the luma quarter-sample vector, unchanged in value.
697pub fn chroma_mv_420(mv: [i16; 2]) -> [i32; 2] {
698 to32(mv)
699}
700
701/// A vector widened to `i32`.
702pub fn to32(mv: [i16; 2]) -> [i32; 2] {
703 [i32::from(mv[0]), i32::from(mv[1])]
704}
705
706/// A vector clipped to the 16-bit range of a stored vector.
707pub fn to16(mv: [i32; 2]) -> [i16; 2] {
708 [
709 mv[0].clamp(-32768, 32767) as i16,
710 mv[1].clamp(-32768, 32767) as i16,
711 ]
712}