forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

deblock.rs549 lines, 20.3 KiBHistoryRawDownload
1//! The in-loop deblocking filter of the decoder (8.7.2).
2//!
3//! The filter runs over row ranges of the picture ([`deblock_rows`]). In each range
4//! all vertical edges go first, luma and chroma, then all horizontal edges over what
5//! that pass left; see [`super::rowfilter`] for the order the ranges run in.
6//! Luma edges sit on the 8x8 luma grid. Chroma of a 4:2:0 picture sits on its
7//! own 8x8 grid (the luma grid of 16) and is filtered only where the boundary
8//! strength is 2. Boundary strengths, filter switches and offsets come from the
9//! block maps; the samples are read and rewritten in place.
10
11use super::pic::{BlockInfo, CtbInfo, EDGE_TU, PicState, PuMotion, SliceFilter};
12use crate::transform::chroma_qp_for;
13use std::ops::Range;
14
15/// beta' by Q (table 8-12, first column).
16const BETA: [i32; 52] = [
17 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
18 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
19];
20
21/// tC' by Q (table 8-12, second column).
22const TC: [i32; 54] = [
23 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3,
24 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24,
25];
26
27/// Everything the filter reads from the picture, borrowed apart from the
28/// sample planes so that those can be rewritten while the maps are in use.
29struct Maps<'a> {
30 info: &'a [BlockInfo],
31 motion: &'a [PuMotion],
32 ctb: &'a [CtbInfo],
33 slices: &'a [SliceFilter],
34 w4: usize,
35 ctb_log2: u32,
36 ctb_cols: usize,
37 width: usize,
38 /// `BitDepthY` and `BitDepthC`.
39 bit_depth: [u32; 2],
40 /// `pps_cb_qp_offset` and `pps_cr_qp_offset`.
41 cqp_offset: [i32; 2],
42 /// The log2 chroma subsampling `(sub_x, sub_y)`.
43 sub: (u32, u32),
44 /// `chroma_format_idc`, which picks the chroma QP mapping (Table 8-10 or Min(qPi, 51)).
45 chroma_format_idc: u32,
46 pcm_lf_off: bool,
47 /// `loop_filter_across_tiles_enabled_flag`.
48 across_tiles: bool,
49}
50
51impl Maps<'_> {
52 /// The index of the 4x4 unit containing luma position `(x, y)`.
53 fn unit(&self, x: usize, y: usize) -> usize {
54 (y >> 2) * self.w4 + (x >> 2)
55 }
56
57 /// The CTB raster address of luma position `(x, y)`.
58 fn ctb_addr(&self, x: usize, y: usize) -> usize {
59 (y >> self.ctb_log2) * self.ctb_cols + (x >> self.ctb_log2)
60 }
61
62 /// The slice filter parameters that govern the edge between the luma
63 /// positions `p` and `q` (the slice of `q`), or `None` when filterEdgeFlag
64 /// is 0: the slice of `q` has deblocking disabled, or the edge is a slice
65 /// boundary that the slice of `q` does not filter across.
66 fn filtered_edge(&self, p: (usize, usize), q: (usize, usize)) -> Option<SliceFilter> {
67 let cq = self.ctb.get(self.ctb_addr(q.0, q.1))?;
68 let sf = *self.slices.get(usize::from(cq.slice))?;
69 if sf.deblock_disabled {
70 return None;
71 }
72 let cp = self.ctb.get(self.ctb_addr(p.0, p.1))?;
73 if cp.slice_addr != cq.slice_addr && !sf.loop_filter_across_slices {
74 return None;
75 }
76 if cp.tile != cq.tile && !self.across_tiles {
77 return None;
78 }
79 Some(sf)
80 }
81
82 /// Whether the samples of unit `u` must stay as they are: a lossless
83 /// (transquant bypass) unit, or a PCM unit with the PCM loop filter off.
84 fn locked(&self, u: usize) -> bool {
85 let b = &self.info[u];
86 b.bypass || (b.pcm && self.pcm_lf_off)
87 }
88
89 /// The boundary strength (8.7.2.4) across the edge between units `p` and
90 /// `q`. `tu` says the edge is a transform block edge.
91 fn strength(&self, p: usize, q: usize, tu: bool) -> u8 {
92 let (bp, bq) = (&self.info[p], &self.info[q]);
93 if bp.intra || bq.intra {
94 2
95 } else if tu && (bp.nz_luma || bq.nz_luma) {
96 1
97 } else {
98 motion_strength(&self.motion[p], &self.motion[q])
99 }
100 }
101}
102
103/// The motion part of bS (8.7.2.4): 1 when the reference pictures or the
104/// motion vectors of the two units differ enough, 0 otherwise.
105fn motion_strength(p: &PuMotion, q: &PuMotion) -> u8 {
106 let count = |m: &PuMotion| usize::from(m.pred[0]) + usize::from(m.pred[1]);
107 let (np, nq) = (count(p), count(q));
108 if np != nq {
109 return 1;
110 }
111 match np {
112 0 => 0,
113 1 => {
114 let lp = if p.pred[0] { 0 } else { 1 };
115 let lq = if q.pred[0] { 0 } else { 1 };
116 if p.ref_pic[lp] != q.ref_pic[lq] {
117 1
118 } else {
119 u8::from(mv_far(p.mv[lp], q.mv[lq]))
120 }
121 }
122 _ => {
123 let same_set = (p.ref_pic[0] == q.ref_pic[0] && p.ref_pic[1] == q.ref_pic[1])
124 || (p.ref_pic[0] == q.ref_pic[1] && p.ref_pic[1] == q.ref_pic[0]);
125 if !same_set {
126 1
127 } else if p.ref_pic[0] != p.ref_pic[1] {
128 // Compare the motion vectors that refer to the same picture.
129 let (a, b) = if p.ref_pic[0] == q.ref_pic[0] {
130 (0, 1)
131 } else {
132 (1, 0)
133 };
134 u8::from(mv_far(p.mv[0], q.mv[a]) || mv_far(p.mv[1], q.mv[b]))
135 } else {
136 // Both vectors of each unit refer to one picture: either
137 // pairing may match, so bS is 1 only when both fail.
138 let straight = mv_far(p.mv[0], q.mv[0]) || mv_far(p.mv[1], q.mv[1]);
139 let crossed = mv_far(p.mv[0], q.mv[1]) || mv_far(p.mv[1], q.mv[0]);
140 u8::from(straight && crossed)
141 }
142 }
143 }
144}
145
146/// Whether two motion vectors differ by at least one integer sample (4 quarter
147/// samples) in either component.
148fn mv_far(a: [i32; 2], b: [i32; 2]) -> bool {
149 a[0].abs_diff(b[0]) >= 4 || a[1].abs_diff(b[1]) >= 4
150}
151
152/// One line of samples across an edge: `at` is the index of q0 and `step` the
153/// distance between neighbouring samples across the edge.
154#[derive(Clone, Copy)]
155struct Line {
156 at: usize,
157 step: usize,
158}
159
160impl Line {
161 fn p(&self, plane: &[u16], i: usize) -> i32 {
162 i32::from(plane[self.at - (i + 1) * self.step])
163 }
164
165 fn q(&self, plane: &[u16], i: usize) -> i32 {
166 i32::from(plane[self.at + i * self.step])
167 }
168
169 fn set_p(&self, plane: &mut [u16], i: usize, value: i32, max: i32) {
170 plane[self.at - (i + 1) * self.step] = value.clamp(0, max) as u16;
171 }
172
173 fn set_q(&self, plane: &mut [u16], i: usize, value: i32, max: i32) {
174 plane[self.at + i * self.step] = value.clamp(0, max) as u16;
175 }
176}
177
178/// The second-derivative activity of the p side and of the q side of a line.
179fn activity(line: &Line, plane: &[u16]) -> (i32, i32) {
180 let dp = (line.p(plane, 2) - 2 * line.p(plane, 1) + line.p(plane, 0)).abs();
181 let dq = (line.q(plane, 2) - 2 * line.q(plane, 1) + line.q(plane, 0)).abs();
182 (dp, dq)
183}
184
185/// Whether one line wants the strong filter (8.7.2.5.6).
186fn strong_line(line: &Line, dpq: i32, plane: &[u16], beta: i32, tc: i32) -> bool {
187 2 * dpq < (beta >> 2)
188 && (line.p(plane, 3) - line.p(plane, 0)).abs() + (line.q(plane, 0) - line.q(plane, 3)).abs()
189 < (beta >> 3)
190 && (line.p(plane, 0) - line.q(plane, 0)).abs() < ((5 * tc + 1) >> 1)
191}
192
193/// Filter one four-line luma edge segment (8.7.2.5.3, 8.7.2.5.7). `beta` and
194/// `tc` are already scaled to the bit depth. `locked` is the p and q side
195/// switch of nDp and nDq: a locked side is read but not written.
196fn luma_segment(
197 plane: &mut [u16],
198 lines: [Line; 4],
199 beta: i32,
200 tc: i32,
201 locked: [bool; 2],
202 max: i32,
203) {
204 let [no_p, no_q] = locked;
205 let (dp0, dq0) = activity(&lines[0], plane);
206 let (dp3, dq3) = activity(&lines[3], plane);
207 let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);
208 if dpq0 + dpq3 >= beta {
209 return;
210 }
211 let strong = strong_line(&lines[0], dpq0, plane, beta, tc)
212 && strong_line(&lines[3], dpq3, plane, beta, tc);
213 let side_p1 = dp0 + dp3 < ((beta + (beta >> 1)) >> 3);
214 let side_q1 = dq0 + dq3 < ((beta + (beta >> 1)) >> 3);
215
216 for line in &lines {
217 let p: [i32; 4] = std::array::from_fn(|i| line.p(plane, i));
218 let q: [i32; 4] = std::array::from_fn(|i| line.q(plane, i));
219 if strong {
220 let clip = |base: i32, v: i32| v.clamp(base - 2 * tc, base + 2 * tc);
221 if !no_p {
222 let p0 = clip(
223 p[0],
224 (p[2] + 2 * p[1] + 2 * p[0] + 2 * q[0] + q[1] + 4) >> 3,
225 );
226 let p1 = clip(p[1], (p[2] + p[1] + p[0] + q[0] + 2) >> 2);
227 let p2 = clip(p[2], (2 * p[3] + 3 * p[2] + p[1] + p[0] + q[0] + 4) >> 3);
228 line.set_p(plane, 0, p0, max);
229 line.set_p(plane, 1, p1, max);
230 line.set_p(plane, 2, p2, max);
231 }
232 if !no_q {
233 let q0 = clip(
234 q[0],
235 (p[1] + 2 * p[0] + 2 * q[0] + 2 * q[1] + q[2] + 4) >> 3,
236 );
237 let q1 = clip(q[1], (p[0] + q[0] + q[1] + q[2] + 2) >> 2);
238 let q2 = clip(q[2], (p[0] + q[0] + q[1] + 3 * q[2] + 2 * q[3] + 4) >> 3);
239 line.set_q(plane, 0, q0, max);
240 line.set_q(plane, 1, q1, max);
241 line.set_q(plane, 2, q2, max);
242 }
243 } else {
244 let delta = (9 * (q[0] - p[0]) - 3 * (q[1] - p[1]) + 8) >> 4;
245 if delta.abs() >= tc * 10 {
246 continue;
247 }
248 let delta = delta.clamp(-tc, tc);
249 if !no_p {
250 line.set_p(plane, 0, p[0] + delta, max);
251 if side_p1 {
252 let dp =
253 ((((p[2] + p[0] + 1) >> 1) - p[1] + delta) >> 1).clamp(-(tc >> 1), tc >> 1);
254 line.set_p(plane, 1, p[1] + dp, max);
255 }
256 }
257 if !no_q {
258 line.set_q(plane, 0, q[0] - delta, max);
259 if side_q1 {
260 let dq =
261 ((((q[2] + q[0] + 1) >> 1) - q[1] - delta) >> 1).clamp(-(tc >> 1), tc >> 1);
262 line.set_q(plane, 1, q[1] + dq, max);
263 }
264 }
265 }
266 }
267}
268
269/// Filter one chroma line across an edge (8.7.2.5.5). `tc` is already scaled.
270fn chroma_line(plane: &mut [u16], line: Line, tc: i32, locked: [bool; 2], max: i32) {
271 let (p0, p1) = (line.p(plane, 0), line.p(plane, 1));
272 let (q0, q1) = (line.q(plane, 0), line.q(plane, 1));
273 let delta = ((((q0 - p0) * 4) + p1 - q1 + 4) >> 3).clamp(-tc, tc);
274 if !locked[0] {
275 line.set_p(plane, 0, p0 + delta, max);
276 }
277 if !locked[1] {
278 line.set_q(plane, 0, q0 - delta, max);
279 }
280}
281
282/// Every luma edge of one direction, over the whole picture. Edges are on the
283/// 8x8 grid and skipped at the picture boundary; each 4-sample segment takes
284/// its parameters from the units on either side of it.
285///
286/// `plane` holds the rows from `row0` down, and `rows` are the picture rows whose
287/// edges this call filters (a multiple of 8 at each end, or the picture's own
288/// edge). A vertical pass only writes within each row, so bands of rows are
289/// independent; the horizontal pass reads and writes across rows and is only
290/// run whole.
291fn luma_pass(m: &Maps, plane: &mut [u16], row0: usize, rows: Range<usize>, vertical: bool) {
292 let w = m.width;
293 let scale = 1i32 << m.bit_depth[0].saturating_sub(8);
294 let max = (1i32 << m.bit_depth[0]) - 1;
295 for y in rows.clone().step_by(4) {
296 for x in (0..w).step_by(4) {
297 let (p, lines) = if vertical {
298 if x == 0 || !x.is_multiple_of(8) {
299 continue;
300 }
301 (
302 (x - 1, y),
303 std::array::from_fn(|i| Line {
304 at: (y + i - row0) * w + x,
305 step: 1,
306 }),
307 )
308 } else {
309 if y == 0 || !y.is_multiple_of(8) {
310 continue;
311 }
312 (
313 (x, y - 1),
314 std::array::from_fn(|i| Line {
315 at: (y - row0) * w + x + i,
316 step: w,
317 }),
318 )
319 };
320 let qi = m.unit(x, y);
321 let edge = if vertical {
322 m.info[qi].edge_v
323 } else {
324 m.info[qi].edge_h
325 };
326 if edge == 0 {
327 continue;
328 }
329 let Some(sf) = m.filtered_edge(p, (x, y)) else {
330 continue;
331 };
332 let pi = m.unit(p.0, p.1);
333 let bs = m.strength(pi, qi, edge & EDGE_TU != 0);
334 if bs == 0 {
335 continue;
336 }
337 let qp_l = (i32::from(m.info[qi].qp) + i32::from(m.info[pi].qp) + 1) >> 1;
338 let beta = BETA[(qp_l + 2 * sf.beta_offset_div2).clamp(0, 51) as usize] * scale;
339 let tc = TC
340 [(qp_l + 2 * (i32::from(bs) - 1) + 2 * sf.tc_offset_div2).clamp(0, 53) as usize]
341 * scale;
342 let locked = [m.locked(pi), m.locked(qi)];
343 luma_segment(plane, lines, beta, tc, locked, max);
344 }
345 }
346}
347
348/// Every chroma edge of one direction (4:2:0). A chroma segment of four samples
349/// takes its boundary strength and QP from the luma unit at its first row (or
350/// column) scaled by two, as 8.7.2.5.2 does; only bS 2 is filtered.
351///
352/// Band semantics as in [`luma_pass`], in chroma rows: `planes` hold the rows from
353/// `row0` down, and `rows` are chroma rows.
354fn chroma_pass(
355 m: &Maps,
356 planes: &mut [&mut [u16]; 2],
357 row0: usize,
358 rows: Range<usize>,
359 vertical: bool,
360) {
361 let cw = m.width >> m.sub.0;
362 let scale = 1i32 << m.bit_depth[1].saturating_sub(8);
363 let max = (1i32 << m.bit_depth[1]) - 1;
364 for yc in rows.clone().step_by(4) {
365 for xc in (0..cw).step_by(4) {
366 let (xl, yl) = (xc << m.sub.0, yc << m.sub.1);
367 let p = if vertical {
368 if xc == 0 || !xc.is_multiple_of(8) {
369 continue;
370 }
371 (xl - 1, yl)
372 } else {
373 if yc == 0 || !yc.is_multiple_of(8) {
374 continue;
375 }
376 (xl, yl - 1)
377 };
378 let qi = m.unit(xl, yl);
379 let edge = if vertical {
380 m.info[qi].edge_v
381 } else {
382 m.info[qi].edge_h
383 };
384 if edge == 0 {
385 continue;
386 }
387 let Some(sf) = m.filtered_edge(p, (xl, yl)) else {
388 continue;
389 };
390 let pi = m.unit(p.0, p.1);
391 if m.strength(pi, qi, edge & EDGE_TU != 0) != 2 {
392 continue;
393 }
394 let qp_avg = (i32::from(m.info[qi].qp) + i32::from(m.info[pi].qp) + 1) >> 1;
395 let locked = [m.locked(pi), m.locked(qi)];
396 for (c, plane) in planes.iter_mut().enumerate() {
397 let qpc =
398 chroma_qp_for(qp_avg, m.cqp_offset[c], m.bit_depth[1], m.chroma_format_idc);
399 let tc = TC[(qpc + 2 + 2 * sf.tc_offset_div2).clamp(0, 53) as usize] * scale;
400 for k in 0..4 {
401 let line = if vertical {
402 Line {
403 at: (yc + k - row0) * cw + xc,
404 step: 1,
405 }
406 } else {
407 Line {
408 at: (yc - row0) * cw + xc + k,
409 step: cw,
410 }
411 };
412 chroma_line(plane, line, tc, locked, max);
413 }
414 }
415 }
416 }
417}
418
419/// Deblock the whole picture in place (8.7.2). A picture without sample planes, or
420/// with dimensions that are not multiples of 8 (never the case for a conforming
421/// stream, whose dimensions are multiples of the minimum coding block), is left alone.
422pub fn deblock_picture(pic: &mut PicState) {
423 let h = pic.height;
424 deblock_rows(pic, 0..h);
425}
426
427/// Deblock the luma rows `rows` (and the chroma rows of the same area) in place: all
428/// vertical edges of the rows, then all horizontal edges of the rows. An edge belongs
429/// to the rows that hold its `q` side, so a CTB row (its top edge included) is one such
430/// range. It needs the rows above it to be final (the `p` side) and the rows below it to
431/// be reconstructed, since intra prediction reads unfiltered samples. Edges whose `p`
432/// side is in the rows above are filtered after those rows' own vertical edges, which
433/// is the order 8.7.2 gives for the whole picture.
434pub fn deblock_rows(pic: &mut PicState, rows: Range<usize>) {
435 if !pic.has_pixels() {
436 return;
437 }
438 let (w, h) = (pic.width, pic.height);
439 let (sx, sy) = (pic.sub_x(), pic.sub_y());
440 let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy));
441 let info_ok = w.is_multiple_of(8) && h.is_multiple_of(8) && pic.info.len() >= (w / 4) * (h / 4);
442 let planes = &mut pic.planes;
443 if !info_ok
444 || planes.y.len() != w * h
445 || planes.cb.len() != cw * ch
446 || planes.cr.len() != cw * ch
447 {
448 return;
449 }
450 let rows = rows.start.min(h)..rows.end.min(h);
451 let crows = rows.start >> sy..rows.end.div_ceil(1 << sy);
452 let maps = Maps {
453 info: &pic.info,
454 motion: &pic.motion,
455 ctb: &pic.ctb,
456 slices: &pic.slices,
457 w4: pic.w4,
458 ctb_log2: pic.ctb_log2,
459 ctb_cols: pic.ctb_cols,
460 width: w,
461 bit_depth: [pic.bit_depth_y, pic.bit_depth_c],
462 cqp_offset: [pic.pps_cb_qp_offset, pic.pps_cr_qp_offset],
463 sub: (sx, sy),
464 chroma_format_idc: pic.chroma_format_idc,
465 pcm_lf_off: pic.pcm_loop_filter_disabled,
466 across_tiles: pic.loop_filter_across_tiles,
467 };
468 for vertical in [true, false] {
469 luma_pass(&maps, &mut planes.y, 0, rows.clone(), vertical);
470 chroma_pass(
471 &maps,
472 &mut [planes.cb.as_mut_slice(), planes.cr.as_mut_slice()],
473 0,
474 crows.clone(),
475 vertical,
476 );
477 }
478}
479
480#[cfg(test)]
481mod tests {
482 use super::*;
483
484 /// A 16x16 picture whose luma column `x` holds `value(x)`, with flat chroma,
485 /// every unit intra at QP 37 and an edge on every unit.
486 fn picture(value: impl Fn(usize) -> u16) -> PicState {
487 let mut pic = PicState::new(16, 16, 4, 2, 8, 8, true);
488 for y in 0..16 {
489 for x in 0..16 {
490 pic.planes.y[y * 16 + x] = value(x);
491 }
492 }
493 for v in pic.planes.cb.iter_mut().chain(pic.planes.cr.iter_mut()) {
494 *v = 128;
495 }
496 for u in pic.info.iter_mut() {
497 *u = BlockInfo {
498 intra: true,
499 qp: 37,
500 edge_v: EDGE_TU,
501 edge_h: EDGE_TU,
502 ..BlockInfo::default()
503 };
504 }
505 pic.slices = vec![SliceFilter::default()];
506 pic
507 }
508
509 /// A flat picture has nothing to smooth.
510 #[test]
511 fn a_flat_picture_is_unchanged() {
512 let mut pic = picture(|_| 128);
513 let before = pic.planes.clone();
514 deblock_picture(&mut pic);
515 assert_eq!(pic.planes, before);
516 }
517
518 /// A step of 30 across the 8x8 edge at x = 8 is small enough to smooth:
519 /// the two samples at the edge move toward each other.
520 #[test]
521 fn a_step_across_an_8x8_edge_is_smoothed() {
522 let mut pic = picture(|x| if x < 8 { 100 } else { 130 });
523 deblock_picture(&mut pic);
524 for y in 0..16 {
525 let row = &pic.planes.y[y * 16..y * 16 + 16];
526 assert!(row[7] > 100, "p0 not pulled up at row {y}");
527 assert!(row[8] < 130, "q0 not pulled down at row {y}");
528 }
529 }
530
531 /// A PCM unit on the p side with the PCM loop filter off keeps its samples;
532 /// the q side is still filtered.
533 #[test]
534 fn a_pcm_unit_on_the_p_side_is_not_modified() {
535 let mut pic = picture(|x| if x < 8 { 100 } else { 130 });
536 pic.pcm_loop_filter_disabled = true;
537 for y in (0..16).step_by(4) {
538 // Unit column 1 covers luma x 4..8, the p side of the edge at x = 8.
539 pic.info[(y >> 2) * pic.w4 + 1].pcm = true;
540 }
541 deblock_picture(&mut pic);
542 for y in 0..16 {
543 let row = &pic.planes.y[y * 16..y * 16 + 16];
544 assert_eq!(row[7], 100, "p0 changed at row {y}");
545 assert_eq!(row[6], 100, "p1 changed at row {y}");
546 assert!(row[8] < 130, "q0 not filtered at row {y}");
547 }
548 }
549}