forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

transform.rs657 lines, 25.4 KiBHistoryRawDownload
1//! The integer transforms and the quantizer (8.6.2 - 8.6.4).
2//!
3//! The *inverse* path here is normative: a decoder does exactly this, so the
4//! encoder's reconstruction runs the same code and is bit-identical to what any
5//! conformant decoder produces. The forward path and the quantizer are the
6//! encoder's own choice; what makes them correct is that they invert the
7//! normative path — which is what [`tests::round_trip_recovers_flat_blocks`]
8//! and the the oracle conformance test in `tests/` check.
9//!
10//! One transcription safeguard is worth naming: only the first 16 columns of the
11//! 32x32 matrix are typed in. The rest follow from `M[m][31 - n] = (-1)^m M[m][n]`,
12//! which the spec's own second half satisfies, and a test asserts that half back
13//! entry by entry. A wrong column is the classic defect in this kind of table
14//! (it cost this family a week in H.264), so the table is checked against
15//! orthogonality as well as against the printed values.
16
17/// Columns 0..15 of `transMatrix` (8-319), rows 0..31.
18///
19/// The size-N transform uses rows `k * (32 / N)` and columns `0..N`.
20#[rustfmt::skip]
21const TRANS_MATRIX_HALF: [[i32; 16]; 32] = [
22 [64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
23 [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4],
24 [90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90],
25 [90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13],
26 [89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89],
27 [88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22],
28 [87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87],
29 [85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31],
30 [83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83],
31 [82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38],
32 [80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80],
33 [78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46],
34 [75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75],
35 [73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54],
36 [70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70],
37 [67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61],
38 [64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64],
39 [61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67],
40 [57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57],
41 [54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73],
42 [50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50],
43 [46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78],
44 [43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43],
45 [38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82],
46 [36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36],
47 [31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85],
48 [25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25],
49 [22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88],
50 [18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18],
51 [13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90],
52 [9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9],
53 [4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90],
54];
55
56/// `transMatrix` for `trType = 1`: the 4x4 DST used for luma intra 4x4 blocks
57/// (8-316).
58#[rustfmt::skip]
59const DST_MATRIX: [[i32; 4]; 4] = [
60 [29, 55, 74, 84],
61 [74, 74, 0, -74],
62 [84, -29, -74, 55],
63 [55, -84, 74, -29],
64];
65
66/// `M[m][n]` of the 32-point matrix, mirrored out of the stored half.
67#[inline]
68const fn m32(row: usize, col: usize) -> i32 {
69 if col < 16 {
70 TRANS_MATRIX_HALF[row][col]
71 } else if row % 2 == 0 {
72 TRANS_MATRIX_HALF[row][31 - col]
73 } else {
74 -TRANS_MATRIX_HALF[row][31 - col]
75 }
76}
77
78/// The full 32x32 matrix, mirrored out at compile time so the hot butterfly
79/// loops below index a flat table instead of taking [`m32`]'s per-element
80/// branch: same values (this *is* [`m32`], evaluated ahead of time), fewer
81/// instructions per multiply-add.
82const fn build_full_matrix() -> [[i32; 32]; 32] {
83 let mut out = [[0i32; 32]; 32];
84 let mut row = 0;
85 while row < 32 {
86 let mut col = 0;
87 while col < 32 {
88 out[row][col] = m32(row, col);
89 col += 1;
90 }
91 row += 1;
92 }
93 out
94}
95const FULL_MATRIX: [[i32; 32]; 32] = build_full_matrix();
96
97/// [`FULL_MATRIX`] transposed: `FULL_MATRIX_T[col][row] == FULL_MATRIX[row][col]`.
98/// [`inverse_1d`]'s odd sum walks a fixed column across varying rows, which
99/// this makes a contiguous read.
100const fn transpose(m: &[[i32; 32]; 32]) -> [[i32; 32]; 32] {
101 let mut out = [[0i32; 32]; 32];
102 let mut row = 0;
103 while row < 32 {
104 let mut col = 0;
105 while col < 32 {
106 out[col][row] = m[row][col];
107 col += 1;
108 }
109 row += 1;
110 }
111 out
112}
113const FULL_MATRIX_T: [[i32; 32]; 32] = transpose(&FULL_MATRIX);
114
115/// `levelScale[k]`, 8.6.3.
116const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72];
117
118/// The quantizer's reciprocal of [`LEVEL_SCALE`], `round(2^20 / levelScale)`.
119///
120/// Derived rather than transcribed: the product of the two is 2^20 to within a
121/// count, which is the whole design of the HEVC quantizer, and
122/// [`tests::quant_scale_is_the_reciprocal`] holds it to that.
123const QUANT_SCALE: [i32; 6] = [26_214, 23_302, 20_560, 18_396, 16_384, 14_564];
124
125/// Largest and smallest coefficient a Main-profile decoder may hold (`CoeffMin`,
126/// `CoeffMax` for `extended_precision_processing_flag = 0`).
127const COEFF_MIN: i32 = -32_768;
128const COEFF_MAX: i32 = 32_767;
129
130/// Dot product of two equal-length slices, SIMD in 8-wide chunks with a
131/// scalar tail.
132///
133/// Both `forward_1d` and `inverse_1d`'s odd sums are `sum_j m[j] * x[j]` over
134/// at most 16 terms; matrix entries are `|m| <= 90` and `x` is a coefficient
135/// or residual sample clamped to `COEFF_MIN..=COEFF_MAX` (+/-32768), so each
136/// product is bounded by ~3.0e6 and the full sum of 16 by ~4.7e7 — nowhere
137/// near overflowing i32, whether accumulated in one lane or spread across
138/// eight and reduced at the end.
139#[inline]
140fn dot(a: &[i32], b: &[i32]) -> i32 {
141 debug_assert_eq!(a.len(), b.len());
142 let mut acc = wide::i32x8::splat(0);
143 let mut i = 0;
144 while i + 8 <= a.len() {
145 let av = wide::i32x8::from(<[i32; 8]>::try_from(&a[i..i + 8]).unwrap());
146 let bv = wide::i32x8::from(<[i32; 8]>::try_from(&b[i..i + 8]).unwrap());
147 acc += av * bv;
148 i += 8;
149 }
150 let mut total: i32 = acc.to_array().iter().sum();
151 for j in i..a.len() {
152 total += a[j] * b[j];
153 }
154 total
155}
156
157/// One-dimensional inverse transform, `y[i] = sum_j M[j][i] * x[j]`.
158///
159/// Split even/odd once per level: the even rows of the size-N matrix *are* the
160/// size-N/2 matrix, so the recursion costs ~N^2/3 multiplies where the plain
161/// product costs N^2.
162fn inverse_1d(n: usize, src: &[i32], dst: &mut [i32]) {
163 if n == 1 {
164 dst[0] = 64 * src[0];
165 return;
166 }
167 let half = n / 2;
168 let stride = 32 / n;
169 let mut even_src = [0i32; 16];
170 for j in 0..half {
171 even_src[j] = src[2 * j];
172 }
173 let mut even = [0i32; 16];
174 inverse_1d(half, &even_src[..half], &mut even[..half]);
175 // `src[2 * j + 1]` doesn't depend on `x`: gather it once instead of once
176 // per `x` (it was being re-read `half` times over).
177 let mut odd_src = [0i32; 16];
178 for j in 0..half {
179 odd_src[j] = src[2 * j + 1];
180 }
181 for x in 0..half {
182 let matrix_col = &FULL_MATRIX_T[x];
183 let mut odd_matrix = [0i32; 16];
184 for j in 0..half {
185 odd_matrix[j] = matrix_col[(2 * j + 1) * stride];
186 }
187 let odd = dot(&odd_matrix[..half], &odd_src[..half]);
188 dst[x] = even[x] + odd;
189 dst[n - 1 - x] = even[x] - odd;
190 }
191}
192
193/// One-dimensional forward transform, `c[k] = sum_x M[k][x] * src[x]`.
194fn forward_1d(n: usize, src: &[i32], dst: &mut [i32]) {
195 if n == 1 {
196 dst[0] = 64 * src[0];
197 return;
198 }
199 let half = n / 2;
200 let stride = 32 / n;
201 let mut sums = [0i32; 16];
202 let mut diffs = [0i32; 16];
203 for (x, (sum, diff)) in sums[..half]
204 .iter_mut()
205 .zip(diffs[..half].iter_mut())
206 .enumerate()
207 {
208 *sum = src[x] + src[n - 1 - x];
209 *diff = src[x] - src[n - 1 - x];
210 }
211 let mut even = [0i32; 16];
212 forward_1d(half, &sums[..half], &mut even[..half]);
213 for j in 0..half {
214 dst[2 * j] = even[j];
215 let matrix_row = &FULL_MATRIX[(2 * j + 1) * stride];
216 dst[2 * j + 1] = dot(&matrix_row[..half], &diffs[..half]);
217 }
218}
219
220/// Forward 4x4 DST (the inverse of the normative `trType = 1` transform).
221fn forward_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
222 for (k, out) in dst.iter_mut().enumerate() {
223 *out = (0..4).map(|x| DST_MATRIX[k][x] * src[x]).sum();
224 }
225}
226
227/// Inverse 4x4 DST, `y[i] = sum_j M[j][i] * x[j]` (8-315).
228fn inverse_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
229 for (i, out) in dst.iter_mut().enumerate() {
230 *out = (0..4).map(|j| DST_MATRIX[j][i] * src[j]).sum();
231 }
232}
233
234/// True when a block takes the DST: luma, intra, 4x4 (8.6.4.1).
235pub fn uses_dst(size: usize, is_luma: bool) -> bool {
236 is_luma && size == 4
237}
238
239/// Forward transform of an `n x n` residual block into coefficients.
240///
241/// `residual` and `coeffs` are both row-major `n x n`; `coeffs[v * n + k]` is
242/// vertical frequency `v`, horizontal frequency `k`, which is the order the
243/// scans and the residual coder index.
244pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) {
245 let log2n = n.trailing_zeros() as i32;
246 // 8-bit input: shift1 = log2N + bitDepth - 9, shift2 = log2N + 6. Together
247 // they leave the DC at 128 x the mean residual whatever the block size,
248 // which is what the dequantiser's shift assumes.
249 let shift1 = log2n - 1;
250 let shift2 = log2n + 6;
251 let round1 = 1 << (shift1 - 1);
252 let round2 = 1 << (shift2 - 1);
253 let mut tmp = [0i32; 32 * 32];
254 let mut row = [0i32; 32];
255 let mut out = [0i32; 32];
256 for y in 0..n {
257 row[..n].copy_from_slice(&residual[y * n..y * n + n]);
258 if dst_type {
259 let mut src4 = [0i32; 4];
260 src4.copy_from_slice(&row[..4]);
261 let mut dst4 = [0i32; 4];
262 forward_dst4(&src4, &mut dst4);
263 out[..4].copy_from_slice(&dst4);
264 } else {
265 forward_1d(n, &row[..n], &mut out[..n]);
266 }
267 // Transposed store: the second pass then runs over what were columns.
268 for (k, &value) in out[..n].iter().enumerate() {
269 tmp[k * n + y] = (value + round1) >> shift1;
270 }
271 }
272 for k in 0..n {
273 row[..n].copy_from_slice(&tmp[k * n..k * n + n]);
274 if dst_type {
275 let mut src4 = [0i32; 4];
276 src4.copy_from_slice(&row[..4]);
277 let mut dst4 = [0i32; 4];
278 forward_dst4(&src4, &mut dst4);
279 out[..4].copy_from_slice(&dst4);
280 } else {
281 forward_1d(n, &row[..n], &mut out[..n]);
282 }
283 for (v, &value) in out[..n].iter().enumerate() {
284 coeffs[v * n + k] = (value + round2) >> shift2;
285 }
286 }
287}
288
289/// `bdShift` (8-299) at 8-bit: 20 - BitDepth.
290const BD_SHIFT: i32 = 12;
291
292/// Inverse transform of scaled coefficients into residual samples, exactly as
293/// clause 8.6.4 specifies including its intermediate clipping.
294pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) {
295 let mut e = [0i32; 32 * 32];
296 let mut col = [0i32; 32];
297 let mut out = [0i32; 32];
298 // Stage 1: every column, i.e. along the vertical frequency index.
299 for k in 0..n {
300 let mut any = false;
301 for y in 0..n {
302 col[y] = scaled[y * n + k];
303 any |= col[y] != 0;
304 }
305 if !any {
306 // A column of zeros transforms to zeros; most columns of a coded
307 // block are zeros, which is what quantisation is for.
308 for y in 0..n {
309 e[y * n + k] = 0;
310 }
311 continue;
312 }
313 if dst_type {
314 let mut src4 = [0i32; 4];
315 src4.copy_from_slice(&col[..4]);
316 let mut dst4 = [0i32; 4];
317 inverse_dst4(&src4, &mut dst4);
318 out[..4].copy_from_slice(&dst4);
319 } else {
320 inverse_1d(n, &col[..n], &mut out[..n]);
321 }
322 for y in 0..n {
323 e[y * n + k] = ((out[y] + 64) >> 7).clamp(COEFF_MIN, COEFF_MAX);
324 }
325 }
326 // Stage 2: every row, then the bit-depth shift (8-299).
327 let round = 1 << (BD_SHIFT - 1);
328 for y in 0..n {
329 col[..n].copy_from_slice(&e[y * n..y * n + n]);
330 if dst_type {
331 let mut src4 = [0i32; 4];
332 src4.copy_from_slice(&col[..4]);
333 let mut dst4 = [0i32; 4];
334 inverse_dst4(&src4, &mut dst4);
335 out[..4].copy_from_slice(&dst4);
336 } else {
337 inverse_1d(n, &col[..n], &mut out[..n]);
338 }
339 for x in 0..n {
340 residual[y * n + x] = (out[x] + round) >> BD_SHIFT;
341 }
342 }
343}
344
345/// Forward transform skip (8.6.2): no transform at all, the residual samples
346/// standing in for coefficients.
347///
348/// The decoder scales what it reads by `tsShift = 5 + Log2(nTbS)` and then
349/// takes the bit-depth shift of 20 - 8 off it again, so a coefficient has to
350/// carry the residual scaled by the difference for the round trip to return
351/// the sample it started from — a factor of 32 at 4x4, the same gain the
352/// integer transform leaves behind.
353pub fn forward_transform_skip(residual: &[i32], coeffs: &mut [i32], n: usize) {
354 let shift = BD_SHIFT - (5 + n.trailing_zeros() as i32);
355 for (i, &r) in residual[..n * n].iter().enumerate() {
356 coeffs[i] = r << shift;
357 }
358}
359
360/// Inverse transform skip (8.6.2): the scaled coefficient shifted up by
361/// `tsShift` and then down by the bit-depth shift, exactly as the decoder
362/// does it, so the encoder reconstructs the samples the decoder will.
363pub fn inverse_transform_skip(scaled: &[i32], residual: &mut [i32], n: usize) {
364 let ts_shift = 5 + n.trailing_zeros() as i32;
365 let round = 1i32 << (BD_SHIFT - 1);
366 for (i, &d) in scaled[..n * n].iter().enumerate() {
367 residual[i] = ((d.clamp(COEFF_MIN, COEFF_MAX) << ts_shift) + round) >> BD_SHIFT;
368 }
369}
370
371/// Quantise coefficients in place, returning the number of non-zero levels.
372///
373/// The rounding offset is a third of a step, which is the intra bias every
374/// encoder in this class uses: it costs a little distortion at the rounding
375/// boundary and buys back more in rate.
376pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize {
377 quantize_offset(coeffs, levels, n, qp, 3)
378}
379
380/// [`quantize`] with the rounding written out: `dead_zone` is the divisor of
381/// the quantiser step the rounding offset is, so 3 is the intra default and 2
382/// is round-to-nearest.
383///
384/// A rate-distortion search over the levels wants the wider rounding: a search
385/// that only ever takes levels down measures the rounding it started from, not
386/// its own decisions.
387pub fn quantize_offset(
388 coeffs: &[i32],
389 levels: &mut [i32],
390 n: usize,
391 qp: i32,
392 dead_zone: i64,
393) -> usize {
394 let log2n = n.trailing_zeros() as i32;
395 let qbits = 21 + qp / 6 - log2n;
396 let scale = QUANT_SCALE[(qp % 6) as usize] as i64;
397 let offset = (1i64 << qbits) / dead_zone;
398 // `scale` <= 26_214 and `|coeffs[i]|` <= 32_768 (COEFF_MIN/MAX), and qp is
399 // clamped to 0..=51 (crates/ec-h265/src/encoder.rs), so
400 // `abs(c) * scale + offset` never exceeds ~1e9: it fits in i32 without
401 // overflow, which is what lets this run in 32-bit SIMD lanes and still be
402 // the exact same integer as the scalar i64 computation below.
403 debug_assert!(scale <= i64::from(i32::MAX) && offset <= i64::from(i32::MAX));
404 let scale32 = scale as i32;
405 let offset32 = offset as i32;
406 let mut nonzero = 0;
407 let coeffs = &coeffs[..n * n];
408 let mut i = 0;
409 while i + 8 <= coeffs.len() {
410 let c = wide::i32x8::from(<[i32; 8]>::try_from(&coeffs[i..i + 8]).unwrap());
411 let mag =
412 ((c.abs() * scale32 + offset32) >> (qbits as u32)).min(wide::i32x8::splat(COEFF_MAX));
413 let level = c.simd_lt(wide::i32x8::splat(0)).select(-mag, mag);
414 for (j, &lv) in level.to_array().iter().enumerate() {
415 levels[i + j] = lv;
416 if lv != 0 {
417 nonzero += 1;
418 }
419 }
420 i += 8;
421 }
422 for j in i..coeffs.len() {
423 let c = coeffs[j];
424 let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32;
425 let level = magnitude.min(COEFF_MAX);
426 levels[j] = if c < 0 { -level } else { level };
427 if level != 0 {
428 nonzero += 1;
429 }
430 }
431 nonzero
432}
433
434/// The unrounded level a coefficient would quantise to: the quantiser divides
435/// by a step, and this is that division carried out in full precision. Sign
436/// data hiding needs it to tell which coefficient is cheapest to nudge.
437pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 {
438 let log2n = n.trailing_zeros() as i32;
439 let qbits = 21 + qp / 6 - log2n;
440 let scale = QUANT_SCALE[(qp % 6) as usize] as f64;
441 (coeff.unsigned_abs() as f64 * scale) / (1u64 << qbits) as f64
442}
443
444/// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
445pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
446 for (i, &level) in levels[..n * n].iter().enumerate() {
447 scaled[i] = dequant_level(level, n, qp);
448 }
449}
450
451/// One level scaled back to a coefficient, the per-coefficient half of
452/// [`dequantize`]. A rate-distortion search over the levels prices one
453/// coefficient at a time and has no use for the whole block.
454pub fn dequant_level(level: i32, n: usize, qp: i32) -> i32 {
455 let log2n = n.trailing_zeros() as i32;
456 let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit
457 let round = 1i64 << (bd_shift - 1);
458 let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64;
459 let shift = qp / 6;
460 let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
461 value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32
462}
463
464/// What a squared error in the transform domain is worth as a squared error in
465/// the sample domain.
466///
467/// The forward transform's shifts leave the DC at 128 times the mean residual
468/// whatever the block size, where an orthonormal transform would leave it at
469/// `n` times; the transform is otherwise orthogonal, so coefficient error
470/// energy is `(128 / n)^2` times sample error energy and this undoes it. A
471/// rate-distortion search over the levels needs it to weigh transform-domain
472/// error against a lambda calibrated on samples.
473pub fn coeff_ssd_scale(n: usize) -> f64 {
474 (n * n) as f64 / (128.0 * 128.0)
475}
476
477/// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset.
478pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 {
479 let qpi = (qp_luma + offset).clamp(0, 57);
480 if qpi < 30 {
481 qpi
482 } else if qpi > 43 {
483 qpi - 6
484 } else {
485 const TABLE: [i32; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
486 TABLE[(qpi - 30) as usize]
487 }
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 #[test]
495 fn mirrored_half_matches_the_spec_second_table() {
496 // Spot values from transMatrixCol16to31 (8-321): row, column, value.
497 let spec: &[(usize, usize, i32)] = &[
498 (0, 16, 64),
499 (0, 31, 64),
500 (1, 16, -4),
501 (1, 31, -90),
502 (2, 16, -90),
503 (2, 31, 90),
504 (3, 16, 13),
505 (3, 23, 73),
506 (4, 16, 89),
507 (8, 16, 83),
508 (16, 16, 64),
509 (16, 17, -64),
510 (31, 16, 90),
511 (31, 31, -4),
512 (30, 16, -9),
513 (29, 31, -13),
514 ];
515 for &(row, col, value) in spec {
516 assert_eq!(m32(row, col), value, "M[{row}][{col}]");
517 }
518 }
519
520 #[test]
521 fn matrix_rows_are_orthogonal() {
522 // Every size's rows: orthogonal, and all of equal norm. A single mistyped
523 // entry breaks both.
524 for log2n in 2..=5u32 {
525 let n = 1usize << log2n;
526 let stride = 32 / n;
527 let norm: i32 = (0..n).map(|x| m32(0, x) * m32(0, x)).sum();
528 for a in 0..n {
529 let self_dot: i32 = (0..n)
530 .map(|x| m32(a * stride, x) * m32(a * stride, x))
531 .sum();
532 // 64^2 * n is exact for the DC row; the others are within the
533 // rounding the integer matrix carries.
534 assert!(
535 (self_dot - norm).abs() * 200 < norm,
536 "row {a} of {n}: norm {self_dot} vs {norm}"
537 );
538 for b in a + 1..n {
539 let dot: i32 = (0..n)
540 .map(|x| m32(a * stride, x) * m32(b * stride, x))
541 .sum();
542 assert!(dot.abs() * 100 < norm, "rows {a},{b} of {n}: dot {dot}");
543 }
544 }
545 }
546 }
547
548 #[test]
549 fn quant_scale_is_the_reciprocal() {
550 for k in 0..6 {
551 let product = QUANT_SCALE[k] as i64 * LEVEL_SCALE[k] as i64;
552 assert!((product - (1 << 20)).abs() < 64, "k={k}: {product}");
553 assert_eq!(
554 QUANT_SCALE[k],
555 ((1 << 20) as f64 / LEVEL_SCALE[k] as f64).round() as i32
556 );
557 }
558 }
559
560 fn round_trip(residual: &[i32], n: usize, qp: i32, dst: bool) -> Vec<i32> {
561 let mut coeffs = vec![0i32; n * n];
562 forward_transform(residual, &mut coeffs, n, dst);
563 let mut levels = vec![0i32; n * n];
564 quantize(&coeffs, &mut levels, n, qp);
565 let mut scaled = vec![0i32; n * n];
566 dequantize(&levels, &mut scaled, n, qp);
567 let mut out = vec![0i32; n * n];
568 inverse_transform(&scaled, &mut out, n, dst);
569 out
570 }
571
572 #[test]
573 fn round_trip_recovers_flat_blocks() {
574 // A constant residual stays constant at any QP — only the DC level
575 // survives — and at low QP it comes back to its own value. At QP 40 one
576 // level step *is* 16 samples, so accuracy is asserted where accuracy is
577 // on offer and flatness everywhere.
578 for &n in &[4usize, 8, 16, 32] {
579 for &qp in &[0i32, 12, 22, 27, 40, 51] {
580 let residual = vec![20i32; n * n];
581 let out = round_trip(&residual, n, qp, false);
582 assert!(out.iter().all(|&v| v == out[0]), "n={n} qp={qp}: {out:?}");
583 if qp <= 22 {
584 assert!((out[0] - 20).abs() <= 2, "n={n} qp={qp}: {}", out[0]);
585 }
586 }
587 }
588 }
589
590 #[test]
591 fn round_trip_is_near_lossless_at_low_qp() {
592 // A textured block at QP 4 comes back within a sample or two; this is
593 // what proves the forward transform is the inverse of the normative one
594 // rather than merely self-consistent.
595 for &n in &[4usize, 8, 16, 32] {
596 for dst in [false, true] {
597 if dst && n != 4 {
598 continue;
599 }
600 let residual: Vec<i32> =
601 (0..n * n).map(|i| (((i * 37) % 61) as i32) - 30).collect();
602 let out = round_trip(&residual, n, 4, dst);
603 let worst = residual
604 .iter()
605 .zip(&out)
606 .map(|(a, b)| (a - b).abs())
607 .max()
608 .unwrap();
609 assert!(worst <= 3, "n={n} dst={dst}: worst {worst}");
610 }
611 }
612 }
613
614 /// Transform skip is only a pair of shifts, so the pair has to be exact:
615 /// what the encoder writes as a coefficient must come back as the residual
616 /// sample it started from, for every sample an 8-bit residual can hold.
617 #[test]
618 fn transform_skip_round_trips_every_residual_sample() {
619 let residual: Vec<i32> = (-255..=255).collect();
620 for chunk in residual.chunks(16) {
621 let mut block = [0i32; 16];
622 block[..chunk.len()].copy_from_slice(chunk);
623 let mut coeffs = [0i32; 16];
624 forward_transform_skip(&block, &mut coeffs, 4);
625 let mut back = [0i32; 16];
626 inverse_transform_skip(&coeffs, &mut back, 4);
627 assert_eq!(back, block, "transform skip is not its own inverse");
628 }
629 }
630
631 #[test]
632 fn dc_only_coefficient_is_flat_after_inverse() {
633 // The spec's inverse of a DC-only block is a constant; a transposed
634 // matrix index would tilt it.
635 for &n in &[4usize, 8, 16, 32] {
636 let mut scaled = vec![0i32; n * n];
637 scaled[0] = 4096;
638 let mut out = vec![0i32; n * n];
639 inverse_transform(&scaled, &mut out, n, false);
640 assert!(out.iter().all(|&v| v == out[0]), "n={n}: {out:?}");
641 // 4096 / 128: the two-stage inverse divides by 2^7 after the first
642 // pass and 2^12 after the second, against 64 x 64 of matrix gain.
643 assert_eq!(out[0], 32);
644 }
645 }
646
647 #[test]
648 fn chroma_qp_table() {
649 assert_eq!(chroma_qp(29, 0), 29);
650 assert_eq!(chroma_qp(30, 0), 29);
651 assert_eq!(chroma_qp(35, 0), 33);
652 assert_eq!(chroma_qp(43, 0), 37);
653 assert_eq!(chroma_qp(44, 0), 38);
654 assert_eq!(chroma_qp(51, 0), 45);
655 assert_eq!(chroma_qp(30, -2), 28);
656 }
657}