forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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