forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB58b009bTahinli2 months ago2045 commits

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