forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-perf3' (048f61f0): inverse transform tables and zero-vector skips, buffered dequant, per-frame film-grain scaling table, bulk msac bit refill; byte-exact on 1080p, 4K and palette dumps, 1080p 17.5 s to 12.9 s

Browse files at this commit

1d06737fa0f8070e12a1843940fd386a75616c4dAhmet Kaan GümüşParent: c541e3abea686b
crates/ec-av1/src/film_grain.rsmodified+39 -18
@@ -297,6 +297,20 @@ fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 {
297 }297 }
298 }298 }
299 299
300+/// [`scale_lut`] evaluated over its whole index domain once per frame.
301+///
302+/// The scaling LUT is fixed for the frame, so the interpolation the spec
303+/// writes per sample is a pure function of the sample value with at most
304+/// `256 << (bit_depth - 8)` distinct answers -- 1024 entries at 10 bit. This
305+/// is the same function, tabulated: `add_noise_to_block` was 9.0% self time
306+/// and ran that branchy interpolation once per luma sample and twice per
307+/// chroma sample.
308+fn expand_scaling_lut(lut: &[i32; 256], bit_depth: u32) -> Vec<i32> {
309+ (0..(256i32 << (bit_depth - 8)))
310+ .map(|i| scale_lut(lut, i, bit_depth))
311+ .collect()
312+}
313+
300 /// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is314 /// `add_noise_to_block` (spec 7.18.3.5), 4:2:0 only. `(py0, px0)` is
301 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,315 /// the luma-plane pixel origin; the matching chroma origin is `(py0/2,
302 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the316 /// px0/2)`. Grain is read from `(grain, stride, row0, col0)` triples so the
@@ -306,9 +320,9 @@ fn scale_lut(lut: &[i32; 256], index: i32, bit_depth: u32) -> i32 {
306 fn add_noise_to_block(320 fn add_noise_to_block(
307 fg: &FilmGrainParams,321 fg: &FilmGrainParams,
308 mc_identity: bool,322 mc_identity: bool,
309- scaling_y: &[i32; 256],323+ scaling_y: &[i32],
310- scaling_cb: &[i32; 256],324+ scaling_cb: &[i32],
311- scaling_cr: &[i32; 256],325+ scaling_cr: &[i32],
312 picture: &mut Picture,326 picture: &mut Picture,
313 py0: i32,327 py0: i32,
314 px0: i32,328 px0: i32,
@@ -386,9 +400,9 @@ fn add_noise_to_block(
386 >> 6)400 >> 6)
387 + cb_offset)401 + cb_offset)
388 .clamp(0, index_max);402 .clamp(0, index_max);
389- let delta = (scale_lut(scaling_cb, scaled, bit_depth) * cb_grain[gidx]403+ let delta =
390- + rounding_offset)404+ (scaling_cb[scaled as usize] * cb_grain[gidx] + rounding_offset)
391- >> scaling_shift;405+ >> scaling_shift;
392 picture.u[cidx] =406 picture.u[cidx] =
393 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;407 ((picture.u[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
394 }408 }
@@ -397,25 +411,27 @@ fn add_noise_to_block(
397 >> 6)411 >> 6)
398 + cr_offset)412 + cr_offset)
399 .clamp(0, index_max);413 .clamp(0, index_max);
400- let delta = (scale_lut(scaling_cr, scaled, bit_depth) * cr_grain[gidx]414+ let delta =
401- + rounding_offset)415+ (scaling_cr[scaled as usize] * cr_grain[gidx] + rounding_offset)
402- >> scaling_shift;416+ >> scaling_shift;
403 picture.v[cidx] =417 picture.v[cidx] =
404 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;418 ((picture.v[cidx] as i32 + delta).clamp(min_chroma, max_chroma)) as u16;
405 }419 }
406 }420 }
407 }421 }
408 if apply_y {422 if apply_y {
423+ // Both operands are contiguous along a row, so the row bases are
424+ // computed once instead of a multiply-add per sample.
425+ let width = (half_w * 2) as usize;
409 for i in 0..half_h * 2 {426 for i in 0..half_h * 2 {
410- for j in 0..half_w * 2 {427+ let prow = ((py0 + i) * y_stride + px0) as usize;
411- let pidx = ((py0 + i) * y_stride + (px0 + j)) as usize;428+ let grow = ((lg_row0 + i) * lg_stride + lg_col0) as usize;
412- let gidx = ((lg_row0 + i) * lg_stride + (lg_col0 + j)) as usize;429+ let pixels = &mut picture.y[prow..prow + width];
413- let delta = (scale_lut(scaling_y, picture.y[pidx] as i32, bit_depth)430+ let grain = &luma_grain[grow..grow + width];
414- * luma_grain[gidx]431+ for (p, &g) in pixels.iter_mut().zip(grain) {
415- + rounding_offset)432+ let delta =
416- >> scaling_shift;433+ (scaling_y[*p as usize] * g + rounding_offset) >> scaling_shift;
417- picture.y[pidx] =434+ *p = ((*p as i32 + delta).clamp(min_luma, max_luma)) as u16;
418- ((picture.y[pidx] as i32 + delta).clamp(min_luma, max_luma)) as u16;
419 }435 }
420 }436 }
421 }437 }
@@ -609,6 +625,11 @@ pub(crate) fn apply_grain(
609 )625 )
610 };626 };
611 627
628+ let expand_bd = grain_bit_depth();
629+ let scaling_y = expand_scaling_lut(&scaling_y, expand_bd);
630+ let scaling_cb = expand_scaling_lut(&scaling_cb, expand_bd);
631+ let scaling_cr = expand_scaling_lut(&scaling_cr, expand_bd);
632+
612 let overlap = fg.overlap_flag;633 let overlap = fg.overlap_flag;
613 634
614 let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize];635 let mut y_line_buf = vec![0i32; (y_stride * 2).max(1) as usize];
crates/ec-av1/src/msac.rsmodified+47 -7
@@ -279,13 +279,22 @@ impl<'a> SymbolDecoder<'a> {
279 279
280 /// `f(n)`: the next `n` bits, most significant first, zero past the end.280 /// `f(n)`: the next `n` bits, most significant first, zero past the end.
281 fn f(&mut self, n: u32) -> u32 {281 fn f(&mut self, n: u32) -> u32 {
282- let mut v = 0;282+ debug_assert!(n <= 32, "f(n) reads at most 32 bits");
283- for _ in 0..n {283+ if n == 0 {
284- let byte = self.data.get(self.bit >> 3).copied().unwrap_or(0);284+ return 0;
285- v = (v << 1) | u32::from((byte >> (7 - (self.bit & 7))) & 1);
286- self.bit += 1;
287 }285 }
288- v286+ // The bit-at-a-time form of this loop was the renormalisation cost
287+ // inside every `symbol_fixed`. Five bytes cover any 32-bit field at
288+ // any bit offset, and a byte past the end reads as zero exactly as
289+ // the per-bit `unwrap_or(0)` did.
290+ let start = self.bit >> 3;
291+ let off = (self.bit & 7) as u32;
292+ let mut acc = 0u64;
293+ for k in 0..5 {
294+ acc = (acc << 8) | u64::from(self.data.get(start + k).copied().unwrap_or(0));
295+ }
296+ self.bit += n as usize;
297+ ((acc >> (40 - off - n)) & ((1u64 << n) - 1)) as u32
289 }298 }
290 299
291 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.300 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
@@ -303,10 +312,13 @@ impl<'a> SymbolDecoder<'a> {
303 let mut cur = self.range;312 let mut cur = self.range;
304 let mut prev;313 let mut prev;
305 let mut symbol = 0;314 let mut symbol = 0;
315+ // Loop-invariant: the coder's range does not move until the symbol is
316+ // chosen, so its top byte is computed once rather than per candidate.
317+ let base = self.range >> 8;
306 loop {318 loop {
307 prev = cur;319 prev = cur;
308 let f = u32::from(CDF_TOP - cdf[symbol]);320 let f = u32::from(CDF_TOP - cdf[symbol]);
309- cur = (((self.range >> 8) * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))321+ cur = ((base * (f >> EC_PROB_SHIFT)) >> (7 - EC_PROB_SHIFT))
310 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;322 + EC_MIN_PROB * (nsyms - 1 - symbol) as u32;
311 if self.value >= cur {323 if self.value >= cur {
312 break;324 break;
@@ -358,6 +370,34 @@ impl<'a> SymbolDecoder<'a> {
358 pub(crate) mod tests {370 pub(crate) mod tests {
359 use super::*;371 use super::*;
360 372
373+ /// `f(n)` now assembles five bytes and shifts instead of walking bits.
374+ /// This pins it against the per-bit form it replaced, at every start
375+ /// offset, every width up to 32, and past the end of the buffer (where
376+ /// both forms must read zeros).
377+ #[test]
378+ fn bulk_bit_reads_match_the_per_bit_form() {
379+ let data: Vec<u8> = (0..40u32).map(|i| (i * 37 + 11) as u8).collect();
380+ let per_bit = |start: usize, n: u32| -> u32 {
381+ let mut bit = start;
382+ let mut v = 0u32;
383+ for _ in 0..n {
384+ let byte = data.get(bit >> 3).copied().unwrap_or(0);
385+ v = (v << 1) | u32::from((byte >> (7 - (bit & 7))) & 1);
386+ bit += 1;
387+ }
388+ v
389+ };
390+ for start in 0..(data.len() * 8 + 16) {
391+ for n in 0..=32u32 {
392+ let mut d = SymbolDecoder::new(&data);
393+ d.bit = start;
394+ let got = d.f(n);
395+ assert_eq!(got, per_bit(start, n), "start {start} width {n}");
396+ assert_eq!(d.bit, start + n as usize, "start {start} width {n} advance");
397+ }
398+ }
399+ }
400+
361 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now401 // `tile.rs`'s own tests reach `SymbolDecoder` through this path; it now
362 // lives in the outer module (non-test code decodes with it too), so this402 // lives in the outer module (non-test code decodes with it too), so this
363 // re-export is what keeps those call sites resolving unmodified.403 // re-export is what keeps those call sites resolving unmodified.
crates/ec-av1/src/quant.rsmodified+62 -5
@@ -226,11 +226,45 @@ pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i3
226 /// [`QuantDeltas`]-shaped `dc_delta`/`ac_delta` pair as [`dequant_coeff_wh`].226 /// [`QuantDeltas`]-shaped `dc_delta`/`ac_delta` pair as [`dequant_coeff_wh`].
227 #[allow(clippy::too_many_arguments)]227 #[allow(clippy::too_many_arguments)]
228 pub fn dequant_wh(levels: &[i32], w: usize, h: usize, bit_depth: u8, q_idx: i32, dc_delta: i32, ac_delta: i32) -> Vec<i32> {228 pub fn dequant_wh(levels: &[i32], w: usize, h: usize, bit_depth: u8, q_idx: i32, dc_delta: i32, ac_delta: i32) -> Vec<i32> {
229- levels229+ let mut out = Vec::new();
230- .iter()230+ dequant_wh_into(levels, &mut out, w, h, bit_depth, q_idx, dc_delta, ac_delta);
231- .enumerate()231+ out
232- .map(|(i, &l)| dequant_coeff_wh(l, i == 0, bit_depth, q_idx, dc_delta, ac_delta, w, h))232+}
233- .collect()233+
234+/// [`dequant_wh`] into a caller-owned buffer, with the two quantizer-table
235+/// lookups, the area denominator and the clamp bound hoisted out of the
236+/// per-coefficient loop -- they depend only on the transform, and this loop
237+/// runs once per coefficient of every transform unit in the stream (7.8%
238+/// self time). A zero level dequantizes to zero for every parameter set, so
239+/// the common all-but-EOB tail costs a compare instead of a 64-bit multiply
240+/// and divide. The arithmetic on a non-zero level is the spec's, unchanged.
241+#[allow(clippy::too_many_arguments)]
242+pub fn dequant_wh_into(
243+ levels: &[i32],
244+ out: &mut Vec<i32>,
245+ w: usize,
246+ h: usize,
247+ bit_depth: u8,
248+ q_idx: i32,
249+ dc_delta: i32,
250+ ac_delta: i32,
251+) {
252+ let dcq = i64::from(dc_q(bit_depth, q_idx + dc_delta));
253+ let acq = i64::from(ac_q(bit_depth, q_idx + ac_delta));
254+ let denom = dq_denom_area(w * h);
255+ let bound = 1i64 << (7 + u32::from(bit_depth));
256+ let apply = |l: i32, q: i64| -> i32 {
257+ let dq = i64::from(l) * q;
258+ let sign = if dq < 0 { -1 } else { 1 };
259+ let dq2 = sign * ((dq.abs() & 0xFF_FFFF) / denom);
260+ dq2.clamp(-bound, bound - 1) as i32
261+ };
262+ out.clear();
263+ out.reserve(levels.len());
264+ out.extend(levels.iter().map(|&l| if l == 0 { 0 } else { apply(l, acq) }));
265+ if let (Some(dst), Some(&l)) = (out.first_mut(), levels.first()) {
266+ *dst = if l == 0 { 0 } else { apply(l, dcq) };
267+ }
234 }268 }
235 269
236 #[cfg(test)]270 #[cfg(test)]
@@ -254,6 +288,29 @@ mod tests {
254 assert_eq!([4, 8, 16, 32, 64].map(dq_denom), [1, 1, 1, 2, 4]);288 assert_eq!([4, 8, 16, 32, 64].map(dq_denom), [1, 1, 1, 2, 4]);
255 }289 }
256 290
291+ /// The hoisted buffer form must agree with the per-coefficient spec
292+ /// function it replaced, at every level sign, both quantizer roles and
293+ /// every denominator band.
294+ #[test]
295+ fn buffered_dequant_matches_the_per_coefficient_form() {
296+ let levels: Vec<i32> = (0..64).map(|i| (i as i32 - 32) * 37).collect();
297+ let mut out = Vec::new();
298+ for (w, h) in [(4, 4), (16, 16), (32, 32), (64, 64), (8, 32), (16, 4)] {
299+ for bit_depth in [8u8, 10, 12] {
300+ for (q_idx, dc, ac) in [(20, 0, 0), (140, -8, 5), (255, 12, -12)] {
301+ let n = (w * h).min(levels.len());
302+ dequant_wh_into(&levels[..n], &mut out, w, h, bit_depth, q_idx, dc, ac);
303+ for (i, &got) in out.iter().enumerate() {
304+ let want = dequant_coeff_wh(
305+ levels[i], i == 0, bit_depth, q_idx, dc, ac, w, h,
306+ );
307+ assert_eq!(got, want, "{w}x{h} depth {bit_depth} q {q_idx} coeff {i}");
308+ }
309+ }
310+ }
311+ }
312+ }
313+
257 /// Negative levels round toward zero, so a level and its negation314 /// Negative levels round toward zero, so a level and its negation
258 /// dequantize to values that differ only in sign.315 /// dequantize to values that differ only in sign.
259 #[test]316 #[test]
crates/ec-av1/src/transform.rsmodified+179 -42
@@ -8,7 +8,7 @@
8 //! rounded DCT would drift away from the decoder by a sample here and there.8 //! rounded DCT would drift away from the decoder by a sample here and there.
9 9
10 /// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.10 /// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.
11-static COS128_LOOKUP: [i32; 65] = [11+const COS128_LOOKUP: [i32; 65] = [
12 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822,12 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822,
13 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967,13 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967,
14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,
@@ -18,15 +18,32 @@ static COS128_LOOKUP: [i32; 65] = [
18 /// The fixed-point position of the cosine table.18 /// The fixed-point position of the cosine table.
19 const COS_BITS: usize = 12;19 const COS_BITS: usize = 12;
20 20
21+/// [`COS128_LOOKUP`] unfolded to the whole circle at compile time -- the same
22+/// four quadrant cases the spec writes, evaluated once here so a butterfly's
23+/// cosine is one load instead of a four-way branch per call.
24+const fn build_cos128_full() -> [i32; 256] {
25+ let mut t = [0i32; 256];
26+ let mut a = 0usize;
27+ while a < 256 {
28+ t[a] = if a <= 64 {
29+ COS128_LOOKUP[a]
30+ } else if a <= 128 {
31+ -COS128_LOOKUP[128 - a]
32+ } else if a <= 192 {
33+ -COS128_LOOKUP[a - 128]
34+ } else {
35+ COS128_LOOKUP[256 - a]
36+ };
37+ a += 1;
38+ }
39+ t
40+}
41+
42+static COS128_FULL: [i32; 256] = build_cos128_full();
43+
21 /// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.44 /// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.
22 fn cos128(angle: i32) -> i32 {45 fn cos128(angle: i32) -> i32 {
23- let angle2 = (angle & 255) as usize;46+ COS128_FULL[(angle & 255) as usize]
24- match angle2 {
25- 0..=64 => COS128_LOOKUP[angle2],
26- 65..=128 => -COS128_LOOKUP[128 - angle2],
27- 129..=192 => -COS128_LOOKUP[angle2 - 128],
28- _ => COS128_LOOKUP[256 - angle2],
29- }
30 }47 }
31 48
32 /// `sin128(angle)` (spec 7.13.2.1).49 /// `sin128(angle)` (spec 7.13.2.1).
@@ -34,9 +51,39 @@ fn sin128(angle: i32) -> i32 {
34 cos128(angle - 64)51 cos128(angle - 64)
35 }52 }
36 53
54+/// `brev(numBits, x)` (spec 7.13.2.1) tabulated at compile time, one row per
55+/// `num_bits`. The bit-fold ran per butterfly index at runtime and was the
56+/// single hottest instruction sequence in `inverse_dct`'s annotation.
57+const fn build_brev(num_bits: u32) -> [u8; 64] {
58+ let mut t = [0u8; 64];
59+ let n0 = 1usize << num_bits;
60+ let mut x = 0usize;
61+ while x < n0 {
62+ let mut v = 0usize;
63+ let mut i = 0u32;
64+ while i < num_bits {
65+ v |= ((x >> i) & 1) << (num_bits - 1 - i);
66+ i += 1;
67+ }
68+ t[x] = v as u8;
69+ x += 1;
70+ }
71+ t
72+}
73+
74+static BREV_TAB: [[u8; 64]; 7] = [
75+ build_brev(0),
76+ build_brev(1),
77+ build_brev(2),
78+ build_brev(3),
79+ build_brev(4),
80+ build_brev(5),
81+ build_brev(6),
82+];
83+
37 /// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.84 /// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.
38 fn brev(num_bits: u32, x: usize) -> usize {85 fn brev(num_bits: u32, x: usize) -> usize {
39- (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i)))86+ BREV_TAB[num_bits as usize][x] as usize
40 }87 }
41 88
42 /// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.89 /// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.
@@ -85,9 +132,13 @@ fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) {
85 /// of the first `1 << n` entries.132 /// of the first `1 << n` entries.
86 fn permute(t: &mut [i32], n: u32) {133 fn permute(t: &mut [i32], n: u32) {
87 let n0 = 1usize << n;134 let n0 = 1usize << n;
88- let copy: Vec<i32> = t[..n0].to_vec();135+ // A stack copy: this ran once per 1D transform and its `Vec` was the
136+ // `malloc` at the top of every `inverse_dct` frame in the annotation.
137+ let mut copy = [0i32; 64];
138+ copy[..n0].copy_from_slice(&t[..n0]);
139+ let tab = &BREV_TAB[n as usize];
89 for (i, v) in t[..n0].iter_mut().enumerate() {140 for (i, v) in t[..n0].iter_mut().enumerate() {
90- *v = copy[brev(n, i)];141+ *v = copy[tab[i] as usize];
91 }142 }
92 }143 }
93 144
@@ -828,54 +879,90 @@ pub fn inverse_transform_2d_typed_wh(
828 assert_eq!(dequant.len(), w * h, "one coefficient per position");879 assert_eq!(dequant.len(), w * h, "one coefficient per position");
829 let row_clamp = usize::from(bit_depth) + 8;880 let row_clamp = usize::from(bit_depth) + 8;
830 let col_clamp = (usize::from(bit_depth) + 6).max(16);881 let col_clamp = (usize::from(bit_depth) + 6).max(16);
831- let mut residual = vec![0i32; w * h];
832 let (row_kind, col_kind) = tx_type.axes();882 let (row_kind, col_kind) = tx_type.axes();
833 let (ud_flip, lr_flip) = tx_type.flip();883 let (ud_flip, lr_flip) = tx_type.flip();
834 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only884 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only
835 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/885 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/
836 // 16x64/64x16).886 // 16x64/64x16).
837 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;887 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;
838-888+ // Loop-invariant: the shift is keyed on the transform size, and was being
839- let mut t = [0i32; 64];889+ // looked up through a match once per output sample.
840- for i in 0..h {890+ let shift = row_shift_wh(w, h);
841- for j in 0..w {
842- let c = if i < 32 && j < 32 { dequant[i * w + j] } else { 0 };
843- t[j] = if rect_scale {
844- round2(c * 2896, 12)
845- } else {
846- c
847- };
848- }
849- inverse_1d(&mut t, log2w, row_clamp, row_kind);
850- for j in 0..w {
851- // The row's output is shifted, then clamped before the column
852- // transform reads it back.
853- residual[i * w + j] = clamp_range(round2(t[j], row_shift_wh(w, h)), col_clamp);
854- }
855- }
856-
857 // A FLIPADST axis reads the row-pass output right-to-left and/or writes891 // A FLIPADST axis reads the row-pass output right-to-left and/or writes
858 // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`892 // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`
859- // lines 291-314): `out` is a second buffer, not `residual` reused in893+ // lines 291-314): `out` is a second buffer, not the row scratch reused in
860 // place, because a flipped read/write pair aliases a column this same894 // place, because a flipped read/write pair aliases a column this same
861 // loop has not visited yet (column `j`'s write target under `lr_flip`895 // loop has not visited yet (column `j`'s write target under `lr_flip`
862 // is a column an unflipped loop would still need to read from later).896 // is a column an unflipped loop would still need to read from later).
863 // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.897 // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.
864 let mut out = vec![0i32; w * h];898 let mut out = vec![0i32; w * h];
865- for j in 0..w {899+ let cols = w.min(32);
866- let src_col = if lr_flip { w - 1 - j } else { j };900+ ROW_SCRATCH.with(|cell| {
901+ let mut scratch = cell.borrow_mut();
902+ if scratch.len() < w * h {
903+ scratch.resize(64 * 64, 0);
904+ }
905+ let residual = &mut scratch[..w * h];
906+ let mut t = [0i32; 64];
867 for i in 0..h {907 for i in 0..h {
868- t[i] = residual[i * w + src_col];908+ let dst = &mut residual[i * w..(i + 1) * w];
909+ // Rows at or past 32 carry no coefficients (the spec zeroes them
910+ // before the row transform), and a zero row transforms to a zero
911+ // row: every butterfly and Hadamard of zeros is zero, and
912+ // `Round2(0, n)` is zero at every `n`, so this is the full
913+ // network's own answer, not an approximation of it.
914+ let src = if i < 32 { &dequant[i * w..i * w + cols] } else { &[][..] };
915+ if src.iter().all(|&c| c == 0) {
916+ dst.fill(0);
917+ continue;
918+ }
919+ if rect_scale {
920+ for (tj, &c) in t[..cols].iter_mut().zip(src) {
921+ *tj = round2(c * 2896, 12);
922+ }
923+ } else {
924+ t[..cols].copy_from_slice(src);
925+ }
926+ t[cols..w].fill(0);
927+ inverse_1d(&mut t, log2w, row_clamp, row_kind);
928+ // The row's output is shifted, then clamped before the column
929+ // transform reads it back.
930+ for (d, &v) in dst.iter_mut().zip(t[..w].iter()) {
931+ *d = clamp_range(round2(v, shift), col_clamp);
932+ }
869 }933 }
870- inverse_1d(&mut t, log2h, col_clamp, col_kind);934+
871- for i in 0..h {935+ for j in 0..w {
872- let dst_row = if ud_flip { h - 1 - i } else { i };936+ let src_col = if lr_flip { w - 1 - j } else { j };
873- out[dst_row * w + j] = round2(t[i], 4);937+ let mut any = 0i32;
938+ for i in 0..h {
939+ let v = residual[i * w + src_col];
940+ t[i] = v;
941+ any |= v;
942+ }
943+ // Same zero-in/zero-out argument as the row pass, and `out` is
944+ // already zero at every position this column would write.
945+ if any == 0 {
946+ continue;
947+ }
948+ inverse_1d(&mut t, log2h, col_clamp, col_kind);
949+ for i in 0..h {
950+ let dst_row = if ud_flip { h - 1 - i } else { i };
951+ out[dst_row * w + j] = round2(t[i], 4);
952+ }
874 }953 }
875- }954+ });
876 out955 out
877 }956 }
878 957
958+thread_local! {
959+ /// Row-pass scratch, reused per thread. The row pass writes every position
960+ /// it later reads, so the buffer needs no zeroing, and the two `Vec`s this
961+ /// function allocated per transform unit become one.
962+ static ROW_SCRATCH: std::cell::RefCell<Vec<i32>> =
963+ const { std::cell::RefCell::new(Vec::new()) };
964+}
965+
879 /// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original966 /// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original
880 /// (and still most common) transform.967 /// (and still most common) transform.
881 pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {968 pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {
@@ -916,8 +1003,19 @@ pub fn dequant_and_inverse_typed_wh(
916 ac_delta: i32,1003 ac_delta: i32,
917 tx_type: TxType,1004 tx_type: TxType,
918 ) -> Vec<i32> {1005 ) -> Vec<i32> {
919- let dq = crate::quant::dequant_wh(levels, w, h, bit_depth, q_idx, dc_delta, ac_delta);1006+ DQ_SCRATCH.with(|cell| {
920- inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type)1007+ let mut dq = cell.borrow_mut();
1008+ crate::quant::dequant_wh_into(levels, &mut dq, w, h, bit_depth, q_idx, dc_delta, ac_delta);
1009+ inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type)
1010+ })
1011+}
1012+
1013+thread_local! {
1014+ /// The dequantized grid, reused per thread: it lives only until the
1015+ /// inverse transform has read it, so it was a `Vec` allocated and dropped
1016+ /// once per transform unit.
1017+ static DQ_SCRATCH: std::cell::RefCell<Vec<i32>> =
1018+ const { std::cell::RefCell::new(Vec::new()) };
921 }1019 }
922 1020
923 /// [`dequant_and_inverse_typed`] at `DCT_DCT`, no per-plane quantizer delta.1021 /// [`dequant_and_inverse_typed`] at `DCT_DCT`, no per-plane quantizer delta.
@@ -1217,6 +1315,45 @@ pub fn forward_and_quantize(
1217 mod tests {1315 mod tests {
1218 use super::*;1316 use super::*;
1219 1317
1318+ /// The row and column passes skip an all-zero vector instead of running
1319+ /// the butterfly network over it. That is only bit-exact because a zero
1320+ /// vector transforms to a zero vector at every size, type and bit depth --
1321+ /// which is what this pins, per 1D transform and end to end.
1322+ #[test]
1323+ fn a_zero_vector_transforms_to_zero() {
1324+ for log2 in 2..=6u32 {
1325+ for kind in [TxType1d::Dct, TxType1d::Adst, TxType1d::Identity] {
1326+ if kind == TxType1d::Adst && log2 > 4 {
1327+ continue;
1328+ }
1329+ if kind == TxType1d::Identity && log2 > 5 {
1330+ continue;
1331+ }
1332+ for bit_depth in [8u8, 10, 12] {
1333+ let r = (usize::from(bit_depth) + 6).max(16);
1334+ let mut t = [0i32; 64];
1335+ inverse_1d(&mut t, log2, r, kind);
1336+ assert!(
1337+ t.iter().all(|&v| v == 0),
1338+ "1D {kind:?} log2={log2} depth={bit_depth} left a non-zero"
1339+ );
1340+ }
1341+ }
1342+ }
1343+ for (w, h) in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64), (8, 16), (16, 8), (4, 16), (32, 8)] {
1344+ for tx in [TxType::DctDct, TxType::AdstAdst, TxType::Idtx, TxType::AdstDct, TxType::DctAdst] {
1345+ if w.max(h) > 16 && tx != TxType::DctDct && tx != TxType::Idtx {
1346+ continue;
1347+ }
1348+ if w.max(h) > 32 && tx != TxType::DctDct {
1349+ continue;
1350+ }
1351+ let out = inverse_transform_2d_typed_wh(&vec![0i32; w * h], w, h, 10, tx);
1352+ assert!(out.iter().all(|&v| v == 0), "2D {w}x{h} {tx:?} left a non-zero");
1353+ }
1354+ }
1355+ }
1356+
1220 /// The orthonormal DCT-II basis the forward transform is written against,1357 /// The orthonormal DCT-II basis the forward transform is written against,
1221 /// computed independently of `dct_basis` so a test is not checking a1358 /// computed independently of `dct_basis` so a test is not checking a
1222 /// function against itself.1359 /// function against itself.