forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB35bdf35Tahinli2 months ago3757 commits

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