forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mc.rs480 lines, 16.1 KiBHistoryRawDownload
1//! Motion compensation (8.5.3.3): fractional sample interpolation and the
2//! prediction-unit driver that turns a motion vector into final samples.
3//!
4//! Samples are `u16` planes of 8 to 10 bits, 4:2:0 chroma. The interpolation is
5//! separable and keeps the spec's intermediate precision: `predSamplesLX` values
6//! live in `i32` buffers. Reference coordinates are clamped to the picture per
7//! sample (the spec's `Clip3`); the source window is gathered once per block so
8//! the filter loops need no bounds logic. Scratch buffers are reused across calls
9//! through [`McScratch`], so the hot path does not allocate after warm-up.
10
11use super::cu_syntax::Motion;
12use super::weighted::{ExplicitWeights, Weight, store};
13use ec_core::error::{Error, Result};
14
15/// The largest prediction block side (a 64x64 PU).
16pub const MAX_PU: usize = 64;
17
18/// Table 8-11: the luma 8-tap filters, indexed by quarter-sample fraction. Index 0
19/// is the full-sample position, which the interpolation never filters.
20pub const LUMA_FILTER: [[i32; 8]; 4] = [
21 [0, 0, 0, 64, 0, 0, 0, 0],
22 [-1, 4, -10, 58, 17, -5, 1, 0],
23 [-1, 4, -11, 40, 40, -11, 4, -1],
24 [0, 1, -5, 17, 58, -10, 4, -1],
25];
26
27/// Table 8-12: the chroma 4-tap filters, indexed by eighth-sample fraction. Index 0
28/// is the full-sample position, which the interpolation never filters.
29pub const CHROMA_FILTER: [[i32; 4]; 8] = [
30 [0, 64, 0, 0],
31 [-2, 58, 10, -2],
32 [-4, 54, 16, -2],
33 [-6, 46, 28, -4],
34 [-4, 36, 36, -4],
35 [-4, 28, 46, -6],
36 [-2, 16, 54, -4],
37 [-2, 10, 58, -2],
38];
39
40/// One sample plane of a reference picture.
41#[derive(Clone, Copy, Debug)]
42pub struct PlaneRef<'a> {
43 /// Samples, row-major, `stride` apart.
44 pub samples: &'a [u16],
45 /// Distance between row starts.
46 pub stride: usize,
47 /// Plane width in samples: the clamping bound of the reference coordinates.
48 pub width: usize,
49 /// Plane height in samples.
50 pub height: usize,
51 /// `BitDepthY` or `BitDepthC`, 8 to 10.
52 pub bit_depth: u32,
53}
54
55/// One writable sample plane of the picture being predicted.
56#[derive(Debug)]
57pub struct PlaneMut<'a> {
58 /// Samples, row-major, `stride` apart.
59 pub samples: &'a mut [u16],
60 /// Distance between row starts.
61 pub stride: usize,
62 /// `BitDepthY` or `BitDepthC`, 8 to 10.
63 pub bit_depth: u32,
64 /// The first row of `samples`, in the plane's own rows (zero for a whole plane).
65 pub origin: usize,
66}
67
68/// The Y, Cb and Cr planes of one reference picture.
69pub type RefPicture<'a> = [PlaneRef<'a>; 3];
70
71/// A rectangle inside one plane, in samples of that plane.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub struct Block {
74 /// Left column.
75 pub x: usize,
76 /// Top row.
77 pub y: usize,
78 /// Width in samples.
79 pub width: usize,
80 /// Height in samples.
81 pub height: usize,
82}
83
84/// Reusable scratch buffers for the motion compensation of one decoder.
85#[derive(Debug, Default)]
86pub struct McScratch {
87 /// The gathered reference window.
88 src: Vec<u16>,
89 /// The horizontally filtered rows of a two-dimensional interpolation.
90 tmp: Vec<i32>,
91 /// `predSamplesL0` and `predSamplesL1` of the current component.
92 pred: [Vec<i32>; 2],
93}
94
95impl McScratch {
96 /// Empty buffers; they grow to the largest block seen and stay there.
97 pub fn new() -> McScratch {
98 McScratch::default()
99 }
100}
101
102/// Predict one prediction unit into the three output planes.
103///
104/// `refs[list][ref_idx]` is the reference picture each list's `refIdxLX` names.
105/// `pu` is the luma rectangle; the chroma rectangle is half of it in each
106/// direction (4:2:0). `weights` selects explicit weighted prediction; `None` is
107/// the default weighted prediction. Each output plane receives the clipped final
108/// samples of the rectangle.
109pub fn predict_pu(
110 refs: [&[RefPicture<'_>]; 2],
111 motion: &Motion,
112 weights: Option<&ExplicitWeights>,
113 pu: Block,
114 out: &mut [PlaneMut<'_>; 3],
115 scratch: &mut McScratch,
116) -> Result<()> {
117 predict_pu_fmt(refs, motion, weights, pu, (1, 1), out, scratch)
118}
119
120/// [`predict_pu`] for any chroma subsampling. `sub` is the log2 `(sub_x, sub_y)` of the
121/// chroma planes: `(1, 1)` for 4:2:0, `(1, 0)` for 4:2:2, `(0, 0)` for 4:4:4. The chroma
122/// vector is then `mvLX * 2 / SubWidthC` and `mvLX * 2 / SubHeightC` in 1/8 chroma samples
123/// (8.5.3.2.10), and the chroma rectangle is `pu` shifted by `sub`.
124#[allow(clippy::too_many_arguments)] // the PU's refs, motion, weights and output
125pub fn predict_pu_fmt(
126 refs: [&[RefPicture<'_>]; 2],
127 motion: &Motion,
128 weights: Option<&ExplicitWeights>,
129 pu: Block,
130 sub: (u32, u32),
131 out: &mut [PlaneMut<'_>; 3],
132 scratch: &mut McScratch,
133) -> Result<()> {
134 let used = motion.pred_flags;
135 if !used[0] && !used[1] {
136 return Err(Error::corrupt(
137 "HEVC motion compensation: a prediction unit with no list in use",
138 ));
139 }
140 let mut pics: [Option<&RefPicture<'_>>; 2] = [None, None];
141 let mut ref_idx = [0usize; 2];
142 for list in 0..2 {
143 if !used[list] {
144 continue;
145 }
146 let idx = usize::try_from(motion.ref_idx[list])
147 .ok()
148 .filter(|&i| i < refs[list].len())
149 .ok_or_else(|| {
150 Error::corrupt(format!(
151 "HEVC motion compensation: refIdxL{list} = {} has no picture",
152 motion.ref_idx[list]
153 ))
154 })?;
155 ref_idx[list] = idx;
156 pics[list] = Some(&refs[list][idx]);
157 }
158 let McScratch { src, tmp, pred } = scratch;
159 for comp in 0..3 {
160 let luma = comp == 0;
161 let blk = if luma {
162 pu
163 } else {
164 Block {
165 x: pu.x >> sub.0,
166 y: pu.y >> sub.1,
167 width: pu.width >> sub.0,
168 height: pu.height >> sub.1,
169 }
170 };
171 check_out(&out[comp], blk)?;
172 for (list, buf) in pred.iter_mut().enumerate() {
173 let Some(pic) = pics[list] else { continue };
174 buf.resize(blk.width * blk.height, 0);
175 // Chroma vector (8.5.3.2.10): mvCLX = mvLX * 2 / SubWidthC (and SubHeightC),
176 // in 1/8 chroma samples.
177 let mv = if luma {
178 motion.mv[list]
179 } else {
180 let m = motion.mv[list];
181 [(m[0] * 2) >> sub.0, (m[1] * 2) >> sub.1]
182 };
183 interp_component(&pic[comp], blk, mv, luma, src, tmp, buf)?;
184 }
185 let explicit = match weights {
186 Some(ew) => {
187 let mut w = [Weight::default(); 2];
188 for (list, slot) in w.iter_mut().enumerate() {
189 if used[list] {
190 *slot = ew.lookup(list, ref_idx[list], comp)?;
191 }
192 }
193 Some((ew.log2_denom[comp], w))
194 }
195 None => None,
196 };
197 let preds = [
198 used[0].then(|| pred[0].as_slice()),
199 used[1].then(|| pred[1].as_slice()),
200 ];
201 store(&mut out[comp], blk, preds, explicit)?;
202 }
203 Ok(())
204}
205
206/// The luma fractional sample interpolation (8.5.3.3.3.1) of one block.
207///
208/// `mv` is the motion vector in quarter samples. The `blk.width * blk.height`
209/// results of `predSamplesLX` are written to `out` row by row, at 14-bit precision.
210pub fn interp_luma(
211 plane: &PlaneRef<'_>,
212 blk: Block,
213 mv: [i32; 2],
214 scratch: &mut McScratch,
215 out: &mut [i32],
216) -> Result<()> {
217 check_plane(plane)?;
218 check_block(blk, out.len())?;
219 let McScratch { src, tmp, .. } = scratch;
220 interp_component(plane, blk, mv, true, src, tmp, out)
221}
222
223/// The chroma fractional sample interpolation (8.5.3.3.3.2) of one block, 4:2:0.
224///
225/// `mv` is the luma motion vector in quarter samples, which in 4:2:0 is the
226/// chroma motion vector in eighth samples. `blk` is in chroma samples.
227pub fn interp_chroma(
228 plane: &PlaneRef<'_>,
229 blk: Block,
230 mv: [i32; 2],
231 scratch: &mut McScratch,
232 out: &mut [i32],
233) -> Result<()> {
234 check_plane(plane)?;
235 check_block(blk, out.len())?;
236 let McScratch { src, tmp, .. } = scratch;
237 interp_component(plane, blk, mv, false, src, tmp, out)
238}
239
240/// Interpolate one block of one component, luma or 4:2:0 chroma.
241fn interp_component(
242 plane: &PlaneRef<'_>,
243 blk: Block,
244 mv: [i32; 2],
245 luma: bool,
246 src: &mut Vec<u16>,
247 tmp: &mut Vec<i32>,
248 out: &mut [i32],
249) -> Result<()> {
250 if luma {
251 let (x_int, y_int) = (
252 blk.x as i64 + i64::from(mv[0] >> 2),
253 blk.y as i64 + i64::from(mv[1] >> 2),
254 );
255 let fx = (mv[0] & 3 != 0).then(|| &LUMA_FILTER[(mv[0] & 3) as usize]);
256 let fy = (mv[1] & 3 != 0).then(|| &LUMA_FILTER[(mv[1] & 3) as usize]);
257 interpolate(
258 plane,
259 (x_int, y_int),
260 (blk.width, blk.height),
261 [fx, fy],
262 src,
263 tmp,
264 out,
265 );
266 } else {
267 let (x_int, y_int) = (
268 blk.x as i64 + i64::from(mv[0] >> 3),
269 blk.y as i64 + i64::from(mv[1] >> 3),
270 );
271 let fx = (mv[0] & 7 != 0).then(|| &CHROMA_FILTER[(mv[0] & 7) as usize]);
272 let fy = (mv[1] & 7 != 0).then(|| &CHROMA_FILTER[(mv[1] & 7) as usize]);
273 interpolate(
274 plane,
275 (x_int, y_int),
276 (blk.width, blk.height),
277 [fx, fy],
278 src,
279 tmp,
280 out,
281 );
282 }
283 Ok(())
284}
285
286/// The shared separable interpolation for a `T`-tap filter (`T` = 8 luma, 4 chroma).
287///
288/// `at` is the integer position of the block's top-left sample in the reference
289/// plane, `filters` the horizontal and vertical coefficients (`None` when that
290/// direction is at a full-sample position). The equations of 8.5.3.3.3 are
291/// `shift1 = Min(4, BitDepth - 8)`, `shift2 = 6`, `shift3 = Max(2, 14 - BitDepth)`.
292fn interpolate<const T: usize>(
293 plane: &PlaneRef<'_>,
294 at: (i64, i64),
295 size: (usize, usize),
296 filters: [Option<&[i32; T]>; 2],
297 src: &mut Vec<u16>,
298 tmp: &mut Vec<i32>,
299 out: &mut [i32],
300) {
301 let (w, h) = size;
302 let pad = T / 2 - 1;
303 let bw = w + T - 1;
304 let bh = h + T - 1;
305 let (x0, y0) = (at.0 - pad as i64, at.1 - pad as i64);
306 // A window wholly inside the plane is read in place; otherwise it is gathered
307 // with the reference coordinates clamped.
308 let inside =
309 x0 >= 0 && y0 >= 0 && x0 as usize + bw <= plane.width && y0 as usize + bh <= plane.height;
310 let (view, vs): (&[u16], usize) = if inside {
311 (
312 &plane.samples[y0 as usize * plane.stride + x0 as usize..],
313 plane.stride,
314 )
315 } else {
316 gather(plane, x0, y0, bw, bh, src);
317 (src.as_slice(), bw)
318 };
319 let bd = plane.bit_depth;
320 let shift1 = (bd - 8).min(4);
321 let shift3 = 14u32.saturating_sub(bd).max(2);
322 let out = &mut out[..w * h];
323 match filters {
324 [None, None] => {
325 for (r, out_row) in out.chunks_exact_mut(w).enumerate() {
326 let row = &view[(r + pad) * vs + pad..][..w];
327 for (o, &s) in out_row.iter_mut().zip(row) {
328 *o = i32::from(s) << shift3;
329 }
330 }
331 }
332 [Some(cx), None] => {
333 for (r, out_row) in out.chunks_exact_mut(w).enumerate() {
334 filter_row(&view[(r + pad) * vs..][..bw], cx, shift1, out_row);
335 }
336 }
337 [None, Some(cy)] => {
338 for (r, out_row) in out.chunks_exact_mut(w).enumerate() {
339 filter_col(&view[r * vs + pad..], vs, cy, shift1, out_row);
340 }
341 }
342 [Some(cx), Some(cy)] => {
343 tmp.resize(bh * w, 0);
344 for (r, tmp_row) in tmp.chunks_exact_mut(w).enumerate() {
345 filter_row(&view[r * vs..][..bw], cx, shift1, tmp_row);
346 }
347 for (r, out_row) in out.chunks_exact_mut(w).enumerate() {
348 filter_col(&tmp[r * w..], w, cy, 6, out_row);
349 }
350 }
351 }
352}
353
354/// One horizontal filter pass: `out[c] = (sum_i coef[i] * row[c + i]) >> shift`.
355///
356/// The taps run in the outer loop so each pass is a plain multiply-add over a
357/// contiguous run of outputs, which the compiler vectorises. `out.len()` is at most
358/// [`MAX_PU`], the accumulator size.
359fn filter_row<const T: usize>(row: &[u16], coef: &[i32; T], shift: u32, out: &mut [i32]) {
360 filter_taps(coef, row, 1, shift, out);
361}
362
363/// One vertical filter pass: `out[c] = (sum_i coef[i] * src[i * stride + c]) >> shift`.
364/// Same shape as [`filter_row`], with the taps `stride` apart.
365fn filter_col<S: Copy + Into<i32>, const T: usize>(
366 src: &[S],
367 stride: usize,
368 coef: &[i32; T],
369 shift: u32,
370 out: &mut [i32],
371) {
372 filter_taps(coef, src, stride, shift, out);
373}
374
375/// The shared tap loop of [`filter_row`] and [`filter_col`]. The taps run in the
376/// outer loop so each pass is a plain multiply-add over a contiguous run of outputs.
377fn filter_taps<S: Copy + Into<i32>, const T: usize>(
378 coef: &[i32; T],
379 src: &[S],
380 stride: usize,
381 shift: u32,
382 out: &mut [i32],
383) {
384 let n = out.len();
385 let mut acc = [0i32; MAX_PU];
386 let acc = &mut acc[..n];
387 for (i, &k) in coef.iter().enumerate() {
388 for (a, &s) in acc.iter_mut().zip(&src[i * stride..][..n]) {
389 *a += k * s.into();
390 }
391 }
392 for (o, &a) in out.iter_mut().zip(acc.iter()) {
393 *o = a >> shift;
394 }
395}
396
397/// Copy the `bw x bh` reference window whose top-left sample is `(x0, y0)` into
398/// `src`, clamping every coordinate into the plane (the spec's `Clip3` on
399/// `xInt` and `yInt`, applied per sample). A window inside the plane horizontally is
400/// copied a row at a time.
401fn gather(plane: &PlaneRef<'_>, x0: i64, y0: i64, bw: usize, bh: usize, src: &mut Vec<u16>) {
402 src.resize(bw * bh, 0);
403 let max_x = plane.width as i64 - 1;
404 let max_y = plane.height as i64 - 1;
405 let inside_x = x0 >= 0 && x0 + bw as i64 - 1 <= max_x;
406 for (r, dst_row) in src.chunks_exact_mut(bw).enumerate() {
407 let sy = (y0 + r as i64).clamp(0, max_y) as usize;
408 let row = &plane.samples[sy * plane.stride..sy * plane.stride + plane.width];
409 if inside_x {
410 let x = x0 as usize;
411 dst_row.copy_from_slice(&row[x..x + bw]);
412 } else {
413 for (c, d) in dst_row.iter_mut().enumerate() {
414 *d = row[(x0 + c as i64).clamp(0, max_x) as usize];
415 }
416 }
417 }
418}
419
420/// Reject a plane whose geometry or bit depth the interpolation cannot read.
421pub(super) fn check_plane(p: &PlaneRef<'_>) -> Result<()> {
422 if p.width == 0
423 || p.height == 0
424 || p.stride < p.width
425 || p.samples.len() < p.stride * (p.height - 1) + p.width
426 {
427 return Err(Error::corrupt(
428 "HEVC motion compensation: reference plane geometry",
429 ));
430 }
431 check_depth(p.bit_depth)
432}
433
434/// Reject a bit depth outside the 8 to 10 bits this module handles.
435pub(super) fn check_depth(bit_depth: u32) -> Result<()> {
436 if (8..=12).contains(&bit_depth) {
437 Ok(())
438 } else {
439 Err(Error::unsupported(
440 format!("bit depth {bit_depth}"),
441 "motion compensation handles 8 to 10 bits",
442 ))
443 }
444}
445
446/// Reject a block that is empty, larger than a PU, or too big for its buffer.
447fn check_block(blk: Block, out_len: usize) -> Result<()> {
448 if blk.width == 0
449 || blk.height == 0
450 || blk.width > MAX_PU
451 || blk.height > MAX_PU
452 || blk.width * blk.height > out_len
453 {
454 return Err(Error::corrupt(
455 "HEVC motion compensation: block size or output buffer",
456 ));
457 }
458 Ok(())
459}
460
461/// Reject an output rectangle that does not fit inside its plane.
462pub(super) fn check_out(dst: &PlaneMut<'_>, blk: Block) -> Result<()> {
463 if blk.width == 0 || blk.height == 0 || blk.x + blk.width > dst.stride || blk.y < dst.origin {
464 return Err(Error::corrupt(
465 "HEVC motion compensation: output rectangle outside the plane",
466 ));
467 }
468 // The last sample written is the bottom-right one.
469 let last = (blk.y + blk.height - 1 - dst.origin) * dst.stride + blk.x + blk.width - 1;
470 if last >= dst.samples.len() {
471 return Err(Error::corrupt(
472 "HEVC motion compensation: output rectangle outside the plane",
473 ));
474 }
475 check_depth(dst.bit_depth)
476}
477
478#[cfg(test)]
479#[path = "mc_tests.rs"]
480mod tests;