forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

transform.rs971 lines, 37.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]
59pub(crate) const 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.is_multiple_of(2) {
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}
95pub(crate) const 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}
113pub(crate) const FULL_MATRIX_T: [[i32; 32]; 32] = transpose(&FULL_MATRIX);
114
115/// `levelScale[k]`, 8.6.3.
116pub(crate) const 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`).
127pub(crate) const COEFF_MIN: i32 = -32_768;
128pub(crate) const 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 1-D transform of `lines` independent vectors at once. `src[x * lines + l]`
221/// is sample `x` of line `l`; `dst[k * lines + l]` is coefficient `k`. The
222/// butterfly is the one in [`forward_1d`], but every operation runs across
223/// the lines, which the compiler turns into SIMD.
224fn forward_lines(n: usize, lines: usize, src: &[i32], dst: &mut [i32], scratch: &mut [i32]) {
225 if n == 1 {
226 for l in 0..lines {
227 dst[l] = 64 * src[l];
228 }
229 return;
230 }
231 let half = n / 2;
232 let stride = 32 / n;
233 let span = half * lines;
234 let (sums, rest) = scratch.split_at_mut(span);
235 let (diffs, rest) = rest.split_at_mut(span);
236 let (even, rest) = rest.split_at_mut(span);
237 for x in 0..half {
238 let a = &src[x * lines..x * lines + lines];
239 let b = &src[(n - 1 - x) * lines..(n - 1 - x) * lines + lines];
240 let s = &mut sums[x * lines..x * lines + lines];
241 let d = &mut diffs[x * lines..x * lines + lines];
242 for l in 0..lines {
243 s[l] = a[l] + b[l];
244 d[l] = a[l] - b[l];
245 }
246 }
247 forward_lines(half, lines, sums, even, rest);
248 for j in 0..half {
249 dst[2 * j * lines..(2 * j + 1) * lines].copy_from_slice(&even[j * lines..(j + 1) * lines]);
250 let matrix_row = &FULL_MATRIX[(2 * j + 1) * stride];
251 let out = &mut dst[(2 * j + 1) * lines..(2 * j + 2) * lines];
252 out.fill(0);
253 for x in 0..half {
254 let m = matrix_row[x];
255 let d = &diffs[x * lines..x * lines + lines];
256 for l in 0..lines {
257 out[l] += m * d[l];
258 }
259 }
260 }
261}
262
263/// [`forward_transform`] for the plain DCT, computed across rows and columns
264/// at once. Bit-identical to the line-at-a-time version. `SQ` is `n * n` and
265/// `SC` the scratch the butterfly needs (`3 * n * n`); they are const so a 4x4
266/// block does not zero 4 KiB buffers it will not use.
267fn forward_dct_gen<const SQ: usize, const SC: usize>(
268 residual: &[i32],
269 coeffs: &mut [i32],
270 n: usize,
271) {
272 let log2n = n.trailing_zeros() as i32;
273 let shift1 = log2n - 1;
274 let shift2 = log2n + 6;
275 let round1 = 1 << (shift1 - 1);
276 let round2 = 1 << (shift2 - 1);
277 let mut xt = [0i32; SQ];
278 let mut a = [0i32; SQ];
279 let mut b = [0i32; SQ];
280 let mut scratch = [0i32; SC];
281 // xt[x][y] = residual[y][x]
282 for y in 0..n {
283 for x in 0..n {
284 xt[x * n + y] = residual[y * n + x];
285 }
286 }
287 // a[k][y]: first pass over rows.
288 forward_lines(n, n, &xt, &mut a, &mut scratch);
289 // b[y][k] = shifted a[k][y]
290 for k in 0..n {
291 for y in 0..n {
292 b[y * n + k] = (a[k * n + y] + round1) >> shift1;
293 }
294 }
295 // Second pass over columns k: coefficient v of line k.
296 forward_lines(n, n, &b, &mut a, &mut scratch);
297 for (c, &v) in coeffs[..n * n].iter_mut().zip(&a) {
298 *c = (v + round2) >> shift2;
299 }
300}
301
302fn forward_dct_fast(residual: &[i32], coeffs: &mut [i32], n: usize) {
303 match n {
304 4 => forward_dct_gen::<16, 48>(residual, coeffs, n),
305 8 => forward_dct_gen::<64, 192>(residual, coeffs, n),
306 16 => forward_dct_gen::<256, 768>(residual, coeffs, n),
307 _ => forward_dct_gen::<1024, 3072>(residual, coeffs, n),
308 }
309}
310
311/// Forward 4x4 DST (the inverse of the normative `trType = 1` transform).
312fn forward_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
313 for (k, out) in dst.iter_mut().enumerate() {
314 *out = (0..4).map(|x| DST_MATRIX[k][x] * src[x]).sum();
315 }
316}
317
318/// Inverse 4x4 DST, `y[i] = sum_j M[j][i] * x[j]` (8-315).
319fn inverse_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
320 for (i, out) in dst.iter_mut().enumerate() {
321 *out = (0..4).map(|j| DST_MATRIX[j][i] * src[j]).sum();
322 }
323}
324
325/// True when a block takes the DST: luma, intra, 4x4 (8.6.4.1).
326pub fn uses_dst(size: usize, is_luma: bool) -> bool {
327 is_luma && size == 4
328}
329
330/// Forward transform of an `n x n` residual block into coefficients.
331///
332/// `residual` and `coeffs` are both row-major `n x n`; `coeffs[v * n + k]` is
333/// vertical frequency `v`, horizontal frequency `k`, which is the order the
334/// scans and the residual coder index.
335pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) {
336 #[cfg(target_arch = "x86_64")]
337 if matches!(n, 4 | 8 | 16 | 32)
338 && (!dst_type || n == 4)
339 && crate::simd_tx::forward_transform_avx2(residual, coeffs, n, dst_type)
340 {
341 return;
342 }
343 forward_transform_scalar(residual, coeffs, n, dst_type);
344}
345
346/// [`forward_transform`] without the vector kernels.
347pub(crate) fn forward_transform_scalar(
348 residual: &[i32],
349 coeffs: &mut [i32],
350 n: usize,
351 dst_type: bool,
352) {
353 if !dst_type && n >= 4 {
354 forward_dct_fast(residual, coeffs, n);
355 return;
356 }
357 forward_transform_ref(residual, coeffs, n, dst_type);
358}
359
360/// Line-at-a-time forward transform: the reference the fast path is tested against.
361fn forward_transform_ref(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) {
362 let log2n = n.trailing_zeros() as i32;
363 // 8-bit input: shift1 = log2N + bitDepth - 9, shift2 = log2N + 6. Together
364 // they leave the DC at 128 x the mean residual whatever the block size,
365 // which is what the dequantiser's shift assumes.
366 let shift1 = log2n - 1;
367 let shift2 = log2n + 6;
368 let round1 = 1 << (shift1 - 1);
369 let round2 = 1 << (shift2 - 1);
370 let mut tmp = [0i32; 32 * 32];
371 let mut row = [0i32; 32];
372 let mut out = [0i32; 32];
373 for y in 0..n {
374 row[..n].copy_from_slice(&residual[y * n..y * n + n]);
375 if dst_type {
376 let mut src4 = [0i32; 4];
377 src4.copy_from_slice(&row[..4]);
378 let mut dst4 = [0i32; 4];
379 forward_dst4(&src4, &mut dst4);
380 out[..4].copy_from_slice(&dst4);
381 } else {
382 forward_1d(n, &row[..n], &mut out[..n]);
383 }
384 // Transposed store: the second pass then runs over what were columns.
385 for (k, &value) in out[..n].iter().enumerate() {
386 tmp[k * n + y] = (value + round1) >> shift1;
387 }
388 }
389 for k in 0..n {
390 row[..n].copy_from_slice(&tmp[k * n..k * n + n]);
391 if dst_type {
392 let mut src4 = [0i32; 4];
393 src4.copy_from_slice(&row[..4]);
394 let mut dst4 = [0i32; 4];
395 forward_dst4(&src4, &mut dst4);
396 out[..4].copy_from_slice(&dst4);
397 } else {
398 forward_1d(n, &row[..n], &mut out[..n]);
399 }
400 for (v, &value) in out[..n].iter().enumerate() {
401 coeffs[v * n + k] = (value + round2) >> shift2;
402 }
403 }
404}
405
406/// `bdShift` (8-299) at 8-bit: 20 - BitDepth.
407const BD_SHIFT: i32 = 12;
408
409/// Inverse transform of scaled coefficients into residual samples, exactly as
410/// clause 8.6.4 specifies including its intermediate clipping. 8-bit samples.
411pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) {
412 inverse_transform_bd(scaled, residual, n, dst_type, 8);
413}
414
415/// [`inverse_transform`] at any bit depth: the final shift is `20 - BitDepth`.
416pub fn inverse_transform_bd(
417 scaled: &[i32],
418 residual: &mut [i32],
419 n: usize,
420 dst_type: bool,
421 bit_depth: u32,
422) {
423 #[cfg(target_arch = "x86_64")]
424 if matches!(n, 4 | 8 | 16 | 32)
425 && (!dst_type || n == 4)
426 && crate::simd_tx::inverse_transform_avx2(
427 scaled,
428 residual,
429 n,
430 dst_type,
431 20 - bit_depth as i32,
432 )
433 {
434 return;
435 }
436 inverse_transform_scalar(scaled, residual, n, dst_type, bit_depth);
437}
438
439/// [`inverse_transform_bd`] without the vector kernels.
440pub(crate) fn inverse_transform_scalar(
441 scaled: &[i32],
442 residual: &mut [i32],
443 n: usize,
444 dst_type: bool,
445 bit_depth: u32,
446) {
447 let bd_shift = 20 - bit_depth as i32;
448 let mut col = [0i32; 32];
449 let mut out = [0i32; 32];
450 // Stage 1: every column, i.e. along the vertical frequency index. The
451 // intermediate `e` lives in `residual` itself: stage 2 reads a row before it
452 // writes that row and touches no other, so no second buffer is needed.
453 // `max_k` is one past the last column with a non-zero coefficient.
454 let mut max_k = 0;
455 for k in 0..n {
456 let mut nz = 0;
457 for y in 0..n {
458 col[y] = scaled[y * n + k];
459 if col[y] != 0 {
460 nz = y + 1;
461 }
462 }
463 if nz == 0 {
464 // A column of zeros transforms to zeros; most columns of a coded
465 // block are zeros, which is what quantisation is for.
466 for y in 0..n {
467 residual[y * n + k] = 0;
468 }
469 continue;
470 }
471 max_k = k + 1;
472 transform_1d(n, dst_type, &col[..n], nz, &mut out[..n]);
473 for y in 0..n {
474 residual[y * n + k] = ((out[y] + 64) >> 7).clamp(COEFF_MIN, COEFF_MAX);
475 }
476 }
477 // Stage 2: every row, then the bit-depth shift (8-299). Columns past
478 // `max_k` are zero after stage 1, so the row transform stops there.
479 let round = 1 << (bd_shift - 1);
480 for y in 0..n {
481 col[..n].copy_from_slice(&residual[y * n..y * n + n]);
482 transform_1d(n, dst_type, &col[..n], max_k, &mut out[..n]);
483 for x in 0..n {
484 residual[y * n + x] = (out[x] + round) >> bd_shift;
485 }
486 }
487}
488
489/// One 1-D inverse transform of `src` into `out` (`n` samples each). `nz` bounds
490/// the non-zero inputs: `src[nz..]` are all zero, so the direct sum can stop there.
491/// The DST is only used for 4x4 blocks, where `nz` does not matter.
492fn transform_1d(n: usize, dst_type: bool, src: &[i32], nz: usize, out: &mut [i32]) {
493 if dst_type {
494 let mut src4 = [0i32; 4];
495 src4.copy_from_slice(&src[..4]);
496 let mut dst4 = [0i32; 4];
497 inverse_dst4(&src4, &mut dst4);
498 out[..4].copy_from_slice(&dst4);
499 } else if nz <= DIRECT_MAX_NZ {
500 inverse_1d_direct(n, &src[..nz], &mut out[..n]);
501 } else {
502 inverse_1d(n, &src[..n], &mut out[..n]);
503 }
504}
505
506/// Up to this many non-zero inputs, [`inverse_1d_direct`] beats the butterfly.
507const DIRECT_MAX_NZ: usize = 16;
508
509/// The plain product `out[i] = sum_k M_n[k][i] * src[k]` over the first `src.len()`
510/// rows of the size-`n` matrix, which is the 32-point matrix's rows `k * (32 / n)`
511/// and its first `n` columns. The inner loop runs over outputs, so it is a
512/// contiguous multiply-add.
513fn inverse_1d_direct(n: usize, src: &[i32], out: &mut [i32]) {
514 let stride = 32 / n;
515 let mut acc = [0i32; 32];
516 let acc = &mut acc[..n];
517 for (k, &c) in src.iter().enumerate() {
518 if c == 0 {
519 continue;
520 }
521 let row = &FULL_MATRIX[k * stride][..n];
522 for (a, &m) in acc.iter_mut().zip(row) {
523 *a += m * c;
524 }
525 }
526 out[..n].copy_from_slice(acc);
527}
528
529/// Forward transform skip (8.6.2): no transform at all, the residual samples
530/// standing in for coefficients.
531///
532/// The decoder scales what it reads by `tsShift = 5 + Log2(nTbS)` and then
533/// takes the bit-depth shift of 20 - 8 off it again, so a coefficient has to
534/// carry the residual scaled by the difference for the round trip to return
535/// the sample it started from — a factor of 32 at 4x4, the same gain the
536/// integer transform leaves behind.
537pub fn forward_transform_skip(residual: &[i32], coeffs: &mut [i32], n: usize) {
538 let shift = BD_SHIFT - (5 + n.trailing_zeros() as i32);
539 for (i, &r) in residual[..n * n].iter().enumerate() {
540 coeffs[i] = r << shift;
541 }
542}
543
544/// Inverse transform skip (8.6.2): the scaled coefficient shifted up by
545/// `tsShift` and then down by the bit-depth shift, exactly as the decoder
546/// does it, so the encoder reconstructs the samples the decoder will.
547pub fn inverse_transform_skip(scaled: &[i32], residual: &mut [i32], n: usize) {
548 inverse_transform_skip_bd(scaled, residual, n, 8);
549}
550
551/// [`inverse_transform_skip`] at any bit depth (8.6.4.2 with `bdShift = 20 - BitDepth`).
552pub fn inverse_transform_skip_bd(scaled: &[i32], residual: &mut [i32], n: usize, bit_depth: u32) {
553 let ts_shift = 5 + n.trailing_zeros() as i32;
554 let bd_shift = 20 - bit_depth as i32;
555 let round = 1i32 << (bd_shift - 1);
556 for (i, &d) in scaled[..n * n].iter().enumerate() {
557 residual[i] = ((d.clamp(COEFF_MIN, COEFF_MAX) << ts_shift) + round) >> bd_shift;
558 }
559}
560
561/// Quantise coefficients in place, returning the number of non-zero levels.
562///
563/// The rounding offset is a third of a step, which is the intra bias every
564/// encoder in this class uses: it costs a little distortion at the rounding
565/// boundary and buys back more in rate.
566pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize {
567 quantize_offset(coeffs, levels, n, qp, 3)
568}
569
570/// [`quantize`] with the rounding written out: `dead_zone` is the divisor of
571/// the quantiser step the rounding offset is, so 3 is the intra default and 2
572/// is round-to-nearest.
573///
574/// A rate-distortion search over the levels wants the wider rounding: a search
575/// that only ever takes levels down measures the rounding it started from, not
576/// its own decisions.
577pub fn quantize_offset(
578 coeffs: &[i32],
579 levels: &mut [i32],
580 n: usize,
581 qp: i32,
582 dead_zone: i64,
583) -> usize {
584 let log2n = n.trailing_zeros() as i32;
585 // QpY may be negative at 10 bits (down to -12), so the split is Euclidean.
586 let qbits = 21 + qp.div_euclid(6) - log2n;
587 let scale = QUANT_SCALE[qp.rem_euclid(6) as usize] as i64;
588 let offset = (1i64 << qbits) / dead_zone;
589 // `scale` <= 26_214 and `|coeffs[i]|` <= 32_768 (COEFF_MIN/MAX), and qp is
590 // clamped to 0..=51 (crates/ec-h265/src/encoder.rs), so
591 // `abs(c) * scale + offset` never exceeds ~1e9: it fits in i32 without
592 // overflow, which is what lets this run in 32-bit SIMD lanes and still be
593 // the exact same integer as the scalar i64 computation below.
594 debug_assert!(scale <= i64::from(i32::MAX) && offset <= i64::from(i32::MAX));
595 let scale32 = scale as i32;
596 let offset32 = offset as i32;
597 let mut nonzero = 0;
598 #[cfg(target_arch = "x86_64")]
599 if (n * n).is_multiple_of(8)
600 && let Some(nonzero) =
601 crate::simd_tx::quantize_avx2(coeffs, levels, n * n, scale32, offset32, qbits)
602 {
603 return nonzero;
604 }
605 let coeffs = &coeffs[..n * n];
606 let mut i = 0;
607 while i + 8 <= coeffs.len() {
608 let c = wide::i32x8::from(<[i32; 8]>::try_from(&coeffs[i..i + 8]).unwrap());
609 let mag =
610 ((c.abs() * scale32 + offset32) >> (qbits as u32)).min(wide::i32x8::splat(COEFF_MAX));
611 let level = c.simd_lt(wide::i32x8::splat(0)).select(-mag, mag);
612 for (j, &lv) in level.to_array().iter().enumerate() {
613 levels[i + j] = lv;
614 if lv != 0 {
615 nonzero += 1;
616 }
617 }
618 i += 8;
619 }
620 for j in i..coeffs.len() {
621 let c = coeffs[j];
622 let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32;
623 let level = magnitude.min(COEFF_MAX);
624 levels[j] = if c < 0 { -level } else { level };
625 if level != 0 {
626 nonzero += 1;
627 }
628 }
629 nonzero
630}
631
632/// The smallest coefficient magnitude [`quantize_offset`] turns into a non-zero level for an
633/// `n` x `n` block at `qp` with the given `dead_zone` divisor.
634pub fn min_nonzero_coeff(n: usize, qp: i32, dead_zone: i64) -> i64 {
635 let log2n = n.trailing_zeros() as i32;
636 let qbits = 21 + qp.div_euclid(6) - log2n;
637 let scale = QUANT_SCALE[qp.rem_euclid(6) as usize] as i64;
638 let step = 1i64 << qbits;
639 let offset = step / dead_zone;
640 (step - offset + scale - 1) / scale
641}
642
643/// The unrounded level a coefficient would quantise to: the quantiser divides
644/// by a step, and this is that division carried out in full precision. Sign
645/// data hiding needs it to tell which coefficient is cheapest to nudge.
646pub fn ideal_level(coeff: i32, n: usize, qp: i32) -> f64 {
647 let log2n = n.trailing_zeros() as i32;
648 let qbits = 21 + qp.div_euclid(6) - log2n;
649 let scale = QUANT_SCALE[qp.rem_euclid(6) as usize] as f64;
650 (coeff.unsigned_abs() as f64 * scale) / (1u64 << qbits) as f64
651}
652
653/// Scale levels back into coefficients, exactly as clause 8.6.3 specifies, with
654/// the flat matrix of 16.
655pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
656 dequantize_weighted(levels, scaled, n, qp, 8, None);
657}
658
659/// The QP the quantizer works on, given the dequantizer's qP.
660///
661/// [`dequantize_bd`] at qP' (QpY + QpBdOffset) with the `bd - 8` extra shift gives the same
662/// coefficient step as the 8-bit dequantizer at QpY, so the quantizer runs at QpY.
663pub fn quant_qp(qp: i32, bit_depth: u32) -> i32 {
664 qp - 6 * (bit_depth as i32 - 8)
665}
666
667/// Bring a forward transform's output to the 16-bit coefficient range at `bit_depth`.
668///
669/// The forward transform gives coefficients 4^(bd-8) times the 8-bit ones for the same
670/// content, and the spec's `CoeffMin`/`CoeffMax` (-32768..=32767 without extended
671/// precision) are what a 10-bit stream must stay inside. The division is the forward half
672/// of the `20 - BitDepth` inverse shift, rounded.
673pub fn scale_forward_bd(coeffs: &mut [i32], n: usize, bit_depth: u32) {
674 let s = bit_depth.saturating_sub(8);
675 if s == 0 {
676 return;
677 }
678 let round = 1i32 << (s - 1);
679 for c in coeffs[..n * n].iter_mut() {
680 *c = (*c + round) >> s;
681 }
682}
683
684/// [`dequantize`] at any bit depth; `qp` is qP (QpBdOffset included).
685pub fn dequantize_bd(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, bit_depth: u32) {
686 dequantize_weighted(levels, scaled, n, qp, bit_depth, None);
687}
688
689/// [`dequantize`] with a scaling matrix (8.6.4.2): `m` is the block's
690/// `ScalingFactor` in raster order, or `None` for the flat 16 that a stream
691/// without scaling lists (or a transform-skipped block larger than 4x4) uses.
692pub fn dequantize_with(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, m: Option<&[u8]>) {
693 dequantize_weighted(levels, scaled, n, qp, 8, m);
694}
695
696/// The loop behind every dequantize entry point: one block at `bit_depth`, with
697/// the weight matrix `m` (or flat 16 for `None`).
698pub fn dequantize_weighted(
699 levels: &[i32],
700 scaled: &mut [i32],
701 n: usize,
702 qp: i32,
703 bit_depth: u32,
704 m: Option<&[u8]>,
705) {
706 #[cfg(target_arch = "x86_64")]
707 if m.is_none() && crate::simd_tx::dequantize_avx2(levels, scaled, n, qp, bit_depth) {
708 return;
709 }
710 for (i, &level) in levels[..n * n].iter().enumerate() {
711 let weight = m.map_or(16, |m| i64::from(m[i]));
712 scaled[i] = dequant_weighted(level, n, qp, bit_depth, weight);
713 }
714}
715
716/// One level scaled back to a coefficient, the per-coefficient half of
717/// [`dequantize`]. A rate-distortion search over the levels prices one
718/// coefficient at a time and has no use for the whole block.
719pub fn dequant_level(level: i32, n: usize, qp: i32) -> i32 {
720 dequant_level_bd(level, n, qp, 8)
721}
722
723/// [`dequant_level`] at any bit depth: `bdShift = BitDepth + Log2(nTbS) - 5`
724/// (8-300 with no scaling list, m = 16). `qp` is qP, which includes QpBdOffset.
725pub fn dequant_level_bd(level: i32, n: usize, qp: i32, bit_depth: u32) -> i32 {
726 dequant_weighted(level, n, qp, bit_depth, 16)
727}
728
729/// [`dequant_level`] with the scaling-matrix weight `m` in place of 16.
730fn dequant_weighted(level: i32, n: usize, qp: i32, bit_depth: u32, m: i64) -> i32 {
731 let log2n = n.trailing_zeros() as i32;
732 let bd_shift = bit_depth as i32 + log2n - 5;
733 let round = 1i64 << (bd_shift - 1);
734 let scale = m * i64::from(LEVEL_SCALE[(qp % 6) as usize]);
735 let shift = qp / 6;
736 let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
737 value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32
738}
739
740/// What a squared error in the transform domain is worth as a squared error in
741/// the sample domain.
742///
743/// The forward transform's shifts leave the DC at 128 times the mean residual
744/// whatever the block size, where an orthonormal transform would leave it at
745/// `n` times; the transform is otherwise orthogonal, so coefficient error
746/// energy is `(128 / n)^2` times sample error energy and this undoes it. A
747/// rate-distortion search over the levels needs it to weigh transform-domain
748/// error against a lambda calibrated on samples.
749pub fn coeff_ssd_scale(n: usize) -> f64 {
750 (n * n) as f64 / (128.0 * 128.0)
751}
752
753/// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset.
754pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 {
755 chroma_qp_bd(qp_luma, offset, 8)
756}
757
758/// [`chroma_qp_bd`] for any chroma format: Table 8-10 when `ChromaArrayType` is 1 (4:2:0),
759/// and `Min(qPi, 51)` otherwise (8.6.1, 4:2:2 and 4:4:4).
760pub fn chroma_qp_for(qp_luma: i32, offset: i32, bit_depth: u32, chroma_format_idc: u32) -> i32 {
761 if chroma_format_idc == 1 {
762 return chroma_qp_bd(qp_luma, offset, bit_depth);
763 }
764 let qp_bd_offset_c = 6 * (bit_depth as i32 - 8);
765 (qp_luma + offset).clamp(-qp_bd_offset_c, 57).min(51)
766}
767
768/// [`chroma_qp`] at any bit depth (8.6.1): qPiCb is clipped to
769/// `-QpBdOffsetC..=57`, so the result can be negative at high bit depths.
770/// The caller adds QpBdOffsetC to get qP.
771pub fn chroma_qp_bd(qp_luma: i32, offset: i32, bit_depth: u32) -> i32 {
772 let qp_bd_offset_c = 6 * (bit_depth as i32 - 8);
773 let qpi = (qp_luma + offset).clamp(-qp_bd_offset_c, 57);
774 if qpi < 30 {
775 qpi
776 } else if qpi > 43 {
777 qpi - 6
778 } else {
779 const TABLE: [i32; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
780 TABLE[(qpi - 30) as usize]
781 }
782}
783
784#[cfg(test)]
785mod tests {
786 #[test]
787 fn fast_forward_matches_reference() {
788 let mut seed = 12345u32;
789 for &n in &[4usize, 8, 16, 32] {
790 for _ in 0..50 {
791 let res: Vec<i32> = (0..n * n)
792 .map(|_| {
793 seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
794 ((seed >> 16) % 511) as i32 - 255
795 })
796 .collect();
797 let mut a = vec![0; n * n];
798 let mut b = vec![0; n * n];
799 forward_transform(&res, &mut a, n, false);
800 forward_transform_ref(&res, &mut b, n, false);
801 assert_eq!(a, b, "n={n}");
802 }
803 }
804 }
805
806 use super::*;
807
808 #[test]
809 fn mirrored_half_matches_the_spec_second_table() {
810 // Spot values from transMatrixCol16to31 (8-321): row, column, value.
811 let spec: &[(usize, usize, i32)] = &[
812 (0, 16, 64),
813 (0, 31, 64),
814 (1, 16, -4),
815 (1, 31, -90),
816 (2, 16, -90),
817 (2, 31, 90),
818 (3, 16, 13),
819 (3, 23, 73),
820 (4, 16, 89),
821 (8, 16, 83),
822 (16, 16, 64),
823 (16, 17, -64),
824 (31, 16, 90),
825 (31, 31, -4),
826 (30, 16, -9),
827 (29, 31, -13),
828 ];
829 for &(row, col, value) in spec {
830 assert_eq!(m32(row, col), value, "M[{row}][{col}]");
831 }
832 }
833
834 #[test]
835 fn matrix_rows_are_orthogonal() {
836 // Every size's rows: orthogonal, and all of equal norm. A single mistyped
837 // entry breaks both.
838 for log2n in 2..=5u32 {
839 let n = 1usize << log2n;
840 let stride = 32 / n;
841 let norm: i32 = (0..n).map(|x| m32(0, x) * m32(0, x)).sum();
842 for a in 0..n {
843 let self_dot: i32 = (0..n)
844 .map(|x| m32(a * stride, x) * m32(a * stride, x))
845 .sum();
846 // 64^2 * n is exact for the DC row; the others are within the
847 // rounding the integer matrix carries.
848 assert!(
849 (self_dot - norm).abs() * 200 < norm,
850 "row {a} of {n}: norm {self_dot} vs {norm}"
851 );
852 for b in a + 1..n {
853 let dot: i32 = (0..n)
854 .map(|x| m32(a * stride, x) * m32(b * stride, x))
855 .sum();
856 assert!(dot.abs() * 100 < norm, "rows {a},{b} of {n}: dot {dot}");
857 }
858 }
859 }
860 }
861
862 #[test]
863 fn quant_scale_is_the_reciprocal() {
864 for k in 0..6 {
865 let product = QUANT_SCALE[k] as i64 * LEVEL_SCALE[k] as i64;
866 assert!((product - (1 << 20)).abs() < 64, "k={k}: {product}");
867 assert_eq!(
868 QUANT_SCALE[k],
869 ((1 << 20) as f64 / LEVEL_SCALE[k] as f64).round() as i32
870 );
871 }
872 }
873
874 fn round_trip(residual: &[i32], n: usize, qp: i32, dst: bool) -> Vec<i32> {
875 let mut coeffs = vec![0i32; n * n];
876 forward_transform(residual, &mut coeffs, n, dst);
877 let mut levels = vec![0i32; n * n];
878 quantize(&coeffs, &mut levels, n, qp);
879 let mut scaled = vec![0i32; n * n];
880 dequantize(&levels, &mut scaled, n, qp);
881 let mut out = vec![0i32; n * n];
882 inverse_transform(&scaled, &mut out, n, dst);
883 out
884 }
885
886 #[test]
887 fn round_trip_recovers_flat_blocks() {
888 // A constant residual stays constant at any QP — only the DC level
889 // survives — and at low QP it comes back to its own value. At QP 40 one
890 // level step *is* 16 samples, so accuracy is asserted where accuracy is
891 // on offer and flatness everywhere.
892 for &n in &[4usize, 8, 16, 32] {
893 for &qp in &[0i32, 12, 22, 27, 40, 51] {
894 let residual = vec![20i32; n * n];
895 let out = round_trip(&residual, n, qp, false);
896 assert!(out.iter().all(|&v| v == out[0]), "n={n} qp={qp}: {out:?}");
897 if qp <= 22 {
898 assert!((out[0] - 20).abs() <= 2, "n={n} qp={qp}: {}", out[0]);
899 }
900 }
901 }
902 }
903
904 #[test]
905 fn round_trip_is_near_lossless_at_low_qp() {
906 // A textured block at QP 4 comes back within a sample or two; this is
907 // what proves the forward transform is the inverse of the normative one
908 // rather than merely self-consistent.
909 for &n in &[4usize, 8, 16, 32] {
910 for dst in [false, true] {
911 if dst && n != 4 {
912 continue;
913 }
914 let residual: Vec<i32> =
915 (0..n * n).map(|i| (((i * 37) % 61) as i32) - 30).collect();
916 let out = round_trip(&residual, n, 4, dst);
917 let worst = residual
918 .iter()
919 .zip(&out)
920 .map(|(a, b)| (a - b).abs())
921 .max()
922 .unwrap();
923 assert!(worst <= 3, "n={n} dst={dst}: worst {worst}");
924 }
925 }
926 }
927
928 /// Transform skip is only a pair of shifts, so the pair has to be exact:
929 /// what the encoder writes as a coefficient must come back as the residual
930 /// sample it started from, for every sample an 8-bit residual can hold.
931 #[test]
932 fn transform_skip_round_trips_every_residual_sample() {
933 let residual: Vec<i32> = (-255..=255).collect();
934 for chunk in residual.chunks(16) {
935 let mut block = [0i32; 16];
936 block[..chunk.len()].copy_from_slice(chunk);
937 let mut coeffs = [0i32; 16];
938 forward_transform_skip(&block, &mut coeffs, 4);
939 let mut back = [0i32; 16];
940 inverse_transform_skip(&coeffs, &mut back, 4);
941 assert_eq!(back, block, "transform skip is not its own inverse");
942 }
943 }
944
945 #[test]
946 fn dc_only_coefficient_is_flat_after_inverse() {
947 // The spec's inverse of a DC-only block is a constant; a transposed
948 // matrix index would tilt it.
949 for &n in &[4usize, 8, 16, 32] {
950 let mut scaled = vec![0i32; n * n];
951 scaled[0] = 4096;
952 let mut out = vec![0i32; n * n];
953 inverse_transform(&scaled, &mut out, n, false);
954 assert!(out.iter().all(|&v| v == out[0]), "n={n}: {out:?}");
955 // 4096 / 128: the two-stage inverse divides by 2^7 after the first
956 // pass and 2^12 after the second, against 64 x 64 of matrix gain.
957 assert_eq!(out[0], 32);
958 }
959 }
960
961 #[test]
962 fn chroma_qp_table() {
963 assert_eq!(chroma_qp(29, 0), 29);
964 assert_eq!(chroma_qp(30, 0), 29);
965 assert_eq!(chroma_qp(35, 0), 33);
966 assert_eq!(chroma_qp(43, 0), 37);
967 assert_eq!(chroma_qp(44, 0), 38);
968 assert_eq!(chroma_qp(51, 0), 45);
969 assert_eq!(chroma_qp(30, -2), 28);
970 }
971}