forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

transform.rs472 lines, 18.0 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]
68fn m32(row: usize, col: usize) -> i32 {
69 if col < 16 {
70 TRANS_MATRIX_HALF[row][col]
71 } else if row.is_multiple_of(2) {
72 TRANS_MATRIX_HALF[row][31 - col]
73 } else {
74 -TRANS_MATRIX_HALF[row][31 - col]
75 }
76}
77
78/// `levelScale[k]`, 8.6.3.
79const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72];
80
81/// The quantizer's reciprocal of [`LEVEL_SCALE`], `round(2^20 / levelScale)`.
82///
83/// Derived rather than transcribed: the product of the two is 2^20 to within a
84/// count, which is the whole design of the HEVC quantizer, and
85/// [`tests::quant_scale_is_the_reciprocal`] holds it to that.
86const QUANT_SCALE: [i32; 6] = [26_214, 23_302, 20_560, 18_396, 16_384, 14_564];
87
88/// Largest and smallest coefficient a Main-profile decoder may hold (`CoeffMin`,
89/// `CoeffMax` for `extended_precision_processing_flag = 0`).
90const COEFF_MIN: i32 = -32_768;
91const COEFF_MAX: i32 = 32_767;
92
93/// One-dimensional inverse transform, `y[i] = sum_j M[j][i] * x[j]`.
94///
95/// Split even/odd once per level: the even rows of the size-N matrix *are* the
96/// size-N/2 matrix, so the recursion costs ~N^2/3 multiplies where the plain
97/// product costs N^2.
98fn inverse_1d(n: usize, src: &[i32], dst: &mut [i32]) {
99 if n == 1 {
100 dst[0] = 64 * src[0];
101 return;
102 }
103 let half = n / 2;
104 let stride = 32 / n;
105 let mut even_src = [0i32; 16];
106 for j in 0..half {
107 even_src[j] = src[2 * j];
108 }
109 let mut even = [0i32; 16];
110 inverse_1d(half, &even_src[..half], &mut even[..half]);
111 for x in 0..half {
112 let mut odd = 0i32;
113 for j in 0..half {
114 odd += m32((2 * j + 1) * stride, x) * src[2 * j + 1];
115 }
116 dst[x] = even[x] + odd;
117 dst[n - 1 - x] = even[x] - odd;
118 }
119}
120
121/// One-dimensional forward transform, `c[k] = sum_x M[k][x] * src[x]`.
122fn forward_1d(n: usize, src: &[i32], dst: &mut [i32]) {
123 if n == 1 {
124 dst[0] = 64 * src[0];
125 return;
126 }
127 let half = n / 2;
128 let stride = 32 / n;
129 let mut sums = [0i32; 16];
130 let mut diffs = [0i32; 16];
131 for (x, (sum, diff)) in sums[..half]
132 .iter_mut()
133 .zip(diffs[..half].iter_mut())
134 .enumerate()
135 {
136 *sum = src[x] + src[n - 1 - x];
137 *diff = src[x] - src[n - 1 - x];
138 }
139 let mut even = [0i32; 16];
140 forward_1d(half, &sums[..half], &mut even[..half]);
141 for j in 0..half {
142 dst[2 * j] = even[j];
143 let mut odd = 0i32;
144 for (x, &diff) in diffs[..half].iter().enumerate() {
145 odd += m32((2 * j + 1) * stride, x) * diff;
146 }
147 dst[2 * j + 1] = odd;
148 }
149}
150
151/// Forward 4x4 DST (the inverse of the normative `trType = 1` transform).
152fn forward_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
153 for (k, out) in dst.iter_mut().enumerate() {
154 *out = (0..4).map(|x| DST_MATRIX[k][x] * src[x]).sum();
155 }
156}
157
158/// Inverse 4x4 DST, `y[i] = sum_j M[j][i] * x[j]` (8-315).
159fn inverse_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
160 for (i, out) in dst.iter_mut().enumerate() {
161 *out = (0..4).map(|j| DST_MATRIX[j][i] * src[j]).sum();
162 }
163}
164
165/// True when a block takes the DST: luma, intra, 4x4 (8.6.4.1).
166pub fn uses_dst(size: usize, is_luma: bool) -> bool {
167 is_luma && size == 4
168}
169
170/// Forward transform of an `n x n` residual block into coefficients.
171///
172/// `residual` and `coeffs` are both row-major `n x n`; `coeffs[v * n + k]` is
173/// vertical frequency `v`, horizontal frequency `k`, which is the order the
174/// scans and the residual coder index.
175pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) {
176 let log2n = n.trailing_zeros() as i32;
177 // 8-bit input: shift1 = log2N + bitDepth - 9, shift2 = log2N + 6. Together
178 // they leave the DC at 128 x the mean residual whatever the block size,
179 // which is what the dequantiser's shift assumes.
180 let shift1 = log2n - 1;
181 let shift2 = log2n + 6;
182 let round1 = 1 << (shift1 - 1);
183 let round2 = 1 << (shift2 - 1);
184 let mut tmp = [0i32; 32 * 32];
185 let mut row = [0i32; 32];
186 let mut out = [0i32; 32];
187 for y in 0..n {
188 row[..n].copy_from_slice(&residual[y * n..y * n + n]);
189 if dst_type {
190 let mut src4 = [0i32; 4];
191 src4.copy_from_slice(&row[..4]);
192 let mut dst4 = [0i32; 4];
193 forward_dst4(&src4, &mut dst4);
194 out[..4].copy_from_slice(&dst4);
195 } else {
196 forward_1d(n, &row[..n], &mut out[..n]);
197 }
198 // Transposed store: the second pass then runs over what were columns.
199 for (k, &value) in out[..n].iter().enumerate() {
200 tmp[k * n + y] = (value + round1) >> shift1;
201 }
202 }
203 for k in 0..n {
204 row[..n].copy_from_slice(&tmp[k * n..k * n + n]);
205 if dst_type {
206 let mut src4 = [0i32; 4];
207 src4.copy_from_slice(&row[..4]);
208 let mut dst4 = [0i32; 4];
209 forward_dst4(&src4, &mut dst4);
210 out[..4].copy_from_slice(&dst4);
211 } else {
212 forward_1d(n, &row[..n], &mut out[..n]);
213 }
214 for (v, &value) in out[..n].iter().enumerate() {
215 coeffs[v * n + k] = (value + round2) >> shift2;
216 }
217 }
218}
219
220/// Inverse transform of scaled coefficients into residual samples, exactly as
221/// clause 8.6.4 specifies including its intermediate clipping.
222pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) {
223 let mut e = [0i32; 32 * 32];
224 let mut col = [0i32; 32];
225 let mut out = [0i32; 32];
226 // Stage 1: every column, i.e. along the vertical frequency index.
227 for k in 0..n {
228 let mut any = false;
229 for y in 0..n {
230 col[y] = scaled[y * n + k];
231 any |= col[y] != 0;
232 }
233 if !any {
234 // A column of zeros transforms to zeros; most columns of a coded
235 // block are zeros, which is what quantisation is for.
236 for y in 0..n {
237 e[y * n + k] = 0;
238 }
239 continue;
240 }
241 if dst_type {
242 let mut src4 = [0i32; 4];
243 src4.copy_from_slice(&col[..4]);
244 let mut dst4 = [0i32; 4];
245 inverse_dst4(&src4, &mut dst4);
246 out[..4].copy_from_slice(&dst4);
247 } else {
248 inverse_1d(n, &col[..n], &mut out[..n]);
249 }
250 for y in 0..n {
251 e[y * n + k] = ((out[y] + 64) >> 7).clamp(COEFF_MIN, COEFF_MAX);
252 }
253 }
254 // Stage 2: every row, then the bit-depth shift (8-299).
255 const BD_SHIFT: i32 = 12; // 20 - bitDepth, 8-bit
256 let round = 1 << (BD_SHIFT - 1);
257 for y in 0..n {
258 col[..n].copy_from_slice(&e[y * n..y * n + n]);
259 if dst_type {
260 let mut src4 = [0i32; 4];
261 src4.copy_from_slice(&col[..4]);
262 let mut dst4 = [0i32; 4];
263 inverse_dst4(&src4, &mut dst4);
264 out[..4].copy_from_slice(&dst4);
265 } else {
266 inverse_1d(n, &col[..n], &mut out[..n]);
267 }
268 for x in 0..n {
269 residual[y * n + x] = (out[x] + round) >> BD_SHIFT;
270 }
271 }
272}
273
274/// Quantise coefficients in place, returning the number of non-zero levels.
275///
276/// The rounding offset is a third of a step, which is the intra bias every
277/// encoder in this class uses: it costs a little distortion at the rounding
278/// boundary and buys back more in rate.
279pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize {
280 let log2n = n.trailing_zeros() as i32;
281 let qbits = 21 + qp / 6 - log2n;
282 let scale = QUANT_SCALE[(qp % 6) as usize] as i64;
283 let offset = (1i64 << qbits) / 3;
284 let mut nonzero = 0;
285 for (i, &c) in coeffs[..n * n].iter().enumerate() {
286 let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32;
287 let level = magnitude.min(COEFF_MAX);
288 levels[i] = if c < 0 { -level } else { level };
289 if level != 0 {
290 nonzero += 1;
291 }
292 }
293 nonzero
294}
295
296/// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
297pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
298 let log2n = n.trailing_zeros() as i32;
299 let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit
300 let round = 1i64 << (bd_shift - 1);
301 let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64;
302 let shift = qp / 6;
303 for (i, &level) in levels[..n * n].iter().enumerate() {
304 let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
305 scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32;
306 }
307}
308
309/// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset.
310pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 {
311 let qpi = (qp_luma + offset).clamp(0, 57);
312 if qpi < 30 {
313 qpi
314 } else if qpi > 43 {
315 qpi - 6
316 } else {
317 const TABLE: [i32; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
318 TABLE[(qpi - 30) as usize]
319 }
320}
321
322#[cfg(test)]
323mod tests {
324 use super::*;
325
326 #[test]
327 fn mirrored_half_matches_the_spec_second_table() {
328 // Spot values from transMatrixCol16to31 (8-321): row, column, value.
329 let spec: &[(usize, usize, i32)] = &[
330 (0, 16, 64),
331 (0, 31, 64),
332 (1, 16, -4),
333 (1, 31, -90),
334 (2, 16, -90),
335 (2, 31, 90),
336 (3, 16, 13),
337 (3, 23, 73),
338 (4, 16, 89),
339 (8, 16, 83),
340 (16, 16, 64),
341 (16, 17, -64),
342 (31, 16, 90),
343 (31, 31, -4),
344 (30, 16, -9),
345 (29, 31, -13),
346 ];
347 for &(row, col, value) in spec {
348 assert_eq!(m32(row, col), value, "M[{row}][{col}]");
349 }
350 }
351
352 #[test]
353 fn matrix_rows_are_orthogonal() {
354 // Every size's rows: orthogonal, and all of equal norm. A single mistyped
355 // entry breaks both.
356 for log2n in 2..=5u32 {
357 let n = 1usize << log2n;
358 let stride = 32 / n;
359 let norm: i32 = (0..n).map(|x| m32(0, x) * m32(0, x)).sum();
360 for a in 0..n {
361 let self_dot: i32 = (0..n)
362 .map(|x| m32(a * stride, x) * m32(a * stride, x))
363 .sum();
364 // 64^2 * n is exact for the DC row; the others are within the
365 // rounding the integer matrix carries.
366 assert!(
367 (self_dot - norm).abs() * 200 < norm,
368 "row {a} of {n}: norm {self_dot} vs {norm}"
369 );
370 for b in a + 1..n {
371 let dot: i32 = (0..n)
372 .map(|x| m32(a * stride, x) * m32(b * stride, x))
373 .sum();
374 assert!(dot.abs() * 100 < norm, "rows {a},{b} of {n}: dot {dot}");
375 }
376 }
377 }
378 }
379
380 #[test]
381 fn quant_scale_is_the_reciprocal() {
382 for k in 0..6 {
383 let product = QUANT_SCALE[k] as i64 * LEVEL_SCALE[k] as i64;
384 assert!((product - (1 << 20)).abs() < 64, "k={k}: {product}");
385 assert_eq!(
386 QUANT_SCALE[k],
387 ((1 << 20) as f64 / LEVEL_SCALE[k] as f64).round() as i32
388 );
389 }
390 }
391
392 fn round_trip(residual: &[i32], n: usize, qp: i32, dst: bool) -> Vec<i32> {
393 let mut coeffs = vec![0i32; n * n];
394 forward_transform(residual, &mut coeffs, n, dst);
395 let mut levels = vec![0i32; n * n];
396 quantize(&coeffs, &mut levels, n, qp);
397 let mut scaled = vec![0i32; n * n];
398 dequantize(&levels, &mut scaled, n, qp);
399 let mut out = vec![0i32; n * n];
400 inverse_transform(&scaled, &mut out, n, dst);
401 out
402 }
403
404 #[test]
405 fn round_trip_recovers_flat_blocks() {
406 // A constant residual stays constant at any QP — only the DC level
407 // survives — and at low QP it comes back to its own value. At QP 40 one
408 // level step *is* 16 samples, so accuracy is asserted where accuracy is
409 // on offer and flatness everywhere.
410 for &n in &[4usize, 8, 16, 32] {
411 for &qp in &[0i32, 12, 22, 27, 40, 51] {
412 let residual = vec![20i32; n * n];
413 let out = round_trip(&residual, n, qp, false);
414 assert!(out.iter().all(|&v| v == out[0]), "n={n} qp={qp}: {out:?}");
415 if qp <= 22 {
416 assert!((out[0] - 20).abs() <= 2, "n={n} qp={qp}: {}", out[0]);
417 }
418 }
419 }
420 }
421
422 #[test]
423 fn round_trip_is_near_lossless_at_low_qp() {
424 // A textured block at QP 4 comes back within a sample or two; this is
425 // what proves the forward transform is the inverse of the normative one
426 // rather than merely self-consistent.
427 for &n in &[4usize, 8, 16, 32] {
428 for dst in [false, true] {
429 if dst && n != 4 {
430 continue;
431 }
432 let residual: Vec<i32> =
433 (0..n * n).map(|i| (((i * 37) % 61) as i32) - 30).collect();
434 let out = round_trip(&residual, n, 4, dst);
435 let worst = residual
436 .iter()
437 .zip(&out)
438 .map(|(a, b)| (a - b).abs())
439 .max()
440 .unwrap();
441 assert!(worst <= 3, "n={n} dst={dst}: worst {worst}");
442 }
443 }
444 }
445
446 #[test]
447 fn dc_only_coefficient_is_flat_after_inverse() {
448 // The spec's inverse of a DC-only block is a constant; a transposed
449 // matrix index would tilt it.
450 for &n in &[4usize, 8, 16, 32] {
451 let mut scaled = vec![0i32; n * n];
452 scaled[0] = 4096;
453 let mut out = vec![0i32; n * n];
454 inverse_transform(&scaled, &mut out, n, false);
455 assert!(out.iter().all(|&v| v == out[0]), "n={n}: {out:?}");
456 // 4096 / 128: the two-stage inverse divides by 2^7 after the first
457 // pass and 2^12 after the second, against 64 x 64 of matrix gain.
458 assert_eq!(out[0], 32);
459 }
460 }
461
462 #[test]
463 fn chroma_qp_table() {
464 assert_eq!(chroma_qp(29, 0), 29);
465 assert_eq!(chroma_qp(30, 0), 29);
466 assert_eq!(chroma_qp(35, 0), 33);
467 assert_eq!(chroma_qp(43, 0), 37);
468 assert_eq!(chroma_qp(44, 0), 38);
469 assert_eq!(chroma_qp(51, 0), 45);
470 assert_eq!(chroma_qp(30, -2), 28);
471 }
472}