forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli4 days ago4021 commits

sao.rs452 lines, 15.8 KiBHistoryRawDownload
1//! Sample adaptive offset (clause 8.7.3). It runs on the whole picture after
2//! deblocking. Every CTB and colour component whose `SaoTypeIdx` is not 0 is
3//! rewritten from a copy of the deblocked planes, so an edge offset always
4//! compares against deblocked neighbours and never against a sample that SAO
5//! has already changed. Samples of PCM units (when `pcm_loop_filter_disabled`
6//! is set) and of transquant-bypass units are left alone. So are edge samples
7//! whose neighbour lies outside the picture or across a slice boundary that
8//! the slice header forbids.
9
10use super::pic::{PicState, SaoParams};
11
12/// `hPos` and `vPos` of the two neighbours for each `SaoEoClass`.
13const EO_NEIGHBOURS: [([isize; 2], [isize; 2]); 4] = [
14 ([-1, 1], [0, 0]),
15 ([0, 0], [-1, 1]),
16 ([-1, 1], [-1, 1]),
17 ([1, -1], [-1, 1]),
18];
19
20/// The size of one colour plane and how luma positions map onto it.
21#[derive(Clone, Copy)]
22struct Plane {
23 /// Width in samples of this plane.
24 w: usize,
25 /// Height in samples of this plane.
26 h: usize,
27 /// Horizontal shift from a luma position to a position in this plane (1 for
28 /// 4:2:0 and 4:2:2 chroma, 0 for luma and 4:4:4 chroma).
29 sub_x: usize,
30 /// Vertical shift (1 for 4:2:0 chroma only).
31 sub_y: usize,
32}
33
34/// Apply SAO to the whole picture in place.
35pub fn sao_picture(pic: &mut PicState) {
36 sao_picture_threads(pic, 1);
37}
38
39/// [`sao_picture`] with each plane's CTB rows split into `threads` bands, filtered
40/// in parallel. A band reads the deblocked input (shared, read-only) and writes only
41/// its own rows of the output, so the bands never touch the same sample.
42pub fn sao_picture_threads(pic: &mut PicState, threads: usize) {
43 if !pic.has_pixels() {
44 return;
45 }
46 let ro: &PicState = pic;
47 let y = filter_plane(ro, 0, &ro.planes.y, threads);
48 let cb = filter_plane(ro, 1, &ro.planes.cb, threads);
49 let cr = filter_plane(ro, 2, &ro.planes.cr, threads);
50 pic.planes.y = y;
51 pic.planes.cb = cb;
52 pic.planes.cr = cr;
53}
54
55/// The SAO output of colour component `c`, computed from the input plane `src`.
56///
57/// Each CTB is handled with its neighbour availability worked out once (see
58/// [`neighbour_cells`]), so the per-sample loop only compares a neighbour's CTB
59/// cell against a 3x3 table instead of looking up slice and tile state.
60fn filter_plane(pic: &PicState, c: usize, src: &[u16], threads: usize) -> Vec<u16> {
61 let mut dst = src.to_vec();
62 let plane = if c == 0 {
63 Plane {
64 w: pic.width,
65 h: pic.height,
66 sub_x: 0,
67 sub_y: 0,
68 }
69 } else {
70 Plane {
71 w: pic.width.div_ceil(1 << pic.sub_x()),
72 h: pic.height.div_ceil(1 << pic.sub_y()),
73 sub_x: pic.sub_x() as usize,
74 sub_y: pic.sub_y() as usize,
75 }
76 };
77 let ctb_h = (1usize << pic.ctb_log2) >> plane.sub_y;
78 let threads = threads.clamp(1, pic.ctb_rows.max(1));
79 if threads == 1 {
80 filter_ctb_rows(pic, c, src, plane, 0..pic.ctb_rows, &mut dst, 0);
81 } else {
82 let rows_per_band = pic.ctb_rows.div_ceil(threads);
83 let band_len = rows_per_band * ctb_h * plane.w;
84 std::thread::scope(|s| {
85 for (i, band) in dst.chunks_mut(band_len).enumerate() {
86 let ry0 = i * rows_per_band;
87 let ry1 = (ry0 + rows_per_band).min(pic.ctb_rows);
88 let y0 = ry0 * ctb_h;
89 s.spawn(move || filter_ctb_rows(pic, c, src, plane, ry0..ry1, band, y0));
90 }
91 });
92 }
93 dst
94}
95
96/// SAO for the CTB rows `rows` of plane `c`, writing into `dst`, which holds the
97/// plane rows from `row0` down (so `dst` may be a band of the whole output).
98fn filter_ctb_rows(
99 pic: &PicState,
100 c: usize,
101 src: &[u16],
102 plane: Plane,
103 rows: std::ops::Range<usize>,
104 dst: &mut [u16],
105 row0: usize,
106) {
107 let ctb_w = (1usize << pic.ctb_log2) >> plane.sub_x;
108 let ctb_h = (1usize << pic.ctb_log2) >> plane.sub_y;
109 let max = (1i32 << pic.bit_depth(c)) - 1;
110 let band_shift = pic.bit_depth(c).saturating_sub(5);
111 for ry in rows {
112 for rx in 0..pic.ctb_cols {
113 let Some(ctb) = pic.ctb.get(ry * pic.ctb_cols + rx) else {
114 continue;
115 };
116 let p = &ctb.sao;
117 if p.type_idx[c] == 0 {
118 continue;
119 }
120 let x0 = rx * ctb_w;
121 let y0 = ry * ctb_h;
122 let bounds = Bounds {
123 x0,
124 y0,
125 x1: (x0 + ctb_w).min(plane.w),
126 y1: (y0 + ctb_h).min(plane.h),
127 ctb_w,
128 ctb_h,
129 };
130 let excl = ctb_has_excluded(pic, plane, &bounds);
131 match p.type_idx[c] {
132 1 => {
133 // Band offset: `band_index` of 8.7.3.2 as a 32-entry table.
134 let mut table = [0i32; 32];
135 let bp = usize::from(p.band_position[c]) & 31;
136 for k in 0..4 {
137 table[(k + bp) & 31] = sao_offset(p, c, k + 1);
138 }
139 for y in bounds.y0..bounds.y1 {
140 for x in bounds.x0..bounds.x1 {
141 if excl && excluded(pic, x << plane.sub_x, y << plane.sub_y) {
142 continue;
143 }
144 let i = src_index(plane, x, y, row0);
145 let cur = i32::from(src[y * plane.w + x]);
146 let off = table[((cur >> band_shift) & 31) as usize];
147 dst[i] = (cur + off).clamp(0, max) as u16;
148 }
149 }
150 }
151 2 => {
152 let Some(&pos) = EO_NEIGHBOURS.get(usize::from(p.eo_class[c])) else {
153 continue;
154 };
155 // SaoOffsetVal by sign sum + 2: edgeIdx 1, 2, 0, 3, 4.
156 let eo_off = [
157 sao_offset(p, c, 1),
158 sao_offset(p, c, 2),
159 0,
160 sao_offset(p, c, 3),
161 sao_offset(p, c, 4),
162 ];
163 let cells = neighbour_cells(pic, rx, ry);
164 for y in bounds.y0..bounds.y1 {
165 for x in bounds.x0..bounds.x1 {
166 if excl && excluded(pic, x << plane.sub_x, y << plane.sub_y) {
167 continue;
168 }
169 let i = src_index(plane, x, y, row0);
170 let cur = i32::from(src[y * plane.w + x]);
171 let Some(sign_sum) =
172 edge_sign_sum(src, plane, &bounds, &cells, pos, x, y)
173 else {
174 continue;
175 };
176 let off = eo_off[(sign_sum + 2) as usize];
177 dst[i] = (cur + off).clamp(0, max) as u16;
178 }
179 }
180 }
181 _ => {}
182 }
183 }
184 }
185}
186
187/// SAO of the CTB row `ry` of colour component `c` (8.7.3), written into `dst`, which
188/// holds the plane rows of that CTB row from its first row on. `src` is the deblocked
189/// plane (a full-size buffer; the rows of `ry` and the row of each side are read from it).
190pub(super) fn sao_ctb_row(pic: &PicState, c: usize, src: &[u16], ry: usize, dst: &mut [u16]) {
191 let plane = plane_of(pic, c);
192 let row0 = (ry << pic.ctb_log2) >> plane.sub_y;
193 filter_ctb_rows(pic, c, src, plane, ry..ry + 1, dst, row0);
194}
195
196/// The size of colour component `c` of `pic`.
197fn plane_of(pic: &PicState, c: usize) -> Plane {
198 if c == 0 {
199 Plane {
200 w: pic.width,
201 h: pic.height,
202 sub_x: 0,
203 sub_y: 0,
204 }
205 } else {
206 Plane {
207 w: pic.width.div_ceil(1 << pic.sub_x()),
208 h: pic.height.div_ceil(1 << pic.sub_y()),
209 sub_x: pic.sub_x() as usize,
210 sub_y: pic.sub_y() as usize,
211 }
212 }
213}
214
215/// The index of plane position `(x, y)` in a buffer that starts at plane row `row0`.
216fn src_index(plane: Plane, x: usize, y: usize, row0: usize) -> usize {
217 (y - row0) * plane.w + x
218}
219
220/// The luma-to-plane bounds of one CTB: `[x0, x1) x [y0, y1)` in plane samples,
221/// clipped to the picture, and the unclipped CTB size in plane samples.
222#[derive(Clone, Copy)]
223struct Bounds {
224 x0: usize,
225 y0: usize,
226 x1: usize,
227 y1: usize,
228 ctb_w: usize,
229 ctb_h: usize,
230}
231
232/// Sum of the two edge signs of sample `(x, y)` (each in -1..=1), or `None` when a
233/// neighbour is outside the picture or across a forbidden slice or tile boundary.
234fn edge_sign_sum(
235 src: &[u16],
236 plane: Plane,
237 b: &Bounds,
238 cells: &[bool; 9],
239 pos: ([isize; 2], [isize; 2]),
240 x: usize,
241 y: usize,
242) -> Option<i32> {
243 let cur = i32::from(*src.get(y * plane.w + x)?);
244 let mut sign_sum = 0i32;
245 for k in 0..2 {
246 let nx = x as isize + pos.0[k];
247 let ny = y as isize + pos.1[k];
248 if nx < 0 || ny < 0 || nx as usize >= plane.w || ny as usize >= plane.h {
249 return None;
250 }
251 let (nx, ny) = (nx as usize, ny as usize);
252 let cx = cell(nx, b.x0, b.ctb_w);
253 let cy = cell(ny, b.y0, b.ctb_h);
254 if !cells[cy * 3 + cx] {
255 return None;
256 }
257 let n = i32::from(src[ny * plane.w + nx]);
258 sign_sum += (cur - n).signum();
259 }
260 Some(sign_sum)
261}
262
263/// Which of the three CTB columns (or rows) a neighbouring plane position falls in,
264/// given the first position of the current CTB: 0 before it, 2 past its end, else 1.
265fn cell(v: usize, start: usize, ctb_size: usize) -> usize {
266 if v < start {
267 0
268 } else if v >= start + ctb_size {
269 2
270 } else {
271 1
272 }
273}
274
275/// Whether a neighbouring CTB may be used by the CTB at `(rx, ry)`, for each cell
276/// of its 3x3 neighbourhood (row-major, `cell = cy * 3 + cx`). The centre cell is
277/// always usable; a cell off the CTB grid is not. Slice and tile rules are decided
278/// per CTB pair by [`across_slice_allowed`] on the CTB origins.
279fn neighbour_cells(pic: &PicState, rx: usize, ry: usize) -> [bool; 9] {
280 let luma = 1usize << pic.ctb_log2;
281 let mut cells = [false; 9];
282 for cy in 0..3 {
283 for cx in 0..3 {
284 let nrx = rx as isize + cx as isize - 1;
285 let nry = ry as isize + cy as isize - 1;
286 let ok = if cx == 1 && cy == 1 {
287 true
288 } else if nrx < 0
289 || nry < 0
290 || nrx as usize >= pic.ctb_cols
291 || nry as usize >= pic.ctb_rows
292 {
293 false
294 } else {
295 across_slice_allowed(
296 pic,
297 (rx * luma, ry * luma),
298 (nrx as usize * luma, nry as usize * luma),
299 )
300 };
301 cells[cy * 3 + cx] = ok;
302 }
303 }
304 cells
305}
306
307/// Whether any 4x4 unit of the CTB is excluded from SAO (see [`excluded`]).
308fn ctb_has_excluded(pic: &PicState, plane: Plane, b: &Bounds) -> bool {
309 let (lx0, ly0) = (b.x0 << plane.sub_x, b.y0 << plane.sub_y);
310 let lx1 = (b.x1 << plane.sub_x).min(pic.width);
311 let ly1 = (b.y1 << plane.sub_y).min(pic.height);
312 (ly0..ly1)
313 .step_by(4)
314 .any(|y| (lx0..lx1).step_by(4).any(|x| excluded(pic, x, y)))
315}
316
317/// `SaoOffsetVal[idx]` of component `c`: 0 for index 0, else the signed,
318/// scaled offset `idx`.
319fn sao_offset(p: &SaoParams, c: usize, idx: usize) -> i32 {
320 idx.checked_sub(1)
321 .and_then(|k| p.offset[c].get(k))
322 .map_or(0, |&v| i32::from(v))
323}
324
325/// Whether the neighbouring luma position `nb` may be used by a sample at
326/// luma position `cur` under the slice and tile boundary rules of 8.7.3.2. For a
327/// slice boundary the flag of the later slice in decoding order decides.
328fn across_slice_allowed(pic: &PicState, cur: (usize, usize), nb: (usize, usize)) -> bool {
329 let (Some(cc), Some(nc)) = (
330 pic.ctb.get(pic.ctb_rs(cur.0, cur.1)),
331 pic.ctb.get(pic.ctb_rs(nb.0, nb.1)),
332 ) else {
333 return false;
334 };
335 if cc.tile != nc.tile && !pic.loop_filter_across_tiles {
336 return false;
337 }
338 if cc.slice_addr == nc.slice_addr {
339 return true;
340 }
341 let owner = if pic.zscan(nb.0, nb.1) < pic.zscan(cur.0, cur.1) {
342 cc.slice
343 } else {
344 nc.slice
345 };
346 pic.slices
347 .get(usize::from(owner))
348 .is_some_and(|s| s.loop_filter_across_slices)
349}
350
351/// Whether the luma unit at `(x, y)` is a PCM unit with loop filtering
352/// disabled or a transquant-bypass unit, whose samples SAO must not change.
353fn excluded(pic: &PicState, x: usize, y: usize) -> bool {
354 pic.info
355 .get(pic.unit(x, y))
356 .is_some_and(|i| i.bypass || (i.pcm && pic.pcm_loop_filter_disabled))
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 /// A 16x16 8-bit picture with one 16x16 CTB and no slices.
364 fn picture() -> PicState {
365 PicState::new(16, 16, 4, 2, 8, 8, true)
366 }
367
368 /// SAO parameters for the luma component only.
369 fn luma_sao(type_idx: u8, eo_class: u8, offset: [i16; 4]) -> SaoParams {
370 SaoParams {
371 type_idx: [type_idx, 0, 0],
372 band_position: [0; 3],
373 eo_class: [eo_class, 0, 0],
374 offset: [offset, [0; 4], [0; 4]],
375 }
376 }
377
378 /// Fill the luma plane with 10 on even columns and 20 on odd columns, so
379 /// every interior sample is a local extremum along the horizontal.
380 fn zigzag(pic: &mut PicState) {
381 for y in 0..16 {
382 for x in 0..16 {
383 pic.planes.y[y * 16 + x] = if x % 2 == 0 { 10 } else { 20 };
384 }
385 }
386 }
387
388 /// The class-0 edge result of [`zigzag`] with offsets `[5, 6, 7, 8]`:
389 /// a 10 sample has edgeIdx 1 (offset 5), a 20 sample edgeIdx 4 (offset 8).
390 fn zigzag_result(x: usize) -> u16 {
391 if x.is_multiple_of(2) { 15 } else { 28 }
392 }
393
394 #[test]
395 fn band_offset_adds_offset_only_inside_bands() {
396 let mut pic = picture();
397 pic.planes.y.iter_mut().for_each(|s| *s = 8);
398 pic.planes.y[5] = 40;
399 pic.ctb[0].sao = luma_sao(1, 0, [1, 2, 3, 4]);
400 sao_picture(&mut pic);
401 // 8 >> 3 = band 1, which is k = 1 and so offset[1] = 2.
402 assert_eq!(pic.planes.y[0], 10);
403 // 40 >> 3 = band 5, outside the four bands: unchanged.
404 assert_eq!(pic.planes.y[5], 40);
405 }
406
407 #[test]
408 fn edge_offset_class0_on_ramp_keeps_picture_edges() {
409 let mut pic = picture();
410 zigzag(&mut pic);
411 pic.ctb[0].sao = luma_sao(2, 0, [5, 6, 7, 8]);
412 sao_picture(&mut pic);
413 for y in 0..16 {
414 for x in 1..15 {
415 assert_eq!(pic.planes.y[y * 16 + x], zigzag_result(x), "x={x} y={y}");
416 }
417 // Picture edge samples have a neighbour outside the picture.
418 assert_eq!(pic.planes.y[y * 16], 10);
419 assert_eq!(pic.planes.y[y * 16 + 15], 20);
420 }
421 }
422
423 #[test]
424 fn bypass_units_are_untouched() {
425 let mut pic = picture();
426 zigzag(&mut pic);
427 pic.update_info(4, 0, 4, 16, |i| i.bypass = true);
428 pic.ctb[0].sao = luma_sao(2, 0, [5, 6, 7, 8]);
429 sao_picture(&mut pic);
430 for y in 0..16 {
431 for x in 4..8 {
432 assert_eq!(
433 pic.planes.y[y * 16 + x],
434 if x % 2 == 0 { 10 } else { 20 },
435 "x={x} y={y}"
436 );
437 }
438 // The neighbour of a bypass unit is still filtered (x = 3 is odd).
439 assert_eq!(pic.planes.y[y * 16 + 3], 28);
440 }
441 }
442
443 #[test]
444 fn disabled_type_leaves_samples_unchanged() {
445 let mut pic = picture();
446 zigzag(&mut pic);
447 let before = pic.planes.y.clone();
448 pic.ctb[0].sao = luma_sao(0, 0, [5, 6, 7, 8]);
449 sao_picture(&mut pic);
450 assert_eq!(pic.planes.y, before);
451 }
452}