forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8ce79c1Tahinli2 months ago2682 commits

transform.rs3029 lines, 116.9 KiBHistoryRawDownload
1//! The inverse transform (spec 7.13), so the encoder can reconstruct exactly
2//! what a decoder will show.
3//!
4//! Only the inverse DCT is here, which is all this encoder's subset codes: a
5//! square `DCT_DCT` transform per block. The butterfly network is the spec's
6//! own, stage for stage — every stage's rounding and intermediate clamp is
7//! part of the bitstream contract, so a mathematically equal but differently
8//! rounded DCT would drift away from the decoder by a sample here and there.
9
10/// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.
11const COS128_LOOKUP: [i32; 65] = [
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,
14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,
15 1567, 1474, 1380, 1285, 1189, 1092, 995, 897, 799, 700, 601, 501, 401, 301, 201, 101, 0,
16];
17
18/// The fixed-point position of the cosine table.
19const COS_BITS: usize = 12;
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.
24const 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
42static COS128_FULL: [i32; 256] = build_cos128_full();
43
44/// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.
45fn cos128(angle: i32) -> i32 {
46 COS128_FULL[(angle & 255) as usize]
47}
48
49/// `sin128(angle)` (spec 7.13.2.1).
50fn sin128(angle: i32) -> i32 {
51 cos128(angle - 64)
52}
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.
57const 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
74static 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
84/// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.
85fn brev(num_bits: u32, x: usize) -> usize {
86 BREV_TAB[num_bits as usize][x] as usize
87}
88
89/// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.
90fn round2(x: i32, n: usize) -> i32 {
91 if n == 0 {
92 x
93 } else {
94 // The intermediate can exceed 32 bits before the shift brings it
95 // back, which is why it is done in 64.
96 ((i64::from(x) + (1i64 << (n - 1))) >> n) as i32
97 }
98}
99
100/// `Clip3` against a signed integer of `r` bits, which is what bounds every
101/// intermediate of the transform.
102fn clamp_range(x: i32, r: usize) -> i32 {
103 let hi = ((1i64 << (r - 1)) - 1) as i32;
104 let lo = (-(1i64 << (r - 1))) as i32;
105 x.clamp(lo, hi)
106}
107
108/// One value the DCT network carries: a single coefficient (the row pass, and
109/// every caller of the slice-taking [`inverse_dct`]) or eight neighbouring
110/// columns at once (the column pass, where eight columns of the row-pass
111/// output share the whole network). The two impls are elementwise-identical
112/// integer arithmetic, so the eight-wide pass is byte-exact with the scalar
113/// one by construction -- the network itself is written once, above.
114// `unsafe fn` only so the AVX2 impl can carry `#[target_feature]` (rustc
115// rejects it on a SAFE trait method); the two scalar impls below require
116// nothing of their caller.
117#[allow(unsafe_code)]
118trait Lane: Copy {
119 /// One butterfly rotation's two outputs, at pre-multiplied `cos`/`sin`.
120 ///
121 /// # Safety
122 /// An impl may require CPU features: `M256`'s is `#[target_feature]` AVX2,
123 /// which is the only way its intrinsics compile INLINE -- as plain safe
124 /// methods every `_mm256_*` stayed an out-of-line call (13% of the 4K
125 /// segment's profile). `M256` values exist only inside
126 /// [`simd::column_pass_dct`], which its caller has feature-detected; the
127 /// scalar impls require nothing.
128 unsafe fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self);
129 /// One Hadamard rotation's two outputs, clamped to `r` bits.
130 ///
131 /// # Safety
132 /// As [`Lane::btf`].
133 unsafe fn had(a: Self, b: Self, r: usize) -> (Self, Self);
134}
135
136/// `Round2(x, COS_BITS)` on a butterfly's 64-bit product sum.
137fn round_cos(x: i64) -> i32 {
138 ((x + (1 << (COS_BITS - 1))) >> COS_BITS) as i32
139}
140
141#[allow(unsafe_code)]
142impl Lane for i32 {
143 unsafe fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
144 let (ta, tb) = (i64::from(a), i64::from(b));
145 (round_cos(ta * c - tb * s), round_cos(ta * s + tb * c))
146 }
147
148 unsafe fn had(a: Self, b: Self, r: usize) -> (Self, Self) {
149 (clamp_range(a.wrapping_add(b), r), clamp_range(a.wrapping_sub(b), r))
150 }
151}
152
153/// Eight columns at once. Every operation is the [`i32`] impl's, lane by lane,
154/// which is what the optimiser turns into one vector op per line.
155#[allow(unsafe_code)]
156impl Lane for [i32; 8] {
157 unsafe fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
158 let mut x = [0i32; 8];
159 let mut y = [0i32; 8];
160 for l in 0..8 {
161 let (ta, tb) = (i64::from(a[l]), i64::from(b[l]));
162 x[l] = round_cos(ta * c - tb * s);
163 y[l] = round_cos(ta * s + tb * c);
164 }
165 (x, y)
166 }
167
168 unsafe fn had(a: Self, b: Self, r: usize) -> (Self, Self) {
169 let mut x = [0i32; 8];
170 let mut y = [0i32; 8];
171 for l in 0..8 {
172 x[l] = clamp_range(a[l].wrapping_add(b[l]), r);
173 y[l] = clamp_range(a[l].wrapping_sub(b[l]), r);
174 }
175 (x, y)
176 }
177}
178
179/// The same eight-wide column pass in explicit AVX2. Every operation below is
180/// the [`i32`] impl's arithmetic, lane for lane, in 64-bit products -- so it is
181/// byte-exact with the scalar network on every input, not only on conformant
182/// ones (`the_avx2_dct_matches_the_scalar_one_over_the_full_range`).
183#[cfg(target_arch = "x86_64")]
184#[allow(unsafe_code)]
185mod simd {
186 use super::{COS_BITS, Lane, inverse_dct_n};
187 use std::arch::x86_64::*;
188
189 /// Eight `i32` lanes in one AVX2 register.
190 #[derive(Clone, Copy)]
191 pub(super) struct M256(pub(super) __m256i);
192
193 impl Lane for M256 {
194 /// `round_cos(a*c - b*s)`, `round_cos(a*s + b*c)`.
195 ///
196 /// `_mm256_mul_epi32` multiplies the sign-extended low `i32` of each
197 /// 64-bit lane, so the four even lanes go through directly and the four
198 /// odd ones after a shuffle; the products and their sum are exact in 64
199 /// bits (`|a| < 2^31`, `|c| <= 2^12`), and only the low 32 bits of the
200 /// shifted sum are kept -- which is what the scalar `as i32` keeps, so
201 /// the logical shift below stands in for the arithmetic one exactly.
202 #[target_feature(enable = "avx2")]
203 unsafe fn btf(a: Self, b: Self, c: i64, s: i64) -> (Self, Self) {
204 let cv = _mm256_set1_epi32(c as i32);
205 let sv = _mm256_set1_epi32(s as i32);
206 let rnd = _mm256_set1_epi64x(1 << (COS_BITS - 1));
207 let (ae, be) = (a.0, b.0);
208 let (ao, bo) = (_mm256_shuffle_epi32(a.0, 0xB1), _mm256_shuffle_epi32(b.0, 0xB1));
209 let half = |x: __m256i, y: __m256i, u: __m256i, v: __m256i| {
210 let p = _mm256_sub_epi64(_mm256_mul_epi32(x, u), _mm256_mul_epi32(y, v));
211 let q = _mm256_add_epi64(_mm256_mul_epi32(x, v), _mm256_mul_epi32(y, u));
212 (
213 _mm256_srli_epi64::<{ COS_BITS as i32 }>(_mm256_add_epi64(p, rnd)),
214 _mm256_srli_epi64::<{ COS_BITS as i32 }>(_mm256_add_epi64(q, rnd)),
215 )
216 };
217 let (xe, ye) = half(ae, be, cv, sv);
218 let (xo, yo) = half(ao, bo, cv, sv);
219 (
220 M256(_mm256_blend_epi32::<0xAA>(xe, _mm256_slli_epi64::<32>(xo))),
221 M256(_mm256_blend_epi32::<0xAA>(ye, _mm256_slli_epi64::<32>(yo))),
222 )
223 }
224
225 #[target_feature(enable = "avx2")]
226 unsafe fn had(a: Self, b: Self, r: usize) -> (Self, Self) {
227 let hi = _mm256_set1_epi32(((1i64 << (r - 1)) - 1) as i32);
228 let lo = _mm256_set1_epi32((-(1i64 << (r - 1))) as i32);
229 let clamp = |v| _mm256_min_epi32(_mm256_max_epi32(v, lo), hi);
230 (
231 M256(clamp(_mm256_add_epi32(a.0, b.0))),
232 M256(clamp(_mm256_sub_epi32(a.0, b.0))),
233 )
234 }
235 }
236
237 /// [`super::inverse_dct_fixed`] over eight AVX2 lanes -- the network the
238 /// column pass below runs, reachable on its own for the equivalence gate.
239 ///
240 /// # Safety
241 /// The caller has checked for AVX2 ([`crate::mc::simd_level`]).
242 #[target_feature(enable = "avx2")]
243 pub(super) unsafe fn dct_x8_avx2(t: &mut [M256; 64], n: u32, r: usize) {
244 match n {
245 2 => inverse_dct_n::<M256, 2>(t, r),
246 3 => inverse_dct_n::<M256, 3>(t, r),
247 4 => inverse_dct_n::<M256, 4>(t, r),
248 5 => inverse_dct_n::<M256, 5>(t, r),
249 6 => inverse_dct_n::<M256, 6>(t, r),
250 _ => unreachable!("the inverse DCT is defined for 4..64"),
251 }
252 }
253
254 /// The whole DCT column pass of one transform unit: `residual` is the
255 /// row-pass output (`h` rows of `w`), `out` the residual it writes.
256 ///
257 /// # Safety
258 /// The caller has checked for AVX2 ([`crate::mc::simd_level`]).
259 #[target_feature(enable = "avx2")]
260 pub(super) unsafe fn column_pass_dct(
261 residual: &[i32],
262 out: &mut [i32],
263 w: usize,
264 h: usize,
265 log2h: u32,
266 r: usize,
267 ud_flip: bool,
268 ) {
269 let mut t = [M256(_mm256_setzero_si256()); 64];
270 for j in (0..w).step_by(8) {
271 let mut any = _mm256_setzero_si256();
272 for i in 0..h {
273 let v = unsafe { _mm256_loadu_si256(residual[i * w + j..].as_ptr().cast()) };
274 t[i] = M256(v);
275 any = _mm256_or_si256(any, v);
276 }
277 // Zero in, zero out -- and `out` is already zero here.
278 if _mm256_testz_si256(any, any) == 1 {
279 continue;
280 }
281 // SAFETY: this function's own AVX2 contract.
282 unsafe { dct_x8_avx2(&mut t, log2h, r) };
283 // `round2(v, 4)` on eight lanes: the shift is arithmetic here
284 // because the value stays in its own 32-bit lane.
285 let rnd = _mm256_set1_epi32(8);
286 for i in 0..h {
287 let dst_row = if ud_flip { h - 1 - i } else { i };
288 let v = _mm256_srai_epi32::<4>(_mm256_add_epi32(t[i].0, rnd));
289 unsafe { _mm256_storeu_si256(out[dst_row * w + j..].as_mut_ptr().cast(), v) };
290 }
291 }
292 }
293
294 /// The eight scalar lanes of `v`, for the equivalence gate.
295 #[cfg(test)]
296 pub(super) fn lanes(v: M256) -> [i32; 8] {
297 let mut o = [0i32; 8];
298 unsafe { _mm256_storeu_si256(o.as_mut_ptr().cast(), v.0) };
299 o
300 }
301
302 /// `M256` from eight lanes, for the equivalence gate.
303 #[cfg(test)]
304 pub(super) fn splat(v: [i32; 8]) -> M256 {
305 unsafe { M256(_mm256_loadu_si256(v.as_ptr().cast())) }
306 }
307}
308
309/// `B(a, b, angle, flip, r)` (spec 7.13.2.1): a butterfly rotation, and an
310/// exchange of the two entries when `flip` is set.
311#[inline(always)]
312fn butterfly<T: Lane>(t: &mut [T; 64], a: usize, b: usize, angle: i32, flip: bool, _r: usize) {
313 let (c, s) = (i64::from(cos128(angle)), i64::from(sin128(angle)));
314 // SAFETY: [`Lane::btf`] -- an `M256` reaches here only from the
315 // feature-detected [`simd::column_pass_dct`].
316 #[allow(unsafe_code)]
317 let (x, y) = unsafe { T::btf(t[a], t[b], c, s) };
318 t[a] = x;
319 t[b] = y;
320 if flip {
321 t.swap(a, b);
322 }
323}
324
325/// `H(a, b, flip, r)` (spec 7.13.2.1): a Hadamard rotation, with the indices
326/// exchanged when `flip` is set.
327#[inline(always)]
328fn hadamard<T: Lane>(t: &mut [T; 64], a: usize, b: usize, flip: bool, r: usize) {
329 let (a, b) = if flip { (b, a) } else { (a, b) };
330 // SAFETY: as [`butterfly`]'s.
331 #[allow(unsafe_code)]
332 let (x, y) = unsafe { T::had(t[a], t[b], r) };
333 t[a] = x;
334 t[b] = y;
335}
336
337/// The inverse DCT array permutation (spec 7.13.2.2): an in-place bit-reversal
338/// of the first `1 << n` entries.
339#[inline(always)]
340fn permute<T: Lane>(t: &mut [T; 64], n: u32) {
341 let n0 = 1usize << n;
342 // In place: a bit reversal is an involution, so swapping every `i` with
343 // `brev(i) > i` visits each transposed pair once. The scratch copy this
344 // replaces was a `[T; 64]` fill -- 2 KB per call at `T = M256`.
345 let tab = &BREV_TAB[n as usize];
346 for i in 0..n0 {
347 let j = tab[i] as usize;
348 if j > i {
349 t.swap(i, j);
350 }
351 }
352}
353
354/// The inverse DCT process (spec 7.13.2.3): an in-place inverse DCT of the
355/// first `1 << n` entries of `t`, clamping intermediates to `r` bits.
356///
357/// The stage list is the spec's, in the spec's order; the guards on `n` are
358/// what make one network serve every transform size from 4 to 64.
359pub fn inverse_dct(t: &mut [i32], n: u32, r: usize) {
360 // lane-perf10: the network below indexes a 64-entry scratch with computed
361 // indices, and on a `&mut [i32]` every one of them carried a bounds check.
362 // A `&mut [i32; 64]` lets the optimiser discharge them all against the
363 // constant length; this wrapper keeps the slice-taking signature for
364 // callers outside the 2D driver.
365 let m = 1usize << n;
366 let mut fixed = [0i32; 64];
367 fixed[..m].copy_from_slice(&t[..m]);
368 inverse_dct_fixed(&mut fixed, n, r);
369 t[..m].copy_from_slice(&fixed[..m]);
370}
371
372/// [`inverse_dct`] on the driver's own 64-entry scratch.
373/// [`inverse_dct`] on the driver's own 64-entry scratch: a thin dispatch to
374/// [`inverse_dct_n`], which is the same network monomorphised per size so
375/// the size guards, the `brev` folds and every butterfly angle become
376/// compile-time constants instead of per-call work.
377fn inverse_dct_fixed(t: &mut [i32; 64], n: u32, r: usize) {
378 match n {
379 2 => inverse_dct_n::<i32, 2>(t, r),
380 3 => inverse_dct_n::<i32, 3>(t, r),
381 4 => inverse_dct_n::<i32, 4>(t, r),
382 5 => inverse_dct_n::<i32, 5>(t, r),
383 6 => inverse_dct_n::<i32, 6>(t, r),
384 _ => unreachable!("the inverse DCT is defined for 4..64"),
385 }
386}
387
388/// [`inverse_dct_fixed`] over eight columns at once (the column pass).
389fn inverse_dct_x8(t: &mut [[i32; 8]; 64], n: u32, r: usize) {
390 match n {
391 2 => inverse_dct_n::<[i32; 8], 2>(t, r),
392 3 => inverse_dct_n::<[i32; 8], 3>(t, r),
393 4 => inverse_dct_n::<[i32; 8], 4>(t, r),
394 5 => inverse_dct_n::<[i32; 8], 5>(t, r),
395 6 => inverse_dct_n::<[i32; 8], 6>(t, r),
396 _ => unreachable!("the inverse DCT is defined for 4..64"),
397 }
398}
399
400/// [`inverse_dct_fixed`] at one fixed `N = log2(size)`.
401// `#[inline(always)]`: the AVX2 instantiation has to land INSIDE the
402// `target_feature` wrapper, or every `_mm256_*` in it stays an out-of-line
403// call (measured: +5.6% instructions on the 4K segment). Every other
404// instantiation has exactly one caller, so this costs no extra copy.
405#[inline(always)]
406fn inverse_dct_n<T: Lane, const N: u32>(t: &mut [T; 64], r: usize) {
407 permute(t, N);
408
409 if N == 6 {
410 for i in 0..16 {
411 butterfly(t, 32 + i, 63 - i, 63 - 4 * brev(4, i) as i32, false, r);
412 }
413 }
414 if N >= 5 {
415 for i in 0..8 {
416 butterfly(
417 t,
418 16 + i,
419 31 - i,
420 6 + ((brev(3, 7 - i) as i32) << 3),
421 false,
422 r,
423 );
424 }
425 }
426 if N == 6 {
427 for i in 0..16 {
428 hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r);
429 }
430 }
431 if N >= 4 {
432 for i in 0..4 {
433 butterfly(
434 t,
435 8 + i,
436 15 - i,
437 12 + ((brev(2, 3 - i) as i32) << 4),
438 false,
439 r,
440 );
441 }
442 }
443 if N >= 5 {
444 for i in 0..8 {
445 hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
446 }
447 }
448 if N == 6 {
449 for i in 0..4 {
450 for j in 0..2 {
451 let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32;
452 butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r);
453 }
454 }
455 }
456 if N >= 3 {
457 for i in 0..2 {
458 butterfly(t, 4 + i, 7 - i, 56 - 32 * i as i32, false, r);
459 }
460 }
461 if N >= 4 {
462 for i in 0..4 {
463 hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r);
464 }
465 }
466 if N >= 5 {
467 for i in 0..2 {
468 for j in 0..2 {
469 let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5);
470 butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r);
471 }
472 }
473 }
474 if N == 6 {
475 for i in 0..8 {
476 for j in 0..2 {
477 hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r);
478 }
479 }
480 }
481 for i in 0..2 {
482 butterfly(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0, r);
483 }
484 if N >= 3 {
485 for i in 0..2 {
486 hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r);
487 }
488 }
489 if N >= 4 {
490 for i in 0..2 {
491 butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r);
492 }
493 }
494 if N >= 5 {
495 for i in 0..4 {
496 for j in 0..2 {
497 hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r);
498 }
499 }
500 }
501 if N == 6 {
502 for i in 0..2 {
503 for j in 0..4 {
504 let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64;
505 butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r);
506 }
507 }
508 }
509 for i in 0..2 {
510 hadamard(t, i, 3 - i, false, r);
511 }
512 if N >= 3 {
513 butterfly(t, 6, 5, 32, true, r);
514 }
515 if N >= 4 {
516 for i in 0..2 {
517 for j in 0..2 {
518 hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r);
519 }
520 }
521 }
522 if N >= 5 {
523 for i in 0..4 {
524 butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r);
525 }
526 }
527 if N == 6 {
528 for i in 0..4 {
529 for j in 0..4 {
530 hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r);
531 }
532 }
533 }
534 if N >= 3 {
535 for i in 0..4 {
536 hadamard(t, i, 7 - i, false, r);
537 }
538 }
539 if N >= 4 {
540 for i in 0..2 {
541 butterfly(t, 13 - i, 10 + i, 32, true, r);
542 }
543 }
544 if N >= 5 {
545 for i in 0..2 {
546 for j in 0..4 {
547 hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
548 }
549 }
550 }
551 if N == 6 {
552 for i in 0..8 {
553 butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r);
554 }
555 }
556 if N >= 4 {
557 for i in 0..8 {
558 hadamard(t, i, 15 - i, false, r);
559 }
560 }
561 if N >= 5 {
562 for i in 0..4 {
563 butterfly(t, 27 - i, 20 + i, 32, true, r);
564 }
565 }
566 if N == 6 {
567 for i in 0..8 {
568 hadamard(t, 32 + i, 47 - i, false, r);
569 hadamard(t, 48 + i, 63 - i, true, r);
570 }
571 }
572 if N >= 5 {
573 for i in 0..16 {
574 hadamard(t, i, 31 - i, false, r);
575 }
576 }
577 if N == 6 {
578 for i in 0..8 {
579 butterfly(t, 55 - i, 40 + i, 32, true, r);
580 }
581 }
582 if N == 6 {
583 for i in 0..32 {
584 hadamard(t, i, 63 - i, false, r);
585 }
586 }
587}
588
589/// `Transform_Row_Shift` (spec 7.13.3) / `av1_inv_txfm_shift_ls`
590/// (`av1_inv_txfm2d.c:132-158`): `shift[0]`, keyed on the full `(w, h)` TX
591/// size, not a single log2 -- the five square values (unchanged from the
592/// pre-lane `row_shift(log2)`) plus the fourteen rectangular ones the lane
593/// charter transcribed from the same table.
594fn row_shift_wh(w: usize, h: usize) -> usize {
595 match (w, h) {
596 (4, 4) => 0,
597 (8, 8) => 1,
598 (16, 16) | (32, 32) | (64, 64) => 2,
599 (4, 8) | (8, 4) => 0,
600 (8, 16) | (16, 8) => 1,
601 (16, 32) | (32, 16) => 1,
602 (32, 64) | (64, 32) => 1,
603 (4, 16) | (16, 4) => 1,
604 (8, 32) | (32, 8) => 2,
605 (16, 64) | (64, 16) => 2,
606 _ => unreachable!("unsupported transform size {w}x{h}"),
607 }
608}
609
610/// One 1D inverse transform family, ported from libaom's `av1_inv_txfm1d.c`
611/// (`av1_iadst4`/`8`/`16`, `av1_iidentity*`) rather than derived from the
612/// spec's own butterfly writeup -- see the ADST family below.
613#[derive(Clone, Copy, PartialEq, Eq, Debug)]
614enum TxType1d {
615 Dct,
616 Adst,
617 Identity,
618}
619
620/// `Tx_Type_Intra_Inv_Set2`'s five members (spec 9.3), in the CDF's own
621/// symbol order (`0..=4`): `IDTX, DCT_DCT, ADST_ADST, ADST_DCT, DCT_ADST`.
622/// [`crate::decode`] reads the symbol; this is what it dispatches to.
623#[derive(Clone, Copy, PartialEq, Eq, Debug)]
624pub enum TxType {
625 /// Identity on both axes.
626 Idtx,
627 /// DCT on both axes -- this crate's original, still most common case.
628 DctDct,
629 /// ADST on both axes.
630 AdstAdst,
631 /// ADST down the column axis, DCT across the row axis.
632 AdstDct,
633 /// DCT down the column axis, ADST across the row axis.
634 DctAdst,
635 /// DCT down the column axis, identity across the row axis
636 /// (`V_DCT` -- `TX_SET_INTRA_1` only).
637 VDct,
638 /// Identity down the column axis, DCT across the row axis
639 /// (`H_DCT` -- `TX_SET_INTRA_1` only).
640 HDct,
641 /// FLIPADST down the column axis, DCT across the row axis (lane-cdffwd2:
642 /// reachable once `reduced_tx_set == false`'s wider inter sets are read
643 /// -- `EXT_TX_SET_DTT9_IDTX_1DDCT`/`EXT_TX_SET_ALL16`). FLIPADST is the
644 /// same 1D ADST kernel [`AdstDct`] uses (`vtx_tab`/`htx_tab`,
645 /// `common_data.h`), just read/written flipped -- see [`TxType::flip`].
646 FlipAdstDct,
647 /// DCT down the column axis, FLIPADST across the row axis.
648 DctFlipAdst,
649 /// FLIPADST on both axes.
650 FlipAdstFlipAdst,
651 /// ADST down the column axis, FLIPADST across the row axis.
652 AdstFlipAdst,
653 /// FLIPADST down the column axis, ADST across the row axis.
654 FlipAdstAdst,
655 /// ADST down the column axis, identity across the row axis (`V_ADST` --
656 /// `EXT_TX_SET_ALL16` only).
657 VAdst,
658 /// Identity down the column axis, ADST across the row axis (`H_ADST`).
659 HAdst,
660 /// FLIPADST down the column axis, identity across the row axis
661 /// (`V_FLIPADST`).
662 VFlipAdst,
663 /// Identity down the column axis, FLIPADST across the row axis
664 /// (`H_FLIPADST`).
665 HFlipAdst,
666}
667
668impl TxType {
669 /// The inverse of `Tx_Type_Intra_Inv_Set2`'s CDF symbol order.
670 pub fn from_symbol(t: usize) -> Option<Self> {
671 match t {
672 0 => Some(Self::Idtx),
673 1 => Some(Self::DctDct),
674 2 => Some(Self::AdstAdst),
675 3 => Some(Self::AdstDct),
676 4 => Some(Self::DctAdst),
677 _ => None,
678 }
679 }
680
681 /// The inverse of `Tx_Type_Intra_Inv_Set1`'s CDF symbol order
682 /// (`av1_ext_tx_inv[EXT_TX_SET_DTT4_IDTX_1DDCT]`, entropymode.h:
683 /// `{9, 0, 10, 11, 3, 1, 2}` = IDTX, DCT_DCT, V_DCT, H_DCT, ADST_ADST,
684 /// ADST_DCT, DCT_ADST) -- the seven-type set a `reduced_tx_set == 0`
685 /// frame's small intra transforms read from.
686 pub fn from_symbol_set1(t: usize) -> Option<Self> {
687 match t {
688 0 => Some(Self::Idtx),
689 1 => Some(Self::DctDct),
690 2 => Some(Self::VDct),
691 3 => Some(Self::HDct),
692 4 => Some(Self::AdstAdst),
693 5 => Some(Self::AdstDct),
694 6 => Some(Self::DctAdst),
695 _ => None,
696 }
697 }
698
699 /// The inverse of `Tx_Type_Inter_Inv_Set2`'s CDF symbol order
700 /// (`av1_ext_tx_inv[EXT_TX_SET_DTT9_IDTX_1DDCT]`, `entropymode.h`:
701 /// `{9, 10, 11, 0, 1, 2, 4, 5, 3, 6, 7, 8}`) -- the twelve-type set a
702 /// `reduced_tx_set == 0` frame's 16x16 *inter* transform reads from
703 /// (`av1_get_ext_tx_set_type`'s `tx_size_sqr == TX_16X16` branch of
704 /// `av1_ext_tx_set_lookup[1]`).
705 pub fn from_symbol_set2_12(t: usize) -> Option<Self> {
706 match t {
707 0 => Some(Self::Idtx),
708 1 => Some(Self::VDct),
709 2 => Some(Self::HDct),
710 3 => Some(Self::DctDct),
711 4 => Some(Self::AdstDct),
712 5 => Some(Self::DctAdst),
713 6 => Some(Self::FlipAdstDct),
714 7 => Some(Self::DctFlipAdst),
715 8 => Some(Self::AdstAdst),
716 9 => Some(Self::FlipAdstFlipAdst),
717 10 => Some(Self::AdstFlipAdst),
718 11 => Some(Self::FlipAdstAdst),
719 _ => None,
720 }
721 }
722
723 /// The inverse of `Tx_Type_Inter_Inv_Set1`'s CDF symbol order
724 /// (`av1_ext_tx_inv[EXT_TX_SET_ALL16]`, `entropymode.h`:
725 /// `{9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 4, 5, 3, 6, 7, 8}`) -- the full
726 /// sixteen-type set a `reduced_tx_set == 0` frame's 8x8 (and 4x4) inter
727 /// transform reads from (`av1_ext_tx_set_lookup[1][0]`).
728 pub fn from_symbol_all16(t: usize) -> Option<Self> {
729 match t {
730 0 => Some(Self::Idtx),
731 1 => Some(Self::VDct),
732 2 => Some(Self::HDct),
733 3 => Some(Self::VAdst),
734 4 => Some(Self::HAdst),
735 5 => Some(Self::VFlipAdst),
736 6 => Some(Self::HFlipAdst),
737 7 => Some(Self::DctDct),
738 8 => Some(Self::AdstDct),
739 9 => Some(Self::DctAdst),
740 10 => Some(Self::FlipAdstDct),
741 11 => Some(Self::DctFlipAdst),
742 12 => Some(Self::AdstAdst),
743 13 => Some(Self::FlipAdstFlipAdst),
744 14 => Some(Self::AdstFlipAdst),
745 15 => Some(Self::FlipAdstAdst),
746 _ => None,
747 }
748 }
749
750 /// `(row, col)`: the transform `inverse_transform_2d_typed`'s row pass
751 /// (`htx_tab`, spec/libaom "horizontal") and column pass (`vtx_tab`,
752 /// "vertical") each run. Read off libaom's `av1_inv_txfm2d.c` `vtx_tab`/
753 /// `htx_tab` tables directly, not derived: e.g. `ADST_DCT` has
754 /// `vtx_tab = ADST_1D` (column), `htx_tab = DCT_1D` (row) -- the name's
755 /// first half is the *column* transform, not the row one.
756 fn axes(self) -> (TxType1d, TxType1d) {
757 use TxType1d::{Adst, Dct, Identity};
758 match self {
759 Self::Idtx => (Identity, Identity),
760 Self::DctDct => (Dct, Dct),
761 Self::AdstAdst => (Adst, Adst),
762 Self::AdstDct => (Dct, Adst),
763 Self::DctAdst => (Adst, Dct),
764 // `av1_inv_txfm2d.c`: V_DCT vtx=DCT htx=IDTX, H_DCT the mirror.
765 Self::VDct => (Identity, Dct),
766 Self::HDct => (Dct, Identity),
767 // FLIPADST reads the same 1D ADST kernel as ADST -- `vtx_tab`/
768 // `htx_tab` (`common_data.h`) map `FLIPADST_1D` and `ADST_1D`
769 // to the exact same butterfly network; only [`Self::flip`]
770 // differs. So every FLIPADST-bearing axis below mirrors its
771 // plain-ADST counterpart's kernel pairing.
772 Self::FlipAdstDct => (Dct, Adst),
773 Self::DctFlipAdst => (Adst, Dct),
774 Self::FlipAdstFlipAdst | Self::AdstFlipAdst | Self::FlipAdstAdst => (Adst, Adst),
775 Self::VAdst | Self::VFlipAdst => (Identity, Adst),
776 Self::HAdst | Self::HFlipAdst => (Adst, Identity),
777 }
778 }
779
780 /// `(ud_flip, lr_flip)` (`get_flip_cfg`, `av1_txfm.h`): whether the
781 /// column pass reads its input right-to-left and/or the finished
782 /// residual is written bottom-to-top. Every FLIPADST-bearing type sets
783 /// one or both; every other type is `(false, false)`.
784 fn flip(self) -> (bool, bool) {
785 match self {
786 Self::FlipAdstDct | Self::FlipAdstAdst | Self::VFlipAdst => (true, false),
787 Self::DctFlipAdst | Self::AdstFlipAdst | Self::HFlipAdst => (false, true),
788 Self::FlipAdstFlipAdst => (true, true),
789 _ => (false, false),
790 }
791 }
792}
793
794/// `sinpi[]` at `cos_bit = 12` (`av1_sinpi_arr_data[2]`, `av1_txfm.c`): the
795/// fixed constants [`inverse_adst4`] alone uses, unrelated to [`cos128`].
796const SINPI: [i64; 5] = [0, 1321, 2482, 3344, 3803];
797
798/// `NewSqrt2`/`NewSqrt2Bits` (`av1_txfm.h`): the `sqrt(2)` scale
799/// [`inverse_identity`] uses at sizes 4 and 16.
800const NEW_SQRT2: i64 = 5793;
801const NEW_SQRT2_BITS: u32 = 12;
802
803/// `round_shift` (`av1_txfm.h`): round-to-nearest to `bit` places, taking the
804/// pre-shift value in 64 bits since the ADST/identity intermediates
805/// routinely exceed 32.
806fn round_shift(x: i64, bit: u32) -> i32 {
807 ((x + (1i64 << (bit - 1))) >> bit) as i32
808}
809
810/// `half_btf(w0, in0, w1, in1, bit)` (`av1_txfm.h`) at `bit = COS_BITS`,
811/// the only value AV1's inverse transforms ever pass (`INV_COS_BIT`).
812fn half_btf(w0: i32, in0: i32, w1: i32, in1: i32) -> i32 {
813 let acc = i64::from(w0) * i64::from(in0) + i64::from(w1) * i64::from(in1);
814 round_shift(acc, COS_BITS as u32)
815}
816
817/// `av1_iadst4` (`av1_inv_txfm1d.c`): every intermediate stage there goes
818/// through `range_check_value`, which is a debug-only no-op in a conformant
819/// decoder (unlike `av1_iadst8`/`16`'s `clamp_value`, a real clamp) -- so
820/// this port carries no [`clamp_range`] calls, matching the reference
821/// exactly rather than adding a clamp libaom's own default build never
822/// takes.
823fn inverse_adst4(t: &mut [i32]) {
824 let (x0, x1, x2, x3) = (
825 i64::from(t[0]),
826 i64::from(t[1]),
827 i64::from(t[2]),
828 i64::from(t[3]),
829 );
830 if x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 {
831 t[0] = 0;
832 t[1] = 0;
833 t[2] = 0;
834 t[3] = 0;
835 return;
836 }
837 let mut s0 = SINPI[1] * x0;
838 let mut s1 = SINPI[2] * x0;
839 let s2 = SINPI[3] * x1;
840 let mut s3 = SINPI[4] * x2;
841 let s4 = SINPI[1] * x2;
842 let s5 = SINPI[2] * x3;
843 let s6 = SINPI[4] * x3;
844 let s7 = (x0 - x2) + x3;
845
846 s0 += s3;
847 s1 -= s4;
848 s3 = s2;
849 let s2 = SINPI[3] * s7;
850 s0 += s5;
851 s1 -= s6;
852
853 let o0 = s0 + s3;
854 let o1 = s1 + s3;
855 let o2 = s2;
856 let o3 = (s0 + s1) - s3;
857
858 t[0] = round_shift(o0, COS_BITS as u32);
859 t[1] = round_shift(o1, COS_BITS as u32);
860 t[2] = round_shift(o2, COS_BITS as u32);
861 t[3] = round_shift(o3, COS_BITS as u32);
862}
863
864/// `av1_iadst8` (`av1_inv_txfm1d.c`), stage for stage; `r` is the same
865/// per-stage clamp bit width `av1_gen_inv_stage_range` hands every stage in
866/// the square, 8-bit-depth case this decoder targets (row and column both
867/// land on 16 there, matching [`inverse_transform_2d_typed`]'s own
868/// `row_clamp`/`col_clamp`).
869fn inverse_adst8(t: &mut [i32], r: usize) {
870 let bf1 = [t[7], t[0], t[5], t[2], t[3], t[4], t[1], t[6]];
871
872 let mut step = [0i32; 8];
873 step[0] = half_btf(cos128(4), bf1[0], cos128(60), bf1[1]);
874 step[1] = half_btf(cos128(60), bf1[0], -cos128(4), bf1[1]);
875 step[2] = half_btf(cos128(20), bf1[2], cos128(44), bf1[3]);
876 step[3] = half_btf(cos128(44), bf1[2], -cos128(20), bf1[3]);
877 step[4] = half_btf(cos128(36), bf1[4], cos128(28), bf1[5]);
878 step[5] = half_btf(cos128(28), bf1[4], -cos128(36), bf1[5]);
879 step[6] = half_btf(cos128(52), bf1[6], cos128(12), bf1[7]);
880 step[7] = half_btf(cos128(12), bf1[6], -cos128(52), bf1[7]);
881
882 let mut out = [0i32; 8];
883 for i in 0..4 {
884 out[i] = clamp_range(step[i] + step[i + 4], r);
885 out[i + 4] = clamp_range(step[i] - step[i + 4], r);
886 }
887
888 step[0] = out[0];
889 step[1] = out[1];
890 step[2] = out[2];
891 step[3] = out[3];
892 step[4] = half_btf(cos128(16), out[4], cos128(48), out[5]);
893 step[5] = half_btf(cos128(48), out[4], -cos128(16), out[5]);
894 step[6] = half_btf(-cos128(48), out[6], cos128(16), out[7]);
895 step[7] = half_btf(cos128(16), out[6], cos128(48), out[7]);
896
897 out[0] = clamp_range(step[0] + step[2], r);
898 out[1] = clamp_range(step[1] + step[3], r);
899 out[2] = clamp_range(step[0] - step[2], r);
900 out[3] = clamp_range(step[1] - step[3], r);
901 out[4] = clamp_range(step[4] + step[6], r);
902 out[5] = clamp_range(step[5] + step[7], r);
903 out[6] = clamp_range(step[4] - step[6], r);
904 out[7] = clamp_range(step[5] - step[7], r);
905
906 step[0] = out[0];
907 step[1] = out[1];
908 step[2] = half_btf(cos128(32), out[2], cos128(32), out[3]);
909 step[3] = half_btf(cos128(32), out[2], -cos128(32), out[3]);
910 step[4] = out[4];
911 step[5] = out[5];
912 step[6] = half_btf(cos128(32), out[6], cos128(32), out[7]);
913 step[7] = half_btf(cos128(32), out[6], -cos128(32), out[7]);
914
915 t[0] = step[0];
916 t[1] = -step[4];
917 t[2] = step[6];
918 t[3] = -step[2];
919 t[4] = step[3];
920 t[5] = -step[7];
921 t[6] = step[5];
922 t[7] = -step[1];
923}
924
925/// `av1_iadst16` (`av1_inv_txfm1d.c`), stage for stage; `r` as
926/// [`inverse_adst8`].
927fn inverse_adst16(t: &mut [i32], r: usize) {
928 let inp: [i32; 16] = t[..16].try_into().expect("16-point input");
929 let bf1 = [
930 inp[15], inp[0], inp[13], inp[2], inp[11], inp[4], inp[9], inp[6], inp[7], inp[8], inp[5],
931 inp[10], inp[3], inp[12], inp[1], inp[14],
932 ];
933
934 let mut step = [0i32; 16];
935 step[0] = half_btf(cos128(2), bf1[0], cos128(62), bf1[1]);
936 step[1] = half_btf(cos128(62), bf1[0], -cos128(2), bf1[1]);
937 step[2] = half_btf(cos128(10), bf1[2], cos128(54), bf1[3]);
938 step[3] = half_btf(cos128(54), bf1[2], -cos128(10), bf1[3]);
939 step[4] = half_btf(cos128(18), bf1[4], cos128(46), bf1[5]);
940 step[5] = half_btf(cos128(46), bf1[4], -cos128(18), bf1[5]);
941 step[6] = half_btf(cos128(26), bf1[6], cos128(38), bf1[7]);
942 step[7] = half_btf(cos128(38), bf1[6], -cos128(26), bf1[7]);
943 step[8] = half_btf(cos128(34), bf1[8], cos128(30), bf1[9]);
944 step[9] = half_btf(cos128(30), bf1[8], -cos128(34), bf1[9]);
945 step[10] = half_btf(cos128(42), bf1[10], cos128(22), bf1[11]);
946 step[11] = half_btf(cos128(22), bf1[10], -cos128(42), bf1[11]);
947 step[12] = half_btf(cos128(50), bf1[12], cos128(14), bf1[13]);
948 step[13] = half_btf(cos128(14), bf1[12], -cos128(50), bf1[13]);
949 step[14] = half_btf(cos128(58), bf1[14], cos128(6), bf1[15]);
950 step[15] = half_btf(cos128(6), bf1[14], -cos128(58), bf1[15]);
951
952 let mut out = [0i32; 16];
953 for i in 0..8 {
954 out[i] = clamp_range(step[i] + step[i + 8], r);
955 out[i + 8] = clamp_range(step[i] - step[i + 8], r);
956 }
957
958 step[..8].copy_from_slice(&out[..8]);
959 step[8] = half_btf(cos128(8), out[8], cos128(56), out[9]);
960 step[9] = half_btf(cos128(56), out[8], -cos128(8), out[9]);
961 step[10] = half_btf(cos128(40), out[10], cos128(24), out[11]);
962 step[11] = half_btf(cos128(24), out[10], -cos128(40), out[11]);
963 step[12] = half_btf(-cos128(56), out[12], cos128(8), out[13]);
964 step[13] = half_btf(cos128(8), out[12], cos128(56), out[13]);
965 step[14] = half_btf(-cos128(24), out[14], cos128(40), out[15]);
966 step[15] = half_btf(cos128(40), out[14], cos128(24), out[15]);
967
968 out[0] = clamp_range(step[0] + step[4], r);
969 out[1] = clamp_range(step[1] + step[5], r);
970 out[2] = clamp_range(step[2] + step[6], r);
971 out[3] = clamp_range(step[3] + step[7], r);
972 out[4] = clamp_range(step[0] - step[4], r);
973 out[5] = clamp_range(step[1] - step[5], r);
974 out[6] = clamp_range(step[2] - step[6], r);
975 out[7] = clamp_range(step[3] - step[7], r);
976 out[8] = clamp_range(step[8] + step[12], r);
977 out[9] = clamp_range(step[9] + step[13], r);
978 out[10] = clamp_range(step[10] + step[14], r);
979 out[11] = clamp_range(step[11] + step[15], r);
980 out[12] = clamp_range(step[8] - step[12], r);
981 out[13] = clamp_range(step[9] - step[13], r);
982 out[14] = clamp_range(step[10] - step[14], r);
983 out[15] = clamp_range(step[11] - step[15], r);
984
985 step[0] = out[0];
986 step[1] = out[1];
987 step[2] = out[2];
988 step[3] = out[3];
989 step[4] = half_btf(cos128(16), out[4], cos128(48), out[5]);
990 step[5] = half_btf(cos128(48), out[4], -cos128(16), out[5]);
991 step[6] = half_btf(-cos128(48), out[6], cos128(16), out[7]);
992 step[7] = half_btf(cos128(16), out[6], cos128(48), out[7]);
993 step[8] = out[8];
994 step[9] = out[9];
995 step[10] = out[10];
996 step[11] = out[11];
997 step[12] = half_btf(cos128(16), out[12], cos128(48), out[13]);
998 step[13] = half_btf(cos128(48), out[12], -cos128(16), out[13]);
999 step[14] = half_btf(-cos128(48), out[14], cos128(16), out[15]);
1000 step[15] = half_btf(cos128(16), out[14], cos128(48), out[15]);
1001
1002 out[0] = clamp_range(step[0] + step[2], r);
1003 out[1] = clamp_range(step[1] + step[3], r);
1004 out[2] = clamp_range(step[0] - step[2], r);
1005 out[3] = clamp_range(step[1] - step[3], r);
1006 out[4] = clamp_range(step[4] + step[6], r);
1007 out[5] = clamp_range(step[5] + step[7], r);
1008 out[6] = clamp_range(step[4] - step[6], r);
1009 out[7] = clamp_range(step[5] - step[7], r);
1010 out[8] = clamp_range(step[8] + step[10], r);
1011 out[9] = clamp_range(step[9] + step[11], r);
1012 out[10] = clamp_range(step[8] - step[10], r);
1013 out[11] = clamp_range(step[9] - step[11], r);
1014 out[12] = clamp_range(step[12] + step[14], r);
1015 out[13] = clamp_range(step[13] + step[15], r);
1016 out[14] = clamp_range(step[12] - step[14], r);
1017 out[15] = clamp_range(step[13] - step[15], r);
1018
1019 step[0] = out[0];
1020 step[1] = out[1];
1021 step[2] = half_btf(cos128(32), out[2], cos128(32), out[3]);
1022 step[3] = half_btf(cos128(32), out[2], -cos128(32), out[3]);
1023 step[4] = out[4];
1024 step[5] = out[5];
1025 step[6] = half_btf(cos128(32), out[6], cos128(32), out[7]);
1026 step[7] = half_btf(cos128(32), out[6], -cos128(32), out[7]);
1027 step[8] = out[8];
1028 step[9] = out[9];
1029 step[10] = half_btf(cos128(32), out[10], cos128(32), out[11]);
1030 step[11] = half_btf(cos128(32), out[10], -cos128(32), out[11]);
1031 step[12] = out[12];
1032 step[13] = out[13];
1033 step[14] = half_btf(cos128(32), out[14], cos128(32), out[15]);
1034 step[15] = half_btf(cos128(32), out[14], -cos128(32), out[15]);
1035
1036 t[0] = step[0];
1037 t[1] = -step[8];
1038 t[2] = step[12];
1039 t[3] = -step[4];
1040 t[4] = step[6];
1041 t[5] = -step[14];
1042 t[6] = step[10];
1043 t[7] = -step[2];
1044 t[8] = step[3];
1045 t[9] = -step[11];
1046 t[10] = step[15];
1047 t[11] = -step[7];
1048 t[12] = step[5];
1049 t[13] = -step[13];
1050 t[14] = step[9];
1051 t[15] = -step[1];
1052}
1053
1054/// `av1_iidentity4_c`/`8_c`/`16_c`/`32_c` (`av1_inv_txfm1d.c`): a fixed
1055/// per-size scale, `sqrt(2)`-based at 4 and 16 (`NewSqrt2`/`NewSqrt2Bits`),
1056/// exact doubling at 8 and 32.
1057fn inverse_identity(t: &mut [i32], side: usize) {
1058 match side {
1059 4 => {
1060 for v in &mut t[..4] {
1061 *v = round_shift(NEW_SQRT2 * i64::from(*v), NEW_SQRT2_BITS);
1062 }
1063 }
1064 8 => {
1065 for v in &mut t[..8] {
1066 *v = (i64::from(*v) * 2) as i32;
1067 }
1068 }
1069 16 => {
1070 for v in &mut t[..16] {
1071 *v = round_shift(NEW_SQRT2 * 2 * i64::from(*v), NEW_SQRT2_BITS);
1072 }
1073 }
1074 32 => {
1075 for v in &mut t[..32] {
1076 *v = (i64::from(*v) * 4) as i32;
1077 }
1078 }
1079 _ => unreachable!("identity is defined at sizes 4, 8, 16 and 32"),
1080 }
1081}
1082
1083/// Dispatches one row or column's 1D inverse transform by [`TxType1d`],
1084/// `log2` the spec's transform-size log (as [`inverse_dct`] takes).
1085fn inverse_1d(t: &mut [i32; 64], log2: u32, r: usize, kind: TxType1d) {
1086 match kind {
1087 TxType1d::Dct => inverse_dct_fixed(t, log2, r),
1088 TxType1d::Adst => match log2 {
1089 2 => inverse_adst4(t),
1090 3 => inverse_adst8(t, r),
1091 4 => inverse_adst16(t, r),
1092 _ => unreachable!("ADST is undefined at sizes above 16 (spec: 32+ uses DCT/identity)"),
1093 },
1094 TxType1d::Identity => inverse_identity(t, 1usize << log2),
1095 }
1096}
1097
1098/// The 2D inverse transform (spec 7.13.3) for a square block of any
1099/// [`TxType`]. `dequant` is the dequantized coefficient grid in raster order;
1100/// the returned residual is in the same order. A 64-point transform only ever
1101/// carries coefficients in its first 32 rows and columns, and the spec
1102/// zeroes the rest before the row transform, which is what the `< 32` guard
1103/// does (`TxType`s other than `DctDct` never reach a 64-point transform in
1104/// this decoder -- `Luma64`'s CDF set carries no `tx_type` symbol).
1105pub fn inverse_transform_2d_typed(
1106 dequant: &[i32],
1107 side: usize,
1108 bit_depth: u8,
1109 tx_type: TxType,
1110) -> Vec<i32> {
1111 inverse_transform_2d_typed_wh(dequant, side, side, bit_depth, tx_type)
1112}
1113
1114/// [`inverse_transform_2d_typed`] widened to `(w, h)` (lane-recttx): the row
1115/// pass transforms `w`-point vectors (`log2(w)`), the column pass
1116/// `h`-point vectors (`log2(h)`), and a rect-only pre-row-transform scale
1117/// is applied when the two axes are exactly one power-of-two apart (spec
1118/// 7.13.3; `av1_inv_txfm2d.c:272-276`, `abs(rect_type) == 1`). `dequant` is
1119/// still raster order (`dequant[i * w + j]`, row `i` of `h`, column `j` of
1120/// `w`) -- libaom's own buffer for the same math is column-major, an
1121/// unrelated fact about ITS storage, not the spec's arithmetic (class
1122/// `reference-layout-not-spec`).
1123pub fn inverse_transform_2d_typed_wh(
1124 dequant: &[i32],
1125 w: usize,
1126 h: usize,
1127 bit_depth: u8,
1128 tx_type: TxType,
1129) -> Vec<i32> {
1130 let log2w = w.trailing_zeros();
1131 let log2h = h.trailing_zeros();
1132 assert_eq!(1usize << log2w, w, "width must be a power of two");
1133 assert_eq!(1usize << log2h, h, "height must be a power of two");
1134 assert_eq!(dequant.len(), w * h, "one coefficient per position");
1135 let row_clamp = usize::from(bit_depth) + 8;
1136 let col_clamp = (usize::from(bit_depth) + 6).max(16);
1137 let (row_kind, col_kind) = tx_type.axes();
1138 let (ud_flip, lr_flip) = tx_type.flip();
1139 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only
1140 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/
1141 // 16x64/64x16).
1142 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;
1143 // Loop-invariant: the shift is keyed on the transform size, and was being
1144 // looked up through a match once per output sample.
1145 let shift = row_shift_wh(w, h);
1146 // A FLIPADST axis reads the row-pass output right-to-left and/or writes
1147 // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`
1148 // lines 291-314): `out` is a second buffer, not the row scratch reused in
1149 // place, because a flipped read/write pair aliases a column this same
1150 // loop has not visited yet (column `j`'s write target under `lr_flip`
1151 // is a column an unflipped loop would still need to read from later).
1152 // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.
1153 let mut out = vec![0i32; w * h];
1154 let cols = w.min(32);
1155 ROW_SCRATCH.with(|cell| {
1156 let mut scratch = cell.borrow_mut();
1157 if scratch.len() < w * h {
1158 scratch.resize(64 * 64, 0);
1159 }
1160 let residual = &mut scratch[..w * h];
1161 let mut t = [0i32; 64];
1162 // lane-perf10: rows the row pass left non-zero, and whether the first
1163 // of them came out constant along the row -- see the fast path below.
1164 let mut nz_rows = 0usize;
1165 let mut nz_row = 0usize;
1166 let mut const_row = false;
1167 for i in 0..h {
1168 let dst = &mut residual[i * w..(i + 1) * w];
1169 // Rows at or past 32 carry no coefficients (the spec zeroes them
1170 // before the row transform), and a zero row transforms to a zero
1171 // row: every butterfly and Hadamard of zeros is zero, and
1172 // `Round2(0, n)` is zero at every `n`, so this is the full
1173 // network's own answer, not an approximation of it.
1174 let src = if i < 32 { &dequant[i * w..i * w + cols] } else { &[][..] };
1175 if src.iter().all(|&c| c == 0) {
1176 dst.fill(0);
1177 continue;
1178 }
1179 if rect_scale {
1180 for (tj, &c) in t[..cols].iter_mut().zip(src) {
1181 *tj = round2(c * 2896, 12);
1182 }
1183 } else {
1184 t[..cols].copy_from_slice(src);
1185 }
1186 t[cols..w].fill(0);
1187 inverse_1d(&mut t, log2w, row_clamp, row_kind);
1188 // The row's output is shifted, then clamped before the column
1189 // transform reads it back.
1190 for (d, &v) in dst.iter_mut().zip(t[..w].iter()) {
1191 *d = clamp_range(round2(v, shift), col_clamp);
1192 }
1193 nz_rows += 1;
1194 nz_row = i;
1195 const_row = nz_rows == 1 && dst.iter().all(|&v| v == dst[0]);
1196 }
1197
1198 // A block whose row pass left exactly one non-zero row, constant along
1199 // that row, feeds every column of the column pass the same vector --
1200 // the DC-only case, which dominates inter residuals. `inverse_1d` is a
1201 // pure function of its input, so one column transform broadcast across
1202 // the block is byte-identical to `w` of them, and the per-column gather
1203 // disappears with it.
1204 if nz_rows <= 1 && const_row {
1205 t[..h].fill(0);
1206 t[nz_row] = residual[nz_row * w];
1207 inverse_1d(&mut t, log2h, col_clamp, col_kind);
1208 for i in 0..h {
1209 let dst_row = if ud_flip { h - 1 - i } else { i };
1210 out[dst_row * w..dst_row * w + w].fill(round2(t[i], 4));
1211 }
1212 return;
1213 }
1214
1215 // The column pass over a plain-DCT axis takes eight neighbouring
1216 // columns through one network ([`Lane`]): eight columns of one
1217 // row-pass row are eight adjacent `i32`s, so the gather is a
1218 // contiguous load and every butterfly is one vector op instead of
1219 // eight scalar ones. `lr_flip` reads the columns right-to-left, which
1220 // is not a contiguous chunk, so it stays on the scalar path below.
1221 if col_kind == TxType1d::Dct && w >= 8 && !lr_flip {
1222 #[cfg(target_arch = "x86_64")]
1223 if matches!(crate::mc::simd_level(), crate::mc::SimdLevel::Avx2) {
1224 // SAFETY: the branch above is the AVX2 feature detection.
1225 #[allow(unsafe_code)]
1226 unsafe {
1227 simd::column_pass_dct(residual, &mut out, w, h, log2h, col_clamp, ud_flip);
1228 }
1229 return;
1230 }
1231 let mut t8 = [[0i32; 8]; 64];
1232 for j in (0..w).step_by(8) {
1233 let mut any = 0i32;
1234 for i in 0..h {
1235 let src = &residual[i * w + j..][..8];
1236 for (d, &v) in t8[i].iter_mut().zip(src) {
1237 *d = v;
1238 any |= v;
1239 }
1240 }
1241 if any == 0 {
1242 continue;
1243 }
1244 inverse_dct_x8(&mut t8, log2h, col_clamp);
1245 for i in 0..h {
1246 let dst_row = if ud_flip { h - 1 - i } else { i };
1247 let dst = &mut out[dst_row * w + j..][..8];
1248 for (d, &v) in dst.iter_mut().zip(t8[i].iter()) {
1249 *d = round2(v, 4);
1250 }
1251 }
1252 }
1253 return;
1254 }
1255
1256 for j in 0..w {
1257 let src_col = if lr_flip { w - 1 - j } else { j };
1258 let mut any = 0i32;
1259 for i in 0..h {
1260 let v = residual[i * w + src_col];
1261 t[i] = v;
1262 any |= v;
1263 }
1264 // Same zero-in/zero-out argument as the row pass, and `out` is
1265 // already zero at every position this column would write.
1266 if any == 0 {
1267 continue;
1268 }
1269 inverse_1d(&mut t, log2h, col_clamp, col_kind);
1270 for i in 0..h {
1271 let dst_row = if ud_flip { h - 1 - i } else { i };
1272 out[dst_row * w + j] = round2(t[i], 4);
1273 }
1274 }
1275 });
1276 out
1277}
1278
1279thread_local! {
1280 /// Row-pass scratch, reused per thread. The row pass writes every position
1281 /// it later reads, so the buffer needs no zeroing, and the two `Vec`s this
1282 /// function allocated per transform unit become one.
1283 static ROW_SCRATCH: std::cell::RefCell<Vec<i32>> =
1284 const { std::cell::RefCell::new(Vec::new()) };
1285}
1286
1287/// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original
1288/// (and still most common) transform.
1289pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {
1290 inverse_transform_2d_typed(dequant, side, bit_depth, TxType::DctDct)
1291}
1292
1293/// Dequantize (spec 7.12.3) and inverse transform one square block of any
1294/// [`TxType`], returning its residual in raster order.
1295///
1296/// This is the encoder's model of what the decoder will add to its prediction,
1297/// so it follows the spec's dequantization exactly, truncation toward zero and
1298/// all.
1299#[allow(clippy::too_many_arguments)]
1300pub fn dequant_and_inverse_typed(
1301 levels: &[i32],
1302 side: usize,
1303 bit_depth: u8,
1304 q_idx: i32,
1305 dc_delta: i32,
1306 ac_delta: i32,
1307 tx_type: TxType,
1308) -> Vec<i32> {
1309 let r =
1310 dequant_and_inverse_typed_wh(levels, side, side, bit_depth, q_idx, dc_delta, ac_delta, tx_type);
1311 // This square entry point keeps the dense contract (its callers are the
1312 // encoder-side model and the gates, which index the result directly);
1313 // only the decoder's `_wh` path speaks the empty marker.
1314 if r.is_empty() { vec![0i32; side * side] } else { r }
1315}
1316
1317/// [`dequant_and_inverse_typed`] widened to `(w, h)` (lane-recttx). `dc_delta`/
1318/// `ac_delta` are the per-plane quantizer-index offsets (lane-sbpart r11,
1319/// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- `0`/`0` for the
1320/// unaffected callers below.
1321#[allow(clippy::too_many_arguments)]
1322pub fn dequant_and_inverse_typed_wh(
1323 levels: &[i32],
1324 w: usize,
1325 h: usize,
1326 bit_depth: u8,
1327 q_idx: i32,
1328 dc_delta: i32,
1329 ac_delta: i32,
1330 tx_type: TxType,
1331) -> Vec<i32> {
1332 // 60% of the transform units of a 4K inter stream carry no coefficient at
1333 // all (measured on the perf segment: 3.46M of 5.7M calls). Dequantization
1334 // maps zero to zero (`dequant_wh_into`) and a zero grid inverse-transforms
1335 // to a zero residual, which is exactly the buffer below already returns --
1336 // so one scan of the levels replaces the dequantization, the row pass and
1337 // the column pass for those.
1338 // The residual is returned EMPTY in that case, not as `w * h` zeros: an
1339 // empty residual is this decoder's "all zero" marker (`ZERO_RESIDUAL` in
1340 // `decode.rs`), which also drops the `vec![0; w * h]` memset here and the
1341 // `to_vec` clone the recorded [`crate::decode::Residual`] made of it --
1342 // together 6.5% of the 4K segment's profile (memset + memmove).
1343 if crate::decode::is_zero_grid(levels) {
1344 return Vec::new();
1345 }
1346 DQ_SCRATCH.with(|cell| {
1347 let mut dq = cell.borrow_mut();
1348 crate::quant::dequant_wh_into(levels, &mut dq, w, h, bit_depth, q_idx, dc_delta, ac_delta);
1349 inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type)
1350 })
1351}
1352
1353thread_local! {
1354 /// The dequantized grid, reused per thread: it lives only until the
1355 /// inverse transform has read it, so it was a `Vec` allocated and dropped
1356 /// once per transform unit.
1357 static DQ_SCRATCH: std::cell::RefCell<Vec<i32>> =
1358 const { std::cell::RefCell::new(Vec::new()) };
1359}
1360
1361/// [`dequant_and_inverse_typed`] at `DCT_DCT`, no per-plane quantizer delta.
1362pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i32> {
1363 dequant_and_inverse_typed(levels, side, bit_depth, q_idx, 0, 0, TxType::DctDct)
1364}
1365
1366/// The orthonormal DCT-II basis row for output `u` of an `n`-point transform.
1367///
1368/// The decoder's network is this basis scaled by a constant the encoder has to
1369/// undo, and nothing else: measuring the network's response to a unit
1370/// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of
1371/// `dqDenom`, which is what [`forward_transform_2d`] divides out.
1372fn build_dct_basis(n: usize) -> Vec<f64> {
1373 let mut basis = vec![0.0f64; n * n];
1374 let scale = (2.0 / n as f64).sqrt();
1375 for u in 0..n {
1376 let alpha = if u == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 };
1377 for i in 0..n {
1378 let angle = std::f64::consts::PI * (2.0 * i as f64 + 1.0) * u as f64 / (2.0 * n as f64);
1379 basis[u * n + i] = alpha * scale * angle.cos();
1380 }
1381 }
1382 basis
1383}
1384
1385/// [`build_dct_basis`], computed once per transform size and reused: the
1386/// search calls [`forward_transform_2d`] for every mode of every block, and
1387/// the basis does not depend on the residual, only on `n` -- recomputing
1388/// `n * n` cosines per call was measured as this search's single largest
1389/// per-trial cost (`stage_timing_breakdown`, ec-av1 perf lane). `n` is always
1390/// one of the transform sizes this crate codes (4 to 64, a power of two), so
1391/// a small fixed table indexed by `log2(n)` covers every caller without a
1392/// hash lookup.
1393// Also the reference [`forward_gain`] measures the fixed-point network against.
1394fn dct_basis(n: usize) -> &'static [f64] {
1395 use std::sync::OnceLock;
1396 // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.
1397 static CACHE: OnceLock<[OnceLock<Vec<f64>>; 5]> = OnceLock::new();
1398 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
1399 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1400 cache[idx].get_or_init(|| build_dct_basis(n))
1401}
1402
1403/// The orthonormal basis of one 1D axis, measured from the decoder's own
1404/// inverse network rather than written out: a unit coefficient through
1405/// [`inverse_1d`] IS the basis function that kernel synthesises, and
1406/// normalising each to unit length gives the analysis basis a forward
1407/// transform pairs with. AV1 normalises every 1D kernel to the same gain --
1408/// that is what lets one shift chain serve mixed types -- so the
1409/// [`INVERSE_GAIN_RECIPROCAL`] correction a DCT axis takes is the one an ADST
1410/// axis takes too.
1411fn build_axis_basis(n: usize, kind: TxType1d) -> Vec<f64> {
1412 if kind == TxType1d::Dct {
1413 return build_dct_basis(n);
1414 }
1415 let log2 = n.trailing_zeros();
1416 let mut basis = vec![0.0f64; n * n];
1417 for u in 0..n {
1418 let mut t = [0i32; 64];
1419 // Large enough that the network's own rounding is negligible, small
1420 // enough that nothing clamps at the 24-bit range passed below.
1421 t[u] = 1 << 12;
1422 inverse_1d(&mut t, log2, 24, kind);
1423 let norm = (0..n).map(|i| f64::from(t[i]) * f64::from(t[i])).sum::<f64>().sqrt();
1424 for i in 0..n {
1425 basis[u * n + i] = f64::from(t[i]) / norm;
1426 }
1427 }
1428 basis
1429}
1430
1431/// [`build_axis_basis`], computed once per (size, kind).
1432fn axis_basis(n: usize, kind: TxType1d) -> &'static [f64] {
1433 use std::sync::OnceLock;
1434 static CACHE: OnceLock<[[OnceLock<Vec<f64>>; 5]; 3]> = OnceLock::new();
1435 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new())));
1436 let k = match kind {
1437 TxType1d::Dct => 0,
1438 TxType1d::Adst => 1,
1439 TxType1d::Identity => 2,
1440 };
1441 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1442 cache[k][idx].get_or_init(|| build_axis_basis(n, kind))
1443}
1444
1445/// [`axis_basis`] transposed: `[i * n + u]` is basis function `u`'s sample
1446/// `i`. Both of [`forward_transform_2d_typed`]'s passes sum over the sample
1447/// index and are independent across the basis index, so this layout makes the
1448/// basis index the contiguous one and the two matmuls vectorize -- without
1449/// touching either sum's order, which is what keeps the levels bit-identical
1450/// to the strided `.map().sum()` this replaced.
1451fn axis_basis_t(n: usize, kind: TxType1d) -> &'static [f64] {
1452 use std::sync::OnceLock;
1453 static CACHE: OnceLock<[[OnceLock<Vec<f64>>; 5]; 3]> = OnceLock::new();
1454 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| std::array::from_fn(|_| OnceLock::new())));
1455 let k = match kind {
1456 TxType1d::Dct => 0,
1457 TxType1d::Adst => 1,
1458 TxType1d::Identity => 2,
1459 };
1460 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1461 cache[k][idx].get_or_init(|| {
1462 let basis = axis_basis(n, kind);
1463 let mut t = vec![0.0f64; n * n];
1464 for u in 0..n {
1465 for i in 0..n {
1466 t[i * n + u] = basis[u * n + i];
1467 }
1468 }
1469 t
1470 })
1471}
1472
1473/// [`forward_transform_2d`] for a block whose transform type is not
1474/// `DCT_DCT` -- what an intra chroma block coded in a non-`DC_PRED` mode
1475/// gets, since chroma never codes a `tx_type` symbol and the decoder derives
1476/// it from the mode (`Intra_Mode_To_Tx_Type`, spec 9.3).
1477///
1478/// The forward transform is the encoder's own business: only the levels and
1479/// the type reach the decoder, so an approximate analysis basis costs rate,
1480/// never correctness -- the reconstruction the search scores comes back
1481/// through the decoder's exact inverse either way.
1482pub fn forward_transform_2d_typed(residual: &[i32], side: usize, tx_type: TxType) -> Vec<f64> {
1483 if tx_type == TxType::DctDct {
1484 return forward_transform_2d(residual, side);
1485 }
1486 debug_assert_eq!(
1487 tx_type.flip(),
1488 (false, false),
1489 "a flipped ADST needs its residual mirrored before this basis applies"
1490 );
1491 let (row_kind, col_kind) = tx_type.axes();
1492 let (hb, vb) = (axis_basis_t(side, row_kind), axis_basis_t(side, col_kind));
1493 let mut rows = vec![0.0f64; side * side];
1494 // Which rows of `rows` the pass below actually fills; the column pass
1495 // walks only those. A row of `+0.0` contributes `0.0 * b` terms, which
1496 // are `+-0.0`, and adding either to a running sum that is never `-0.0`
1497 // (it starts at `+0.0` and `x + -x` is `+0.0`) leaves it unchanged.
1498 let mut filled: [usize; 64] = [0; 64];
1499 let mut nfilled = 0usize;
1500 // Zero in, zero out, and `rows` is already zero here -- the skip
1501 // [`forward_rows`] takes for the same reason, which this path was
1502 // missing: a census of the BD gate's own ladder (lane-av1fwd) found 68%
1503 // of the 1.9M calls here carry an all-zero residual, and another 6.5M
1504 // individual rows of the rest are zero. A row of zeros contributes only
1505 // `0.0 * b` terms, and a sum of zeros is `+0.0`, so this is exact.
1506 let mut any = false;
1507 for i in 0..side {
1508 let source = &residual[i * side..][..side];
1509 if source.iter().all(|&r| r == 0) {
1510 continue;
1511 }
1512 any = true;
1513 filled[nfilled] = i;
1514 nfilled += 1;
1515 let out = &mut rows[i * side..][..side];
1516 // `k` ascending is the term order the strided `.map().sum()` had, so
1517 // every lane's partial sums are the same values in the same order.
1518 for (k, &r) in source.iter().enumerate() {
1519 let r = f64::from(r);
1520 for (o, &b) in out.iter_mut().zip(&hb[k * side..][..side]) {
1521 *o += r * b;
1522 }
1523 }
1524 }
1525 if !any {
1526 return rows;
1527 }
1528 let mut out = vec![0.0f64; side * side];
1529 for u in 0..side {
1530 let acc = &mut out[u * side..][..side];
1531 for &i in &filled[..nfilled] {
1532 let c = vb[i * side + u];
1533 for (a, &r) in acc.iter_mut().zip(&rows[i * side..][..side]) {
1534 *a += r * c;
1535 }
1536 }
1537 for a in acc.iter_mut() {
1538 *a *= INVERSE_GAIN_RECIPROCAL;
1539 }
1540 }
1541 out
1542}
1543
1544/// [`forward_and_quantize`] at a named transform type.
1545pub fn forward_and_quantize_typed(
1546 residual: &[i32],
1547 side: usize,
1548 bit_depth: u8,
1549 q_idx: i32,
1550 deadzone: f64,
1551 tx_type: TxType,
1552) -> Vec<i32> {
1553 let coeffs = forward_transform_2d_typed(residual, side, tx_type);
1554 quantize(&coeffs, side, bit_depth, q_idx, deadzone)
1555}
1556
1557/// [`forward_and_quantize_typed`] that also hands back each coded position's
1558/// pre-rounding scaled coefficient (`coeff / q`, the exact real-valued level
1559/// the quantiser rounded). The RDOQ pass ([`crate::tile::rdoq`]) prices
1560/// `level - 1` against `level` and needs the distance to both, which the
1561/// levels alone no longer carry.
1562pub fn forward_and_quantize_typed_scaled(
1563 residual: &[i32],
1564 side: usize,
1565 bit_depth: u8,
1566 q_idx: i32,
1567 deadzone: f64,
1568 tx_type: TxType,
1569) -> (Vec<i32>, Vec<f32>) {
1570 let coeffs = forward_transform_2d_typed(residual, side, tx_type);
1571 let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx));
1572 let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx));
1573 let mut scaled = vec![0f32; side * side];
1574 let coded = side.min(32);
1575 for row in 0..coded {
1576 for col in 0..coded {
1577 let i = row * side + col;
1578 scaled[i] = (coeffs[i] / if i == 0 { dc } else { ac }) as f32;
1579 }
1580 }
1581 // Same levels as the plain entry point: this is the same division the
1582 // quantiser does, and the levels come from the quantiser itself.
1583 (quantize(&coeffs, side, bit_depth, q_idx, deadzone), scaled)
1584}
1585
1586/// How much the decoder's inverse transform shrinks an orthonormal DCT.
1587///
1588/// Measured, not asserted: feeding a single dequantized coefficient through
1589/// `inverse_transform_2d` reproduces the orthonormal basis function scaled by
1590/// `dq_denom(side) / 8` at every size (see `the_inverse_network_is_an_orthonormal_dct_over_eight`).
1591/// The dequantizer has already divided by `dq_denom`, so the two cancel and
1592/// what an encoder owes a level is size-independent:
1593/// `level = 8 * orthonormal(residual) / q`.
1594///
1595/// The spec fixes the decoder; the encoder is free in how it reaches the
1596/// coefficients it sends, and this constant is the one thing the two ends have
1597/// to agree on for a level to mean what the encoder thinks it means.
1598const INVERSE_GAIN_RECIPROCAL: f64 = 8.0;
1599
1600/// The forward DCT network: [`inverse_dct_n`]'s stages in reverse order, each
1601/// one transposed.
1602///
1603/// The encoder's forward transform is its own business -- only the quantized
1604/// levels reach the decoder, and the reconstruction the search scores comes
1605/// back through the decoder's exact inverse -- so what it owes is a good
1606/// analysis basis, not a specified one. The cheapest good one is the
1607/// decoder's: a butterfly network's transpose is that network run backwards
1608/// with every elementary matrix transposed, and all of this one's elements
1609/// are symmetric except the unflipped rotation, whose transpose is the same
1610/// rotation at the negated angle. (`hadamard` is `[[1, 1], [1, -1]]` without
1611/// its flip and `[[-1, 1], [1, 1]]` with it; a flipped `butterfly` is
1612/// `[[s, c], [c, -s]]`; `permute` is a bit reversal, an involution.) So the
1613/// body below -- the inverse's stages reversed, its unflipped angles negated,
1614/// its permutation moved to the end -- is the analysis half of the same
1615/// orthogonal transform, in `i32` arithmetic against the decoder's own cosine
1616/// table: no libm, no complex FFT, and the eight-wide [`Lane`] impls apply to
1617/// it unchanged.
1618///
1619/// The gain is the inverse network's, since a transpose preserves it;
1620/// [`forward_gain`] measures it from this network rather than asserting it.
1621#[inline(always)]
1622fn forward_dct_n<T: Lane, const N: u32>(t: &mut [T; 64], r: usize) {
1623 if N == 6 {
1624 for i in 0..32 {
1625 hadamard(t, i, 63 - i, false, r);
1626 }
1627 }
1628 if N == 6 {
1629 for i in 0..8 {
1630 butterfly(t, 55 - i, 40 + i, 32, true, r);
1631 }
1632 }
1633 if N >= 5 {
1634 for i in 0..16 {
1635 hadamard(t, i, 31 - i, false, r);
1636 }
1637 }
1638 if N == 6 {
1639 for i in 0..8 {
1640 hadamard(t, 32 + i, 47 - i, false, r);
1641 hadamard(t, 48 + i, 63 - i, true, r);
1642 }
1643 }
1644 if N >= 5 {
1645 for i in 0..4 {
1646 butterfly(t, 27 - i, 20 + i, 32, true, r);
1647 }
1648 }
1649 if N >= 4 {
1650 for i in 0..8 {
1651 hadamard(t, i, 15 - i, false, r);
1652 }
1653 }
1654 if N == 6 {
1655 for i in 0..8 {
1656 butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r);
1657 }
1658 }
1659 if N >= 5 {
1660 for i in 0..2 {
1661 for j in 0..4 {
1662 hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
1663 }
1664 }
1665 }
1666 if N >= 4 {
1667 for i in 0..2 {
1668 butterfly(t, 13 - i, 10 + i, 32, true, r);
1669 }
1670 }
1671 if N >= 3 {
1672 for i in 0..4 {
1673 hadamard(t, i, 7 - i, false, r);
1674 }
1675 }
1676 if N == 6 {
1677 for i in 0..4 {
1678 for j in 0..4 {
1679 hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r);
1680 }
1681 }
1682 }
1683 if N >= 5 {
1684 for i in 0..4 {
1685 butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r);
1686 }
1687 }
1688 if N >= 4 {
1689 for i in 0..2 {
1690 for j in 0..2 {
1691 hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r);
1692 }
1693 }
1694 }
1695 if N >= 3 {
1696 butterfly(t, 6, 5, 32, true, r);
1697 }
1698 for i in 0..2 {
1699 hadamard(t, i, 3 - i, false, r);
1700 }
1701 if N == 6 {
1702 for i in 0..2 {
1703 for j in 0..4 {
1704 let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64;
1705 butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r);
1706 }
1707 }
1708 }
1709 if N >= 5 {
1710 for i in 0..4 {
1711 for j in 0..2 {
1712 hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r);
1713 }
1714 }
1715 }
1716 if N >= 4 {
1717 for i in 0..2 {
1718 butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r);
1719 }
1720 }
1721 if N >= 3 {
1722 for i in 0..2 {
1723 hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r);
1724 }
1725 }
1726 for i in 0..2 {
1727 butterfly(t, 2 * i, 2 * i + 1, if i == 0 { 32 + 16 * i as i32 } else { -(32 + 16 * i as i32) }, i == 0, r);
1728 }
1729 if N == 6 {
1730 for i in 0..8 {
1731 for j in 0..2 {
1732 hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r);
1733 }
1734 }
1735 }
1736 if N >= 5 {
1737 for i in 0..2 {
1738 for j in 0..2 {
1739 let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5);
1740 butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r);
1741 }
1742 }
1743 }
1744 if N >= 4 {
1745 for i in 0..4 {
1746 hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r);
1747 }
1748 }
1749 if N >= 3 {
1750 for i in 0..2 {
1751 butterfly(t, 4 + i, 7 - i, -(56 - 32 * i as i32), false, r);
1752 }
1753 }
1754 if N == 6 {
1755 for i in 0..4 {
1756 for j in 0..2 {
1757 let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32;
1758 butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r);
1759 }
1760 }
1761 }
1762 if N >= 5 {
1763 for i in 0..8 {
1764 hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
1765 }
1766 }
1767 if N >= 4 {
1768 for i in 0..4 {
1769 butterfly(
1770 t,
1771 8 + i,
1772 15 - i, -(12 + ((brev(2, 3 - i) as i32) << 4)),
1773 false,
1774 r);
1775 }
1776 }
1777 if N == 6 {
1778 for i in 0..16 {
1779 hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r);
1780 }
1781 }
1782 if N >= 5 {
1783 for i in 0..8 {
1784 butterfly(
1785 t,
1786 16 + i,
1787 31 - i, -(6 + ((brev(3, 7 - i) as i32) << 3)),
1788 false,
1789 r);
1790 }
1791 }
1792 if N == 6 {
1793 for i in 0..16 {
1794 butterfly(t, 32 + i, 63 - i, -(63 - 4 * brev(4, i) as i32), false, r);
1795 }
1796 }
1797
1798 permute(t, N);
1799}
1800
1801/// [`forward_dct_n`] dispatched on the size, as [`inverse_dct_fixed`] is.
1802fn forward_dct_fixed(t: &mut [i32; 64], n: u32, r: usize) {
1803 match n {
1804 2 => forward_dct_n::<i32, 2>(t, r),
1805 3 => forward_dct_n::<i32, 3>(t, r),
1806 4 => forward_dct_n::<i32, 4>(t, r),
1807 5 => forward_dct_n::<i32, 5>(t, r),
1808 6 => forward_dct_n::<i32, 6>(t, r),
1809 _ => unreachable!("the forward DCT is defined for 4..64"),
1810 }
1811}
1812
1813/// The range the forward network's intermediates are clamped to. The residual
1814/// is at most +-2^bit_depth and one pass multiplies by the network's gain
1815/// (`sqrt(n / 2)`, at most 5.66), so two passes stay under 2^20 for 8-bit and
1816/// nothing here ever reaches this bound -- it exists so `Lane::had` has the
1817/// same shape it has in the decoder.
1818const FORWARD_RANGE: usize = 32;
1819
1820/// Headroom bits the residual is shifted up by before the row pass.
1821///
1822/// The network rounds to an integer at every butterfly, so its output LSB is
1823/// what the quantizer's input resolution costs: unshifted, one LSB at 4x4 is
1824/// four whole units of the `8 * orthonormal` scale the levels are formed on
1825/// -- coarser than a fine quantizer's own step, and worth 3.9 BD points on
1826/// screen capture. Ten bits put it at 1/256 of a unit, which is where the BD
1827/// gate stops moving (13 bits measured identical), and cost nothing: the
1828/// widest case, a 12-bit residual through two 64-point passes (gain 32),
1829/// stays under 2^27 -- inside `i32` and far inside [`FORWARD_RANGE`].
1830const FORWARD_PRECISION_BITS: u32 = 10;
1831
1832/// [`forward_dct_n`]'s uniform gain at one size, measured from the network
1833/// itself rather than derived: an impulse through it is `g` times
1834/// [`dct_basis`]'s corresponding column, so a least-squares fit over the
1835/// whole column returns `g` without trusting any single output's rounding.
1836/// Cached per size, like every other table here.
1837fn forward_gain(n: usize) -> f64 {
1838 use std::sync::OnceLock;
1839 static CACHE: OnceLock<[OnceLock<f64>; 5]> = OnceLock::new();
1840 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
1841 *cache[(n.trailing_zeros() as usize).saturating_sub(2)].get_or_init(|| {
1842 // Large enough that the network's rounding is negligible against it,
1843 // far below anything `FORWARD_RANGE` clamps.
1844 const AMP: i32 = 1 << 14;
1845 let mut t = [0i32; 64];
1846 t[0] = AMP;
1847 forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE);
1848 let basis = dct_basis(n);
1849 let num: f64 = (0..n).map(|u| f64::from(t[u]) * basis[u * n]).sum();
1850 let den: f64 = (0..n).map(|u| basis[u * n] * basis[u * n]).sum();
1851 num / (f64::from(AMP) * den)
1852 })
1853}
1854
1855/// The forward transform (encoder side, spec-free): the transpose of what the
1856/// decoder's inverse does, so that `inverse_transform_2d` of the result
1857/// reproduces `residual`.
1858///
1859/// AV1 specifies only the inverse transform. The encoder may reach its
1860/// coefficients however it likes, and this reaches them via [`dct1d`], an
1861/// `O(n log n)` orthonormal DCT-II factorization equal to the direct
1862/// `O(n^2)` matmul up to floating-point rounding (see
1863/// `fast_forward_matches_the_naive_matmul`), scaled to the decoder's
1864/// fixed-point gain. It is deterministic, and its accuracy is measured
1865/// against the decoder's own inverse rather than asserted.
1866pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {
1867 let rows = forward_rows(residual, side);
1868 let scale = forward_scale(side);
1869 let mut out = vec![0.0f64; side * side];
1870 let mut t = [0i32; 64];
1871 for v in 0..side {
1872 if !forward_column(&rows, side, v, &mut t) {
1873 continue;
1874 }
1875 for u in 0..side {
1876 out[u * side + v] = f64::from(t[u]) * scale;
1877 }
1878 }
1879 out
1880}
1881
1882/// The row pass, in fixed point: each of `side` residual rows through
1883/// [`forward_dct_fixed`], at [`FORWARD_PRECISION_BITS`] extra precision and
1884/// the network's own gain (both of which [`forward_scale`] divides back out).
1885///
1886/// The `Vec` is per call on purpose: holding it in a thread-local scratch, as
1887/// the inverse transform's row pass does, was MEASURED +5.0% instructions on
1888/// the sequence bench -- a fresh zeroed allocation costs less here than the
1889/// `memset` reusing one needs plus the thread-local access, because the
1890/// zeroing is what the all-zero-row skip below reads.
1891fn forward_rows(residual: &[i32], side: usize) -> Vec<i32> {
1892 assert_eq!(
1893 residual.len(),
1894 side * side,
1895 "one residual sample per position"
1896 );
1897 let log2 = side.trailing_zeros();
1898 let mut rows = vec![0i32; side * side];
1899 let mut t = [0i32; 64];
1900 for i in 0..side {
1901 let source = &residual[i * side..][..side];
1902 // Zero in, zero out, and `rows` is already zero here -- the skip the
1903 // decoder's column pass takes for the same reason.
1904 if source.iter().all(|&r| r == 0) {
1905 continue;
1906 }
1907 for (dst, &r) in t[..side].iter_mut().zip(source) {
1908 *dst = r << FORWARD_PRECISION_BITS;
1909 }
1910 forward_dct_fixed(&mut t, log2, FORWARD_RANGE);
1911 rows[i * side..][..side].copy_from_slice(&t[..side]);
1912 }
1913 rows
1914}
1915
1916/// One column of [`forward_rows`]'s output through the network, into `t`;
1917/// `false` when the column is all zero and `t` was left untouched.
1918///
1919/// One column at a time, and the caller consumes `t` before asking for the
1920/// next: eight columns through the same `[i32; 8]` [`Lane`] the decoder's
1921/// column pass uses was MEASURED SLOWER (+3.4% instructions on the sequence
1922/// bench, and +2.3% for an in-place whole-buffer column pass). This encoder's
1923/// transforms are mostly small -- a group of eight loses the per-column zero
1924/// skip that a 4x4 or 8x8 residual keeps hitting, and the levels stop being
1925/// formed while the column is still in registers.
1926fn forward_column(rows: &[i32], side: usize, v: usize, t: &mut [i32; 64]) -> bool {
1927 let mut any = 0i32;
1928 for i in 0..side {
1929 t[i] = rows[i * side + v];
1930 any |= t[i];
1931 }
1932 if any == 0 {
1933 return false;
1934 }
1935 forward_dct_fixed(t, side.trailing_zeros(), FORWARD_RANGE);
1936 true
1937}
1938
1939/// What one fixed-point coefficient is worth on the `8 * orthonormal` scale
1940/// the levels are formed on: both passes carry the network's gain, and the
1941/// row pass carried the headroom shift too.
1942fn forward_scale(side: usize) -> f64 {
1943 let g = forward_gain(side);
1944 INVERSE_GAIN_RECIPROCAL / (g * g * f64::from(1u32 << FORWARD_PRECISION_BITS))
1945}
1946
1947/// The old direct `O(n^2)` matmul against [`build_dct_basis`], kept only as
1948/// the differential oracle for [`forward_transform_2d`]'s fast replacement
1949/// (`fast_forward_matches_the_naive_matmul`).
1950#[cfg(test)]
1951fn forward_transform_2d_naive(residual: &[i32], side: usize) -> Vec<f64> {
1952 let basis = dct_basis(side);
1953 let mut rows = vec![0.0f64; side * side];
1954 for i in 0..side {
1955 let residual_row = &residual[i * side..][..side];
1956 for u in 0..side {
1957 let sum: f64 = residual_row
1958 .iter()
1959 .zip(&basis[u * side..][..side])
1960 .map(|(&r, &b)| f64::from(r) * b)
1961 .sum();
1962 rows[i * side + u] = sum;
1963 }
1964 }
1965 let mut rows_t = vec![0.0f64; side * side];
1966 for i in 0..side {
1967 for v in 0..side {
1968 rows_t[v * side + i] = rows[i * side + v];
1969 }
1970 }
1971 let mut out = vec![0.0f64; side * side];
1972 for u in 0..side {
1973 for v in 0..side {
1974 let sum: f64 = rows_t[v * side..][..side]
1975 .iter()
1976 .zip(&basis[u * side..][..side])
1977 .map(|(&r, &b)| r * b)
1978 .sum();
1979 out[u * side + v] = sum;
1980 }
1981 }
1982 let scale = INVERSE_GAIN_RECIPROCAL;
1983 for v in &mut out {
1984 *v *= scale;
1985 }
1986 out
1987}
1988
1989/// Quantize forward-transform coefficients into the levels the tile syntax
1990/// carries.
1991///
1992/// `deadzone` is the fraction of a quantizer step a coefficient has to reach
1993/// before it is coded at all, as a rounding offset: 0.5 rounds to nearest,
1994/// smaller values pull coefficients toward zero, which is what buys the rate
1995/// back on noisy content. A 64-point transform only carries its top-left
1996/// 32x32, so everything outside that is dropped here rather than silently by
1997/// the writer.
1998pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone: f64) -> Vec<i32> {
1999 assert_eq!(coeffs.len(), side * side, "one coefficient per position");
2000 let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx));
2001 let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx));
2002 let mut levels = vec![0i32; side * side];
2003 let coded = side.min(32);
2004 for row in 0..coded {
2005 for col in 0..coded {
2006 let i = row * side + col;
2007 let q = if i == 0 { dc } else { ac };
2008 let scaled = coeffs[i] / q;
2009 let magnitude = scaled.abs() + deadzone;
2010 let level = if magnitude < 1.0 {
2011 0
2012 } else {
2013 magnitude.floor().min(f64::from(i32::MAX)) as i32
2014 };
2015 levels[i] = if scaled < 0.0 { -level } else { level };
2016 }
2017 }
2018 levels
2019}
2020
2021/// Transform and quantize one block's residual, the encoder's half of the
2022/// round trip [`dequant_and_inverse`] completes.
2023pub fn forward_and_quantize(
2024 residual: &[i32],
2025 side: usize,
2026 bit_depth: u8,
2027 q_idx: i32,
2028 deadzone: f64,
2029) -> Vec<i32> {
2030 forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, None)
2031}
2032
2033/// [`forward_and_quantize`] plus the pre-rounding scaled coefficients, for the
2034/// same reason [`forward_and_quantize_typed_scaled`] exists. The levels are
2035/// bit-identical: it is the one loop below, with the value it rounds also
2036/// written out.
2037pub fn forward_and_quantize_scaled(
2038 residual: &[i32],
2039 side: usize,
2040 bit_depth: u8,
2041 q_idx: i32,
2042 deadzone: f64,
2043) -> (Vec<i32>, Vec<f32>) {
2044 let mut scaled = vec![0f32; side * side];
2045 let levels =
2046 forward_and_quantize_into(residual, side, bit_depth, q_idx, deadzone, Some(&mut scaled));
2047 (levels, scaled)
2048}
2049
2050fn forward_and_quantize_into(
2051 residual: &[i32],
2052 side: usize,
2053 bit_depth: u8,
2054 q_idx: i32,
2055 deadzone: f64,
2056 mut scaled_out: Option<&mut [f32]>,
2057) -> Vec<i32> {
2058 // 72% of this encoder's forward DCTs are of an all-zero residual
2059 // (measured over the BD gate's own ladder, lane-av1fwd): every row and
2060 // every column of the network is skipped for them anyway, so the levels
2061 // are zero without allocating the row pass's buffer at all.
2062 if residual.iter().all(|&r| r == 0) {
2063 return vec![0i32; side * side];
2064 }
2065 // Fused: the levels are formed straight off the fixed-point coefficients,
2066 // so neither the `Vec<f64>` of coefficients nor the pass that reads it
2067 // exists.
2068 let rows = forward_rows(residual, side);
2069 let scale = forward_scale(side);
2070 let dc = scale / f64::from(crate::quant::dc_q(bit_depth, q_idx));
2071 let ac = scale / f64::from(crate::quant::ac_q(bit_depth, q_idx));
2072 // A 64-point transform carries its top-left 32x32 alone, so the other
2073 // half's columns are not even transformed.
2074 let coded = side.min(32);
2075 let mut levels = vec![0i32; side * side];
2076 let mut t = [0i32; 64];
2077 for v in 0..coded {
2078 if !forward_column(&rows, side, v, &mut t) {
2079 continue;
2080 }
2081 for u in 0..coded {
2082 let scaled = f64::from(t[u]) * if u == 0 && v == 0 { dc } else { ac };
2083 if let Some(out) = scaled_out.as_deref_mut() {
2084 out[u * side + v] = scaled as f32;
2085 }
2086 let magnitude = scaled.abs() + deadzone;
2087 let level = if magnitude < 1.0 {
2088 0
2089 } else {
2090 magnitude.floor().min(f64::from(i32::MAX)) as i32
2091 };
2092 levels[u * side + v] = if scaled < 0.0 { -level } else { level };
2093 }
2094 }
2095 levels
2096}
2097
2098#[cfg(test)]
2099mod tests {
2100 use super::*;
2101
2102 /// The row and column passes skip an all-zero vector instead of running
2103 /// the butterfly network over it. That is only bit-exact because a zero
2104 /// vector transforms to a zero vector at every size, type and bit depth --
2105 /// which is what this pins, per 1D transform and end to end.
2106 #[test]
2107 fn a_zero_vector_transforms_to_zero() {
2108 for log2 in 2..=6u32 {
2109 for kind in [TxType1d::Dct, TxType1d::Adst, TxType1d::Identity] {
2110 if kind == TxType1d::Adst && log2 > 4 {
2111 continue;
2112 }
2113 if kind == TxType1d::Identity && log2 > 5 {
2114 continue;
2115 }
2116 for bit_depth in [8u8, 10, 12] {
2117 let r = (usize::from(bit_depth) + 6).max(16);
2118 let mut t = [0i32; 64];
2119 inverse_1d(&mut t, log2, r, kind);
2120 assert!(
2121 t.iter().all(|&v| v == 0),
2122 "1D {kind:?} log2={log2} depth={bit_depth} left a non-zero"
2123 );
2124 }
2125 }
2126 }
2127 for (w, h) in [(4, 4), (8, 8), (16, 16), (32, 32), (64, 64), (8, 16), (16, 8), (4, 16), (32, 8)] {
2128 for tx in [TxType::DctDct, TxType::AdstAdst, TxType::Idtx, TxType::AdstDct, TxType::DctAdst] {
2129 if w.max(h) > 16 && tx != TxType::DctDct && tx != TxType::Idtx {
2130 continue;
2131 }
2132 if w.max(h) > 32 && tx != TxType::DctDct {
2133 continue;
2134 }
2135 let out = inverse_transform_2d_typed_wh(&vec![0i32; w * h], w, h, 10, tx);
2136 assert!(out.iter().all(|&v| v == 0), "2D {w}x{h} {tx:?} left a non-zero");
2137 }
2138 }
2139 }
2140
2141 /// The typed forward transform is the decoder's exact inverse undone:
2142 /// quantized and taken back, an ADST-typed residual returns with the same
2143 /// error a `DCT_DCT` one does. This is what pins the *gain* of the ADST
2144 /// basis measured off the inverse network -- an approximate shape only
2145 /// costs rate, but a wrong gain would put every level in the wrong decade
2146 /// and the mode search would read as a loss.
2147 #[test]
2148 fn a_typed_forward_round_trips_like_the_dct_one() {
2149 for side in [4usize, 8, 16] {
2150 let residual: Vec<i32> = noise(side * side, 7 + side as u64)
2151 .iter()
2152 .map(|&v| v / 4)
2153 .collect();
2154 let rmse = |tx: TxType| {
2155 let levels = forward_and_quantize_typed(&residual, side, 8, 60, 0.5, tx);
2156 let back = dequant_and_inverse_typed(&levels, side, 8, 60, 0, 0, tx);
2157 let sum: f64 = residual
2158 .iter()
2159 .zip(&back)
2160 .map(|(&a, &b)| f64::from(a - b) * f64::from(a - b))
2161 .sum();
2162 (sum / (side * side) as f64).sqrt()
2163 };
2164 let dct = rmse(TxType::DctDct);
2165 for tx in [TxType::AdstDct, TxType::DctAdst, TxType::AdstAdst] {
2166 let e = rmse(tx);
2167 assert!(
2168 e < 2.0 * dct,
2169 "{side}x{side} {tx:?} round trip rmse {e:.2} against DCT_DCT's {dct:.2}"
2170 );
2171 }
2172 }
2173 }
2174
2175 /// The orthonormal DCT-II basis the forward transform is written against,
2176 /// computed independently of `dct_basis` so a test is not checking a
2177 /// function against itself.
2178 fn reference_basis(n: usize) -> Vec<f64> {
2179 let mut c = vec![0.0; n * n];
2180 for u in 0..n {
2181 let alpha = if u == 0 { (0.5f64).sqrt() } else { 1.0 };
2182 for x in 0..n {
2183 let angle =
2184 (2.0 * x as f64 + 1.0) * u as f64 * std::f64::consts::PI / (2.0 * n as f64);
2185 c[u * n + x] = alpha * (2.0 / n as f64).sqrt() * angle.cos();
2186 }
2187 }
2188 c
2189 }
2190
2191 /// A deterministic pseudo-random residual in `-100..=100`.
2192 fn noise(len: usize, seed: u64) -> Vec<i32> {
2193 let mut state = seed;
2194 (0..len)
2195 .map(|_| {
2196 state = state
2197 .wrapping_mul(6_364_136_223_846_793_005)
2198 .wrapping_add(1_442_695_040_888_963_407);
2199 ((state >> 33) % 201) as i32 - 100
2200 })
2201 .collect()
2202 }
2203
2204 #[test]
2205 #[ignore]
2206 fn scratch_probe_32x32_dequant() {
2207 let mut levels = vec![0i32; 32 * 32];
2208 levels[0] = -2;
2209 levels[1] = -2;
2210 levels[2] = -2;
2211 let dq = crate::quant::dequant(&levels, 32, 8, 60);
2212 eprintln!("dq[0..4]={:?}", &dq[0..4]);
2213 let residual = dequant_and_inverse(&levels, 32, 8, 60);
2214 eprintln!("row0: {:?}", &residual[0..32]);
2215 eprintln!("row1: {:?}", &residual[32..64]);
2216
2217 // superposition probe: does inverse_transform_2d at side=32 sum
2218 // three simultaneous low-frequency coefficients the same as it
2219 // reconstructs each alone?
2220 let side = 32usize;
2221 let mut single_sum = vec![0i32; side * side];
2222 for &(pos, val) in &[(0usize, -57i32), (1, -67), (2, -67)] {
2223 let mut c = vec![0i32; side * side];
2224 c[pos] = val;
2225 let got = inverse_transform_2d(&c, side, 8);
2226 for i in 0..side * side {
2227 single_sum[i] += got[i];
2228 }
2229 }
2230 let mut combined = vec![0i32; side * side];
2231 combined[0] = -57;
2232 combined[1] = -67;
2233 combined[2] = -67;
2234 let got_combined = inverse_transform_2d(&combined, side, 8);
2235 eprintln!("single_sum row0: {:?}", &single_sum[0..8]);
2236 eprintln!("combined row0: {:?}", &got_combined[0..8]);
2237 }
2238
2239 fn rmse(a: &[i32], b: &[i32]) -> f64 {
2240 let sum: f64 = a
2241 .iter()
2242 .zip(b)
2243 .map(|(&x, &y)| f64::from(x - y) * f64::from(x - y))
2244 .sum();
2245 (sum / a.len() as f64).sqrt()
2246 }
2247
2248 /// [`forward_transform_2d`]'s fast FFT-based factorization against
2249 /// [`forward_transform_2d_naive`]'s direct matmul: same summation
2250 /// reordered, so equal up to floating-point rounding, not bit-exact.
2251 #[test]
2252 fn the_fixed_point_forward_matches_the_exact_matmul() {
2253 for &side in &[4usize, 8, 16, 32, 64] {
2254 for seed in [1u64, 2, 3] {
2255 let residual = noise(side * side, seed * 1000 + side as u64);
2256 let fast = forward_transform_2d(&residual, side);
2257 let naive = forward_transform_2d_naive(&residual, side);
2258 let worst = fast
2259 .iter()
2260 .zip(&naive)
2261 .map(|(f, n)| (f - n).abs())
2262 .fold(0.0f64, f64::max);
2263 let energy: f64 = naive.iter().map(|n| n * n).sum::<f64>().sqrt();
2264 let err: f64 = fast
2265 .iter()
2266 .zip(&naive)
2267 .map(|(f, n)| (f - n) * (f - n))
2268 .sum::<f64>()
2269 .sqrt();
2270 // The network rounds at every butterfly, so it is not the
2271 // matmul to the last bit -- it is the same transform to well
2272 // inside one quantizer step. One unit here is an eighth of an
2273 // orthonormal coefficient ([`INVERSE_GAIN_RECIPROCAL`]), and
2274 // the finest step any level is formed on is `dc_q(8, 0) = 4`.
2275 assert!(worst < 1.0, "{side}x{side} seed {seed}: worst {worst}");
2276 assert!(
2277 err < 1e-3 * energy,
2278 "{side}x{side} seed {seed}: rmse {err} of energy {energy}"
2279 );
2280 }
2281 }
2282 }
2283
2284 /// The gain [`forward_transform_2d`] divides out is the network's own, and
2285 /// it is ONE number per size -- if the network's gain varied by output the
2286 /// single scale would tilt the spectrum. Pinned per size against the
2287 /// orthonormal basis it is measured from.
2288 #[test]
2289 fn the_forward_network_has_one_uniform_gain() {
2290 for &n in &[4usize, 8, 16, 32, 64] {
2291 let g = forward_gain(n);
2292 assert!(
2293 (g - (n as f64 / 2.0).sqrt()).abs() < 1e-3,
2294 "{n}-point gain {g}"
2295 );
2296 let basis = dct_basis(n);
2297 for i in 0..n {
2298 let mut t = [0i32; 64];
2299 t[i] = 1 << 14;
2300 forward_dct_fixed(&mut t, n.trailing_zeros(), FORWARD_RANGE);
2301 for u in 0..n {
2302 let want = g * f64::from(1 << 14) * basis[u * n + i];
2303 // A thousandth of the impulse's own amplitude: the
2304 // network's rounding accumulates over its stages, and
2305 // what is pinned here is that the SHAPE is the basis.
2306 assert!(
2307 (f64::from(t[u]) - want).abs() < 1e-3 * g * f64::from(1 << 14),
2308 "{n}-point impulse {i} output {u}: {} vs {want}",
2309 t[u]
2310 );
2311 }
2312 }
2313 }
2314 }
2315
2316 #[test]
2317 fn the_inverse_network_is_an_orthonormal_dct_over_eight() {
2318 for &side in &[4usize, 8, 16, 32, 64] {
2319 let basis = reference_basis(side);
2320 for &(u, v) in &[(0usize, 0usize), (0, 1), (1, 0), (2, 3), (5, 7)] {
2321 if u >= side || v >= side {
2322 continue;
2323 }
2324 let mut coeffs = vec![0i32; side * side];
2325 coeffs[u * side + v] = 4096;
2326 let got = inverse_transform_2d(&coeffs, side, 8);
2327 let want: Vec<f64> = (0..side * side)
2328 .map(|i| 4096.0 * basis[u * side + i / side] * basis[v * side + i % side])
2329 .collect();
2330 // Least-squares fit of one scale over the whole block.
2331 let num: f64 = want.iter().zip(&got).map(|(w, &g)| w * f64::from(g)).sum();
2332 let den: f64 = want.iter().map(|w| w * w).sum();
2333 let k = num / den;
2334 let expected = crate::quant::dq_denom(side) as f64 / 8.0;
2335 assert!(
2336 (k - expected).abs() < 0.01 * expected,
2337 "{side}x{side} ({u},{v}): gain {k}, expected {expected}"
2338 );
2339 // And the block really is that basis function, not merely a
2340 // block of the same energy: no sample off by more than one.
2341 for (i, (w, &g)) in want.iter().zip(&got).enumerate() {
2342 let scaled = k * w;
2343 assert!(
2344 (scaled - f64::from(g)).abs() <= 1.0,
2345 "{side}x{side} ({u},{v}) sample {i}: {g} vs {scaled}"
2346 );
2347 }
2348 }
2349 }
2350 }
2351
2352 /// A fine quantizer costs almost nothing: forward, quantize, dequantize
2353 /// and invert returns the residual to within a sample or two at every
2354 /// transform size the spec's DCT covers.
2355 ///
2356 /// 64x64 is excluded here because it cannot carry a white-noise residual
2357 /// at all — see
2358 /// [`a_64x64_transform_keeps_what_fits_in_its_coded_quarter`].
2359 #[test]
2360 fn a_fine_quantizer_roundtrips_a_residual_almost_exactly() {
2361 for &side in &[4usize, 8, 16, 32] {
2362 let residual = noise(side * side, 12_345 + side as u64);
2363 let levels = forward_and_quantize(&residual, side, 8, 10, 0.5);
2364 let back = dequant_and_inverse(&levels, side, 8, 10);
2365 let error = rmse(&back, &residual);
2366 assert!(error < 1.0, "{side}x{side}: rmse {error}");
2367 }
2368 }
2369
2370 /// Error grows with the quantizer and with nothing else. A calibration
2371 /// that is off by a constant factor shows up here as a floor that a finer
2372 /// quantizer cannot get under — which is exactly what a wrong gain
2373 /// constant produced while this was being written.
2374 #[test]
2375 fn the_roundtrip_error_is_the_quantizer_and_only_the_quantizer() {
2376 for &side in &[4usize, 8, 16, 32] {
2377 let residual = noise(side * side, 999 + side as u64);
2378 let mut previous = 0.0;
2379 for &q_idx in &[10i32, 60, 100, 180] {
2380 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
2381 let back = dequant_and_inverse(&levels, side, 8, q_idx);
2382 let error = rmse(&back, &residual);
2383 assert!(
2384 error > previous,
2385 "{side}x{side} q {q_idx}: {error} <= {previous}"
2386 );
2387 // A quantizer step is q/8 in residual units, and rounding to
2388 // nearest costs no more than half a step per coefficient.
2389 let step = f64::from(crate::quant::ac_q(8, q_idx)) / 8.0;
2390 assert!(
2391 error < step,
2392 "{side}x{side} q {q_idx}: rmse {error}, step {step}"
2393 );
2394 previous = error;
2395 }
2396 }
2397 }
2398
2399 /// A 64x64 transform codes only its top-left 32x32 coefficients, so it
2400 /// keeps everything below half the Nyquist rate in each direction and
2401 /// drops the rest. A band-limited residual survives it; white noise loses
2402 /// the three quarters of its energy that live outside the coded quarter,
2403 /// and that loss is the transform's, not the quantizer's — it does not
2404 /// move when the quantizer does.
2405 #[test]
2406 fn a_64x64_transform_keeps_what_fits_in_its_coded_quarter() {
2407 let side = 64;
2408 // Band-limited: built from basis functions inside the coded quarter.
2409 let basis = reference_basis(side);
2410 let mut smooth = vec![0.0f64; side * side];
2411 for &(u, v, amplitude) in &[(0usize, 0usize, 900.0f64), (1, 2, 400.0), (9, 30, 250.0)] {
2412 for i in 0..side * side {
2413 smooth[i] += amplitude * basis[u * side + i / side] * basis[v * side + i % side];
2414 }
2415 }
2416 let smooth: Vec<i32> = smooth.iter().map(|&s| s.round() as i32).collect();
2417 let levels = forward_and_quantize(&smooth, side, 8, 10, 0.5);
2418 let back = dequant_and_inverse(&levels, side, 8, 10);
2419 let kept = rmse(&back, &smooth);
2420 assert!(kept < 1.5, "band-limited 64x64: rmse {kept}");
2421
2422 let residual = noise(side * side, 4_242);
2423 let mut errors = Vec::new();
2424 for &q_idx in &[10i32, 180] {
2425 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
2426 let back = dequant_and_inverse(&levels, side, 8, q_idx);
2427 errors.push(rmse(&back, &residual));
2428 }
2429 // Three quarters of a white-noise block's energy is outside the coded
2430 // quarter, so the error is sqrt(3/4) of the residual's own magnitude
2431 // whatever the quantizer does.
2432 let magnitude = rmse(&residual, &vec![0; side * side]);
2433 for error in &errors {
2434 let ratio = error / magnitude;
2435 assert!(
2436 (ratio - 0.75f64.sqrt()).abs() < 0.05,
2437 "64x64 white noise: ratio {ratio}"
2438 );
2439 }
2440 assert!(
2441 (errors[1] - errors[0]).abs() < 0.05 * errors[0],
2442 "64x64 white noise moved with the quantizer: {errors:?}"
2443 );
2444 }
2445
2446 /// The deadzone pulls coefficients toward zero: a wider one codes fewer
2447 /// of them and costs more error, and rounding to nearest is the tightest
2448 /// of them.
2449 #[test]
2450 fn a_wider_deadzone_codes_fewer_coefficients() {
2451 let side = 16;
2452 let residual = noise(side * side, 77);
2453 let mut previous_nonzero = usize::MAX;
2454 let mut previous_error = 0.0;
2455 for &deadzone in &[0.5f64, 0.35, 0.2] {
2456 let levels = forward_and_quantize(&residual, side, 8, 100, deadzone);
2457 let back = dequant_and_inverse(&levels, side, 8, 100);
2458 let nonzero = levels.iter().filter(|&&l| l != 0).count();
2459 let error = rmse(&back, &residual);
2460 assert!(
2461 nonzero < previous_nonzero,
2462 "deadzone {deadzone}: {nonzero} coefficients"
2463 );
2464 assert!(error > previous_error, "deadzone {deadzone}: rmse {error}");
2465 previous_nonzero = nonzero;
2466 previous_error = error;
2467 }
2468 }
2469
2470 /// Negating a residual negates its levels: the forward transform carries
2471 /// no offset of its own.
2472 #[test]
2473 fn negating_the_residual_negates_every_level() {
2474 for &side in &[4usize, 32] {
2475 let residual = noise(side * side, 5_150 + side as u64);
2476 let negated: Vec<i32> = residual.iter().map(|&r| -r).collect();
2477 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
2478 let other = forward_and_quantize(&negated, side, 8, 100, 0.5);
2479 for (i, (a, b)) in levels.iter().zip(&other).enumerate() {
2480 assert_eq!(*a, -*b, "{side}x{side} coefficient {i}");
2481 }
2482 }
2483 }
2484
2485 /// A flat residual is a DC level and nothing else, at the value the
2486 /// dequantizer's own arithmetic asks for.
2487 #[test]
2488 fn a_flat_residual_is_a_dc_level_alone() {
2489 for &side in &[4usize, 8, 16, 32, 64] {
2490 let residual = vec![40i32; side * side];
2491 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
2492 for (i, &level) in levels.iter().enumerate() {
2493 if i == 0 {
2494 // level = 8 * (40 * side) / dc_q, the orthonormal DC of a
2495 // flat block being its value times the side.
2496 let want = (8.0 * 40.0 * side as f64 / f64::from(crate::quant::dc_q(8, 100)))
2497 .round() as i32;
2498 assert_eq!(level, want, "{side}x{side} DC");
2499 } else {
2500 assert_eq!(level, 0, "{side}x{side} coefficient {i}");
2501 }
2502 }
2503 }
2504 }
2505
2506 // --- ADST/identity family: reference vectors from libaom's own
2507 // `av1_iadst4`/`8`/`16` and `av1_iidentity*_c`, computed by a small C
2508 // probe (`gcc` against `/tmp/libaom-src/build/decoder-debug/libaom.a`,
2509 // calling those exported symbols directly with the inputs pinned below --
2510 // no hand-derived arithmetic) so these are decisive, not memory-derived.
2511
2512 #[test]
2513 fn iadst4_matches_libaoms_own_output() {
2514 let mut t = [100, -50, 25, 7];
2515 inverse_adst4(&mut t);
2516 assert_eq!(t, [19, 5, 67, 147]);
2517 }
2518
2519 #[test]
2520 fn iadst4_an_all_zero_input_short_circuits_to_zero() {
2521 let mut t = [0, 0, 0, 0];
2522 inverse_adst4(&mut t);
2523 assert_eq!(t, [0, 0, 0, 0]);
2524 }
2525
2526 #[test]
2527 fn iadst8_matches_libaoms_own_output() {
2528 let mut t = [100, -50, 25, 7, -3, 60, -12, 8];
2529 inverse_adst8(&mut t, 16);
2530 assert_eq!(t, [59, 15, -25, 52, 25, 27, 207, 130]);
2531 }
2532
2533 #[test]
2534 fn iadst16_matches_libaoms_own_output() {
2535 let mut t = [
2536 100, -50, 25, 7, -3, 60, -12, 8, 15, -40, 33, -5, 22, 1, -70, 44,
2537 ];
2538 inverse_adst16(&mut t, 16);
2539 assert_eq!(
2540 t,
2541 [
2542 32, 73, 28, 6, -45, -28, 111, -52, 135, -54, 85, -67, 305, 190, 102, 145
2543 ]
2544 );
2545 }
2546
2547 #[test]
2548 fn iidentity_matches_libaoms_own_output_at_every_size() {
2549 let mut t4 = [100, -50, 25, 7];
2550 inverse_identity(&mut t4, 4);
2551 assert_eq!(t4, [141, -71, 35, 10]);
2552
2553 let mut t8 = [100, -50, 25, 7, -3, 60, -12, 8];
2554 inverse_identity(&mut t8, 8);
2555 assert_eq!(t8, [200, -100, 50, 14, -6, 120, -24, 16]);
2556
2557 let mut t16 = [
2558 100, -50, 25, 7, -3, 60, -12, 8, 15, -40, 33, -5, 22, 1, -70, 44,
2559 ];
2560 inverse_identity(&mut t16, 16);
2561 assert_eq!(
2562 t16,
2563 [
2564 283, -141, 71, 20, -8, 170, -34, 23, 42, -113, 93, -14, 62, 3, -198, 124
2565 ]
2566 );
2567
2568 let mut t32 = [0i32; 32];
2569 for (i, v) in t32.iter_mut().enumerate() {
2570 *v = i as i32 * 7 - 100;
2571 }
2572 inverse_identity(&mut t32, 32);
2573 assert_eq!(
2574 t32,
2575 [
2576 -400, -372, -344, -316, -288, -260, -232, -204, -176, -148, -120, -92, -64, -36,
2577 -8, 20, 48, 76, 104, 132, 160, 188, 216, 244, 272, 300, 328, 356, 384, 412, 440,
2578 468
2579 ]
2580 );
2581 }
2582
2583 /// The axis-convention gate: an impulse in row 0 (`ADST_DCT`'s row
2584 /// transform is DCT, so an ADST call here stands in for `DCT_ADST`'s row
2585 /// pass) fed through `inverse_adst8` at "row position 0" must differ from
2586 /// the same impulse at "column position 1" -- i.e. ADST is not a
2587 /// symmetric function of its input's position, which is what lets
2588 /// `ADST_DCT` and `DCT_ADST` decode to different residuals for the same
2589 /// coefficient grid. Values pinned from the same libaom probe.
2590 #[test]
2591 fn iadst8_is_not_symmetric_in_its_input_position() {
2592 let mut row = [40, 0, 0, 0, 0, 0, 0, 0];
2593 let mut col = [0, 40, 0, 0, 0, 0, 0, 0];
2594 inverse_adst8(&mut row, 16);
2595 inverse_adst8(&mut col, 16);
2596 assert_eq!(row, [4, 12, 18, 25, 31, 35, 38, 40]);
2597 assert_eq!(col, [12, 31, 40, 35, 18, -4, -26, -38]);
2598 assert_ne!(
2599 row, col,
2600 "an asymmetric input must not decode symmetrically"
2601 );
2602 }
2603
2604 /// The decisive end-to-end asymmetry gate `inverse_transform_2d_typed`
2605 /// itself: `ADST_DCT` and `DCT_ADST` must decode the same asymmetric
2606 /// coefficient grid to *different* residuals, which is only true if the
2607 /// row/column axis assignment (`TxType::axes`) is not accidentally
2608 /// symmetric (e.g. both pointing at the same 1D transform, or swapped
2609 /// with each other in a way that cancels out on this input).
2610 #[test]
2611 fn adst_dct_and_dct_adst_disagree_on_an_asymmetric_grid() {
2612 let side = 8;
2613 let mut dequant = vec![0i32; side * side];
2614 // An asymmetric coefficient: nonzero only at (row=0, col=1).
2615 dequant[1] = 64;
2616 let adst_dct = inverse_transform_2d_typed(&dequant, side, 8, TxType::AdstDct);
2617 let dct_adst = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctAdst);
2618 assert_ne!(
2619 adst_dct, dct_adst,
2620 "ADST_DCT and DCT_ADST must not be interchangeable on an asymmetric grid"
2621 );
2622 // Also distinct from plain DCT_DCT and ADST_ADST at the same input.
2623 let dct_dct = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctDct);
2624 let adst_adst = inverse_transform_2d_typed(&dequant, side, 8, TxType::AdstAdst);
2625 assert_ne!(adst_dct, dct_dct);
2626 assert_ne!(dct_adst, dct_dct);
2627 assert_ne!(adst_adst, dct_dct);
2628 }
2629
2630 /// The lane-recttx charter's asymmetric coefficient block (`coeff` in
2631 /// `lanes/recttx_dump.c`, which this pin was transcribed alongside): a
2632 /// DC of 640 plus a distinct row-weighted/col-weighted 4x4 corner, zero
2633 /// elsewhere, so a transposed axis produces a genuinely different
2634 /// checksum rather than a coincidentally equal one.
2635 fn recttx_coeff(w: usize, h: usize) -> Vec<i32> {
2636 let mut d = vec![0i32; w * h];
2637 for i in 0..h {
2638 for j in 0..w {
2639 d[i * w + j] = if i == 0 && j == 0 {
2640 640
2641 } else if i < 4 && j < 4 {
2642 (i as i32 + 1) * 24 - (j as i32 + 1) * 17
2643 } else {
2644 0
2645 };
2646 }
2647 }
2648 d
2649 }
2650
2651 fn weighted_checksum(residual: &[i32]) -> i64 {
2652 residual
2653 .iter()
2654 .enumerate()
2655 .map(|(idx, &v)| i64::from(v) * (idx as i64 + 1))
2656 .sum()
2657 }
2658
2659 /// Every one of the 14 rectangular sizes, DCT_DCT, `bit_depth = 8`,
2660 /// pinned against `lanes/recttx_dump.c` / `.expected.txt` -- a real
2661 /// libaom 1D-kernel-linked C harness, not a from-scratch reimplement.
2662 /// The transposed HxW twin runs in the SAME test (class
2663 /// `scan-weights-cross-axis`): a swapped-axis bug in
2664 /// `inverse_transform_2d_typed_wh` would either fail its own pin or
2665 /// accidentally match its twin's pin, and the two expected values here
2666 /// are deliberately different, so neither escape is possible.
2667 #[test]
2668 fn rect_sizes_pinned_against_libaom() {
2669 let cases: &[(usize, usize, i64)] = &[
2670 (4, 8, 7290),
2671 (8, 4, 7223),
2672 (8, 16, 56211),
2673 (16, 8, 56161),
2674 (16, 32, 893635),
2675 (32, 16, 893210),
2676 (32, 64, 14260693),
2677 (64, 32, 14265125),
2678 (4, 16, 20091),
2679 (16, 4, 20156),
2680 (8, 32, 159207),
2681 (32, 8, 159430),
2682 (16, 64, 2537255),
2683 (64, 16, 2548119),
2684 ];
2685 for &(w, h, expected) in cases {
2686 let dequant = recttx_coeff(w, h);
2687 let residual = inverse_transform_2d_typed_wh(&dequant, w, h, 8, TxType::DctDct);
2688 assert_eq!(
2689 weighted_checksum(&residual),
2690 expected,
2691 "{w}x{h} checksum mismatch"
2692 );
2693 }
2694 }
2695
2696 /// The square path must not move: `row_shift_wh(side, side)` reduces to
2697 /// the pre-lane `row_shift(log2)` table, and the `side`-taking wrapper
2698 /// must still equal the `(w, h)` core called with `w == h == side`.
2699 #[test]
2700 fn square_wrapper_matches_wh_core() {
2701 for side in [4, 8, 16, 32, 64] {
2702 let dequant = recttx_coeff(side, side);
2703 let via_wrapper = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctDct);
2704 let via_wh = inverse_transform_2d_typed_wh(&dequant, side, side, 8, TxType::DctDct);
2705 assert_eq!(via_wrapper, via_wh, "side {side}");
2706 }
2707 }
2708
2709 /// The eight-wide column kernel is the scalar network, lane for lane: a
2710 /// pseudo-random sweep over the full coefficient range at every size and
2711 /// both clamp widths (`bit_depth` 8 and 10) has to agree bit for bit, or
2712 /// The AVX2 column pass against the scalar network over the FULL `i32`
2713 /// range, not only the dequantizer's own bound: the explicit intrinsics
2714 /// claim exact 64-bit products, so the sweep includes `i32::MIN`/`MAX`,
2715 /// both clamp boundaries at every `r` the decoder uses, and uniform
2716 /// full-range noise. A single differing lane at any size would be a
2717 /// silent pixel drift on whatever stream first reaches it.
2718 #[cfg(target_arch = "x86_64")]
2719 /// [`forward_transform_2d_typed`]'s contiguous-basis passes are the
2720 /// strided `.map().sum()` they replaced, bit for bit.
2721 ///
2722 /// The reordering is safe only because each output's terms stay in the
2723 /// same order -- only the loop that iterates the *outputs* moved -- so
2724 /// this compares raw bit patterns, not an epsilon: any reassociation
2725 /// would show up here as a last-place difference at some size.
2726 #[test]
2727 fn the_typed_forward_transform_is_bit_identical_to_the_strided_form() {
2728 fn strided(residual: &[i32], side: usize, tx_type: TxType) -> Vec<f64> {
2729 let (row_kind, col_kind) = tx_type.axes();
2730 let (hb, vb) = (axis_basis(side, row_kind), axis_basis(side, col_kind));
2731 let mut rows = vec![0.0f64; side * side];
2732 for i in 0..side {
2733 let source = &residual[i * side..][..side];
2734 if source.iter().all(|&r| r == 0) {
2735 continue;
2736 }
2737 for v in 0..side {
2738 rows[i * side + v] = source
2739 .iter()
2740 .zip(&hb[v * side..][..side])
2741 .map(|(&r, &b)| f64::from(r) * b)
2742 .sum();
2743 }
2744 }
2745 let mut out = vec![0.0f64; side * side];
2746 for u in 0..side {
2747 let column = &vb[u * side..][..side];
2748 for v in 0..side {
2749 let sum: f64 = (0..side).map(|i| rows[i * side + v] * column[i]).sum();
2750 out[u * side + v] = INVERSE_GAIN_RECIPROCAL * sum;
2751 }
2752 }
2753 out
2754 }
2755 let mut seed = 0x9E37_79B9_7F4A_7C15u64;
2756 let mut next = move || {
2757 seed ^= seed << 13;
2758 seed ^= seed >> 7;
2759 seed ^= seed << 17;
2760 seed
2761 };
2762 let types = [
2763 TxType::Idtx,
2764 TxType::AdstAdst,
2765 TxType::AdstDct,
2766 TxType::DctAdst,
2767 TxType::VDct,
2768 TxType::HDct,
2769 ];
2770 for side in [4usize, 8, 16, 32] {
2771 for tx_type in types {
2772 // ADST is undefined above 16 (the spec's 32+ sets are
2773 // DCT/identity only), so those pairs never reach this path.
2774 let adst = matches!(tx_type.axes(), (TxType1d::Adst, _) | (_, TxType1d::Adst));
2775 if side > 16 && adst {
2776 continue;
2777 }
2778 for round in 0..8 {
2779 // Round 0 is an all-zero residual and round 1 has whole
2780 // zero rows, so both skips are exercised at every size.
2781 let residual: Vec<i32> = (0..side * side)
2782 .map(|i| match round {
2783 0 => 0,
2784 1 if (i / side) % 2 == 0 => 0,
2785 _ => (next() % 511) as i32 - 255,
2786 })
2787 .collect();
2788 let ours = forward_transform_2d_typed(&residual, side, tx_type);
2789 let theirs = strided(&residual, side, tx_type);
2790 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2791 assert_eq!(
2792 a.to_bits(),
2793 b.to_bits(),
2794 "{tx_type:?} {side}x{side} round {round} coefficient {i}: \
2795 {a} vs {b}"
2796 );
2797 }
2798 }
2799 }
2800 }
2801 }
2802
2803 #[test]
2804 fn the_avx2_dct_matches_the_scalar_one_over_the_full_range() {
2805 if !std::arch::is_x86_feature_detected!("avx2") {
2806 return;
2807 }
2808 let mut state = 0x9E37_79B9_7F4A_7C15u64;
2809 let mut next = move || {
2810 state ^= state << 13;
2811 state ^= state >> 7;
2812 state ^= state << 17;
2813 state
2814 };
2815 for n in 2..=6u32 {
2816 for &r in &[16usize, 18, 20] {
2817 let (hi, lo) = (((1i64 << (r - 1)) - 1) as i32, (-(1i64 << (r - 1))) as i32);
2818 let edges = [0, 1, -1, hi, lo, hi - 1, lo + 1, i32::MAX, i32::MIN];
2819 for round in 0..96 {
2820 let mut wide = [[0i32; 8]; 64];
2821 let mut cols = [[0i32; 64]; 8];
2822 for i in 0..(1usize << n) {
2823 for l in 0..8 {
2824 let raw = next();
2825 let v = match round % 3 {
2826 // every extreme, and every pair of them
2827 0 => edges[(raw >> 32) as usize % edges.len()],
2828 // uniform over the whole 32-bit range
2829 1 => raw as i32,
2830 // the range a conformant stream stays inside
2831 _ => raw as i32 % (hi / 2 + 1),
2832 };
2833 wide[i][l] = v;
2834 cols[l][i] = v;
2835 }
2836 }
2837 let mut avx = [simd::splat([0i32; 8]); 64];
2838 for i in 0..(1usize << n) {
2839 avx[i] = simd::splat(wide[i]);
2840 }
2841 // SAFETY: guarded by the feature detection above.
2842 #[allow(unsafe_code)]
2843 unsafe {
2844 simd::dct_x8_avx2(&mut avx, n, r);
2845 }
2846 for (l, col) in cols.iter_mut().enumerate() {
2847 inverse_dct_fixed(col, n, r);
2848 for i in 0..(1usize << n) {
2849 assert_eq!(
2850 simd::lanes(avx[i])[l],
2851 col[i],
2852 "avx2 lane {l} of entry {i} at n={n} r={r} round={round}"
2853 );
2854 }
2855 }
2856 }
2857 }
2858 }
2859 }
2860
2861 /// the column pass would drift from the decoder on some block this
2862 /// crate's gate streams happen not to contain.
2863 #[test]
2864 fn the_eight_wide_dct_matches_the_scalar_one() {
2865 let mut state = 0x2545_F491_4F6C_DD1Du64;
2866 let mut next = move || {
2867 state ^= state << 13;
2868 state ^= state >> 7;
2869 state ^= state << 17;
2870 // The transform's input is a dequantized coefficient, bounded by
2871 // `dequant_wh_into`'s own +-(1 << (7 + bit_depth)).
2872 (state >> 32) as i32 % 262_144 - 131_072
2873 };
2874 for n in 2..=6u32 {
2875 for &r in &[16usize, 18] {
2876 for _ in 0..64 {
2877 let mut wide = [[0i32; 8]; 64];
2878 let mut cols = [[0i32; 64]; 8];
2879 for i in 0..(1usize << n) {
2880 for l in 0..8 {
2881 let v = next();
2882 wide[i][l] = v;
2883 cols[l][i] = v;
2884 }
2885 }
2886 inverse_dct_x8(&mut wide, n, r);
2887 for (l, col) in cols.iter_mut().enumerate() {
2888 inverse_dct_fixed(col, n, r);
2889 for i in 0..(1usize << n) {
2890 assert_eq!(wide[i][l], col[i], "n={n} r={r} lane={l} i={i}");
2891 }
2892 }
2893 }
2894 }
2895 }
2896 }
2897
2898}
2899
2900/// The lossless inverse transform: libaom `av1_iwht4x4_16_add_c`
2901/// (`aom_dsp/inv_txfm.c:22`), the 4x4 Walsh-Hadamard a frame with
2902/// `Lossless == 1` uses for every plane instead of the DCT/ADST network
2903/// (`inv_txfm_add`, `av1/common/idct.c:69`: `if (txfm_param->lossless) {
2904/// assert(tx_type == DCT_DCT); av1_iwht4x4_add(...); return; }`).
2905///
2906/// `dq` is the DEQUANTIZED grid; each input is shifted down by
2907/// `UNIT_QUANT_SHIFT` (2, `aom_dsp/inv_txfm.h`) before the row pass, which at
2908/// `qindex == 0` (`dc_q(0) == ac_q(0) == 4` at every bit depth) undoes the
2909/// dequantization exactly -- that is what makes the round trip lossless.
2910pub fn inverse_wht4x4(dq: &[i32]) -> Vec<i32> {
2911 debug_assert_eq!(dq.len(), 16);
2912 // libaom runs pass 1 down the COLUMNS (`ip[4 * k]`, `ip++`) and pass 2
2913 // along the intermediate's ROWS writing dest COLUMNS (`dest[stride * k]`,
2914 // `dest++`); transposing both passes -- rows first, then columns, output
2915 // in place -- is the same map and is what a raster `dq`/residual pair
2916 // wants here. MEASURED: the other orientation reconstructs sample 0 and
2917 // the DC-only units correctly and drifts by +-1 everywhere else.
2918 let mut out = [0i32; 16];
2919 for i in 0..4 {
2920 let (mut a1, mut c1, mut d1, mut b1) =
2921 (dq[i * 4] >> 2, dq[i * 4 + 1] >> 2, dq[i * 4 + 2] >> 2, dq[i * 4 + 3] >> 2);
2922 a1 += c1;
2923 d1 -= b1;
2924 let e1 = (a1 - d1) >> 1;
2925 b1 = e1 - b1;
2926 c1 = e1 - c1;
2927 a1 -= b1;
2928 d1 += c1;
2929 out[i * 4] = a1;
2930 out[i * 4 + 1] = b1;
2931 out[i * 4 + 2] = c1;
2932 out[i * 4 + 3] = d1;
2933 }
2934 let mut res = vec![0i32; 16];
2935 for i in 0..4 {
2936 let (mut a1, mut c1, mut d1, mut b1) =
2937 (out[i], out[4 + i], out[8 + i], out[12 + i]);
2938 a1 += c1;
2939 d1 -= b1;
2940 let e1 = (a1 - d1) >> 1;
2941 b1 = e1 - b1;
2942 c1 = e1 - c1;
2943 a1 -= b1;
2944 d1 += c1;
2945 res[i] = a1;
2946 res[4 + i] = b1;
2947 res[8 + i] = c1;
2948 res[12 + i] = d1;
2949 }
2950 res
2951}
2952
2953/// [`inverse_wht4x4`] with the spec 7.12.3 dequantization in front of it, the
2954/// lossless twin of [`dequant_and_inverse_typed_wh`] (same empty-grid
2955/// marker contract).
2956pub fn dequant_and_inverse_wht4x4(
2957 levels: &[i32],
2958 bit_depth: u8,
2959 q_idx: i32,
2960 dc_delta: i32,
2961 ac_delta: i32,
2962) -> Vec<i32> {
2963 if crate::decode::is_zero_grid(levels) {
2964 return Vec::new();
2965 }
2966 DQ_SCRATCH.with(|cell| {
2967 let mut dq = cell.borrow_mut();
2968 crate::quant::dequant_wh_into(levels, &mut dq, 4, 4, bit_depth, q_idx, dc_delta, ac_delta);
2969 inverse_wht4x4(&dq[..16])
2970 })
2971}
2972
2973#[cfg(test)]
2974mod lossless_tx_tests {
2975 /// The WHT is its own inverse up to the `UNIT_QUANT_SHIFT` scaling: a
2976 /// forward pass (libaom `av1_fwht4x4_c`, which scales UP by 4 through
2977 /// `output[i] * UNIT_QUANT_SHIFT`) followed by [`super::inverse_wht4x4`]
2978 /// on the dequantized levels (`q == 4` at qindex 0) returns the residual
2979 /// EXACTLY -- that identity is the whole lossless claim.
2980 #[test]
2981 fn the_walsh_hadamard_round_trip_is_exact() {
2982 // The exact integer inverse of [`super::inverse_wht4x4`]'s two
2983 // butterflies, run in the opposite order (columns then rows) and
2984 // scaled back up by `UNIT_QUANT_SHIFT` -- the encoder side of the
2985 // lossless pair (libaom `av1_fwht4x4_c`).
2986 fn undo(a2: i32, b2: i32, c2: i32, d2: i32) -> (i32, i32, i32, i32) {
2987 let a1 = a2 + b2;
2988 let d1 = d2 - c2;
2989 let e1 = (a1 - d1) >> 1;
2990 let b = e1 - b2;
2991 let c = e1 - c2;
2992 (a1 - c, b, c, d1 + b)
2993 }
2994 fn fwht(residual: &[i32]) -> Vec<i32> {
2995 let mut t = [0i32; 16];
2996 for i in 0..4 {
2997 let (a, b, c, d) =
2998 undo(residual[i], residual[4 + i], residual[8 + i], residual[12 + i]);
2999 t[i] = a;
3000 t[4 + i] = c;
3001 t[8 + i] = d;
3002 t[12 + i] = b;
3003 }
3004 let mut dq = vec![0i32; 16];
3005 for i in 0..4 {
3006 let (a, b, c, d) = undo(t[i * 4], t[i * 4 + 1], t[i * 4 + 2], t[i * 4 + 3]);
3007 dq[i * 4] = a * 4;
3008 dq[i * 4 + 1] = c * 4;
3009 dq[i * 4 + 2] = d * 4;
3010 dq[i * 4 + 3] = b * 4;
3011 }
3012 dq
3013 }
3014 let mut state = 0x1234_5678u32;
3015 for _ in 0..200 {
3016 let residual: Vec<i32> = (0..16)
3017 .map(|_| {
3018 state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
3019 ((state >> 20) as i32 % 511) - 255
3020 })
3021 .collect();
3022 let levels = fwht(&residual);
3023 // The forward pass already carries libaom's `UNIT_QUANT_SHIFT`
3024 // scale-up, so the coded level is `levels / 4` and qindex 0's
3025 // dequantization (times 4) hands `levels` straight back.
3026 assert_eq!(super::inverse_wht4x4(&levels), residual, "levels={levels:?}");
3027 }
3028 }
3029}