forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

superres.rs299 lines, 13.4 KiBHistoryRawDownload
1//! AV1 spec 7.16 upscaling process (`av1_upscale_normative_rows` in
2//! libaom's `av1/common/resize.c`) -- the horizontal-only linear-filter
3//! upscale that runs on the decoded frame after deblocking and CDEF (and,
4//! once this crate supports loop restoration, BEFORE it -- libaom's
5//! `decodeframe.c` calls `superres_post_decode()` between `av1_cdef_frame`
6//! and `av1_loop_restoration_filter_frame`, not after LR; the charter's
7//! anchor note that superres runs "after loop restoration" does not match
8//! the source and is corrected here).
9//!
10//! Every constant and the 64x8 `av1_resize_filter_normative` coefficient
11//! table below is copied verbatim from libaom `aom_dsp/aom_filter.h` and
12//! `av1/common/resize.c` (`AOM_VERSION=v3.13.3`, `~/.cache/aom-oracle`).
13
14/// `RS_SUBPEL_BITS`.
15const RS_SUBPEL_BITS: u32 = 6;
16/// `RS_SCALE_SUBPEL_BITS`.
17const RS_SCALE_SUBPEL_BITS: u32 = 14;
18/// `RS_SCALE_SUBPEL_MASK`.
19const RS_SCALE_SUBPEL_MASK: i64 = (1i64 << RS_SCALE_SUBPEL_BITS) - 1;
20/// `RS_SCALE_EXTRA_BITS`.
21const RS_SCALE_EXTRA_BITS: u32 = RS_SCALE_SUBPEL_BITS - RS_SUBPEL_BITS;
22/// `RS_SCALE_EXTRA_OFF`.
23const RS_SCALE_EXTRA_OFF: i64 = 1i64 << (RS_SCALE_EXTRA_BITS - 1);
24/// `UPSCALE_NORMATIVE_TAPS`.
25const UPSCALE_NORMATIVE_TAPS: usize = 8;
26/// `FILTER_BITS`.
27const FILTER_BITS: u32 = 7;
28
29/// `av1_resize_filter_normative`, libaom `av1/common/resize.c`. 64 subpel
30/// phases x 8 taps.
31#[rustfmt::skip]
32const RESIZE_FILTER_NORMATIVE: [[i16; UPSCALE_NORMATIVE_TAPS]; 1 << RS_SUBPEL_BITS] = [
33 [0, 0, 0, 128, 0, 0, 0, 0], [0, 0, -1, 128, 2, -1, 0, 0],
34 [0, 1, -3, 127, 4, -2, 1, 0], [0, 1, -4, 127, 6, -3, 1, 0],
35 [0, 2, -6, 126, 8, -3, 1, 0], [0, 2, -7, 125, 11, -4, 1, 0],
36 [-1, 2, -8, 125, 13, -5, 2, 0], [-1, 3, -9, 124, 15, -6, 2, 0],
37 [-1, 3, -10, 123, 18, -6, 2, -1], [-1, 3, -11, 122, 20, -7, 3, -1],
38 [-1, 4, -12, 121, 22, -8, 3, -1], [-1, 4, -13, 120, 25, -9, 3, -1],
39 [-1, 4, -14, 118, 28, -9, 3, -1], [-1, 4, -15, 117, 30, -10, 4, -1],
40 [-1, 5, -16, 116, 32, -11, 4, -1], [-1, 5, -16, 114, 35, -12, 4, -1],
41 [-1, 5, -17, 112, 38, -12, 4, -1], [-1, 5, -18, 111, 40, -13, 5, -1],
42 [-1, 5, -18, 109, 43, -14, 5, -1], [-1, 6, -19, 107, 45, -14, 5, -1],
43 [-1, 6, -19, 105, 48, -15, 5, -1], [-1, 6, -19, 103, 51, -16, 5, -1],
44 [-1, 6, -20, 101, 53, -16, 6, -1], [-1, 6, -20, 99, 56, -17, 6, -1],
45 [-1, 6, -20, 97, 58, -17, 6, -1], [-1, 6, -20, 95, 61, -18, 6, -1],
46 [-2, 7, -20, 93, 64, -18, 6, -2], [-2, 7, -20, 91, 66, -19, 6, -1],
47 [-2, 7, -20, 88, 69, -19, 6, -1], [-2, 7, -20, 86, 71, -19, 6, -1],
48 [-2, 7, -20, 84, 74, -20, 7, -2], [-2, 7, -20, 81, 76, -20, 7, -1],
49 [-2, 7, -20, 79, 79, -20, 7, -2], [-1, 7, -20, 76, 81, -20, 7, -2],
50 [-2, 7, -20, 74, 84, -20, 7, -2], [-1, 6, -19, 71, 86, -20, 7, -2],
51 [-1, 6, -19, 69, 88, -20, 7, -2], [-1, 6, -19, 66, 91, -20, 7, -2],
52 [-2, 6, -18, 64, 93, -20, 7, -2], [-1, 6, -18, 61, 95, -20, 6, -1],
53 [-1, 6, -17, 58, 97, -20, 6, -1], [-1, 6, -17, 56, 99, -20, 6, -1],
54 [-1, 6, -16, 53, 101, -20, 6, -1], [-1, 5, -16, 51, 103, -19, 6, -1],
55 [-1, 5, -15, 48, 105, -19, 6, -1], [-1, 5, -14, 45, 107, -19, 6, -1],
56 [-1, 5, -14, 43, 109, -18, 5, -1], [-1, 5, -13, 40, 111, -18, 5, -1],
57 [-1, 4, -12, 38, 112, -17, 5, -1], [-1, 4, -12, 35, 114, -16, 5, -1],
58 [-1, 4, -11, 32, 116, -16, 5, -1], [-1, 4, -10, 30, 117, -15, 4, -1],
59 [-1, 3, -9, 28, 118, -14, 4, -1], [-1, 3, -9, 25, 120, -13, 4, -1],
60 [-1, 3, -8, 22, 121, -12, 4, -1], [-1, 3, -7, 20, 122, -11, 3, -1],
61 [-1, 2, -6, 18, 123, -10, 3, -1], [0, 2, -6, 15, 124, -9, 3, -1],
62 [0, 2, -5, 13, 125, -8, 2, -1], [0, 1, -4, 11, 125, -7, 2, 0],
63 [0, 1, -3, 8, 126, -6, 2, 0], [0, 1, -3, 6, 127, -4, 1, 0],
64 [0, 1, -2, 4, 127, -3, 1, 0], [0, 0, -1, 2, 128, -1, 0, 0],
65];
66
67/// `av1_get_upscale_convolve_step` (`resize.c`).
68fn upscale_convolve_step(in_length: i64, out_length: i64) -> i64 {
69 ((in_length << RS_SCALE_SUBPEL_BITS) + out_length / 2) / out_length
70}
71
72/// `get_upscale_convolve_x0` (`resize.c`, static there).
73fn upscale_convolve_x0(in_length: i64, out_length: i64, x_step_qn: i64) -> i64 {
74 let err = out_length * x_step_qn - (in_length << RS_SCALE_SUBPEL_BITS);
75 let x0 = (-((out_length - in_length) << (RS_SCALE_SUBPEL_BITS - 1)) + out_length / 2)
76 / out_length
77 + RS_SCALE_EXTRA_OFF
78 - err / 2;
79 x0.rem_euclid(1i64 << RS_SCALE_SUBPEL_BITS) & RS_SCALE_SUBPEL_MASK
80}
81
82/// `av1_convolve_horiz_rs_c` (`convolve.c`): `clip_pixel(ROUND_POWER_OF_TWO(sum, FILTER_BITS))`.
83fn round_power_of_two(sum: i32, bits: u32) -> i32 {
84 (sum + (1 << (bits - 1))) >> bits
85}
86
87/// One row of the spec 7.16 horizontal upscale (`upscale_normative_rect` +
88/// `av1_convolve_horiz_rs_c`, single-tile case: `pad_left`/`pad_right` both
89/// true, replicating the row's own edge pixels rather than sampling a
90/// neighbour tile). `in_width` and `out_width` must both be positive;
91/// `row.len() == in_width` and `out.len() == out_width`.
92/// `bit_depth` only picks the output clamp (`clip_pixel`/`clip_pixel_highbd`
93/// in libaom's `av1_convolve_horiz_rs_c`); the filter, its `Round2` and the
94/// edge padding are bit-depth independent (spec 7.16).
95pub(crate) fn upscale_row(
96 row: &[u16],
97 real_right_margin: &[u16],
98 out_width: usize,
99 out: &mut [u16],
100 bit_depth: u32,
101) {
102 let in_width = row.len();
103 debug_assert!(in_width > 0 && out_width > 0);
104 debug_assert_eq!(out.len(), out_width);
105 let x_step_qn = upscale_convolve_step(in_width as i64, out_width as i64);
106 let x0_qn = upscale_convolve_x0(in_width as i64, out_width as i64, x_step_qn);
107
108 // Right-edge padding: r1 assumed a pure edge-replicate of `row`'s own
109 // last column (matching `upscale_normative_rect`'s single-tile
110 // in-memory fill), but the real decoder's reconstructed buffer already
111 // holds genuine decoded samples past `frame_width` out to the
112 // mi-aligned `true_width` (the coding block straddling the frame edge)
113 // -- libaom's border extension replicates from THAT last real column,
114 // not from `frame_width - 1`. `real_right_margin` (from
115 // `decode::take_last_frame_wide_margin`) supplies those real
116 // pixels first; only once it runs out (or is empty, e.g. `fw` was
117 // already mi-aligned) does this fall back to r1's replicate. Pinned
118 // column-by-column against real libaom via `scripts/superres-pin-
119 // harness.c`'s `row6-realedgeval` case (r3).
120 let pad = UPSCALE_NORMATIVE_TAPS + 2;
121 let mut padded = vec![0u16; in_width + 2 * pad];
122 padded[..pad].fill(row[0]);
123 padded[pad..pad + in_width].copy_from_slice(row);
124 let real_n = real_right_margin.len().min(pad);
125 padded[pad + in_width..pad + in_width + real_n].copy_from_slice(&real_right_margin[..real_n]);
126 let replicate_from = real_right_margin.last().copied().unwrap_or(row[in_width - 1]);
127 padded[pad + in_width + real_n..].fill(replicate_from);
128
129 // `av1_convolve_horiz_rs_c` is called with `input - 1` and itself
130 // subtracts `UPSCALE_NORMATIVE_TAPS/2 - 1` more; net offset from the
131 // real column-0 pixel is `-(UPSCALE_NORMATIVE_TAPS/2)` == -4.
132 let base = pad as i64 - (UPSCALE_NORMATIVE_TAPS as i64 / 2);
133 let mut x_qn = x0_qn;
134 for out_x in out.iter_mut() {
135 let int_pel = x_qn >> RS_SCALE_SUBPEL_BITS;
136 let filter_idx = ((x_qn & RS_SCALE_SUBPEL_MASK) >> RS_SCALE_EXTRA_BITS) as usize;
137 let filter = &RESIZE_FILTER_NORMATIVE[filter_idx];
138 let mut sum = 0i32;
139 for (k, &c) in filter.iter().enumerate() {
140 let idx = base + int_pel + k as i64;
141 sum += padded[idx as usize] as i32 * c as i32;
142 }
143 *out_x = round_power_of_two(sum, FILTER_BITS).clamp(0, (1 << bit_depth) - 1) as u16;
144 x_qn += x_step_qn;
145 }
146}
147
148/// Spec 7.16, applied to a whole plane: `av1_upscale_normative_rows`
149/// widened to every row (`height2 == height`, no vertical scaling -- the
150/// spec only widens columns). `rows` is the plane's row-major byte buffer
151/// at `in_width`; returns a new buffer at `out_width`.
152pub(crate) fn upscale_plane(
153 rows: &[u16],
154 height: usize,
155 in_width: usize,
156 out_width: usize,
157 margin: Option<(&[u16], usize)>,
158 bit_depth: u32,
159) -> Vec<u16> {
160 debug_assert_eq!(rows.len(), height * in_width);
161 let mut out = vec![0u16; height * out_width];
162 for r in 0..height {
163 let src = &rows[r * in_width..(r + 1) * in_width];
164 let dst = &mut out[r * out_width..(r + 1) * out_width];
165 let real_right = match margin {
166 Some((margin_rows, margin_width)) if margin_width > in_width => {
167 &margin_rows[r * margin_width + in_width..(r + 1) * margin_width]
168 }
169 _ => &[],
170 };
171 upscale_row(src, real_right, out_width, dst, bit_depth);
172 }
173 out
174}
175
176thread_local! {
177 /// Firing count for the superres gate (class `gate-blind-to-feature`):
178 /// how many whole pictures actually ran through [`upscale_plane`].
179 static SUPERRES_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
180}
181
182/// Current value of [`SUPERRES_HITS`].
183pub(crate) fn superres_hits() -> usize {
184 SUPERRES_HITS.with(|c| c.get())
185}
186
187/// A whole [`crate::encode::Picture`]'s Y/U/V planes, upscaled from
188/// `frame_width`/`frame_height` (4:2:0 chroma) to `upscaled_width` at the
189/// same height -- spec 7.16 is horizontal-only. Increments
190/// [`SUPERRES_HITS`] once per call. `margin`, when set (r3, from
191/// `decode::take_last_frame_wide_margin`), is the real decoded pixels
192/// beyond `picture`'s own width out to the mi-aligned `true_width` -- see
193/// [`upscale_row`]'s doc for why the right-edge padding needs it.
194pub(crate) fn upscale_picture(
195 picture: &crate::encode::Picture,
196 upscaled_width: usize,
197 margin: Option<&crate::encode::Picture>,
198 bit_depth: u32,
199) -> crate::encode::Picture {
200 SUPERRES_HITS.with(|c| c.set(c.get() + 1));
201 let height = picture.height;
202 let chroma_in_w = picture.width.div_ceil(2);
203 let chroma_out_w = upscaled_width.div_ceil(2);
204 let chroma_h = height.div_ceil(2);
205 crate::encode::Picture {
206 width: upscaled_width,
207 height,
208 y: upscale_plane(
209 &picture.y,
210 height,
211 picture.width,
212 upscaled_width,
213 margin.map(|m| (m.y.as_slice(), m.width)),
214 bit_depth,
215 ),
216 u: upscale_plane(
217 &picture.u,
218 chroma_h,
219 chroma_in_w,
220 chroma_out_w,
221 margin.map(|m| (m.u.as_slice(), m.width.div_ceil(2))),
222 bit_depth,
223 ),
224 v: upscale_plane(
225 &picture.v,
226 chroma_h,
227 chroma_in_w,
228 chroma_out_w,
229 margin.map(|m| (m.v.as_slice(), m.width.div_ceil(2))),
230 bit_depth,
231 ),
232 }
233}
234
235#[cfg(test)]
236mod tests {
237 use super::*;
238
239 /// Pinned against libaom's own compiled code, not a second
240 /// transcription of it: a standalone C harness linked against
241 /// `~/.cache/aom-oracle/build/libaom.a` calls the real (exported)
242 /// `av1_get_upscale_convolve_step` and `av1_convolve_horiz_rs_c` with
243 /// the real (exported) `av1_resize_filter_normative` table -- the only
244 /// piece reimplemented in C rather than called is the one-line static
245 /// `get_upscale_convolve_x0` formula, copied verbatim in both places.
246 /// This is the class `shared-oracle-blindness` guard: a bug in the
247 /// 64x8 table above or in the convolution/rounding kernel is caught
248 /// here independently of this module's own logic.
249 #[test]
250 fn upscale_row_matches_libaom_in8_out12() {
251 let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
252 let mut out = [0u16; 12];
253 upscale_row(&row, &[], 12, &mut out, 8);
254 assert_eq!(out, [9, 14, 22, 29, 35, 42, 48, 55, 61, 68, 76, 81]);
255 }
256
257 #[test]
258 fn upscale_row_matches_libaom_in8_out16() {
259 let row = [10u16, 20, 30, 40, 50, 60, 70, 80];
260 let mut out = [0u16; 16];
261 upscale_row(&row, &[], 16, &mut out, 8);
262 assert_eq!(
263 out,
264 [9, 12, 17, 23, 28, 32, 37, 43, 48, 53, 58, 62, 67, 73, 78, 81]
265 );
266 }
267
268 /// A flat row must upscale to the same flat value everywhere: every
269 /// filter phase's 8 taps sum to exactly 128 (`FILTER_BITS`'s unity
270 /// gain), so a constant input passes through unchanged regardless of
271 /// which phase samples it -- a cheap sanity check independent of the
272 /// captured-row pins above.
273 #[test]
274 fn upscale_row_of_a_flat_input_is_flat() {
275 let row = [200u16; 8];
276 let mut out = [0u16; 12];
277 upscale_row(&row, &[], 12, &mut out, 8);
278 assert_eq!(out, [200u16; 12]);
279 }
280
281 /// r3: the real 43->64 failing case, pinned against real libaom
282 /// including the right-edge margin (`scripts/superres-pin-harness.c`'s
283 /// `row6-realedgeval` case -- input row + real trailing decoded pixel
284 /// 140, not a replicate of the frame-edge pixel 141). Column 62 (0
285 /// indexed) is exactly the pixel this gate mismatched by 1 before the
286 /// margin fix.
287 #[test]
288 fn upscale_row_with_real_margin_matches_libaom_in43_out64() {
289 let row: [u16; 43] = [
290 102, 102, 103, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
291 117, 118, 119, 120, 121, 122, 123, 125, 126, 127, 127, 128, 129, 130, 130, 131, 131,
292 133, 134, 136, 137, 138, 139, 140, 140, 141,
293 ];
294 let real_margin = [140u16];
295 let mut out = [0u16; 64];
296 upscale_row(&row, &real_margin, 64, &mut out, 8);
297 assert_eq!(out[62], 141, "column 62 must match libaom, not the old replicate-padded 140");
298 }
299}