forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

transform.rs741 lines, 27.4 KiBHistoryRawDownload
1//! The inverse transform (spec 7.13), so the encoder can reconstruct exactly
2//! what a decoder will show.
3//!
4//! Only the inverse DCT is here, which is all this encoder's subset codes: a
5//! square `DCT_DCT` transform per block. The butterfly network is the spec's
6//! own, stage for stage — every stage's rounding and intermediate clamp is
7//! part of the bitstream contract, so a mathematically equal but differently
8//! rounded DCT would drift away from the decoder by a sample here and there.
9
10/// `Cos128_Lookup` (spec 7.13.2.1): `4096 * cos(angle * pi / 128)` rounded.
11static COS128_LOOKUP: [i32; 65] = [
12 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3996, 3973, 3948, 3920, 3889, 3857, 3822,
13 3784, 3745, 3703, 3659, 3612, 3564, 3513, 3461, 3406, 3349, 3290, 3229, 3166, 3102, 3035, 2967,
14 2896, 2824, 2751, 2675, 2598, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660,
15 1567, 1474, 1380, 1285, 1189, 1092, 995, 897, 799, 700, 601, 501, 401, 301, 201, 101, 0,
16];
17
18/// The fixed-point position of the cosine table.
19const COS_BITS: usize = 12;
20
21/// `cos128(angle)` (spec 7.13.2.1), folded from the quarter table.
22fn cos128(angle: i32) -> i32 {
23 let angle2 = (angle & 255) as usize;
24 match angle2 {
25 0..=64 => COS128_LOOKUP[angle2],
26 65..=128 => -COS128_LOOKUP[128 - angle2],
27 129..=192 => -COS128_LOOKUP[angle2 - 128],
28 _ => COS128_LOOKUP[256 - angle2],
29 }
30}
31
32/// `sin128(angle)` (spec 7.13.2.1).
33fn sin128(angle: i32) -> i32 {
34 cos128(angle - 64)
35}
36
37/// `brev(numBits, x)` (spec 7.13.2.1): the bit reversal of the low `num_bits`.
38fn brev(num_bits: u32, x: usize) -> usize {
39 (0..num_bits).fold(0, |t, i| t | (((x >> i) & 1) << (num_bits - 1 - i)))
40}
41
42/// `Round2(x, n)` (spec 4.7): shift down `n` places, rounding halves up.
43fn round2(x: i32, n: usize) -> i32 {
44 if n == 0 {
45 x
46 } else {
47 // The intermediate can exceed 32 bits before the shift brings it
48 // back, which is why it is done in 64.
49 ((i64::from(x) + (1i64 << (n - 1))) >> n) as i32
50 }
51}
52
53/// `Clip3` against a signed integer of `r` bits, which is what bounds every
54/// intermediate of the transform.
55fn clamp_range(x: i32, r: usize) -> i32 {
56 let hi = ((1i64 << (r - 1)) - 1) as i32;
57 let lo = (-(1i64 << (r - 1))) as i32;
58 x.clamp(lo, hi)
59}
60
61/// `B(a, b, angle, flip, r)` (spec 7.13.2.1): a butterfly rotation, and an
62/// exchange of the two entries when `flip` is set.
63fn butterfly(t: &mut [i32], a: usize, b: usize, angle: i32, flip: bool, _r: usize) {
64 let (ta, tb) = (i64::from(t[a]), i64::from(t[b]));
65 let (c, s) = (i64::from(cos128(angle)), i64::from(sin128(angle)));
66 let x = ta * c - tb * s;
67 let y = ta * s + tb * c;
68 t[a] = ((x + (1 << (COS_BITS - 1))) >> COS_BITS) as i32;
69 t[b] = ((y + (1 << (COS_BITS - 1))) >> COS_BITS) as i32;
70 if flip {
71 t.swap(a, b);
72 }
73}
74
75/// `H(a, b, flip, r)` (spec 7.13.2.1): a Hadamard rotation, with the indices
76/// exchanged when `flip` is set.
77fn hadamard(t: &mut [i32], a: usize, b: usize, flip: bool, r: usize) {
78 let (a, b) = if flip { (b, a) } else { (a, b) };
79 let (x, y) = (t[a], t[b]);
80 t[a] = clamp_range(x.wrapping_add(y), r);
81 t[b] = clamp_range(x.wrapping_sub(y), r);
82}
83
84/// The inverse DCT array permutation (spec 7.13.2.2): an in-place bit-reversal
85/// of the first `1 << n` entries.
86fn permute(t: &mut [i32], n: u32) {
87 let n0 = 1usize << n;
88 let copy: Vec<i32> = t[..n0].to_vec();
89 for (i, v) in t[..n0].iter_mut().enumerate() {
90 *v = copy[brev(n, i)];
91 }
92}
93
94/// The inverse DCT process (spec 7.13.2.3): an in-place inverse DCT of the
95/// first `1 << n` entries of `t`, clamping intermediates to `r` bits.
96///
97/// The stage list is the spec's, in the spec's order; the guards on `n` are
98/// what make one network serve every transform size from 4 to 64.
99pub fn inverse_dct(t: &mut [i32], n: u32, r: usize) {
100 assert!((2..=6).contains(&n), "the inverse DCT is defined for 4..64");
101 permute(t, n);
102
103 if n == 6 {
104 for i in 0..16 {
105 butterfly(t, 32 + i, 63 - i, 63 - 4 * brev(4, i) as i32, false, r);
106 }
107 }
108 if n >= 5 {
109 for i in 0..8 {
110 butterfly(
111 t,
112 16 + i,
113 31 - i,
114 6 + ((brev(3, 7 - i) as i32) << 3),
115 false,
116 r,
117 );
118 }
119 }
120 if n == 6 {
121 for i in 0..16 {
122 hadamard(t, 32 + i * 2, 33 + i * 2, i & 1 == 1, r);
123 }
124 }
125 if n >= 4 {
126 for i in 0..4 {
127 butterfly(
128 t,
129 8 + i,
130 15 - i,
131 12 + ((brev(2, 3 - i) as i32) << 4),
132 false,
133 r,
134 );
135 }
136 }
137 if n >= 5 {
138 for i in 0..8 {
139 hadamard(t, 16 + 2 * i, 17 + 2 * i, i & 1 == 1, r);
140 }
141 }
142 if n == 6 {
143 for i in 0..4 {
144 for j in 0..2 {
145 let angle = 60 - 16 * brev(2, i) as i32 + 64 * j as i32;
146 butterfly(t, 62 - i * 4 - j, 33 + i * 4 + j, angle, true, r);
147 }
148 }
149 }
150 if n >= 3 {
151 for i in 0..2 {
152 butterfly(t, 4 + i, 7 - i, 56 - 32 * i as i32, false, r);
153 }
154 }
155 if n >= 4 {
156 for i in 0..4 {
157 hadamard(t, 8 + 2 * i, 9 + 2 * i, i & 1 == 1, r);
158 }
159 }
160 if n >= 5 {
161 for i in 0..2 {
162 for j in 0..2 {
163 let angle = 24 + ((j as i32) << 6) + ((1 - i as i32) << 5);
164 butterfly(t, 30 - 4 * i - j, 17 + 4 * i + j, angle, true, r);
165 }
166 }
167 }
168 if n == 6 {
169 for i in 0..8 {
170 for j in 0..2 {
171 hadamard(t, 32 + i * 4 + j, 35 + i * 4 - j, i & 1 == 1, r);
172 }
173 }
174 }
175 for i in 0..2 {
176 butterfly(t, 2 * i, 2 * i + 1, 32 + 16 * i as i32, i == 0, r);
177 }
178 if n >= 3 {
179 for i in 0..2 {
180 hadamard(t, 4 + 2 * i, 5 + 2 * i, i == 1, r);
181 }
182 }
183 if n >= 4 {
184 for i in 0..2 {
185 butterfly(t, 14 - i, 9 + i, 48 + 64 * i as i32, true, r);
186 }
187 }
188 if n >= 5 {
189 for i in 0..4 {
190 for j in 0..2 {
191 hadamard(t, 16 + 4 * i + j, 19 + 4 * i - j, i & 1 == 1, r);
192 }
193 }
194 }
195 if n == 6 {
196 for i in 0..2 {
197 for j in 0..4 {
198 let angle = 56 - (i as i32) * 32 + ((j as i32) >> 1) * 64;
199 butterfly(t, 61 - i * 8 - j, 34 + i * 8 + j, angle, true, r);
200 }
201 }
202 }
203 for i in 0..2 {
204 hadamard(t, i, 3 - i, false, r);
205 }
206 if n >= 3 {
207 butterfly(t, 6, 5, 32, true, r);
208 }
209 if n >= 4 {
210 for i in 0..2 {
211 for j in 0..2 {
212 hadamard(t, 8 + 4 * i + j, 11 + 4 * i - j, i == 1, r);
213 }
214 }
215 }
216 if n >= 5 {
217 for i in 0..4 {
218 butterfly(t, 29 - i, 18 + i, 48 + ((i as i32) >> 1) * 64, true, r);
219 }
220 }
221 if n == 6 {
222 for i in 0..4 {
223 for j in 0..4 {
224 hadamard(t, 32 + 8 * i + j, 39 + 8 * i - j, i & 1 == 1, r);
225 }
226 }
227 }
228 if n >= 3 {
229 for i in 0..4 {
230 hadamard(t, i, 7 - i, false, r);
231 }
232 }
233 if n >= 4 {
234 for i in 0..2 {
235 butterfly(t, 13 - i, 10 + i, 32, true, r);
236 }
237 }
238 if n >= 5 {
239 for i in 0..2 {
240 for j in 0..4 {
241 hadamard(t, 16 + i * 8 + j, 23 + i * 8 - j, i == 1, r);
242 }
243 }
244 }
245 if n == 6 {
246 for i in 0..8 {
247 butterfly(t, 59 - i, 36 + i, if i < 4 { 48 } else { 112 }, true, r);
248 }
249 }
250 if n >= 4 {
251 for i in 0..8 {
252 hadamard(t, i, 15 - i, false, r);
253 }
254 }
255 if n >= 5 {
256 for i in 0..4 {
257 butterfly(t, 27 - i, 20 + i, 32, true, r);
258 }
259 }
260 if n == 6 {
261 for i in 0..8 {
262 hadamard(t, 32 + i, 47 - i, false, r);
263 hadamard(t, 48 + i, 63 - i, true, r);
264 }
265 }
266 if n >= 5 {
267 for i in 0..16 {
268 hadamard(t, i, 31 - i, false, r);
269 }
270 }
271 if n == 6 {
272 for i in 0..8 {
273 butterfly(t, 55 - i, 40 + i, 32, true, r);
274 }
275 }
276 if n == 6 {
277 for i in 0..32 {
278 hadamard(t, i, 63 - i, false, r);
279 }
280 }
281}
282
283/// `Transform_Row_Shift` (spec 7.13.3) for the square transforms.
284fn row_shift(log2: u32) -> usize {
285 match log2 {
286 2 => 0,
287 3 => 1,
288 _ => 2,
289 }
290}
291
292/// The 2D inverse transform (spec 7.13.3) for a square `DCT_DCT` block.
293///
294/// `dequant` is the dequantized coefficient grid in raster order; the returned
295/// residual is in the same order. A 64-point transform only ever carries
296/// coefficients in its first 32 rows and columns, and the spec zeroes the rest
297/// before the row transform, which is what the `< 32` guard does.
298pub fn inverse_transform_2d(dequant: &[i32], side: usize, bit_depth: u8) -> Vec<i32> {
299 let log2 = side.trailing_zeros();
300 assert_eq!(1usize << log2, side, "the transform is square");
301 assert_eq!(dequant.len(), side * side, "one coefficient per position");
302 let row_clamp = usize::from(bit_depth) + 8;
303 let col_clamp = (usize::from(bit_depth) + 6).max(16);
304 let mut residual = vec![0i32; side * side];
305
306 let mut t = [0i32; 64];
307 for i in 0..side {
308 for j in 0..side {
309 t[j] = if i < 32 && j < 32 {
310 dequant[i * side + j]
311 } else {
312 0
313 };
314 }
315 inverse_dct(&mut t, log2, row_clamp);
316 for j in 0..side {
317 // The row's output is shifted, then clamped before the column
318 // transform reads it back.
319 residual[i * side + j] = clamp_range(round2(t[j], row_shift(log2)), col_clamp);
320 }
321 }
322
323 for j in 0..side {
324 for i in 0..side {
325 t[i] = residual[i * side + j];
326 }
327 inverse_dct(&mut t, log2, col_clamp);
328 for i in 0..side {
329 residual[i * side + j] = round2(t[i], 4);
330 }
331 }
332 residual
333}
334
335/// Dequantize (spec 7.12.3) and inverse transform one square `DCT_DCT` block,
336/// returning its residual in raster order.
337///
338/// This is the encoder's model of what the decoder will add to its prediction,
339/// so it follows the spec's dequantization exactly, truncation toward zero and
340/// all.
341pub fn dequant_and_inverse(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i32> {
342 let dq = crate::quant::dequant(levels, side, bit_depth, q_idx);
343 inverse_transform_2d(&dq, side, bit_depth)
344}
345
346/// The orthonormal DCT-II basis row for output `u` of an `n`-point transform.
347///
348/// The decoder's network is this basis scaled by a constant the encoder has to
349/// undo, and nothing else: measuring the network's response to a unit
350/// coefficient at every size gives the same `1 / (8 * sqrt(2))` per unit of
351/// `dqDenom`, which is what [`forward_transform_2d`] divides out.
352fn build_dct_basis(n: usize) -> Vec<f64> {
353 let mut basis = vec![0.0f64; n * n];
354 let scale = (2.0 / n as f64).sqrt();
355 for u in 0..n {
356 let alpha = if u == 0 { 1.0 / 2.0f64.sqrt() } else { 1.0 };
357 for i in 0..n {
358 let angle = std::f64::consts::PI * (2.0 * i as f64 + 1.0) * u as f64 / (2.0 * n as f64);
359 basis[u * n + i] = alpha * scale * angle.cos();
360 }
361 }
362 basis
363}
364
365/// [`build_dct_basis`], computed once per transform size and reused: the
366/// search calls [`forward_transform_2d`] for every mode of every block, and
367/// the basis does not depend on the residual, only on `n` -- recomputing
368/// `n * n` cosines per call was measured as this search's single largest
369/// per-trial cost (`stage_timing_breakdown`, ec-av1 perf lane). `n` is always
370/// one of the transform sizes this crate codes (4 to 64, a power of two), so
371/// a small fixed table indexed by `log2(n)` covers every caller without a
372/// hash lookup.
373fn dct_basis(n: usize) -> &'static [f64] {
374 use std::sync::OnceLock;
375 // log2(4)=2 .. log2(64)=6, so index by trailing_zeros() - 2.
376 static CACHE: OnceLock<[OnceLock<Vec<f64>>; 5]> = OnceLock::new();
377 let cache = CACHE.get_or_init(|| std::array::from_fn(|_| OnceLock::new()));
378 let idx = (n.trailing_zeros() as usize).saturating_sub(2);
379 cache[idx].get_or_init(|| build_dct_basis(n))
380}
381
382/// How much the decoder's inverse transform shrinks an orthonormal DCT.
383///
384/// Measured, not asserted: feeding a single dequantized coefficient through
385/// `inverse_transform_2d` reproduces the orthonormal basis function scaled by
386/// `dq_denom(side) / 8` at every size (see `the_inverse_network_is_an_orthonormal_dct_over_eight`).
387/// The dequantizer has already divided by `dq_denom`, so the two cancel and
388/// what an encoder owes a level is size-independent:
389/// `level = 8 * orthonormal(residual) / q`.
390///
391/// The spec fixes the decoder; the encoder is free in how it reaches the
392/// coefficients it sends, and this constant is the one thing the two ends have
393/// to agree on for a level to mean what the encoder thinks it means.
394const INVERSE_GAIN_RECIPROCAL: f64 = 8.0;
395
396/// The forward transform (encoder side, spec-free): the transpose of what the
397/// decoder's inverse does, so that `inverse_transform_2d` of the result
398/// reproduces `residual`.
399///
400/// AV1 specifies only the inverse transform. The encoder may reach its
401/// coefficients however it likes, and this reaches them the direct way — an
402/// orthonormal DCT-II in double precision, scaled to the decoder's fixed-point
403/// gain. It is deterministic, and its accuracy is measured against the
404/// decoder's own inverse rather than asserted.
405pub fn forward_transform_2d(residual: &[i32], side: usize) -> Vec<f64> {
406 assert_eq!(
407 residual.len(),
408 side * side,
409 "one residual sample per position"
410 );
411 let basis = dct_basis(side);
412 // Rows first, into a scratch of the same shape, then columns. Both passes
413 // are written as a contiguous dot product (row of `residual`/`rows_t`
414 // against a row of `basis`) rather than an index loop with one strided
415 // operand -- same summation order, so the same bits out, but a shape the
416 // optimizer can autovectorize (measured: this halved the per-call cost
417 // that `stage_timing_breakdown`, ec-av1 perf lane, found dominant).
418 let mut rows = vec![0.0f64; side * side];
419 for i in 0..side {
420 let residual_row = &residual[i * side..][..side];
421 for u in 0..side {
422 let sum: f64 = residual_row
423 .iter()
424 .zip(&basis[u * side..][..side])
425 .map(|(&r, &b)| f64::from(r) * b)
426 .sum();
427 rows[i * side + u] = sum;
428 }
429 }
430 // Transposed so the column pass reads `rows` contiguously too, without
431 // changing which terms are summed in which order.
432 let mut rows_t = vec![0.0f64; side * side];
433 for i in 0..side {
434 for v in 0..side {
435 rows_t[v * side + i] = rows[i * side + v];
436 }
437 }
438 let mut out = vec![0.0f64; side * side];
439 for u in 0..side {
440 for v in 0..side {
441 let sum: f64 = rows_t[v * side..][..side]
442 .iter()
443 .zip(&basis[u * side..][..side])
444 .map(|(&r, &b)| r * b)
445 .sum();
446 out[u * side + v] = sum;
447 }
448 }
449 let scale = INVERSE_GAIN_RECIPROCAL;
450 for v in &mut out {
451 *v *= scale;
452 }
453 out
454}
455
456/// Quantize forward-transform coefficients into the levels the tile syntax
457/// carries.
458///
459/// `deadzone` is the fraction of a quantizer step a coefficient has to reach
460/// before it is coded at all, as a rounding offset: 0.5 rounds to nearest,
461/// smaller values pull coefficients toward zero, which is what buys the rate
462/// back on noisy content. A 64-point transform only carries its top-left
463/// 32x32, so everything outside that is dropped here rather than silently by
464/// the writer.
465pub fn quantize(coeffs: &[f64], side: usize, bit_depth: u8, q_idx: i32, deadzone: f64) -> Vec<i32> {
466 assert_eq!(coeffs.len(), side * side, "one coefficient per position");
467 let dc = f64::from(crate::quant::dc_q(bit_depth, q_idx));
468 let ac = f64::from(crate::quant::ac_q(bit_depth, q_idx));
469 let mut levels = vec![0i32; side * side];
470 for (i, &c) in coeffs.iter().enumerate() {
471 let (row, col) = (i / side, i % side);
472 if row >= 32 || col >= 32 {
473 continue;
474 }
475 let q = if i == 0 { dc } else { ac };
476 let scaled = c / q;
477 let magnitude = scaled.abs() + deadzone;
478 let level = if magnitude < 1.0 {
479 0
480 } else {
481 magnitude.floor().min(f64::from(i32::MAX)) as i32
482 };
483 levels[i] = if scaled < 0.0 { -level } else { level };
484 }
485 levels
486}
487
488/// Transform and quantize one block's residual, the encoder's half of the
489/// round trip [`dequant_and_inverse`] completes.
490pub fn forward_and_quantize(
491 residual: &[i32],
492 side: usize,
493 bit_depth: u8,
494 q_idx: i32,
495 deadzone: f64,
496) -> Vec<i32> {
497 let coeffs = forward_transform_2d(residual, side);
498 quantize(&coeffs, side, bit_depth, q_idx, deadzone)
499}
500
501#[cfg(test)]
502mod tests {
503 use super::*;
504
505 /// The orthonormal DCT-II basis the forward transform is written against,
506 /// computed independently of `dct_basis` so a test is not checking a
507 /// function against itself.
508 fn reference_basis(n: usize) -> Vec<f64> {
509 let mut c = vec![0.0; n * n];
510 for u in 0..n {
511 let alpha = if u == 0 { (0.5f64).sqrt() } else { 1.0 };
512 for x in 0..n {
513 let angle =
514 (2.0 * x as f64 + 1.0) * u as f64 * std::f64::consts::PI / (2.0 * n as f64);
515 c[u * n + x] = alpha * (2.0 / n as f64).sqrt() * angle.cos();
516 }
517 }
518 c
519 }
520
521 /// A deterministic pseudo-random residual in `-100..=100`.
522 fn noise(len: usize, seed: u64) -> Vec<i32> {
523 let mut state = seed;
524 (0..len)
525 .map(|_| {
526 state = state
527 .wrapping_mul(6_364_136_223_846_793_005)
528 .wrapping_add(1_442_695_040_888_963_407);
529 ((state >> 33) % 201) as i32 - 100
530 })
531 .collect()
532 }
533
534 fn rmse(a: &[i32], b: &[i32]) -> f64 {
535 let sum: f64 = a
536 .iter()
537 .zip(b)
538 .map(|(&x, &y)| f64::from(x - y) * f64::from(x - y))
539 .sum();
540 (sum / a.len() as f64).sqrt()
541 }
542
543 /// The one thing the encoder and the decoder have to agree on.
544 ///
545 /// The spec's inverse network is not documented as a scaled orthonormal
546 /// DCT, so this measures it: each dequantized coefficient, on its own,
547 /// comes back out as its orthonormal basis function scaled by
548 /// `dq_denom(side) / 8` — the same factor for every coefficient of a
549 /// size, which is what makes a single constant enough for the encoder.
550 /// The fit is checked as well as the scale, so an inverse that scaled
551 /// right but mixed positions apart could not pass.
552 #[test]
553 fn the_inverse_network_is_an_orthonormal_dct_over_eight() {
554 for &side in &[4usize, 8, 16, 32, 64] {
555 let basis = reference_basis(side);
556 for &(u, v) in &[(0usize, 0usize), (0, 1), (1, 0), (2, 3), (5, 7)] {
557 if u >= side || v >= side {
558 continue;
559 }
560 let mut coeffs = vec![0i32; side * side];
561 coeffs[u * side + v] = 4096;
562 let got = inverse_transform_2d(&coeffs, side, 8);
563 let want: Vec<f64> = (0..side * side)
564 .map(|i| 4096.0 * basis[u * side + i / side] * basis[v * side + i % side])
565 .collect();
566 // Least-squares fit of one scale over the whole block.
567 let num: f64 = want.iter().zip(&got).map(|(w, &g)| w * f64::from(g)).sum();
568 let den: f64 = want.iter().map(|w| w * w).sum();
569 let k = num / den;
570 let expected = crate::quant::dq_denom(side) as f64 / 8.0;
571 assert!(
572 (k - expected).abs() < 0.01 * expected,
573 "{side}x{side} ({u},{v}): gain {k}, expected {expected}"
574 );
575 // And the block really is that basis function, not merely a
576 // block of the same energy: no sample off by more than one.
577 for (i, (w, &g)) in want.iter().zip(&got).enumerate() {
578 let scaled = k * w;
579 assert!(
580 (scaled - f64::from(g)).abs() <= 1.0,
581 "{side}x{side} ({u},{v}) sample {i}: {g} vs {scaled}"
582 );
583 }
584 }
585 }
586 }
587
588 /// A fine quantizer costs almost nothing: forward, quantize, dequantize
589 /// and invert returns the residual to within a sample or two at every
590 /// transform size the spec's DCT covers.
591 ///
592 /// 64x64 is excluded here because it cannot carry a white-noise residual
593 /// at all — see
594 /// [`a_64x64_transform_keeps_what_fits_in_its_coded_quarter`].
595 #[test]
596 fn a_fine_quantizer_roundtrips_a_residual_almost_exactly() {
597 for &side in &[4usize, 8, 16, 32] {
598 let residual = noise(side * side, 12_345 + side as u64);
599 let levels = forward_and_quantize(&residual, side, 8, 10, 0.5);
600 let back = dequant_and_inverse(&levels, side, 8, 10);
601 let error = rmse(&back, &residual);
602 assert!(error < 1.0, "{side}x{side}: rmse {error}");
603 }
604 }
605
606 /// Error grows with the quantizer and with nothing else. A calibration
607 /// that is off by a constant factor shows up here as a floor that a finer
608 /// quantizer cannot get under — which is exactly what a wrong gain
609 /// constant produced while this was being written.
610 #[test]
611 fn the_roundtrip_error_is_the_quantizer_and_only_the_quantizer() {
612 for &side in &[4usize, 8, 16, 32] {
613 let residual = noise(side * side, 999 + side as u64);
614 let mut previous = 0.0;
615 for &q_idx in &[10i32, 60, 100, 180] {
616 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
617 let back = dequant_and_inverse(&levels, side, 8, q_idx);
618 let error = rmse(&back, &residual);
619 assert!(
620 error > previous,
621 "{side}x{side} q {q_idx}: {error} <= {previous}"
622 );
623 // A quantizer step is q/8 in residual units, and rounding to
624 // nearest costs no more than half a step per coefficient.
625 let step = f64::from(crate::quant::ac_q(8, q_idx)) / 8.0;
626 assert!(
627 error < step,
628 "{side}x{side} q {q_idx}: rmse {error}, step {step}"
629 );
630 previous = error;
631 }
632 }
633 }
634
635 /// A 64x64 transform codes only its top-left 32x32 coefficients, so it
636 /// keeps everything below half the Nyquist rate in each direction and
637 /// drops the rest. A band-limited residual survives it; white noise loses
638 /// the three quarters of its energy that live outside the coded quarter,
639 /// and that loss is the transform's, not the quantizer's — it does not
640 /// move when the quantizer does.
641 #[test]
642 fn a_64x64_transform_keeps_what_fits_in_its_coded_quarter() {
643 let side = 64;
644 // Band-limited: built from basis functions inside the coded quarter.
645 let basis = reference_basis(side);
646 let mut smooth = vec![0.0f64; side * side];
647 for &(u, v, amplitude) in &[(0usize, 0usize, 900.0f64), (1, 2, 400.0), (9, 30, 250.0)] {
648 for i in 0..side * side {
649 smooth[i] += amplitude * basis[u * side + i / side] * basis[v * side + i % side];
650 }
651 }
652 let smooth: Vec<i32> = smooth.iter().map(|&s| s.round() as i32).collect();
653 let levels = forward_and_quantize(&smooth, side, 8, 10, 0.5);
654 let back = dequant_and_inverse(&levels, side, 8, 10);
655 let kept = rmse(&back, &smooth);
656 assert!(kept < 1.5, "band-limited 64x64: rmse {kept}");
657
658 let residual = noise(side * side, 4_242);
659 let mut errors = Vec::new();
660 for &q_idx in &[10i32, 180] {
661 let levels = forward_and_quantize(&residual, side, 8, q_idx, 0.5);
662 let back = dequant_and_inverse(&levels, side, 8, q_idx);
663 errors.push(rmse(&back, &residual));
664 }
665 // Three quarters of a white-noise block's energy is outside the coded
666 // quarter, so the error is sqrt(3/4) of the residual's own magnitude
667 // whatever the quantizer does.
668 let magnitude = rmse(&residual, &vec![0; side * side]);
669 for error in &errors {
670 let ratio = error / magnitude;
671 assert!(
672 (ratio - 0.75f64.sqrt()).abs() < 0.05,
673 "64x64 white noise: ratio {ratio}"
674 );
675 }
676 assert!(
677 (errors[1] - errors[0]).abs() < 0.05 * errors[0],
678 "64x64 white noise moved with the quantizer: {errors:?}"
679 );
680 }
681
682 /// The deadzone pulls coefficients toward zero: a wider one codes fewer
683 /// of them and costs more error, and rounding to nearest is the tightest
684 /// of them.
685 #[test]
686 fn a_wider_deadzone_codes_fewer_coefficients() {
687 let side = 16;
688 let residual = noise(side * side, 77);
689 let mut previous_nonzero = usize::MAX;
690 let mut previous_error = 0.0;
691 for &deadzone in &[0.5f64, 0.35, 0.2] {
692 let levels = forward_and_quantize(&residual, side, 8, 100, deadzone);
693 let back = dequant_and_inverse(&levels, side, 8, 100);
694 let nonzero = levels.iter().filter(|&&l| l != 0).count();
695 let error = rmse(&back, &residual);
696 assert!(
697 nonzero < previous_nonzero,
698 "deadzone {deadzone}: {nonzero} coefficients"
699 );
700 assert!(error > previous_error, "deadzone {deadzone}: rmse {error}");
701 previous_nonzero = nonzero;
702 previous_error = error;
703 }
704 }
705
706 /// Negating a residual negates its levels: the forward transform carries
707 /// no offset of its own.
708 #[test]
709 fn negating_the_residual_negates_every_level() {
710 for &side in &[4usize, 32] {
711 let residual = noise(side * side, 5_150 + side as u64);
712 let negated: Vec<i32> = residual.iter().map(|&r| -r).collect();
713 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
714 let other = forward_and_quantize(&negated, side, 8, 100, 0.5);
715 for (i, (a, b)) in levels.iter().zip(&other).enumerate() {
716 assert_eq!(*a, -*b, "{side}x{side} coefficient {i}");
717 }
718 }
719 }
720
721 /// A flat residual is a DC level and nothing else, at the value the
722 /// dequantizer's own arithmetic asks for.
723 #[test]
724 fn a_flat_residual_is_a_dc_level_alone() {
725 for &side in &[4usize, 8, 16, 32, 64] {
726 let residual = vec![40i32; side * side];
727 let levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
728 for (i, &level) in levels.iter().enumerate() {
729 if i == 0 {
730 // level = 8 * (40 * side) / dc_q, the orthonormal DC of a
731 // flat block being its value times the side.
732 let want = (8.0 * 40.0 * side as f64 / f64::from(crate::quant::dc_q(8, 100)))
733 .round() as i32;
734 assert_eq!(level, want, "{side}x{side} DC");
735 } else {
736 assert_eq!(level, 0, "{side}x{side} coefficient {i}");
737 }
738 }
739 }
740 }
741}