forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

mc.rs93 lines, 3.1 KiBHistoryRawDownload
1//! Motion compensation primitives (7.6.4): half-sample interpolation from a
2//! reference image with edge replication.
3
4/// A reference image (one plane of a picture), optionally one field of it.
5#[derive(Clone, Copy)]
6pub(crate) struct Image<'a> {
7 pub(crate) data: &'a [u8],
8 pub(crate) stride: usize,
9 /// Width in samples.
10 pub(crate) w: usize,
11 /// Height in lines of this image (half the plane for a field).
12 pub(crate) h: usize,
13 /// `Some(parity)` when reading one field of the plane.
14 pub(crate) field: Option<u8>,
15}
16
17impl Image<'_> {
18 #[inline(always)]
19 fn row(&self, line: i32) -> &[u8] {
20 let l = line.clamp(0, self.h as i32 - 1) as usize;
21 let r = match self.field {
22 Some(p) => 2 * l + p as usize,
23 None => l,
24 };
25 &self.data[r * self.stride..r * self.stride + self.w]
26 }
27}
28
29/// Predict a `w` x `rows` block at integer position (`x`, `y`) with half-sample
30/// fractions (`fx`, `fy`); rows are written to `dst` at line `dst_row0 +
31/// k * dst_step` (pitch 16). With `avg` the result is averaged into `dst`.
32#[allow(clippy::too_many_arguments)]
33pub(crate) fn predict(
34 img: &Image,
35 x: i32,
36 y: i32,
37 fx: bool,
38 fy: bool,
39 w: usize,
40 rows: usize,
41 dst: &mut [u8; 256],
42 dst_row0: usize,
43 dst_step: usize,
44 avg: bool,
45) {
46 // Source patch of (rows + 1) lines of (w + 1) samples.
47 let mut patch = [[0u8; 17]; 17];
48 let inside = x >= 0 && (x as usize) + w < img.w;
49 for (j, prow) in patch.iter_mut().enumerate().take(rows + 1) {
50 let src = img.row(y + j as i32);
51 if inside {
52 prow[..w + 1].copy_from_slice(&src[x as usize..x as usize + w + 1]);
53 } else {
54 for (i, p) in prow.iter_mut().enumerate().take(w + 1) {
55 *p = src[(x + i as i32).clamp(0, img.w as i32 - 1) as usize];
56 }
57 }
58 }
59 for j in 0..rows {
60 let out = &mut dst[(dst_row0 + j * dst_step) * 16..][..w];
61 let a = &patch[j];
62 let b = &patch[j + 1];
63 match (fx, fy) {
64 (false, false) => {
65 if avg {
66 for i in 0..w {
67 out[i] = ((out[i] as u32 + a[i] as u32 + 1) >> 1) as u8;
68 }
69 } else {
70 out.copy_from_slice(&a[..w]);
71 }
72 }
73 (true, false) => {
74 for i in 0..w {
75 let v = (a[i] as u32 + a[i + 1] as u32 + 1) >> 1;
76 out[i] = if avg { ((out[i] as u32 + v + 1) >> 1) as u8 } else { v as u8 };
77 }
78 }
79 (false, true) => {
80 for i in 0..w {
81 let v = (a[i] as u32 + b[i] as u32 + 1) >> 1;
82 out[i] = if avg { ((out[i] as u32 + v + 1) >> 1) as u8 } else { v as u8 };
83 }
84 }
85 (true, true) => {
86 for i in 0..w {
87 let v = (a[i] as u32 + a[i + 1] as u32 + b[i] as u32 + b[i + 1] as u32 + 2) >> 2;
88 out[i] = if avg { ((out[i] as u32 + v + 1) >> 1) as u8 } else { v as u8 };
89 }
90 }
91 }
92 }
93}