forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

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