forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

quant.rs472 lines, 17.5 KiBHistoryRawDownload
1//! Forward transforms and quantisation.
2//!
3//! Nothing here is normative: the standard specifies only the *inverse*
4//! transforms, which the decoder side of this crate already implements
5//! ([`crate::transform`]). The forward direction is chosen so that the
6//! round trip through the normative inverse lands back on the source, and
7//! that is what the tests at the bottom check across the whole QP range.
8//!
9//! The multiplier table pairs with `normAdjust4x4` (Table 8-15 through the
10//! `LevelScale` of Equation 8-313): `MF[m][class] * normAdjust4x4[m][class] *
11//! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)`
12//! invert the decoder's dequantisation.
13
14use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8};
15use crate::transform::LevelScale8x8;
16
17/// Quantisation multipliers per `qp % 6`, indexed by the same position class
18/// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed).
19const MF: [[i32; 3]; 6] = [
20 [13107, 5243, 8066],
21 [11916, 4660, 7490],
22 [10082, 4194, 6554],
23 [9362, 3647, 5825],
24 [8192, 3355, 5243],
25 [7282, 2893, 4559],
26];
27
28/// Rounding offset numerator: an intra block rounds at 1/3 of a step, an inter
29/// block at 1/6 — the classic asymmetry, which spends bits where prediction is
30/// weakest. Measured against 1/3 and 1/2 for the inter case on 1080p camera
31/// and screen-capture clips: 1/6 is level or ahead at matched bitrate.
32///
33/// Re-measured 2026-08-23 against x264 with `bd_psnr_vs_x264` on a 3840x1608
34/// clip, sweeping both numerators as sixty-fourths the way x264 spells
35/// `--deadzone-intra` / `--deadzone-inter`. The intra offset is the one that
36/// matters and ours is the better of the two: x264's 11/64 reads -1.667 dB
37/// all-intra where ours (21/64, i.e. 1/3) reads -0.745 dB, with the inter
38/// value making no difference to that. The inter offset is inert across the
39/// whole useful range -- 6/64, 16/64, 21/64 and 32/64 span -1.571 to
40/// -1.532 dB, a 0.04 dB spread, while the bit counts move by 0.8%. So the
41/// remaining distance to x264 is not in the dead zone.
42#[inline]
43fn round_offset(qbits: u32, intra: bool) -> i32 {
44 (1i32 << qbits) / if intra { 3 } else { 6 }
45}
46
47/// Forward 4x4 core transform (the inverse of spec 8.5.12.2), raster in and
48/// out, integer and exact.
49pub(crate) fn forward_4x4(d: &mut [i32; 16]) {
50 for i in 0..4 {
51 let o = i * 4;
52 let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]);
53 let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e);
54 d[o] = s0 + s1;
55 d[o + 1] = 2 * s3 + s2;
56 d[o + 2] = s0 - s1;
57 d[o + 3] = s3 - 2 * s2;
58 }
59 for j in 0..4 {
60 let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]);
61 let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e);
62 d[j] = s0 + s1;
63 d[4 + j] = 2 * s3 + s2;
64 d[8 + j] = s0 - s1;
65 d[12 + j] = s3 - 2 * s2;
66 }
67}
68
69/// Forward 4x4 Hadamard over the sixteen luma DC coefficients of an
70/// Intra_16x16 macroblock (the inverse of spec 8.5.10), raster in and out.
71pub(crate) fn forward_hadamard_4x4(d: &mut [i32; 16]) {
72 for i in 0..4 {
73 let o = i * 4;
74 let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]);
75 d[o] = a + b + c + e;
76 d[o + 1] = a + b - c - e;
77 d[o + 2] = a - b - c + e;
78 d[o + 3] = a - b + c - e;
79 }
80 for j in 0..4 {
81 let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]);
82 d[j] = a + b + c + e;
83 d[4 + j] = a + b - c - e;
84 d[8 + j] = a - b - c + e;
85 d[12 + j] = a - b + c - e;
86 }
87}
88
89/// Forward 2x2 Hadamard over the four chroma DC coefficients (the inverse of
90/// spec 8.5.11).
91pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) {
92 let (a, b, c, e) = (d[0], d[1], d[2], d[3]);
93 d[0] = a + b + c + e;
94 d[1] = a - b + c - e;
95 d[2] = a + b - c - e;
96 d[3] = a - b - c + e;
97}
98
99/// Forward 8x8 core transform (the exact algebraic inverse of `idct8_1d` /
100/// [`crate::transform::inverse_transform_8x8`]), raster in, scaled coefficients
101/// out.
102///
103/// `idct8_1d`'s matrix `M` (one 1D pass) is not its own transpose-inverse pair
104/// the way the 4x4 transform's small butterfly nearly is: `M^T * M` is
105/// diagonal but `M * M^T` is not, so a hand-picked small-integer transpose
106/// leaks between frequencies by ~15%, which is too much for the ±1-per-sample
107/// tolerance this encoder's residuals need (up to ±255, far past the small
108/// ranges a 4x4 block sees). [`FWD8`] is `11560 * M^-1`, computed once by
109/// exact rational matrix inversion (`M^-1 * M = I` exactly), so applying it in
110/// the same row-then-column order `idct8_1d` uses, then the real inverse
111/// transform, reproduces the input exactly, scaled by a single known constant
112/// (`11560^2 / 64 = 2_088_025`, see [`quant_8x8`]) — no leakage at all, only
113/// the ordinary quantiser rounding.
114const FWD8: [[i64; 8]; 8] = [
115 [1445, 1445, 1445, 1445, 1445, 1445, 1445, 1445],
116 [1920, 1600, 960, 480, -480, -960, -1600, -1920],
117 [2312, 1156, -1156, -2312, -2312, -1156, 1156, 2312],
118 [1600, -480, -1920, -960, 960, 1920, 480, -1600],
119 [1445, -1445, -1445, 1445, 1445, -1445, -1445, 1445],
120 [960, -1920, 480, 1600, -1600, -480, 1920, -960],
121 [1156, -2312, 2312, -1156, -1156, 2312, -2312, 1156],
122 [480, -960, 1600, -1920, 1920, -1600, 960, -480],
123];
124
125/// One 1D pass of [`FWD8`] over eight values.
126#[inline]
127fn fwd8_1d(d: [i64; 8]) -> [i64; 8] {
128 std::array::from_fn(|i| (0..8).map(|j| FWD8[i][j] * d[j]).sum())
129}
130
131/// Forward 8x8 transform (raster in, raster out), unnormalised: the caller
132/// (`quant_8x8`) divides out the `2_088_025` gain along with the usual
133/// per-position quantiser scale.
134pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] {
135 let mut g = [0i64; 64];
136 for i in 0..8 {
137 let o = i * 8;
138 let row: [i64; 8] = std::array::from_fn(|k| i64::from(d[o + k]));
139 g[o..o + 8].copy_from_slice(&fwd8_1d(row));
140 }
141 let mut r = [0i64; 64];
142 for j in 0..8 {
143 let col = [
144 g[j],
145 g[8 + j],
146 g[16 + j],
147 g[24 + j],
148 g[32 + j],
149 g[40 + j],
150 g[48 + j],
151 g[56 + j],
152 ];
153 for (i, v) in fwd8_1d(col).into_iter().enumerate() {
154 r[i * 8 + j] = v;
155 }
156 }
157 r
158}
159
160/// `raw / denom`, rounded with the same 1/3 (intra) or 1/6 (inter) dead zone
161/// as [`round_offset`], expressed as plain division instead of a
162/// precomputed shift because [`forward_8x8`]'s coefficients already carry
163/// far more headroom than a `<<15`-ish fixed point would give.
164#[inline]
165/// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing
166/// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`]
167/// / QP scale that [`crate::transform::dequant_8x8`] will re-apply.
168pub(crate) fn quant_8x8(
169 coef: &[i64; 64],
170 ls: &LevelScale8x8,
171 qp: i32,
172 intra: bool,
173 out: &mut [i32; 64],
174) -> u8 {
175 quant_8x8_offset(coef, ls, qp, if intra { 3 } else { 6 }, out)
176}
177
178/// [`quant_8x8`] with the rounding offset named outright: the level is
179/// `(raw + denom / divisor) / denom`, so a divisor of 2 rounds to nearest and
180/// 6 is the inter dead zone. A search that offers smaller magnitudes wants to
181/// pick this itself.
182pub(crate) fn quant_8x8_offset(
183 coef: &[i64; 64],
184 ls: &LevelScale8x8,
185 qp: i32,
186 divisor: i32,
187 out: &mut [i32; 64],
188) -> u8 {
189 // 11560^2 / 64, see FWD8's doc comment.
190 const TOTAL_SCALE: i64 = 2_088_025;
191 let m = (qp % 6) as usize;
192 let shift = qp / 6;
193 let p = 6 - shift; // dequant_8x8's exponent, mirrored; qp >= 36 makes it negative.
194 let scale = &ls.scale[m];
195 let mut nz = 0;
196 *out = [0; 64];
197 for k in 0..64 {
198 let raster = ZIGZAG_8X8[k] as usize;
199 let c = coef[raster];
200 let denom = TOTAL_SCALE * i64::from(scale[raster]);
201 let (num, denom) = if p >= 0 {
202 ((c.unsigned_abs() as i64) << p, denom)
203 } else {
204 (c.unsigned_abs() as i64, denom << -p)
205 };
206 let level = ((num + denom / i64::from(divisor)) / denom) as i32;
207 if level != 0 {
208 nz += 1;
209 }
210 out[k] = if c < 0 { -level } else { level };
211 }
212 nz
213}
214
215/// Quantise a transformed 4x4 block into scan (zig-zag) order.
216///
217/// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into
218/// `out[0..15]`, which is the layout the AC residual blocks of Intra_16x16 and
219/// chroma use. Returns the number of non-zero levels.
220pub(crate) fn quant_4x4(
221 coef: &[i32; 16],
222 qp: i32,
223 intra: bool,
224 skip_dc: bool,
225 out: &mut [i32; 16],
226) -> u8 {
227 quant_4x4_offset(coef, qp, if intra { 3 } else { 6 }, skip_dc, out)
228}
229
230/// [`quant_4x4`] with the dead zone spelled out: the rounding offset is
231/// `1 / divisor` of a quantiser step.
232///
233/// Rate-distortion quantisation asks for a *smaller* dead zone than the plain
234/// path uses, because it walks levels down itself and cannot walk them up: a
235/// level the dead zone already dropped is not a candidate any more.
236pub(crate) fn quant_4x4_offset(
237 coef: &[i32; 16],
238 qp: i32,
239 divisor: i32,
240 skip_dc: bool,
241 out: &mut [i32; 16],
242) -> u8 {
243 let m = (qp % 6) as usize;
244 let qbits = 15 + (qp / 6) as u32;
245 let f = (1i32 << qbits) / divisor;
246 let start = usize::from(skip_dc);
247 let mut nz = 0;
248 *out = [0; 16];
249 for k in start..16 {
250 let raster = ZIGZAG_4X4[k] as usize;
251 let c = coef[raster];
252 let mf = MF[m][NORM_ADJUST_CLASS_4X4[raster] as usize];
253 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
254 if level != 0 {
255 nz += 1;
256 }
257 out[k - start] = if c < 0 { -level } else { level };
258 }
259 nz
260}
261
262/// Quantise the sixteen Hadamard-transformed luma DC coefficients into scan
263/// order. Two extra bits of shift pay for the gain of the forward Hadamard,
264/// which the decoder's inverse (8.5.10, a `>> 6` where the AC path shifts by
265/// four) takes back out.
266pub(crate) fn quant_luma_dc(coef: &[i32; 16], qp: i32, out: &mut [i32; 16]) -> u8 {
267 let qbits = 17 + (qp / 6) as u32;
268 let mf = MF[(qp % 6) as usize][0];
269 let f = round_offset(qbits, true);
270 let mut nz = 0;
271 *out = [0; 16];
272 for k in 0..16 {
273 let c = coef[ZIGZAG_4X4[k] as usize];
274 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
275 if level != 0 {
276 nz += 1;
277 }
278 out[k] = if c < 0 { -level } else { level };
279 }
280 nz
281}
282
283/// Quantise the four Hadamard-transformed chroma DC coefficients (raster
284/// order, which is also their scan order).
285pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [i32; 16]) -> u8 {
286 let qbits = 16 + (qp / 6) as u32;
287 let mf = MF[(qp % 6) as usize][0];
288 let f = round_offset(qbits, intra);
289 let mut nz = 0;
290 *out = [0; 16];
291 for k in 0..4 {
292 let c = coef[k];
293 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
294 if level != 0 {
295 nz += 1;
296 }
297 out[k] = if c < 0 { -level } else { level };
298 }
299 nz
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::transform::{LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8};
306
307 fn ls8() -> LevelScale8x8 {
308 LevelScale8x8::new(&[16; 64])
309 }
310
311 /// `forward_8x8` -> `quant_8x8` -> [`dequant_8x8`] -> [`inverse_transform_8x8`]
312 /// lands within the same dead-zone-quantiser bound as the 4x4 path (one
313 /// step, which doubles every six QP — see `ac_round_trip_within_a_quantiser_step`
314 /// above), at every QP, for 1000+ trials of random content across the full
315 /// 8-bit residual range: the property that makes `FWD8` a valid forward
316 /// companion to the normative inverse. With no quantisation at all
317 /// (`round_trip_8x8_identity_within_one_sample` below) the bound tightens
318 /// to the inverse transform's own `+32 >> 6` rounding, ±1.
319 #[test]
320 fn round_trip_8x8_within_a_quantiser_step() {
321 let ls = ls8();
322 for qp in 0..52 {
323 let step = 1 << (qp / 6);
324 let mut worst = 0i32;
325 for seed in 0..20u32 {
326 let src: [i32; 64] = std::array::from_fn(|i| {
327 let v = (seed.wrapping_mul(2654435761))
328 .wrapping_add((i as u32).wrapping_mul(2654435761))
329 >> 20;
330 (v as i32 % 511) - 255
331 });
332 let coef = forward_8x8(&src);
333 let mut scan = [0i32; 64];
334 quant_8x8(&coef, &ls, qp, true, &mut scan);
335 let mut raster = [0i32; 64];
336 unzigzag_8x8(&scan, &mut raster);
337 dequant_8x8(&mut raster, &ls, qp);
338 let mut out = [0i32; 64];
339 inverse_transform_8x8(&raster, &mut out);
340 for i in 0..64 {
341 worst = worst.max((out[i] - src[i]).abs());
342 }
343 }
344 assert!(
345 worst <= 2 + 2 * step,
346 "qp {qp}: worst error {worst} over step {step}"
347 );
348 }
349 }
350
351 /// With no quantisation at all (level = raw coefficient), the round trip
352 /// is exact up to the inverse transform's own `+32 >> 6` rounding.
353 #[test]
354 fn round_trip_8x8_identity_within_one_sample() {
355 let src: [i32; 64] = std::array::from_fn(|i| ((i * 7) % 511) as i32 - 255);
356 let coef = forward_8x8(&src);
357 // coef = 2_088_025 * exact_pre_shift_value; divide that out directly,
358 // bypassing any QP-driven quantiser step.
359 let mut raster = [0i32; 64];
360 for i in 0..64 {
361 let v = coef[i] as f64 / 2_088_025.0;
362 raster[i] = v.round() as i32;
363 }
364 let mut out = [0i32; 64];
365 inverse_transform_8x8(&raster, &mut out);
366 for i in 0..64 {
367 assert!(
368 (out[i] - src[i]).abs() <= 1,
369 "i {i}: {} vs {}",
370 out[i],
371 src[i]
372 );
373 }
374 }
375
376 use crate::transform::{
377 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4,
378 luma_dc_transform, unzigzag,
379 };
380
381 fn ls() -> LevelScale4x4 {
382 LevelScale4x4::new(&[16; 16])
383 }
384
385 /// A residual quantised at QP and put back through the *normative* inverse
386 /// comes back within the quantiser step, at every QP: this is the property
387 /// that makes the forward direction a valid inverse of clause 8.5, and a
388 /// wrong multiplier or shift breaks it by orders of magnitude.
389 #[test]
390 fn ac_round_trip_within_a_quantiser_step() {
391 let ls = ls();
392 for qp in 0..52 {
393 let mut worst = 0i32;
394 for seed in 0..8u32 {
395 let src: [i32; 16] = std::array::from_fn(|i| {
396 let v = (seed.wrapping_mul(2654435761).wrapping_add(i as u32 * 40503)) >> 24;
397 (v as i32 % 61) - 30
398 });
399 let mut coef = src;
400 forward_4x4(&mut coef);
401 let mut scan = [0i32; 16];
402 quant_4x4(&coef, qp, true, false, &mut scan);
403 let mut raster = [0i32; 16];
404 unzigzag(&scan, &mut raster);
405 dequant_4x4(&mut raster, &ls, qp, false);
406 let mut out = [0i32; 16];
407 inverse_transform_4x4(&raster, &mut out);
408 for i in 0..16 {
409 worst = worst.max((out[i] - src[i]).abs());
410 }
411 }
412 // The reconstruction error of a dead-zone quantiser is bounded by
413 // one step, which doubles every six QP.
414 let step = 1 << (qp / 6);
415 assert!(
416 worst <= 2 + 2 * step,
417 "qp {qp}: worst error {worst} over step {step}"
418 );
419 }
420 }
421
422 /// The same for the Intra_16x16 luma DC path: a flat residual across the
423 /// whole macroblock survives Hadamard, quantisation and the decoder's
424 /// 8.5.10 inverse.
425 #[test]
426 fn luma_dc_round_trip() {
427 let ls = ls();
428 for qp in 0..52 {
429 for &x in &[-40i32, -7, 3, 25] {
430 // Every 4x4 block of a flat macroblock has DC = 16 * x.
431 let dc: [i32; 16] = [16 * x; 16];
432 let mut had = dc;
433 forward_hadamard_4x4(&mut had);
434 let mut scan = [0i32; 16];
435 quant_luma_dc(&had, qp, &mut scan);
436 let mut raster = [0i32; 16];
437 unzigzag(&scan, &mut raster);
438 luma_dc_transform(&mut raster, &ls, qp);
439 // Each block reconstructs (dc + 32) >> 6 flat samples.
440 let recon = (raster[0] + 32) >> 6;
441 let step = 1 << (qp / 6);
442 assert!(
443 (recon - x).abs() <= 2 + 2 * step,
444 "qp {qp} x {x}: recon {recon}"
445 );
446 }
447 }
448 }
449
450 /// And the chroma DC path (2x2 Hadamard, 8.5.11).
451 #[test]
452 fn chroma_dc_round_trip() {
453 let ls = ls();
454 for qp in 0..40 {
455 for &x in &[-30i32, -4, 9, 21] {
456 let dc: [i32; 4] = [16 * x; 4];
457 let mut had = dc;
458 forward_hadamard_2x2(&mut had);
459 let mut scan = [0i32; 16];
460 quant_chroma_dc(&had, qp, true, &mut scan);
461 let mut c: [i32; 4] = [scan[0], scan[1], scan[2], scan[3]];
462 chroma_dc_transform_420(&mut c, &ls, qp);
463 let recon = (c[0] + 32) >> 6;
464 let step = 1 << (qp / 6);
465 assert!(
466 (recon - x).abs() <= 2 + 2 * step,
467 "qp {qp} x {x}: recon {recon}"
468 );
469 }
470 }
471 }
472}