forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

intra.rs528 lines, 17.3 KiBHistoryRawDownload
1//! Intra sample prediction, all 35 modes (8.4.2 - 8.4.4.2).
2//!
3//! Reference samples arrive as `corner` (`p[-1][-1]`), `top` (`p[x][-1]`) and
4//! `left` (`p[-1][y]`), each up to `2 * nTbS` long, with a bitmask saying which
5//! of them are real. Substitution, smoothing and the mode itself are then
6//! exactly the decoder's, because the encoder reconstructs with the same code:
7//! a prediction that differs from the decoder's by one sample is a drift that
8//! the picture hash would catch but the eye would not.
9
10/// Reference samples for one transform block, before or after filtering.
11#[derive(Clone, Copy)]
12pub struct Refs {
13 /// `p[-1][-1]`.
14 pub corner: u8,
15 /// `p[x][-1]`, `x = 0..2 * nTbS - 1`.
16 pub top: [u8; 64],
17 /// `p[-1][y]`, `y = 0..2 * nTbS - 1`.
18 pub left: [u8; 64],
19}
20
21impl Default for Refs {
22 fn default() -> Self {
23 Refs {
24 corner: 128,
25 top: [128; 64],
26 left: [128; 64],
27 }
28 }
29}
30
31/// Which reference samples are real, one bit per sample.
32#[derive(Clone, Copy, Default)]
33pub struct Availability {
34 /// Whether `p[-1][-1]` is available.
35 pub corner: bool,
36 /// Bit `x` set when `p[x][-1]` is available.
37 pub top: u64,
38 /// Bit `y` set when `p[-1][y]` is available.
39 pub left: u64,
40}
41
42impl Availability {
43 /// True when nothing at all is available and the whole block predicts flat.
44 pub fn is_empty(&self, n: usize) -> bool {
45 let mask = if 2 * n >= 64 {
46 u64::MAX
47 } else {
48 (1u64 << (2 * n)) - 1
49 };
50 !self.corner && self.top & mask == 0 && self.left & mask == 0
51 }
52}
53
54/// `intraPredAngle` per mode (Table 8-5), indexed by `predModeIntra`.
55#[rustfmt::skip]
56const ANGLE: [i32; 35] = [
57 0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26,
58 -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32,
59];
60
61/// `invAngle` per mode (Table 8-6); only modes 11..25 use it.
62#[rustfmt::skip]
63const INV_ANGLE: [i32; 35] = [
64 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
65 -4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096,
66 0, 0, 0, 0, 0, 0, 0, 0, 0,
67];
68
69/// Reference sample substitution (8.4.4.2.2): fill the holes from the nearest
70/// available sample, walking up the left edge and then along the top.
71pub fn substitute(refs: &mut Refs, avail: &Availability, n: usize, bit_depth: u32) {
72 let span = 2 * n;
73 if avail.is_empty(n) {
74 let mid = 1u8 << (bit_depth - 1);
75 refs.corner = mid;
76 refs.top[..span].fill(mid);
77 refs.left[..span].fill(mid);
78 return;
79 }
80 // Step 1: the bottom-left sample, from the first available going up the
81 // left edge, then across the top.
82 if avail.left & (1 << (span - 1)) == 0 {
83 let mut value = None;
84 for y in (0..span).rev() {
85 if avail.left & (1 << y) != 0 {
86 value = Some(refs.left[y]);
87 break;
88 }
89 }
90 if value.is_none() && avail.corner {
91 value = Some(refs.corner);
92 }
93 if value.is_none() {
94 for x in 0..span {
95 if avail.top & (1 << x) != 0 {
96 value = Some(refs.top[x]);
97 break;
98 }
99 }
100 }
101 refs.left[span - 1] = value.unwrap_or(1 << (bit_depth - 1));
102 }
103 // Step 2: up the left edge, each hole taking the sample below it.
104 for y in (0..span - 1).rev() {
105 if avail.left & (1 << y) == 0 {
106 refs.left[y] = refs.left[y + 1];
107 }
108 }
109 if !avail.corner {
110 refs.corner = refs.left[0];
111 }
112 // Step 3: along the top, each hole taking the sample to its left.
113 for x in 0..span {
114 if avail.top & (1 << x) == 0 {
115 refs.top[x] = if x == 0 { refs.corner } else { refs.top[x - 1] };
116 }
117 }
118}
119
120/// `filterFlag` of 8.4.4.2.3.
121fn filter_flag(mode: u8, n: usize, is_luma: bool) -> bool {
122 if !is_luma || mode == 1 || n == 4 {
123 return false;
124 }
125 let min_dist = (i32::from(mode) - 26)
126 .abs()
127 .min((i32::from(mode) - 10).abs());
128 let threshold = match n {
129 8 => 7,
130 16 => 1,
131 _ => 0,
132 };
133 min_dist > threshold
134}
135
136/// Neighbouring sample filtering (8.4.4.2.3), including the strong bilinear
137/// path for flat 32x32 luma blocks.
138pub fn filter_refs(refs: &Refs, mode: u8, n: usize, is_luma: bool, strong_smoothing: bool) -> Refs {
139 if !filter_flag(mode, n, is_luma) {
140 return *refs;
141 }
142 let span = 2 * n;
143 let mut out = *refs;
144 let bi_int = strong_smoothing
145 && is_luma
146 && n == 32
147 && (i32::from(refs.corner) + i32::from(refs.top[span - 1])
148 - 2 * i32::from(refs.top[n - 1]))
149 .abs()
150 < (1 << 3)
151 && (i32::from(refs.corner) + i32::from(refs.left[span - 1])
152 - 2 * i32::from(refs.left[n - 1]))
153 .abs()
154 < (1 << 3);
155 if bi_int {
156 let corner = i32::from(refs.corner);
157 let bottom_left = i32::from(refs.left[63]);
158 let top_right = i32::from(refs.top[63]);
159 for y in 0..63 {
160 out.left[y] =
161 (((63 - y as i32) * corner + (y as i32 + 1) * bottom_left + 32) >> 6) as u8;
162 }
163 out.left[63] = refs.left[63];
164 for x in 0..63 {
165 out.top[x] = (((63 - x as i32) * corner + (x as i32 + 1) * top_right + 32) >> 6) as u8;
166 }
167 out.top[63] = refs.top[63];
168 return out;
169 }
170 out.corner =
171 ((u32::from(refs.left[0]) + 2 * u32::from(refs.corner) + u32::from(refs.top[0]) + 2) >> 2)
172 as u8;
173 for y in 0..span - 1 {
174 let below = u32::from(refs.left[y + 1]);
175 let here = u32::from(refs.left[y]);
176 let above = if y == 0 {
177 u32::from(refs.corner)
178 } else {
179 u32::from(refs.left[y - 1])
180 };
181 out.left[y] = ((below + 2 * here + above + 2) >> 2) as u8;
182 }
183 for x in 0..span - 1 {
184 let right = u32::from(refs.top[x + 1]);
185 let here = u32::from(refs.top[x]);
186 let left = if x == 0 {
187 u32::from(refs.corner)
188 } else {
189 u32::from(refs.top[x - 1])
190 };
191 out.top[x] = ((right + 2 * here + left + 2) >> 2) as u8;
192 }
193 out
194}
195
196/// Predict an `n x n` block into `out` (row major), for `mode` 0..=34.
197///
198/// `refs` must already be substituted; filtering is applied here so that a
199/// caller trying 35 modes filters once per mode rather than per sample.
200pub fn predict(
201 refs: &Refs,
202 mode: u8,
203 n: usize,
204 is_luma: bool,
205 strong_smoothing: bool,
206 out: &mut [u8],
207) {
208 let filtered = filter_refs(refs, mode, n, is_luma, strong_smoothing);
209 match mode {
210 0 => predict_planar(&filtered, n, out),
211 1 => predict_dc(&filtered, n, is_luma, out),
212 _ => predict_angular(&filtered, mode, n, is_luma, out),
213 }
214}
215
216fn predict_planar(refs: &Refs, n: usize, out: &mut [u8]) {
217 let log2n = n.trailing_zeros();
218 let top_right = i32::from(refs.top[n]);
219 let bottom_left = i32::from(refs.left[n]);
220 for y in 0..n {
221 let left = i32::from(refs.left[y]);
222 for x in 0..n {
223 let value = (n as i32 - 1 - x as i32) * left
224 + (x as i32 + 1) * top_right
225 + (n as i32 - 1 - y as i32) * i32::from(refs.top[x])
226 + (y as i32 + 1) * bottom_left
227 + n as i32;
228 out[y * n + x] = (value >> (log2n + 1)) as u8;
229 }
230 }
231}
232
233fn predict_dc(refs: &Refs, n: usize, is_luma: bool, out: &mut [u8]) {
234 let mut sum = n as u32;
235 for i in 0..n {
236 sum += u32::from(refs.top[i]) + u32::from(refs.left[i]);
237 }
238 let dc = (sum >> (n.trailing_zeros() + 1)) as i32;
239 for value in out[..n * n].iter_mut() {
240 *value = dc as u8;
241 }
242 if is_luma && n < 32 {
243 out[0] = ((i32::from(refs.left[0]) + 2 * dc + i32::from(refs.top[0]) + 2) >> 2) as u8;
244 for (x, sample) in out[1..n].iter_mut().enumerate() {
245 *sample = ((i32::from(refs.top[x + 1]) + 3 * dc + 2) >> 2) as u8;
246 }
247 for y in 1..n {
248 out[y * n] = ((i32::from(refs.left[y]) + 3 * dc + 2) >> 2) as u8;
249 }
250 }
251}
252
253fn predict_angular(refs: &Refs, mode: u8, n: usize, is_luma: bool, out: &mut [u8]) {
254 let angle = ANGLE[mode as usize];
255 let inv_angle = INV_ANGLE[mode as usize];
256 // ref[] is indexed from -nTbS to 2 * nTbS; store it shifted by 32.
257 const BIAS: usize = 32;
258 let mut reference = [0i32; 32 + 65];
259 let (main, side): (&[u8; 64], &[u8; 64]) = if mode >= 18 {
260 (&refs.top, &refs.left)
261 } else {
262 (&refs.left, &refs.top)
263 };
264 reference[BIAS] = i32::from(refs.corner);
265 for x in 1..=n {
266 reference[BIAS + x] = i32::from(main[x - 1]);
267 }
268 if angle < 0 {
269 let last = (n as i32 * angle) >> 5;
270 if last < -1 {
271 for x in last..=-1 {
272 let idx = ((x * inv_angle + 128) >> 8) - 1;
273 reference[(BIAS as i32 + x) as usize] = if idx < 0 {
274 i32::from(refs.corner)
275 } else {
276 i32::from(side[idx as usize])
277 };
278 }
279 }
280 } else {
281 for x in n + 1..=2 * n {
282 reference[BIAS + x] = i32::from(main[x - 1]);
283 }
284 }
285 // `idx`/`fact` depend only on the "row" index along the prediction
286 // direction (y for the vertical modes, x for the horizontal ones — the
287 // whole difference between the two halves of 8.4.4.2.6), not on the
288 // position across it. The mode>=18 branch and the idx/fact division used
289 // to be recomputed at every one of the n*n pixels; hoisting them to one
290 // per row/column turns the inner loop into a contiguous, near-linear scan
291 // over `reference`, which is both fewer instructions and autovectorizes.
292 if mode >= 18 {
293 for y in 0..n {
294 let idx = ((y as i32 + 1) * angle) >> 5;
295 let fact = ((y as i32 + 1) * angle) & 31;
296 let base = (BIAS as i32 + idx + 1) as usize;
297 let row = &mut out[y * n..y * n + n];
298 if fact != 0 {
299 let (w0, w1) = (32 - fact, fact);
300 for x in 0..n {
301 row[x] =
302 ((w0 * reference[base + x] + w1 * reference[base + x + 1] + 16) >> 5) as u8;
303 }
304 } else {
305 for x in 0..n {
306 row[x] = reference[base + x] as u8;
307 }
308 }
309 }
310 } else {
311 for x in 0..n {
312 let idx = ((x as i32 + 1) * angle) >> 5;
313 let fact = ((x as i32 + 1) * angle) & 31;
314 let base = (BIAS as i32 + idx + 1) as usize;
315 if fact != 0 {
316 let (w0, w1) = (32 - fact, fact);
317 for y in 0..n {
318 out[y * n + x] =
319 ((w0 * reference[base + y] + w1 * reference[base + y + 1] + 16) >> 5) as u8;
320 }
321 } else {
322 for y in 0..n {
323 out[y * n + x] = reference[base + y] as u8;
324 }
325 }
326 }
327 }
328 // The vertical and horizontal modes carry a boundary filter on luma
329 // blocks below 32x32 (8-60, 8-68).
330 if is_luma && n < 32 {
331 if mode == 26 {
332 for y in 0..n {
333 let value = i32::from(refs.top[0])
334 + ((i32::from(refs.left[y]) - i32::from(refs.corner)) >> 1);
335 out[y * n] = value.clamp(0, 255) as u8;
336 }
337 } else if mode == 10 {
338 for (x, sample) in out[..n].iter_mut().enumerate() {
339 let value = i32::from(refs.left[0])
340 + ((i32::from(refs.top[x]) - i32::from(refs.corner)) >> 1);
341 *sample = value.clamp(0, 255) as u8;
342 }
343 }
344 }
345}
346
347/// The three most probable modes (8.4.2 step 3) from the left and above
348/// neighbours' modes; `None` means the neighbour is unavailable or not intra.
349pub fn mpm_list(left: Option<u8>, above: Option<u8>) -> [u8; 3] {
350 let cand_a = left.unwrap_or(1);
351 let cand_b = above.unwrap_or(1);
352 if cand_a == cand_b {
353 if cand_a < 2 {
354 [0, 1, 26]
355 } else {
356 [
357 cand_a,
358 2 + ((u32::from(cand_a) + 29) % 32) as u8,
359 2 + ((u32::from(cand_a) - 2 + 1) % 32) as u8,
360 ]
361 }
362 } else if cand_a != 0 && cand_b != 0 {
363 [cand_a, cand_b, 0]
364 } else if cand_a != 1 && cand_b != 1 {
365 [cand_a, cand_b, 1]
366 } else {
367 [cand_a, cand_b, 26]
368 }
369}
370
371/// `scanIdx` for a residual block (7.4.9.11): mode-dependent for the small
372/// luma and chroma blocks, diagonal everywhere else.
373///
374/// 0 = up-right diagonal, 1 = horizontal, 2 = vertical.
375pub fn scan_index(mode: u8, log2_size: u32, is_luma: bool) -> usize {
376 let mode_dependent = if is_luma {
377 log2_size == 2 || log2_size == 3
378 } else {
379 log2_size == 2
380 };
381 if !mode_dependent {
382 return 0;
383 }
384 if (6..=14).contains(&mode) {
385 2
386 } else if (22..=30).contains(&mode) {
387 1
388 } else {
389 0
390 }
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 fn full_refs(value: u8, n: usize) -> (Refs, Availability) {
398 let refs = Refs {
399 corner: value,
400 top: [value; 64],
401 left: [value; 64],
402 };
403 let mask = if 2 * n >= 64 {
404 u64::MAX
405 } else {
406 (1u64 << (2 * n)) - 1
407 };
408 (
409 refs,
410 Availability {
411 corner: true,
412 top: mask,
413 left: mask,
414 },
415 )
416 }
417
418 #[test]
419 fn every_mode_predicts_a_flat_block_flat() {
420 // With every neighbour equal, all 35 modes must return that value —
421 // including the boundary filters, which are differences of equals.
422 for &n in &[4usize, 8, 16, 32] {
423 let (refs, _) = full_refs(96, n);
424 let mut out = vec![0u8; n * n];
425 for mode in 0..35u8 {
426 predict(&refs, mode, n, true, true, &mut out);
427 assert!(
428 out.iter().all(|&v| v == 96),
429 "mode {mode} n {n}: {:?}",
430 &out[..8]
431 );
432 }
433 }
434 }
435
436 #[test]
437 fn substitution_fills_from_the_nearest_real_sample() {
438 let n = 4;
439 let mut refs = Refs {
440 corner: 0,
441 top: [0; 64],
442 left: [0; 64],
443 };
444 refs.left[5] = 70;
445 let avail = Availability {
446 corner: false,
447 top: 0,
448 left: 1 << 5,
449 };
450 substitute(&mut refs, &avail, n, 8);
451 // Everything takes 70: below it by the bottom-left rule, above it by
452 // the walk up, then the corner and the whole top row.
453 assert!(refs.left[..8].iter().all(|&v| v == 70));
454 assert!(refs.top[..8].iter().all(|&v| v == 70));
455 assert_eq!(refs.corner, 70);
456
457 // Nothing available at all: mid-grey.
458 let mut refs = Refs::default();
459 substitute(&mut refs, &Availability::default(), n, 8);
460 assert_eq!(refs.corner, 128);
461 assert!(refs.top[..8].iter().all(|&v| v == 128));
462 }
463
464 #[test]
465 fn vertical_and_horizontal_modes_copy_their_edge() {
466 let n = 8;
467 let mut refs = Refs::default();
468 for i in 0..64 {
469 refs.top[i] = (10 + i) as u8;
470 refs.left[i] = (200 - i) as u8;
471 }
472 refs.corner = 100;
473 let mut out = vec![0u8; n * n];
474 // Mode 26 on chroma has no boundary filter: every row is the top row.
475 predict(&refs, 26, n, false, false, &mut out);
476 for y in 0..n {
477 for x in 0..n {
478 assert_eq!(out[y * n + x], refs.top[x], "mode 26 at {x},{y}");
479 }
480 }
481 // Mode 10 likewise copies the left column across.
482 predict(&refs, 10, n, false, false, &mut out);
483 for y in 0..n {
484 for x in 0..n {
485 assert_eq!(out[y * n + x], refs.left[y], "mode 10 at {x},{y}");
486 }
487 }
488 }
489
490 #[test]
491 fn diagonal_mode_2_walks_the_left_column() {
492 // Mode 2 is the 45-degree "bottom-left" direction: angle 32 means one
493 // whole sample of shift per row along the left reference.
494 let n = 4;
495 let mut refs = Refs::default();
496 for i in 0..64 {
497 refs.left[i] = i as u8;
498 }
499 let mut out = vec![0u8; n * n];
500 predict(&refs, 2, n, false, false, &mut out);
501 for y in 0..n {
502 for x in 0..n {
503 assert_eq!(out[y * n + x], (y + x + 1) as u8, "at {x},{y}");
504 }
505 }
506 }
507
508 #[test]
509 fn mpm_list_follows_the_spec_cases() {
510 assert_eq!(mpm_list(None, None), [0, 1, 26]);
511 assert_eq!(mpm_list(Some(0), Some(0)), [0, 1, 26]);
512 assert_eq!(mpm_list(Some(10), Some(10)), [10, 9, 11]);
513 assert_eq!(mpm_list(Some(2), Some(2)), [2, 33, 3]);
514 assert_eq!(mpm_list(Some(10), Some(26)), [10, 26, 0]);
515 assert_eq!(mpm_list(Some(0), Some(26)), [0, 26, 1]);
516 assert_eq!(mpm_list(Some(0), Some(1)), [0, 1, 26]);
517 }
518
519 #[test]
520 fn scan_index_is_mode_dependent_only_for_small_blocks() {
521 assert_eq!(scan_index(10, 2, true), 2);
522 assert_eq!(scan_index(26, 3, true), 1);
523 assert_eq!(scan_index(26, 4, true), 0);
524 assert_eq!(scan_index(10, 2, false), 2);
525 assert_eq!(scan_index(10, 3, false), 0);
526 assert_eq!(scan_index(0, 2, true), 0);
527 }
528}