forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5a2f5efTahinli3 months ago1409 commits

transform.rs1714 lines, 65.0 KiBHistoryRawDownload
1//! The inverse transform (spec 7.13), so the encoder can reconstruct exactly
2//! what a decoder will show.
3//!
4//! Only the inverse DCT is here, which is all this encoder's subset codes: a
5//! square `DCT_DCT` transform per block. The butterfly network is the spec's
6//! own, stage for stage — every stage's rounding and intermediate clamp is
7//! part of the bitstream contract, so a mathematically equal but differently
8//! rounded DCT would drift away from the decoder by a sample here and there.
9
10/// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.
11static 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(angle)` (spec 7.13.2.1), folded from the quarter table.
22fn cos128(angle: i32) -> i32 {
23 let angle2 = (angle & 255) as usize;
24 match angle2 {
25 0..=64 => COS128_LOOKUP[angle2],
26 65..=128 => -COS128_LOOKUP[128 - angle2],
27 129..=192 => -COS128_LOOKUP[angle2 - 128],
28 _ => COS128_LOOKUP[256 - angle2],
29 }
30}
31
32/// `sin128(angle)` (spec 7.13.2.1).
33fn sin128(angle: i32) -> i32 {
34 cos128(angle - 64)
35}
36
37/// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.
38fn brev(num_bits: u32, x: usize) -> usize {
39 (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i)))
40}
41
42/// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.
43fn round2(x: i32, n: usize) -> i32 {
44 if n == 0 {
45 x
46 } else {
47 // The intermediate can exceed 32 bits before the shift brings it
48 // back, which is why it is done in 64.
49 ((i64::from(x) + (1i64 << (n - 1))) >> n) as i32
50 }
51}
52
53/// `Clip3` against a signed integer of `r` bits, which is what bounds every
54/// intermediate of the transform.
55fn clamp_range(x: i32, r: usize) -> i32 {
56 let hi = ((1i64 << (r - 1)) - 1) as i32;
57 let lo = (-(1i64 << (r - 1))) as i32;
58 x.clamp(lo, hi)
59}
60
61/// `B(a, b, angle, flip, r)` (spec 7.13.2.1): a butterfly rotation, and an
62/// exchange of the two entries when `flip` is set.
63fn butterfly(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool, _r: usize) {
64 let (ta, tb) = (i64::from(t[a]), i64::from(t[b]));
65 let (c, s) = (i64::from(cos128(angle)), i64::from(sin128(angle)));
66 let x = ta * c - tb * s;
67 let y = ta * s + tb * c;
68 t[a] = ((x + (1 << (COS_BITS - 1))) >> COS_BITS) as i32;
69 t[b] = ((y + (1 << (COS_BITS - 1))) >> COS_BITS) as i32;
70 if flip {
71 t.swap(a, b);
72 }
73}
74
75/// `H(a, b, flip, r)` (spec 7.13.2.1): a Hadamard rotation, with the indices
76/// exchanged when `flip` is set.
77fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) {
78 let (a, b) = if flip { (b, a) } else { (a, b) };
79 let (x, y) = (t[a], t[b]);
80 t[a] = clamp_range(x.wrapping_add(y), r);
81 t[b] = clamp_range(x.wrapping_sub(y), r);
82}
83
84/// The inverse DCT array permutation (spec 7.13.2.2): an in-place bit-reversal
85/// of the first `1 << n` entries.
86fn permute(t: &mut [i32], n: u32) {
87 let n0 = 1usize << n;
88 let copy: Vec<i32> = t[..n0].to_vec();
89 for (i, v) in t[..n0].iter_mut().enumerate() {
90 *v = copy[brev(n, i)];
91 }
92}
93
94/// The inverse DCT process (spec 7.13.2.3): an in-place inverse DCT of the
95/// first `1 << n` entries of `t`, clamping intermediates to `r` bits.
96///
97/// The stage list is the spec's, in the spec's order; the guards on `n` are
98/// what make one network serve every transform size from 4 to 64.
99pub fn inverse_dct(t: &mut [i32], n: u32, r: usize) {
100 assert!((2..=6).contains(&n), "the inverse DCT is defined for 4..64");
101 permute(t, n);
102
103 if n == 6 {
104 for i in 0..16 {
105 butterfly(t, 32 + i, 63 - i, 63 - 4 * brev(4, i) as i32, false, r);
106 }
107 }
108 if n >= 5 {
109 for i in 0..8 {
110 butterfly(
111 t,
112 16 + i,
113 31 - i,
114 6 + ((brev(3, 7 - i) as i32) << 3),
115 false,
116 r,
117 );
118 }
119 }
120 if n == 6 {
121 for i in 0..16 {
122 hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r);
123 }
124 }
125 if n >= 4 {
126 for i in 0..4 {
127 butterfly(
128 t,
129 8 + i,
130 15 - i,
131 12 + ((brev(2, 3 - i) as i32) << 4),
132 false,
133 r,
134 );
135 }
136 }
137 if n >= 5 {
138 for i in 0..8 {
139 hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
140 }
141 }
142 if n == 6 {
143 for i in 0..4 {
144 for j in 0..2 {
145 let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32;
146 butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r);
147 }
148 }
149 }
150 if n >= 3 {
151 for i in 0..2 {
152 butterfly(t, 4 + i, 7 - i, 56 - 32 * i as i32, false, r);
153 }
154 }
155 if n >= 4 {
156 for i in 0..4 {
157 hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r);
158 }
159 }
160 if n >= 5 {
161 for i in 0..2 {
162 for j in 0..2 {
163 let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5);
164 butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r);
165 }
166 }
167 }
168 if n == 6 {
169 for i in 0..8 {
170 for j in 0..2 {
171 hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r);
172 }
173 }
174 }
175 for i in 0..2 {
176 butterfly(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0, r);
177 }
178 if n >= 3 {
179 for i in 0..2 {
180 hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r);
181 }
182 }
183 if n >= 4 {
184 for i in 0..2 {
185 butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r);
186 }
187 }
188 if n >= 5 {
189 for i in 0..4 {
190 for j in 0..2 {
191 hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r);
192 }
193 }
194 }
195 if n == 6 {
196 for i in 0..2 {
197 for j in 0..4 {
198 let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64;
199 butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r);
200 }
201 }
202 }
203 for i in 0..2 {
204 hadamard(t, i, 3 - i, false, r);
205 }
206 if n >= 3 {
207 butterfly(t, 6, 5, 32, true, r);
208 }
209 if n >= 4 {
210 for i in 0..2 {
211 for j in 0..2 {
212 hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r);
213 }
214 }
215 }
216 if n >= 5 {
217 for i in 0..4 {
218 butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r);
219 }
220 }
221 if n == 6 {
222 for i in 0..4 {
223 for j in 0..4 {
224 hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r);
225 }
226 }
227 }
228 if n >= 3 {
229 for i in 0..4 {
230 hadamard(t, i, 7 - i, false, r);
231 }
232 }
233 if n >= 4 {
234 for i in 0..2 {
235 butterfly(t, 13 - i, 10 + i, 32, true, r);
236 }
237 }
238 if n >= 5 {
239 for i in 0..2 {
240 for j in 0..4 {
241 hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
242 }
243 }
244 }
245 if n == 6 {
246 for i in 0..8 {
247 butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r);
248 }
249 }
250 if n >= 4 {
251 for i in 0..8 {
252 hadamard(t, i, 15 - i, false, r);
253 }
254 }
255 if n >= 5 {
256 for i in 0..4 {
257 butterfly(t, 27 - i, 20 + i, 32, true, r);
258 }
259 }
260 if n == 6 {
261 for i in 0..8 {
262 hadamard(t, 32 + i, 47 - i, false, r);
263 hadamard(t, 48 + i, 63 - i, true, r);
264 }
265 }
266 if n >= 5 {
267 for i in 0..16 {
268 hadamard(t, i, 31 - i, false, r);
269 }
270 }
271 if n == 6 {
272 for i in 0..8 {
273 butterfly(t, 55 - i, 40 + i, 32, true, r);
274 }
275 }
276 if n == 6 {
277 for i in 0..32 {
278 hadamard(t, i, 63 - i, false, r);
279 }
280 }
281}
282
283/// `Transform_Row_Shift` (spec 7.13.3) / `av1_inv_txfm_shift_ls`
284/// (`av1_inv_txfm2d.c:132-158`): `shift[0]`, keyed on the full `(w, h)` TX
285/// size, not a single log2 -- the five square values (unchanged from the
286/// pre-lane `row_shift(log2)`) plus the fourteen rectangular ones the lane
287/// charter transcribed from the same table.
288fn row_shift_wh(w: usize, h: usize) -> usize {
289 match (w, h) {
290 (4, 4) => 0,
291 (8, 8) => 1,
292 (16, 16) | (32, 32) | (64, 64) => 2,
293 (4, 8) | (8, 4) => 0,
294 (8, 16) | (16, 8) => 1,
295 (16, 32) | (32, 16) => 1,
296 (32, 64) | (64, 32) => 1,
297 (4, 16) | (16, 4) => 1,
298 (8, 32) | (32, 8) => 2,
299 (16, 64) | (64, 16) => 2,
300 _ => unreachable!("unsupported transform size {w}x{h}"),
301 }
302}
303
304/// One 1D inverse transform family, ported from libaom's `av1_inv_txfm1d.c`
305/// (`av1_iadst4`/`8`/`16`, `av1_iidentity*`) rather than derived from the
306/// spec's own butterfly writeup -- see the ADST family below.
307#[derive(Clone, Copy, PartialEq, Eq, Debug)]
308enum TxType1d {
309 Dct,
310 Adst,
311 Identity,
312}
313
314/// `Tx_Type_Intra_Inv_Set2`'s five members (spec 9.3), in the CDF's own
315/// symbol order (`0..=4`): `IDTX, DCT_DCT, ADST_ADST, ADST_DCT, DCT_ADST`.
316/// [`crate::decode`] reads the symbol; this is what it dispatches to.
317#[derive(Clone, Copy, PartialEq, Eq, Debug)]
318pub enum TxType {
319 /// Identity on both axes.
320 Idtx,
321 /// DCT on both axes -- this crate's original, still most common case.
322 DctDct,
323 /// ADST on both axes.
324 AdstAdst,
325 /// ADST down the column axis, DCT across the row axis.
326 AdstDct,
327 /// DCT down the column axis, ADST across the row axis.
328 DctAdst,
329 /// DCT down the column axis, identity across the row axis
330 /// (`V_DCT` -- `TX_SET_INTRA_1` only).
331 VDct,
332 /// Identity down the column axis, DCT across the row axis
333 /// (`H_DCT` -- `TX_SET_INTRA_1` only).
334 HDct,
335 /// FLIPADST down the column axis, DCT across the row axis (lane-cdffwd2:
336 /// reachable once `reduced_tx_set == false`'s wider inter sets are read
337 /// -- `EXT_TX_SET_DTT9_IDTX_1DDCT`/`EXT_TX_SET_ALL16`). FLIPADST is the
338 /// same 1D ADST kernel [`AdstDct`] uses (`vtx_tab`/`htx_tab`,
339 /// `common_data.h`), just read/written flipped -- see [`TxType::flip`].
340 FlipAdstDct,
341 /// DCT down the column axis, FLIPADST across the row axis.
342 DctFlipAdst,
343 /// FLIPADST on both axes.
344 FlipAdstFlipAdst,
345 /// ADST down the column axis, FLIPADST across the row axis.
346 AdstFlipAdst,
347 /// FLIPADST down the column axis, ADST across the row axis.
348 FlipAdstAdst,
349 /// ADST down the column axis, identity across the row axis (`V_ADST` --
350 /// `EXT_TX_SET_ALL16` only).
351 VAdst,
352 /// Identity down the column axis, ADST across the row axis (`H_ADST`).
353 HAdst,
354 /// FLIPADST down the column axis, identity across the row axis
355 /// (`V_FLIPADST`).
356 VFlipAdst,
357 /// Identity down the column axis, FLIPADST across the row axis
358 /// (`H_FLIPADST`).
359 HFlipAdst,
360}
361
362impl TxType {
363 /// The inverse of `Tx_Type_Intra_Inv_Set2`'s CDF symbol order.
364 pub fn from_symbol(t: usize) -> Option<Self> {
365 match t {
366 0 => Some(Self::Idtx),
367 1 => Some(Self::DctDct),
368 2 => Some(Self::AdstAdst),
369 3 => Some(Self::AdstDct),
370 4 => Some(Self::DctAdst),
371 _ => None,
372 }
373 }
374
375 /// The inverse of `Tx_Type_Intra_Inv_Set1`'s CDF symbol order
376 /// (`av1_ext_tx_inv[EXT_TX_SET_DTT4_IDTX_1DDCT]`, entropymode.h:
377 /// `{9, 0, 10, 11, 3, 1, 2}` = IDTX, DCT_DCT, V_DCT, H_DCT, ADST_ADST,
378 /// ADST_DCT, DCT_ADST) -- the seven-type set a `reduced_tx_set == 0`
379 /// frame's small intra transforms read from.
380 pub fn from_symbol_set1(t: usize) -> Option<Self> {
381 match t {
382 0 => Some(Self::Idtx),
383 1 => Some(Self::DctDct),
384 2 => Some(Self::VDct),
385 3 => Some(Self::HDct),
386 4 => Some(Self::AdstAdst),
387 5 => Some(Self::AdstDct),
388 6 => Some(Self::DctAdst),
389 _ => None,
390 }
391 }
392
393 /// The inverse of `Tx_Type_Inter_Inv_Set2`'s CDF symbol order
394 /// (`av1_ext_tx_inv[EXT_TX_SET_DTT9_IDTX_1DDCT]`, `entropymode.h`:
395 /// `{9, 10, 11, 0, 1, 2, 4, 5, 3, 6, 7, 8}`) -- the twelve-type set a
396 /// `reduced_tx_set == 0` frame's 16x16 *inter* transform reads from
397 /// (`av1_get_ext_tx_set_type`'s `tx_size_sqr == TX_16X16` branch of
398 /// `av1_ext_tx_set_lookup[1]`).
399 pub fn from_symbol_set2_12(t: usize) -> Option<Self> {
400 match t {
401 0 => Some(Self::Idtx),
402 1 => Some(Self::VDct),
403 2 => Some(Self::HDct),
404 3 => Some(Self::DctDct),
405 4 => Some(Self::AdstDct),
406 5 => Some(Self::DctAdst),
407 6 => Some(Self::FlipAdstDct),
408 7 => Some(Self::DctFlipAdst),
409 8 => Some(Self::AdstAdst),
410 9 => Some(Self::FlipAdstFlipAdst),
411 10 => Some(Self::AdstFlipAdst),
412 11 => Some(Self::FlipAdstAdst),
413 _ => None,
414 }
415 }
416
417 /// The inverse of `Tx_Type_Inter_Inv_Set1`'s CDF symbol order
418 /// (`av1_ext_tx_inv[EXT_TX_SET_ALL16]`, `entropymode.h`:
419 /// `{9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 4, 5, 3, 6, 7, 8}`) -- the full
420 /// sixteen-type set a `reduced_tx_set == 0` frame's 8x8 (and 4x4) inter
421 /// transform reads from (`av1_ext_tx_set_lookup[1][0]`).
422 pub fn from_symbol_all16(t: usize) -> Option<Self> {
423 match t {
424 0 => Some(Self::Idtx),
425 1 => Some(Self::VDct),
426 2 => Some(Self::HDct),
427 3 => Some(Self::VAdst),
428 4 => Some(Self::HAdst),
429 5 => Some(Self::VFlipAdst),
430 6 => Some(Self::HFlipAdst),
431 7 => Some(Self::DctDct),
432 8 => Some(Self::AdstDct),
433 9 => Some(Self::DctAdst),
434 10 => Some(Self::FlipAdstDct),
435 11 => Some(Self::DctFlipAdst),
436 12 => Some(Self::AdstAdst),
437 13 => Some(Self::FlipAdstFlipAdst),
438 14 => Some(Self::AdstFlipAdst),
439 15 => Some(Self::FlipAdstAdst),
440 _ => None,
441 }
442 }
443
444 /// `(row, col)`: the transform `inverse_transform_2d_typed`'s row pass
445 /// (`htx_tab`, spec/libaom "horizontal") and column pass (`vtx_tab`,
446 /// "vertical") each run. Read off libaom's `av1_inv_txfm2d.c` `vtx_tab`/
447 /// `htx_tab` tables directly, not derived: e.g. `ADST_DCT` has
448 /// `vtx_tab = ADST_1D` (column), `htx_tab = DCT_1D` (row) -- the name's
449 /// first half is the *column* transform, not the row one.
450 fn axes(self) -> (TxType1d, TxType1d) {
451 use TxType1d::{Adst, Dct, Identity};
452 match self {
453 Self::Idtx => (Identity, Identity),
454 Self::DctDct => (Dct, Dct),
455 Self::AdstAdst => (Adst, Adst),
456 Self::AdstDct => (Dct, Adst),
457 Self::DctAdst => (Adst, Dct),
458 // `av1_inv_txfm2d.c`: V_DCT vtx=DCT htx=IDTX, H_DCT the mirror.
459 Self::VDct => (Identity, Dct),
460 Self::HDct => (Dct, Identity),
461 // FLIPADST reads the same 1D ADST kernel as ADST -- `vtx_tab`/
462 // `htx_tab` (`common_data.h`) map `FLIPADST_1D` and `ADST_1D`
463 // to the exact same butterfly network; only [`Self::flip`]
464 // differs. So every FLIPADST-bearing axis below mirrors its
465 // plain-ADST counterpart's kernel pairing.
466 Self::FlipAdstDct => (Dct, Adst),
467 Self::DctFlipAdst => (Adst, Dct),
468 Self::FlipAdstFlipAdst | Self::AdstFlipAdst | Self::FlipAdstAdst => (Adst, Adst),
469 Self::VAdst | Self::VFlipAdst => (Identity, Adst),
470 Self::HAdst | Self::HFlipAdst => (Adst, Identity),
471 }
472 }
473
474 /// `(ud_flip, lr_flip)` (`get_flip_cfg`, `av1_txfm.h`): whether the
475 /// column pass reads its input right-to-left and/or the finished
476 /// residual is written bottom-to-top. Every FLIPADST-bearing type sets
477 /// one or both; every other type is `(false, false)`.
478 fn flip(self) -> (bool, bool) {
479 match self {
480 Self::FlipAdstDct | Self::FlipAdstAdst | Self::VFlipAdst => (true, false),
481 Self::DctFlipAdst | Self::AdstFlipAdst | Self::HFlipAdst => (false, true),
482 Self::FlipAdstFlipAdst => (true, true),
483 _ => (false, false),
484 }
485 }
486}
487
488/// `sinpi[]` at `cos_bit = 12` (`av1_sinpi_arr_data[2]`, `av1_txfm.c`): the
489/// fixed constants [`inverse_adst4`] alone uses, unrelated to [`cos128`].
490const SINPI: [i64; 5] = [0, 1321, 2482, 3344, 3803];
491
492/// `NewSqrt2`/`NewSqrt2Bits` (`av1_txfm.h`): the `sqrt(2)` scale
493/// [`inverse_identity`] uses at sizes 4 and 16.
494const NEW_SQRT2: i64 = 5793;
495const NEW_SQRT2_BITS: u32 = 12;
496
497/// `round_shift` (`av1_txfm.h`): round-to-nearest to `bit` places, taking the
498/// pre-shift value in 64 bits since the ADST/identity intermediates
499/// routinely exceed 32.
500fn round_shift(x: i64, bit: u32) -> i32 {
501 ((x + (1i64 << (bit - 1))) >> bit) as i32
502}
503
504/// `half_btf(w0, in0, w1, in1, bit)` (`av1_txfm.h`) at `bit = COS_BITS`,
505/// the only value AV1's inverse transforms ever pass (`INV_COS_BIT`).
506fn half_btf(w0: i32, in0: i32, w1: i32, in1: i32) -> i32 {
507 let acc = i64::from(w0) * i64::from(in0) + i64::from(w1) * i64::from(in1);
508 round_shift(acc, COS_BITS as u32)
509}
510
511/// `av1_iadst4` (`av1_inv_txfm1d.c`): every intermediate stage there goes
512/// through `range_check_value`, which is a debug-only no-op in a conformant
513/// decoder (unlike `av1_iadst8`/`16`'s `clamp_value`, a real clamp) -- so
514/// this port carries no [`clamp_range`] calls, matching the reference
515/// exactly rather than adding a clamp libaom's own default build never
516/// takes.
517fn inverse_adst4(t: &mut [i32]) {
518 let (x0, x1, x2, x3) = (
519 i64::from(t[0]),
520 i64::from(t[1]),
521 i64::from(t[2]),
522 i64::from(t[3]),
523 );
524 if x0 == 0 && x1 == 0 && x2 == 0 && x3 == 0 {
525 t[0] = 0;
526 t[1] = 0;
527 t[2] = 0;
528 t[3] = 0;
529 return;
530 }
531 let mut s0 = SINPI[1] * x0;
532 let mut s1 = SINPI[2] * x0;
533 let s2 = SINPI[3] * x1;
534 let mut s3 = SINPI[4] * x2;
535 let s4 = SINPI[1] * x2;
536 let s5 = SINPI[2] * x3;
537 let s6 = SINPI[4] * x3;
538 let s7 = (x0 - x2) + x3;
539
540 s0 += s3;
541 s1 -= s4;
542 s3 = s2;
543 let s2 = SINPI[3] * s7;
544 s0 += s5;
545 s1 -= s6;
546
547 let o0 = s0 + s3;
548 let o1 = s1 + s3;
549 let o2 = s2;
550 let o3 = (s0 + s1) - s3;
551
552 t[0] = round_shift(o0, COS_BITS as u32);
553 t[1] = round_shift(o1, COS_BITS as u32);
554 t[2] = round_shift(o2, COS_BITS as u32);
555 t[3] = round_shift(o3, COS_BITS as u32);
556}
557
558/// `av1_iadst8` (`av1_inv_txfm1d.c`), stage for stage; `r` is the same
559/// per-stage clamp bit width `av1_gen_inv_stage_range` hands every stage in
560/// the square, 8-bit-depth case this decoder targets (row and column both
561/// land on 16 there, matching [`inverse_transform_2d_typed`]'s own
562/// `row_clamp`/`col_clamp`).
563fn inverse_adst8(t: &mut [i32], r: usize) {
564 let bf1 = [t[7], t[0], t[5], t[2], t[3], t[4], t[1], t[6]];
565
566 let mut step = [0i32; 8];
567 step[0] = half_btf(cos128(4), bf1[0], cos128(60), bf1[1]);
568 step[1] = half_btf(cos128(60), bf1[0], -cos128(4), bf1[1]);
569 step[2] = half_btf(cos128(20), bf1[2], cos128(44), bf1[3]);
570 step[3] = half_btf(cos128(44), bf1[2], -cos128(20), bf1[3]);
571 step[4] = half_btf(cos128(36), bf1[4], cos128(28), bf1[5]);
572 step[5] = half_btf(cos128(28), bf1[4], -cos128(36), bf1[5]);
573 step[6] = half_btf(cos128(52), bf1[6], cos128(12), bf1[7]);
574 step[7] = half_btf(cos128(12), bf1[6], -cos128(52), bf1[7]);
575
576 let mut out = [0i32; 8];
577 for i in 0..4 {
578 out[i] = clamp_range(step[i] + step[i + 4], r);
579 out[i + 4] = clamp_range(step[i] - step[i + 4], r);
580 }
581
582 step[0] = out[0];
583 step[1] = out[1];
584 step[2] = out[2];
585 step[3] = out[3];
586 step[4] = half_btf(cos128(16), out[4], cos128(48), out[5]);
587 step[5] = half_btf(cos128(48), out[4], -cos128(16), out[5]);
588 step[6] = half_btf(-cos128(48), out[6], cos128(16), out[7]);
589 step[7] = half_btf(cos128(16), out[6], cos128(48), out[7]);
590
591 out[0] = clamp_range(step[0] + step[2], r);
592 out[1] = clamp_range(step[1] + step[3], r);
593 out[2] = clamp_range(step[0] - step[2], r);
594 out[3] = clamp_range(step[1] - step[3], r);
595 out[4] = clamp_range(step[4] + step[6], r);
596 out[5] = clamp_range(step[5] + step[7], r);
597 out[6] = clamp_range(step[4] - step[6], r);
598 out[7] = clamp_range(step[5] - step[7], r);
599
600 step[0] = out[0];
601 step[1] = out[1];
602 step[2] = half_btf(cos128(32), out[2], cos128(32), out[3]);
603 step[3] = half_btf(cos128(32), out[2], -cos128(32), out[3]);
604 step[4] = out[4];
605 step[5] = out[5];
606 step[6] = half_btf(cos128(32), out[6], cos128(32), out[7]);
607 step[7] = half_btf(cos128(32), out[6], -cos128(32), out[7]);
608
609 t[0] = step[0];
610 t[1] = -step[4];
611 t[2] = step[6];
612 t[3] = -step[2];
613 t[4] = step[3];
614 t[5] = -step[7];
615 t[6] = step[5];
616 t[7] = -step[1];
617}
618
619/// `av1_iadst16` (`av1_inv_txfm1d.c`), stage for stage; `r` as
620/// [`inverse_adst8`].
621fn inverse_adst16(t: &mut [i32], r: usize) {
622 let inp: [i32; 16] = t[..16].try_into().expect("16-point input");
623 let bf1 = [
624 inp[15], inp[0], inp[13], inp[2], inp[11], inp[4], inp[9], inp[6], inp[7], inp[8], inp[5],
625 inp[10], inp[3], inp[12], inp[1], inp[14],
626 ];
627
628 let mut step = [0i32; 16];
629 step[0] = half_btf(cos128(2), bf1[0], cos128(62), bf1[1]);
630 step[1] = half_btf(cos128(62), bf1[0], -cos128(2), bf1[1]);
631 step[2] = half_btf(cos128(10), bf1[2], cos128(54), bf1[3]);
632 step[3] = half_btf(cos128(54), bf1[2], -cos128(10), bf1[3]);
633 step[4] = half_btf(cos128(18), bf1[4], cos128(46), bf1[5]);
634 step[5] = half_btf(cos128(46), bf1[4], -cos128(18), bf1[5]);
635 step[6] = half_btf(cos128(26), bf1[6], cos128(38), bf1[7]);
636 step[7] = half_btf(cos128(38), bf1[6], -cos128(26), bf1[7]);
637 step[8] = half_btf(cos128(34), bf1[8], cos128(30), bf1[9]);
638 step[9] = half_btf(cos128(30), bf1[8], -cos128(34), bf1[9]);
639 step[10] = half_btf(cos128(42), bf1[10], cos128(22), bf1[11]);
640 step[11] = half_btf(cos128(22), bf1[10], -cos128(42), bf1[11]);
641 step[12] = half_btf(cos128(50), bf1[12], cos128(14), bf1[13]);
642 step[13] = half_btf(cos128(14), bf1[12], -cos128(50), bf1[13]);
643 step[14] = half_btf(cos128(58), bf1[14], cos128(6), bf1[15]);
644 step[15] = half_btf(cos128(6), bf1[14], -cos128(58), bf1[15]);
645
646 let mut out = [0i32; 16];
647 for i in 0..8 {
648 out[i] = clamp_range(step[i] + step[i + 8], r);
649 out[i + 8] = clamp_range(step[i] - step[i + 8], r);
650 }
651
652 step[..8].copy_from_slice(&out[..8]);
653 step[8] = half_btf(cos128(8), out[8], cos128(56), out[9]);
654 step[9] = half_btf(cos128(56), out[8], -cos128(8), out[9]);
655 step[10] = half_btf(cos128(40), out[10], cos128(24), out[11]);
656 step[11] = half_btf(cos128(24), out[10], -cos128(40), out[11]);
657 step[12] = half_btf(-cos128(56), out[12], cos128(8), out[13]);
658 step[13] = half_btf(cos128(8), out[12], cos128(56), out[13]);
659 step[14] = half_btf(-cos128(24), out[14], cos128(40), out[15]);
660 step[15] = half_btf(cos128(40), out[14], cos128(24), out[15]);
661
662 out[0] = clamp_range(step[0] + step[4], r);
663 out[1] = clamp_range(step[1] + step[5], r);
664 out[2] = clamp_range(step[2] + step[6], r);
665 out[3] = clamp_range(step[3] + step[7], r);
666 out[4] = clamp_range(step[0] - step[4], r);
667 out[5] = clamp_range(step[1] - step[5], r);
668 out[6] = clamp_range(step[2] - step[6], r);
669 out[7] = clamp_range(step[3] - step[7], r);
670 out[8] = clamp_range(step[8] + step[12], r);
671 out[9] = clamp_range(step[9] + step[13], r);
672 out[10] = clamp_range(step[10] + step[14], r);
673 out[11] = clamp_range(step[11] + step[15], r);
674 out[12] = clamp_range(step[8] - step[12], r);
675 out[13] = clamp_range(step[9] - step[13], r);
676 out[14] = clamp_range(step[10] - step[14], r);
677 out[15] = clamp_range(step[11] - step[15], r);
678
679 step[0] = out[0];
680 step[1] = out[1];
681 step[2] = out[2];
682 step[3] = out[3];
683 step[4] = half_btf(cos128(16), out[4], cos128(48), out[5]);
684 step[5] = half_btf(cos128(48), out[4], -cos128(16), out[5]);
685 step[6] = half_btf(-cos128(48), out[6], cos128(16), out[7]);
686 step[7] = half_btf(cos128(16), out[6], cos128(48), out[7]);
687 step[8] = out[8];
688 step[9] = out[9];
689 step[10] = out[10];
690 step[11] = out[11];
691 step[12] = half_btf(cos128(16), out[12], cos128(48), out[13]);
692 step[13] = half_btf(cos128(48), out[12], -cos128(16), out[13]);
693 step[14] = half_btf(-cos128(48), out[14], cos128(16), out[15]);
694 step[15] = half_btf(cos128(16), out[14], cos128(48), out[15]);
695
696 out[0] = clamp_range(step[0] + step[2], r);
697 out[1] = clamp_range(step[1] + step[3], r);
698 out[2] = clamp_range(step[0] - step[2], r);
699 out[3] = clamp_range(step[1] - step[3], r);
700 out[4] = clamp_range(step[4] + step[6], r);
701 out[5] = clamp_range(step[5] + step[7], r);
702 out[6] = clamp_range(step[4] - step[6], r);
703 out[7] = clamp_range(step[5] - step[7], r);
704 out[8] = clamp_range(step[8] + step[10], r);
705 out[9] = clamp_range(step[9] + step[11], r);
706 out[10] = clamp_range(step[8] - step[10], r);
707 out[11] = clamp_range(step[9] - step[11], r);
708 out[12] = clamp_range(step[12] + step[14], r);
709 out[13] = clamp_range(step[13] + step[15], r);
710 out[14] = clamp_range(step[12] - step[14], r);
711 out[15] = clamp_range(step[13] - step[15], r);
712
713 step[0] = out[0];
714 step[1] = out[1];
715 step[2] = half_btf(cos128(32), out[2], cos128(32), out[3]);
716 step[3] = half_btf(cos128(32), out[2], -cos128(32), out[3]);
717 step[4] = out[4];
718 step[5] = out[5];
719 step[6] = half_btf(cos128(32), out[6], cos128(32), out[7]);
720 step[7] = half_btf(cos128(32), out[6], -cos128(32), out[7]);
721 step[8] = out[8];
722 step[9] = out[9];
723 step[10] = half_btf(cos128(32), out[10], cos128(32), out[11]);
724 step[11] = half_btf(cos128(32), out[10], -cos128(32), out[11]);
725 step[12] = out[12];
726 step[13] = out[13];
727 step[14] = half_btf(cos128(32), out[14], cos128(32), out[15]);
728 step[15] = half_btf(cos128(32), out[14], -cos128(32), out[15]);
729
730 t[0] = step[0];
731 t[1] = -step[8];
732 t[2] = step[12];
733 t[3] = -step[4];
734 t[4] = step[6];
735 t[5] = -step[14];
736 t[6] = step[10];
737 t[7] = -step[2];
738 t[8] = step[3];
739 t[9] = -step[11];
740 t[10] = step[15];
741 t[11] = -step[7];
742 t[12] = step[5];
743 t[13] = -step[13];
744 t[14] = step[9];
745 t[15] = -step[1];
746}
747
748/// `av1_iidentity4_c`/`8_c`/`16_c`/`32_c` (`av1_inv_txfm1d.c`): a fixed
749/// per-size scale, `sqrt(2)`-based at 4 and 16 (`NewSqrt2`/`NewSqrt2Bits`),
750/// exact doubling at 8 and 32.
751fn inverse_identity(t: &mut [i32], side: usize) {
752 match side {
753 4 => {
754 for v in &mut t[..4] {
755 *v = round_shift(NEW_SQRT2 * i64::from(*v), NEW_SQRT2_BITS);
756 }
757 }
758 8 => {
759 for v in &mut t[..8] {
760 *v = (i64::from(*v) * 2) as i32;
761 }
762 }
763 16 => {
764 for v in &mut t[..16] {
765 *v = round_shift(NEW_SQRT2 * 2 * i64::from(*v), NEW_SQRT2_BITS);
766 }
767 }
768 32 => {
769 for v in &mut t[..32] {
770 *v = (i64::from(*v) * 4) as i32;
771 }
772 }
773 _ => unreachable!("identity is defined at sizes 4, 8, 16 and 32"),
774 }
775}
776
777/// Dispatches one row or column's 1D inverse transform by [`TxType1d`],
778/// `log2` the spec's transform-size log (as [`inverse_dct`] takes).
779fn inverse_1d(t: &mut [i32], log2: u32, r: usize, kind: TxType1d) {
780 match kind {
781 TxType1d::Dct => inverse_dct(t, log2, r),
782 TxType1d::Adst => match log2 {
783 2 => inverse_adst4(t),
784 3 => inverse_adst8(t, r),
785 4 => inverse_adst16(t, r),
786 _ => unreachable!("ADST is undefined at sizes above 16 (spec: 32+ uses DCT/identity)"),
787 },
788 TxType1d::Identity => inverse_identity(t, 1usize << log2),
789 }
790}
791
792/// The 2D inverse transform (spec 7.13.3) for a square block of any
793/// [`TxType`]. `dequant` is the dequantized coefficient grid in raster order;
794/// the returned residual is in the same order. A 64-point transform only ever
795/// carries coefficients in its first 32 rows and columns, and the spec
796/// zeroes the rest before the row transform, which is what the `< 32` guard
797/// does (`TxType`s other than `DctDct` never reach a 64-point transform in
798/// this decoder -- `Luma64`'s CDF set carries no `tx_type` symbol).
799pub fn inverse_transform_2d_typed(
800 dequant: &[i32],
801 side: usize,
802 bit_depth: u8,
803 tx_type: TxType,
804) -> Vec<i32> {
805 inverse_transform_2d_typed_wh(dequant, side, side, bit_depth, tx_type)
806}
807
808/// [`inverse_transform_2d_typed`] widened to `(w, h)` (lane-recttx): the row
809/// pass transforms `w`-point vectors (`log2(w)`), the column pass
810/// `h`-point vectors (`log2(h)`), and a rect-only pre-row-transform scale
811/// is applied when the two axes are exactly one power-of-two apart (spec
812/// 7.13.3; `av1_inv_txfm2d.c:272-276`, `abs(rect_type) == 1`). `dequant` is
813/// still raster order (`dequant[i * w + j]`, row `i` of `h`, column `j` of
814/// `w`) -- libaom's own buffer for the same math is column-major, an
815/// unrelated fact about ITS storage, not the spec's arithmetic (class
816/// `reference-layout-not-spec`).
817pub fn inverse_transform_2d_typed_wh(
818 dequant: &[i32],
819 w: usize,
820 h: usize,
821 bit_depth: u8,
822 tx_type: TxType,
823) -> Vec<i32> {
824 let log2w = w.trailing_zeros();
825 let log2h = h.trailing_zeros();
826 assert_eq!(1usize << log2w, w, "width must be a power of two");
827 assert_eq!(1usize << log2h, h, "height must be a power of two");
828 assert_eq!(dequant.len(), w * h, "one coefficient per position");
829 let row_clamp = usize::from(bit_depth) + 8;
830 let col_clamp = (usize::from(bit_depth) + 6).max(16);
831 let mut residual = vec![0i32; w * h];
832 let (row_kind, col_kind) = tx_type.axes();
833 let (ud_flip, lr_flip) = tx_type.flip();
834 // `get_rect_tx_log_ratio` (`av1_inv_txfm2d.c:248`): the scale fires only
835 // at ratio exactly 1, never 0 (square) or 2 (e.g. 4x16/16x4/8x32/32x8/
836 // 16x64/64x16).
837 let rect_scale = (log2w as i32 - log2h as i32).abs() == 1;
838
839 let mut t = [0i32; 64];
840 for i in 0..h {
841 for j in 0..w {
842 let c = if i < 32 && j < 32 { dequant[i * w + j] } else { 0 };
843 t[j] = if rect_scale {
844 round2(c * 2896, 12)
845 } else {
846 c
847 };
848 }
849 inverse_1d(&mut t, log2w, row_clamp, row_kind);
850 for j in 0..w {
851 // The row's output is shifted, then clamped before the column
852 // transform reads it back.
853 residual[i * w + j] = clamp_range(round2(t[j], row_shift_wh(w, h)), col_clamp);
854 }
855 }
856
857 // A FLIPADST axis reads the row-pass output right-to-left and/or writes
858 // its own output bottom-to-top (`inv_txfm2d_add_c`, `av1_inv_txfm2d.c`
859 // lines 291-314): `out` is a second buffer, not `residual` reused in
860 // place, because a flipped read/write pair aliases a column this same
861 // loop has not visited yet (column `j`'s write target under `lr_flip`
862 // is a column an unflipped loop would still need to read from later).
863 // `lr_flip` mirrors over `w` (the row axis), `ud_flip` over `h`.
864 let mut out = vec![0i32; w * h];
865 for j in 0..w {
866 let src_col = if lr_flip { w - 1 - j } else { j };
867 for i in 0..h {
868 t[i] = residual[i * w + src_col];
869 }
870 inverse_1d(&mut t, log2h, col_clamp, col_kind);
871 for i in 0..h {
872 let dst_row = if ud_flip { h - 1 - i } else { i };
873 out[dst_row * w + j] = round2(t[i], 4);
874 }
875 }
876 out
877}
878
879/// [`inverse_transform_2d_typed`] at `DCT_DCT`, this crate's original
880/// (and still most common) transform.
881pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {
882 inverse_transform_2d_typed(dequant, side, bit_depth, TxType::DctDct)
883}
884
885/// Dequantize (spec 7.12.3) and inverse transform one square block of any
886/// [`TxType`], returning its residual in raster order.
887///
888/// This is the encoder's model of what the decoder will add to its prediction,
889/// so it follows the spec's dequantization exactly, truncation toward zero and
890/// all.
891#[allow(clippy::too_many_arguments)]
892pub fn dequant_and_inverse_typed(
893 levels: &[i32],
894 side: usize,
895 bit_depth: u8,
896 q_idx: i32,
897 dc_delta: i32,
898 ac_delta: i32,
899 tx_type: TxType,
900) -> Vec<i32> {
901 dequant_and_inverse_typed_wh(levels, side, side, bit_depth, q_idx, dc_delta, ac_delta, tx_type)
902}
903
904/// [`dequant_and_inverse_typed`] widened to `(w, h)` (lane-recttx). `dc_delta`/
905/// `ac_delta` are the per-plane quantizer-index offsets (lane-sbpart r11,
906/// spec 5.9.12/7.12.2, [`crate::quant::QuantDeltas`]) -- `0`/`0` for the
907/// unaffected callers below.
908#[allow(clippy::too_many_arguments)]
909pub fn dequant_and_inverse_typed_wh(
910 levels: &[i32],
911 w: usize,
912 h: usize,
913 bit_depth: u8,
914 q_idx: i32,
915 dc_delta: i32,
916 ac_delta: i32,
917 tx_type: TxType,
918) -> Vec<i32> {
919 let dq = crate::quant::dequant_wh(levels, w, h, bit_depth, q_idx, dc_delta, ac_delta);
920 inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type)
921}
922
923/// [`dequant_and_inverse_typed`] at `DCT_DCT`, no per-plane quantizer delta.
924pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i32> {
925 dequant_and_inverse_typed(levels, side, bit_depth, q_idx, 0, 0, TxType::DctDct)
926}
927
928/// The orthonormal DCT-II basis row for output `u` of an `n`-point transform.
929///
930/// The decoder's network is this basis scaled by a constant the encoder has to
931/// undo, and nothing else: measuring the network's response to a unit
932/// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of
933/// `dqDenom`, which is what [`forward_transform_2d`] divides out.
934fn build_dct_basis(n: usize) -> Vec<f64> {
935 let mut basis = vec![0.0f64; n * n];
936 let scale = (2.0 / n as f64).sqrt();
937 for u in 0..n {
938 let alpha = if u == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 };
939 for i in 0..n {
940 let angle = std::f64::consts::PI * (2.0 * i as f64 + 1.0) * u as f64 / (2.0 * n as f64);
941 basis[u * n + i] = alpha * scale * angle.cos();
942 }
943 }
944 basis
945}
946
947/// [`build_dct_basis`], computed once per transform size and reused: the
948/// search calls [`forward_transform_2d`] for every mode of every block, and
949/// the basis does not depend on the residual, only on `n` -- recomputing
950/// `n * n` cosines per call was measured as this search's single largest
951/// per-trial cost (`stage_timing_breakdown`, ec-av1 perf lane). `n` is always
952/// one of the transform sizes this crate codes (4 to 64, a power of two), so
953/// a small fixed table indexed by `log2(n)` covers every caller without a
954/// hash lookup.
955fn dct_basis(n: usize) -> &'static [f64] {
956 use std::sync::OnceLock;
957 // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.
958 static CACHE: OnceLock<[OnceLock<Vec<f64>>; 5]> = OnceLock::new();
959 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
960 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
961 cache[idx].get_or_init(|| build_dct_basis(n))
962}
963
964/// How much the decoder's inverse transform shrinks an orthonormal DCT.
965///
966/// Measured, not asserted: feeding a single dequantized coefficient through
967/// `inverse_transform_2d` reproduces the orthonormal basis function scaled by
968/// `dq_denom(side) / 8` at every size (see `the_inverse_network_is_an_orthonormal_dct_over_eight`).
969/// The dequantizer has already divided by `dq_denom`, so the two cancel and
970/// what an encoder owes a level is size-independent:
971/// `level = 8 * orthonormal(residual) / q`.
972///
973/// The spec fixes the decoder; the encoder is free in how it reaches the
974/// coefficients it sends, and this constant is the one thing the two ends have
975/// to agree on for a level to mean what the encoder thinks it means.
976const INVERSE_GAIN_RECIPROCAL: f64 = 8.0;
977
978/// A complex sample, `(re, im)`, for the radix-2 FFT beneath [`dct1d`].
979type Complex = (f64, f64);
980
981fn cmul(a: Complex, b: Complex) -> Complex {
982 (a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0)
983}
984
985/// An in-place iterative radix-2 Cooley-Tukey FFT (forward, i.e. the `exp(-i
986/// theta)` convention), `a.len()` a power of two. Only [`dct1d`] calls this,
987/// on sizes 4 to 64, so no bounds beyond "power of two" are enforced.
988fn fft(a: &mut [Complex]) {
989 let n = a.len();
990 if n <= 1 {
991 return;
992 }
993 let mut j = 0;
994 for i in 1..n {
995 let mut bit = n >> 1;
996 while j & bit != 0 {
997 j ^= bit;
998 bit >>= 1;
999 }
1000 j |= bit;
1001 if i < j {
1002 a.swap(i, j);
1003 }
1004 }
1005 let mut len = 2;
1006 while len <= n {
1007 let ang = -2.0 * std::f64::consts::PI / len as f64;
1008 let wlen = (ang.cos(), ang.sin());
1009 let mut i = 0;
1010 while i < n {
1011 let mut w = (1.0, 0.0);
1012 for k in 0..len / 2 {
1013 let u = a[i + k];
1014 let v = cmul(a[i + k + len / 2], w);
1015 a[i + k] = (u.0 + v.0, u.1 + v.1);
1016 a[i + k + len / 2] = (u.0 - v.0, u.1 - v.1);
1017 w = cmul(w, wlen);
1018 }
1019 i += len;
1020 }
1021 len <<= 1;
1022 }
1023}
1024
1025/// The orthonormal DCT-II of one line of `n` samples, in `O(n log n)` via
1026/// Makhoul's FFT reduction rather than the `n^2` direct dot product against
1027/// [`build_dct_basis`]'s rows.
1028///
1029/// The reduction: reorder `x` into `v[i] = x[2i]`, `v[n-1-i] = x[2i+1]` for
1030/// `i < n/2`; an `n`-point FFT of `v` then gives the unnormalized DCT-II as
1031/// `X_k = Re(V_k * exp(-i*pi*k/(2n)))` (measured against the direct
1032/// definition, not the textbook `2 * Re(...)` form, which double-counts here
1033/// because `v`'s construction already folds each input pair once). What is
1034/// returned here is that,
1035/// scaled to match [`build_dct_basis`]'s convention exactly (`alpha_0 =
1036/// 1/sqrt(2)`, `alpha_k = 1` otherwise, both times `sqrt(2/n)`) so the result
1037/// is bit-for-bit the same *contract* as the old matmul, only reordered in
1038/// its summation (equal up to floating-point rounding, checked in
1039/// `fast_forward_matches_the_naive_matmul`).
1040/// The post-FFT twist for [`dct1d`], `(cos(theta_k), sin(theta_k), alpha_k *
1041/// sqrt(2/n))` per output `k` -- cached per size for the same reason
1042/// [`dct_basis`] is: computed from a `k`-dependent angle, so a call-time
1043/// `cos`/`sin` per output (`n` of them, every call) was measured as this
1044/// factorization's actual bottleneck, worse than the matmul it was meant to
1045/// beat.
1046fn dct_twist(n: usize) -> &'static [(f64, f64, f64)] {
1047 use std::sync::OnceLock;
1048 static CACHE: OnceLock<[OnceLock<Vec<(f64, f64, f64)>>; 5]> = OnceLock::new();
1049 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
1050 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
1051 cache[idx].get_or_init(|| {
1052 (0..n)
1053 .map(|k| {
1054 let theta = std::f64::consts::PI * k as f64 / (2.0 * n as f64);
1055 let alpha = if k == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 };
1056 (theta.cos(), theta.sin(), alpha * (2.0 / n as f64).sqrt())
1057 })
1058 .collect()
1059 })
1060}
1061
1062///
1063/// `x` and `out` are both exactly `n` long (`n` at most 64, the largest
1064/// transform side this crate codes); the FFT itself runs on a fixed 64-slot
1065/// stack array rather than a heap `Vec` -- this call happens twice per row
1066/// and twice per column of every RD trial's transform, and the allocations
1067/// that a `Vec` per call cost here were measured as a first source of a first
1068/// cut of this factorization being *slower* than the matmul it replaced (the
1069/// call-time trig in [`dct_twist`]'s table was the other, larger one).
1070fn dct1d(x: &[f64], out: &mut [f64]) {
1071 let n = x.len();
1072 let half = n / 2;
1073 let mut v = [(0.0f64, 0.0f64); 64];
1074 for i in 0..half {
1075 v[i] = (x[2 * i], 0.0);
1076 v[n - 1 - i] = (x[2 * i + 1], 0.0);
1077 }
1078 fft(&mut v[..n]);
1079 let twist = dct_twist(n);
1080 for (k, &(c, s, scale)) in twist.iter().enumerate() {
1081 out[k] = scale * (v[k].0 * c + v[k].1 * s);
1082 }
1083}
1084
1085/// The forward transform (encoder side, spec-free): the transpose of what the
1086/// decoder's inverse does, so that `inverse_transform_2d` of the result
1087/// reproduces `residual`.
1088///
1089/// AV1 specifies only the inverse transform. The encoder may reach its
1090/// coefficients however it likes, and this reaches them via [`dct1d`], an
1091/// `O(n log n)` orthonormal DCT-II factorization equal to the direct
1092/// `O(n^2)` matmul up to floating-point rounding (see
1093/// `fast_forward_matches_the_naive_matmul`), scaled to the decoder's
1094/// fixed-point gain. It is deterministic, and its accuracy is measured
1095/// against the decoder's own inverse rather than asserted.
1096pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {
1097 assert_eq!(
1098 residual.len(),
1099 side * side,
1100 "one residual sample per position"
1101 );
1102 let mut rows = vec![0.0f64; side * side];
1103 let mut buf = [0.0f64; 64];
1104 let mut line = [0.0f64; 64];
1105 for i in 0..side {
1106 for (j, &r) in residual[i * side..][..side].iter().enumerate() {
1107 buf[j] = f64::from(r);
1108 }
1109 dct1d(&buf[..side], &mut line[..side]);
1110 rows[i * side..][..side].copy_from_slice(&line[..side]);
1111 }
1112 let mut out = vec![0.0f64; side * side];
1113 for v in 0..side {
1114 for (i, c) in buf[..side].iter_mut().enumerate() {
1115 *c = rows[i * side + v];
1116 }
1117 dct1d(&buf[..side], &mut line[..side]);
1118 for (u, &t) in line[..side].iter().enumerate() {
1119 out[u * side + v] = t;
1120 }
1121 }
1122 let scale = INVERSE_GAIN_RECIPROCAL;
1123 for v in &mut out {
1124 *v *= scale;
1125 }
1126 out
1127}
1128
1129/// The old direct `O(n^2)` matmul against [`build_dct_basis`], kept only as
1130/// the differential oracle for [`forward_transform_2d`]'s fast replacement
1131/// (`fast_forward_matches_the_naive_matmul`).
1132#[cfg(test)]
1133fn forward_transform_2d_naive(residual: &[i32], side: usize) -> Vec<f64> {
1134 let basis = dct_basis(side);
1135 let mut rows = vec![0.0f64; side * side];
1136 for i in 0..side {
1137 let residual_row = &residual[i * side..][..side];
1138 for u in 0..side {
1139 let sum: f64 = residual_row
1140 .iter()
1141 .zip(&basis[u * side..][..side])
1142 .map(|(&r, &b)| f64::from(r) * b)
1143 .sum();
1144 rows[i * side + u] = sum;
1145 }
1146 }
1147 let mut rows_t = vec![0.0f64; side * side];
1148 for i in 0..side {
1149 for v in 0..side {
1150 rows_t[v * side + i] = rows[i * side + v];
1151 }
1152 }
1153 let mut out = vec![0.0f64; side * side];
1154 for u in 0..side {
1155 for v in 0..side {
1156 let sum: f64 = rows_t[v * side..][..side]
1157 .iter()
1158 .zip(&basis[u * side..][..side])
1159 .map(|(&r, &b)| r * b)
1160 .sum();
1161 out[u * side + v] = sum;
1162 }
1163 }
1164 let scale = INVERSE_GAIN_RECIPROCAL;
1165 for v in &mut out {
1166 *v *= scale;
1167 }
1168 out
1169}
1170
1171/// Quantize forward-transform coefficients into the levels the tile syntax
1172/// carries.
1173///
1174/// `deadzone` is the fraction of a quantizer step a coefficient has to reach
1175/// before it is coded at all, as a rounding offset: 0.5 rounds to nearest,
1176/// smaller values pull coefficients toward zero, which is what buys the rate
1177/// back on noisy content. A 64-point transform only carries its top-left
1178/// 32x32, so everything outside that is dropped here rather than silently by
1179/// the writer.
1180pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone: f64) -> Vec<i32> {
1181 assert_eq!(coeffs.len(), side * side, "one coefficient per position");
1182 let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx));
1183 let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx));
1184 let mut levels = vec![0i32; side * side];
1185 for (i, &c) in coeffs.iter().enumerate() {
1186 let (row, col) = (i / side, i % side);
1187 if row >= 32 || col >= 32 {
1188 continue;
1189 }
1190 let q = if i == 0 { dc } else { ac };
1191 let scaled = c / q;
1192 let magnitude = scaled.abs() + deadzone;
1193 let level = if magnitude < 1.0 {
1194 0
1195 } else {
1196 magnitude.floor().min(f64::from(i32::MAX)) as i32
1197 };
1198 levels[i] = if scaled < 0.0 { -level } else { level };
1199 }
1200 levels
1201}
1202
1203/// Transform and quantize one block's residual, the encoder's half of the
1204/// round trip [`dequant_and_inverse`] completes.
1205pub fn forward_and_quantize(
1206 residual: &[i32],
1207 side: usize,
1208 bit_depth: u8,
1209 q_idx: i32,
1210 deadzone: f64,
1211) -> Vec<i32> {
1212 let coeffs = forward_transform_2d(residual, side);
1213 quantize(&coeffs, side, bit_depth, q_idx, deadzone)
1214}
1215
1216#[cfg(test)]
1217mod tests {
1218 use super::*;
1219
1220 /// The orthonormal DCT-II basis the forward transform is written against,
1221 /// computed independently of `dct_basis` so a test is not checking a
1222 /// function against itself.
1223 fn reference_basis(n: usize) -> Vec<f64> {
1224 let mut c = vec![0.0; n * n];
1225 for u in 0..n {
1226 let alpha = if u == 0 { (0.5f64).sqrt() } else { 1.0 };
1227 for x in 0..n {
1228 let angle =
1229 (2.0 * x as f64 + 1.0) * u as f64 * std::f64::consts::PI / (2.0 * n as f64);
1230 c[u * n + x] = alpha * (2.0 / n as f64).sqrt() * angle.cos();
1231 }
1232 }
1233 c
1234 }
1235
1236 /// A deterministic pseudo-random residual in `-100..=100`.
1237 fn noise(len: usize, seed: u64) -> Vec<i32> {
1238 let mut state = seed;
1239 (0..len)
1240 .map(|_| {
1241 state = state
1242 .wrapping_mul(6_364_136_223_846_793_005)
1243 .wrapping_add(1_442_695_040_888_963_407);
1244 ((state >> 33) % 201) as i32 - 100
1245 })
1246 .collect()
1247 }
1248
1249 #[test]
1250 #[ignore]
1251 fn scratch_probe_32x32_dequant() {
1252 let mut levels = vec![0i32; 32 * 32];
1253 levels[0] = -2;
1254 levels[1] = -2;
1255 levels[2] = -2;
1256 let dq = crate::quant::dequant(&levels, 32, 8, 60);
1257 eprintln!("dq[0..4]={:?}", &dq[0..4]);
1258 let residual = dequant_and_inverse(&levels, 32, 8, 60);
1259 eprintln!("row0: {:?}", &residual[0..32]);
1260 eprintln!("row1: {:?}", &residual[32..64]);
1261
1262 // superposition probe: does inverse_transform_2d at side=32 sum
1263 // three simultaneous low-frequency coefficients the same as it
1264 // reconstructs each alone?
1265 let side = 32usize;
1266 let mut single_sum = vec![0i32; side * side];
1267 for &(pos, val) in &[(0usize, -57i32), (1, -67), (2, -67)] {
1268 let mut c = vec![0i32; side * side];
1269 c[pos] = val;
1270 let got = inverse_transform_2d(&c, side, 8);
1271 for i in 0..side * side {
1272 single_sum[i] += got[i];
1273 }
1274 }
1275 let mut combined = vec![0i32; side * side];
1276 combined[0] = -57;
1277 combined[1] = -67;
1278 combined[2] = -67;
1279 let got_combined = inverse_transform_2d(&combined, side, 8);
1280 eprintln!("single_sum row0: {:?}", &single_sum[0..8]);
1281 eprintln!("combined row0: {:?}", &got_combined[0..8]);
1282 }
1283
1284 fn rmse(a: &[i32], b: &[i32]) -> f64 {
1285 let sum: f64 = a
1286 .iter()
1287 .zip(b)
1288 .map(|(&x, &y)| f64::from(x - y) * f64::from(x - y))
1289 .sum();
1290 (sum / a.len() as f64).sqrt()
1291 }
1292
1293 /// [`forward_transform_2d`]'s fast FFT-based factorization against
1294 /// [`forward_transform_2d_naive`]'s direct matmul: same summation
1295 /// reordered, so equal up to floating-point rounding, not bit-exact.
1296 #[test]
1297 fn fast_forward_matches_the_naive_matmul() {
1298 for &side in &[4usize, 8, 16, 32, 64] {
1299 for seed in [1u64, 2, 3] {
1300 let residual = noise(side * side, seed * 1000 + side as u64);
1301 let fast = forward_transform_2d(&residual, side);
1302 let naive = forward_transform_2d_naive(&residual, side);
1303 for (i, (&f, &n)) in fast.iter().zip(&naive).enumerate() {
1304 assert!(
1305 (f - n).abs() < 1e-6 * n.abs().max(1.0),
1306 "{side}x{side} seed {seed} coefficient {i}: fast {f} vs naive {n}"
1307 );
1308 }
1309 }
1310 }
1311 }
1312
1313 /// The one thing the encoder and the decoder have to agree on.
1314 ///
1315 /// The spec's inverse network is not documented as a scaled orthonormal
1316 /// DCT, so this measures it: each dequantized coefficient, on its own,
1317 /// comes back out as its orthonormal basis function scaled by
1318 /// `dq_denom(side) / 8` — the same factor for every coefficient of a
1319 /// size, which is what makes a single constant enough for the encoder.
1320 /// The fit is checked as well as the scale, so an inverse that scaled
1321 /// right but mixed positions apart could not pass.
1322 #[test]
1323 fn the_inverse_network_is_an_orthonormal_dct_over_eight() {
1324 for &side in &[4usize, 8, 16, 32, 64] {
1325 let basis = reference_basis(side);
1326 for &(u, v) in &[(0usize, 0usize), (0, 1), (1, 0), (2, 3), (5, 7)] {
1327 if u >= side || v >= side {
1328 continue;
1329 }
1330 let mut coeffs = vec![0i32; side * side];
1331 coeffs[u * side + v] = 4096;
1332 let got = inverse_transform_2d(&coeffs, side, 8);
1333 let want: Vec<f64> = (0..side * side)
1334 .map(|i| 4096.0 * basis[u * side + i / side] * basis[v * side + i % side])
1335 .collect();
1336 // Least-squares fit of one scale over the whole block.
1337 let num: f64 = want.iter().zip(&got).map(|(w, &g)| w * f64::from(g)).sum();
1338 let den: f64 = want.iter().map(|w| w * w).sum();
1339 let k = num / den;
1340 let expected = crate::quant::dq_denom(side) as f64 / 8.0;
1341 assert!(
1342 (k - expected).abs() < 0.01 * expected,
1343 "{side}x{side} ({u},{v}): gain {k}, expected {expected}"
1344 );
1345 // And the block really is that basis function, not merely a
1346 // block of the same energy: no sample off by more than one.
1347 for (i, (w, &g)) in want.iter().zip(&got).enumerate() {
1348 let scaled = k * w;
1349 assert!(
1350 (scaled - f64::from(g)).abs() <= 1.0,
1351 "{side}x{side} ({u},{v}) sample {i}: {g} vs {scaled}"
1352 );
1353 }
1354 }
1355 }
1356 }
1357
1358 /// A fine quantizer costs almost nothing: forward, quantize, dequantize
1359 /// and invert returns the residual to within a sample or two at every
1360 /// transform size the spec's DCT covers.
1361 ///
1362 /// 64x64 is excluded here because it cannot carry a white-noise residual
1363 /// at all — see
1364 /// [`a_64x64_transform_keeps_what_fits_in_its_coded_quarter`].
1365 #[test]
1366 fn a_fine_quantizer_roundtrips_a_residual_almost_exactly() {
1367 for &side in &[4usize, 8, 16, 32] {
1368 let residual = noise(side * side, 12_345 + side as u64);
1369 let levels = forward_and_quantize(&residual, side, 8, 10, 0.5);
1370 let back = dequant_and_inverse(&levels, side, 8, 10);
1371 let error = rmse(&back, &residual);
1372 assert!(error < 1.0, "{side}x{side}: rmse {error}");
1373 }
1374 }
1375
1376 /// Error grows with the quantizer and with nothing else. A calibration
1377 /// that is off by a constant factor shows up here as a floor that a finer
1378 /// quantizer cannot get under — which is exactly what a wrong gain
1379 /// constant produced while this was being written.
1380 #[test]
1381 fn the_roundtrip_error_is_the_quantizer_and_only_the_quantizer() {
1382 for &side in &[4usize, 8, 16, 32] {
1383 let residual = noise(side * side, 999 + side as u64);
1384 let mut previous = 0.0;
1385 for &q_idx in &[10i32, 60, 100, 180] {
1386 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
1387 let back = dequant_and_inverse(&levels, side, 8, q_idx);
1388 let error = rmse(&back, &residual);
1389 assert!(
1390 error > previous,
1391 "{side}x{side} q {q_idx}: {error} <= {previous}"
1392 );
1393 // A quantizer step is q/8 in residual units, and rounding to
1394 // nearest costs no more than half a step per coefficient.
1395 let step = f64::from(crate::quant::ac_q(8, q_idx)) / 8.0;
1396 assert!(
1397 error < step,
1398 "{side}x{side} q {q_idx}: rmse {error}, step {step}"
1399 );
1400 previous = error;
1401 }
1402 }
1403 }
1404
1405 /// A 64x64 transform codes only its top-left 32x32 coefficients, so it
1406 /// keeps everything below half the Nyquist rate in each direction and
1407 /// drops the rest. A band-limited residual survives it; white noise loses
1408 /// the three quarters of its energy that live outside the coded quarter,
1409 /// and that loss is the transform's, not the quantizer's — it does not
1410 /// move when the quantizer does.
1411 #[test]
1412 fn a_64x64_transform_keeps_what_fits_in_its_coded_quarter() {
1413 let side = 64;
1414 // Band-limited: built from basis functions inside the coded quarter.
1415 let basis = reference_basis(side);
1416 let mut smooth = vec![0.0f64; side * side];
1417 for &(u, v, amplitude) in &[(0usize, 0usize, 900.0f64), (1, 2, 400.0), (9, 30, 250.0)] {
1418 for i in 0..side * side {
1419 smooth[i] += amplitude * basis[u * side + i / side] * basis[v * side + i % side];
1420 }
1421 }
1422 let smooth: Vec<i32> = smooth.iter().map(|&s| s.round() as i32).collect();
1423 let levels = forward_and_quantize(&smooth, side, 8, 10, 0.5);
1424 let back = dequant_and_inverse(&levels, side, 8, 10);
1425 let kept = rmse(&back, &smooth);
1426 assert!(kept < 1.5, "band-limited 64x64: rmse {kept}");
1427
1428 let residual = noise(side * side, 4_242);
1429 let mut errors = Vec::new();
1430 for &q_idx in &[10i32, 180] {
1431 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
1432 let back = dequant_and_inverse(&levels, side, 8, q_idx);
1433 errors.push(rmse(&back, &residual));
1434 }
1435 // Three quarters of a white-noise block's energy is outside the coded
1436 // quarter, so the error is sqrt(3/4) of the residual's own magnitude
1437 // whatever the quantizer does.
1438 let magnitude = rmse(&residual, &vec![0; side * side]);
1439 for error in &errors {
1440 let ratio = error / magnitude;
1441 assert!(
1442 (ratio - 0.75f64.sqrt()).abs() < 0.05,
1443 "64x64 white noise: ratio {ratio}"
1444 );
1445 }
1446 assert!(
1447 (errors[1] - errors[0]).abs() < 0.05 * errors[0],
1448 "64x64 white noise moved with the quantizer: {errors:?}"
1449 );
1450 }
1451
1452 /// The deadzone pulls coefficients toward zero: a wider one codes fewer
1453 /// of them and costs more error, and rounding to nearest is the tightest
1454 /// of them.
1455 #[test]
1456 fn a_wider_deadzone_codes_fewer_coefficients() {
1457 let side = 16;
1458 let residual = noise(side * side, 77);
1459 let mut previous_nonzero = usize::MAX;
1460 let mut previous_error = 0.0;
1461 for &deadzone in &[0.5f64, 0.35, 0.2] {
1462 let levels = forward_and_quantize(&residual, side, 8, 100, deadzone);
1463 let back = dequant_and_inverse(&levels, side, 8, 100);
1464 let nonzero = levels.iter().filter(|&&l| l != 0).count();
1465 let error = rmse(&back, &residual);
1466 assert!(
1467 nonzero < previous_nonzero,
1468 "deadzone {deadzone}: {nonzero} coefficients"
1469 );
1470 assert!(error > previous_error, "deadzone {deadzone}: rmse {error}");
1471 previous_nonzero = nonzero;
1472 previous_error = error;
1473 }
1474 }
1475
1476 /// Negating a residual negates its levels: the forward transform carries
1477 /// no offset of its own.
1478 #[test]
1479 fn negating_the_residual_negates_every_level() {
1480 for &side in &[4usize, 32] {
1481 let residual = noise(side * side, 5_150 + side as u64);
1482 let negated: Vec<i32> = residual.iter().map(|&r| -r).collect();
1483 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
1484 let other = forward_and_quantize(&negated, side, 8, 100, 0.5);
1485 for (i, (a, b)) in levels.iter().zip(&other).enumerate() {
1486 assert_eq!(*a, -*b, "{side}x{side} coefficient {i}");
1487 }
1488 }
1489 }
1490
1491 /// A flat residual is a DC level and nothing else, at the value the
1492 /// dequantizer's own arithmetic asks for.
1493 #[test]
1494 fn a_flat_residual_is_a_dc_level_alone() {
1495 for &side in &[4usize, 8, 16, 32, 64] {
1496 let residual = vec![40i32; side * side];
1497 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
1498 for (i, &level) in levels.iter().enumerate() {
1499 if i == 0 {
1500 // level = 8 * (40 * side) / dc_q, the orthonormal DC of a
1501 // flat block being its value times the side.
1502 let want = (8.0 * 40.0 * side as f64 / f64::from(crate::quant::dc_q(8, 100)))
1503 .round() as i32;
1504 assert_eq!(level, want, "{side}x{side} DC");
1505 } else {
1506 assert_eq!(level, 0, "{side}x{side} coefficient {i}");
1507 }
1508 }
1509 }
1510 }
1511
1512 // --- ADST/identity family: reference vectors from libaom's own
1513 // `av1_iadst4`/`8`/`16` and `av1_iidentity*_c`, computed by a small C
1514 // probe (`gcc` against `/tmp/libaom-src/build/decoder-debug/libaom.a`,
1515 // calling those exported symbols directly with the inputs pinned below --
1516 // no hand-derived arithmetic) so these are decisive, not memory-derived.
1517
1518 #[test]
1519 fn iadst4_matches_libaoms_own_output() {
1520 let mut t = [100, -50, 25, 7];
1521 inverse_adst4(&mut t);
1522 assert_eq!(t, [19, 5, 67, 147]);
1523 }
1524
1525 #[test]
1526 fn iadst4_an_all_zero_input_short_circuits_to_zero() {
1527 let mut t = [0, 0, 0, 0];
1528 inverse_adst4(&mut t);
1529 assert_eq!(t, [0, 0, 0, 0]);
1530 }
1531
1532 #[test]
1533 fn iadst8_matches_libaoms_own_output() {
1534 let mut t = [100, -50, 25, 7, -3, 60, -12, 8];
1535 inverse_adst8(&mut t, 16);
1536 assert_eq!(t, [59, 15, -25, 52, 25, 27, 207, 130]);
1537 }
1538
1539 #[test]
1540 fn iadst16_matches_libaoms_own_output() {
1541 let mut t = [
1542 100, -50, 25, 7, -3, 60, -12, 8, 15, -40, 33, -5, 22, 1, -70, 44,
1543 ];
1544 inverse_adst16(&mut t, 16);
1545 assert_eq!(
1546 t,
1547 [
1548 32, 73, 28, 6, -45, -28, 111, -52, 135, -54, 85, -67, 305, 190, 102, 145
1549 ]
1550 );
1551 }
1552
1553 #[test]
1554 fn iidentity_matches_libaoms_own_output_at_every_size() {
1555 let mut t4 = [100, -50, 25, 7];
1556 inverse_identity(&mut t4, 4);
1557 assert_eq!(t4, [141, -71, 35, 10]);
1558
1559 let mut t8 = [100, -50, 25, 7, -3, 60, -12, 8];
1560 inverse_identity(&mut t8, 8);
1561 assert_eq!(t8, [200, -100, 50, 14, -6, 120, -24, 16]);
1562
1563 let mut t16 = [
1564 100, -50, 25, 7, -3, 60, -12, 8, 15, -40, 33, -5, 22, 1, -70, 44,
1565 ];
1566 inverse_identity(&mut t16, 16);
1567 assert_eq!(
1568 t16,
1569 [
1570 283, -141, 71, 20, -8, 170, -34, 23, 42, -113, 93, -14, 62, 3, -198, 124
1571 ]
1572 );
1573
1574 let mut t32 = [0i32; 32];
1575 for (i, v) in t32.iter_mut().enumerate() {
1576 *v = i as i32 * 7 - 100;
1577 }
1578 inverse_identity(&mut t32, 32);
1579 assert_eq!(
1580 t32,
1581 [
1582 -400, -372, -344, -316, -288, -260, -232, -204, -176, -148, -120, -92, -64, -36,
1583 -8, 20, 48, 76, 104, 132, 160, 188, 216, 244, 272, 300, 328, 356, 384, 412, 440,
1584 468
1585 ]
1586 );
1587 }
1588
1589 /// The axis-convention gate: an impulse in row 0 (`ADST_DCT`'s row
1590 /// transform is DCT, so an ADST call here stands in for `DCT_ADST`'s row
1591 /// pass) fed through `inverse_adst8` at "row position 0" must differ from
1592 /// the same impulse at "column position 1" -- i.e. ADST is not a
1593 /// symmetric function of its input's position, which is what lets
1594 /// `ADST_DCT` and `DCT_ADST` decode to different residuals for the same
1595 /// coefficient grid. Values pinned from the same libaom probe.
1596 #[test]
1597 fn iadst8_is_not_symmetric_in_its_input_position() {
1598 let mut row = [40, 0, 0, 0, 0, 0, 0, 0];
1599 let mut col = [0, 40, 0, 0, 0, 0, 0, 0];
1600 inverse_adst8(&mut row, 16);
1601 inverse_adst8(&mut col, 16);
1602 assert_eq!(row, [4, 12, 18, 25, 31, 35, 38, 40]);
1603 assert_eq!(col, [12, 31, 40, 35, 18, -4, -26, -38]);
1604 assert_ne!(
1605 row, col,
1606 "an asymmetric input must not decode symmetrically"
1607 );
1608 }
1609
1610 /// The decisive end-to-end asymmetry gate `inverse_transform_2d_typed`
1611 /// itself: `ADST_DCT` and `DCT_ADST` must decode the same asymmetric
1612 /// coefficient grid to *different* residuals, which is only true if the
1613 /// row/column axis assignment (`TxType::axes`) is not accidentally
1614 /// symmetric (e.g. both pointing at the same 1D transform, or swapped
1615 /// with each other in a way that cancels out on this input).
1616 #[test]
1617 fn adst_dct_and_dct_adst_disagree_on_an_asymmetric_grid() {
1618 let side = 8;
1619 let mut dequant = vec![0i32; side * side];
1620 // An asymmetric coefficient: nonzero only at (row=0, col=1).
1621 dequant[1] = 64;
1622 let adst_dct = inverse_transform_2d_typed(&dequant, side, 8, TxType::AdstDct);
1623 let dct_adst = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctAdst);
1624 assert_ne!(
1625 adst_dct, dct_adst,
1626 "ADST_DCT and DCT_ADST must not be interchangeable on an asymmetric grid"
1627 );
1628 // Also distinct from plain DCT_DCT and ADST_ADST at the same input.
1629 let dct_dct = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctDct);
1630 let adst_adst = inverse_transform_2d_typed(&dequant, side, 8, TxType::AdstAdst);
1631 assert_ne!(adst_dct, dct_dct);
1632 assert_ne!(dct_adst, dct_dct);
1633 assert_ne!(adst_adst, dct_dct);
1634 }
1635
1636 /// The lane-recttx charter's asymmetric coefficient block (`coeff` in
1637 /// `lanes/recttx_dump.c`, which this pin was transcribed alongside): a
1638 /// DC of 640 plus a distinct row-weighted/col-weighted 4x4 corner, zero
1639 /// elsewhere, so a transposed axis produces a genuinely different
1640 /// checksum rather than a coincidentally equal one.
1641 fn recttx_coeff(w: usize, h: usize) -> Vec<i32> {
1642 let mut d = vec![0i32; w * h];
1643 for i in 0..h {
1644 for j in 0..w {
1645 d[i * w + j] = if i == 0 && j == 0 {
1646 640
1647 } else if i < 4 && j < 4 {
1648 (i as i32 + 1) * 24 - (j as i32 + 1) * 17
1649 } else {
1650 0
1651 };
1652 }
1653 }
1654 d
1655 }
1656
1657 fn weighted_checksum(residual: &[i32]) -> i64 {
1658 residual
1659 .iter()
1660 .enumerate()
1661 .map(|(idx, &v)| i64::from(v) * (idx as i64 + 1))
1662 .sum()
1663 }
1664
1665 /// Every one of the 14 rectangular sizes, DCT_DCT, `bit_depth = 8`,
1666 /// pinned against `lanes/recttx_dump.c` / `.expected.txt` -- a real
1667 /// libaom 1D-kernel-linked C harness, not a from-scratch reimplement.
1668 /// The transposed HxW twin runs in the SAME test (class
1669 /// `scan-weights-cross-axis`): a swapped-axis bug in
1670 /// `inverse_transform_2d_typed_wh` would either fail its own pin or
1671 /// accidentally match its twin's pin, and the two expected values here
1672 /// are deliberately different, so neither escape is possible.
1673 #[test]
1674 fn rect_sizes_pinned_against_libaom() {
1675 let cases: &[(usize, usize, i64)] = &[
1676 (4, 8, 7290),
1677 (8, 4, 7223),
1678 (8, 16, 56211),
1679 (16, 8, 56161),
1680 (16, 32, 893635),
1681 (32, 16, 893210),
1682 (32, 64, 14260693),
1683 (64, 32, 14265125),
1684 (4, 16, 20091),
1685 (16, 4, 20156),
1686 (8, 32, 159207),
1687 (32, 8, 159430),
1688 (16, 64, 2537255),
1689 (64, 16, 2548119),
1690 ];
1691 for &(w, h, expected) in cases {
1692 let dequant = recttx_coeff(w, h);
1693 let residual = inverse_transform_2d_typed_wh(&dequant, w, h, 8, TxType::DctDct);
1694 assert_eq!(
1695 weighted_checksum(&residual),
1696 expected,
1697 "{w}x{h} checksum mismatch"
1698 );
1699 }
1700 }
1701
1702 /// The square path must not move: `row_shift_wh(side, side)` reduces to
1703 /// the pre-lane `row_shift(log2)` table, and the `side`-taking wrapper
1704 /// must still equal the `(w, h)` core called with `w == h == side`.
1705 #[test]
1706 fn square_wrapper_matches_wh_core() {
1707 for side in [4, 8, 16, 32, 64] {
1708 let dequant = recttx_coeff(side, side);
1709 let via_wrapper = inverse_transform_2d_typed(&dequant, side, 8, TxType::DctDct);
1710 let via_wh = inverse_transform_2d_typed_wh(&dequant, side, side, 8, TxType::DctDct);
1711 assert_eq!(via_wrapper, via_wh, "side {side}");
1712 }
1713 }
1714}