forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

quant.rs258 lines, 9.2 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};
15
16/// Quantisation multipliers per `qp % 6`, indexed by the same position class
17/// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed).
18const MF: [[i32; 3]; 6] = [
19 [13107, 5243, 8066],
20 [11916, 4660, 7490],
21 [10082, 4194, 6554],
22 [9362, 3647, 5825],
23 [8192, 3355, 5243],
24 [7282, 2893, 4559],
25];
26
27/// Rounding offset numerator: an intra block rounds at 1/3 of a step, an inter
28/// block at 1/6 — the classic asymmetry, which spends bits where prediction is
29/// weakest. Measured against 1/3 and 1/2 for the inter case on 1080p camera
30/// and screen-capture clips: 1/6 is level or ahead at matched bitrate.
31#[inline]
32fn round_offset(qbits: u32, intra: bool) -> i32 {
33 (1i32 << qbits) / if intra { 3 } else { 6 }
34}
35
36/// Forward 4x4 core transform (the inverse of spec 8.5.12.2), raster in and
37/// out, integer and exact.
38pub(crate) fn forward_4x4(d: &mut [i32; 16]) {
39 for i in 0..4 {
40 let o = i * 4;
41 let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]);
42 let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e);
43 d[o] = s0 + s1;
44 d[o + 1] = 2 * s3 + s2;
45 d[o + 2] = s0 - s1;
46 d[o + 3] = s3 - 2 * s2;
47 }
48 for j in 0..4 {
49 let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]);
50 let (s0, s1, s2, s3) = (a + e, b + c, b - c, a - e);
51 d[j] = s0 + s1;
52 d[4 + j] = 2 * s3 + s2;
53 d[8 + j] = s0 - s1;
54 d[12 + j] = s3 - 2 * s2;
55 }
56}
57
58/// Forward 4x4 Hadamard over the sixteen luma DC coefficients of an
59/// Intra_16x16 macroblock (the inverse of spec 8.5.10), raster in and out.
60pub(crate) fn forward_hadamard_4x4(d: &mut [i32; 16]) {
61 for i in 0..4 {
62 let o = i * 4;
63 let (a, b, c, e) = (d[o], d[o + 1], d[o + 2], d[o + 3]);
64 d[o] = a + b + c + e;
65 d[o + 1] = a + b - c - e;
66 d[o + 2] = a - b - c + e;
67 d[o + 3] = a - b + c - e;
68 }
69 for j in 0..4 {
70 let (a, b, c, e) = (d[j], d[4 + j], d[8 + j], d[12 + j]);
71 d[j] = a + b + c + e;
72 d[4 + j] = a + b - c - e;
73 d[8 + j] = a - b - c + e;
74 d[12 + j] = a - b + c - e;
75 }
76}
77
78/// Forward 2x2 Hadamard over the four chroma DC coefficients (the inverse of
79/// spec 8.5.11).
80pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) {
81 let (a, b, c, e) = (d[0], d[1], d[2], d[3]);
82 d[0] = a + b + c + e;
83 d[1] = a - b + c - e;
84 d[2] = a + b - c - e;
85 d[3] = a - b - c + e;
86}
87
88/// Quantise a transformed 4x4 block into scan (zig-zag) order.
89///
90/// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into
91/// `out[0..15]`, which is the layout the AC residual blocks of Intra_16x16 and
92/// chroma use. Returns the number of non-zero levels.
93pub(crate) fn quant_4x4(
94 coef: &[i32; 16],
95 qp: i32,
96 intra: bool,
97 skip_dc: bool,
98 out: &mut [i32; 16],
99) -> u8 {
100 let m = (qp % 6) as usize;
101 let qbits = 15 + (qp / 6) as u32;
102 let f = round_offset(qbits, intra);
103 let start = usize::from(skip_dc);
104 let mut nz = 0;
105 *out = [0; 16];
106 for k in start..16 {
107 let raster = ZIGZAG_4X4[k] as usize;
108 let c = coef[raster];
109 let mf = MF[m][NORM_ADJUST_CLASS_4X4[raster] as usize];
110 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
111 if level != 0 {
112 nz += 1;
113 }
114 out[k - start] = if c < 0 { -level } else { level };
115 }
116 nz
117}
118
119/// Quantise the sixteen Hadamard-transformed luma DC coefficients into scan
120/// order. Two extra bits of shift pay for the gain of the forward Hadamard,
121/// which the decoder's inverse (8.5.10, a `>> 6` where the AC path shifts by
122/// four) takes back out.
123pub(crate) fn quant_luma_dc(coef: &[i32; 16], qp: i32, out: &mut [i32; 16]) -> u8 {
124 let qbits = 17 + (qp / 6) as u32;
125 let mf = MF[(qp % 6) as usize][0];
126 let f = round_offset(qbits, true);
127 let mut nz = 0;
128 *out = [0; 16];
129 for k in 0..16 {
130 let c = coef[ZIGZAG_4X4[k] as usize];
131 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
132 if level != 0 {
133 nz += 1;
134 }
135 out[k] = if c < 0 { -level } else { level };
136 }
137 nz
138}
139
140/// Quantise the four Hadamard-transformed chroma DC coefficients (raster
141/// order, which is also their scan order).
142pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [i32; 16]) -> u8 {
143 let qbits = 16 + (qp / 6) as u32;
144 let mf = MF[(qp % 6) as usize][0];
145 let f = round_offset(qbits, intra);
146 let mut nz = 0;
147 *out = [0; 16];
148 for k in 0..4 {
149 let c = coef[k];
150 let level = ((c.unsigned_abs() as i64 * mf as i64 + f as i64) >> qbits) as i32;
151 if level != 0 {
152 nz += 1;
153 }
154 out[k] = if c < 0 { -level } else { level };
155 }
156 nz
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use crate::transform::{
163 LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4,
164 luma_dc_transform, unzigzag,
165 };
166
167 fn ls() -> LevelScale4x4 {
168 LevelScale4x4::new(&[16; 16])
169 }
170
171 /// A residual quantised at QP and put back through the *normative* inverse
172 /// comes back within the quantiser step, at every QP: this is the property
173 /// that makes the forward direction a valid inverse of clause 8.5, and a
174 /// wrong multiplier or shift breaks it by orders of magnitude.
175 #[test]
176 fn ac_round_trip_within_a_quantiser_step() {
177 let ls = ls();
178 for qp in 0..52 {
179 let mut worst = 0i32;
180 for seed in 0..8u32 {
181 let src: [i32; 16] = std::array::from_fn(|i| {
182 let v = (seed.wrapping_mul(2654435761).wrapping_add(i as u32 * 40503)) >> 24;
183 (v as i32 % 61) - 30
184 });
185 let mut coef = src;
186 forward_4x4(&mut coef);
187 let mut scan = [0i32; 16];
188 quant_4x4(&coef, qp, true, false, &mut scan);
189 let mut raster = [0i32; 16];
190 unzigzag(&scan, &mut raster);
191 dequant_4x4(&mut raster, &ls, qp, false);
192 let mut out = [0i32; 16];
193 inverse_transform_4x4(&raster, &mut out);
194 for i in 0..16 {
195 worst = worst.max((out[i] - src[i]).abs());
196 }
197 }
198 // The reconstruction error of a dead-zone quantiser is bounded by
199 // one step, which doubles every six QP.
200 let step = 1 << (qp / 6);
201 assert!(
202 worst <= 2 + 2 * step,
203 "qp {qp}: worst error {worst} over step {step}"
204 );
205 }
206 }
207
208 /// The same for the Intra_16x16 luma DC path: a flat residual across the
209 /// whole macroblock survives Hadamard, quantisation and the decoder's
210 /// 8.5.10 inverse.
211 #[test]
212 fn luma_dc_round_trip() {
213 let ls = ls();
214 for qp in 0..52 {
215 for &x in &[-40i32, -7, 3, 25] {
216 // Every 4x4 block of a flat macroblock has DC = 16 * x.
217 let dc: [i32; 16] = [16 * x; 16];
218 let mut had = dc;
219 forward_hadamard_4x4(&mut had);
220 let mut scan = [0i32; 16];
221 quant_luma_dc(&had, qp, &mut scan);
222 let mut raster = [0i32; 16];
223 unzigzag(&scan, &mut raster);
224 luma_dc_transform(&mut raster, &ls, qp);
225 // Each block reconstructs (dc + 32) >> 6 flat samples.
226 let recon = (raster[0] + 32) >> 6;
227 let step = 1 << (qp / 6);
228 assert!(
229 (recon - x).abs() <= 2 + 2 * step,
230 "qp {qp} x {x}: recon {recon}"
231 );
232 }
233 }
234 }
235
236 /// And the chroma DC path (2x2 Hadamard, 8.5.11).
237 #[test]
238 fn chroma_dc_round_trip() {
239 let ls = ls();
240 for qp in 0..40 {
241 for &x in &[-30i32, -4, 9, 21] {
242 let dc: [i32; 4] = [16 * x; 4];
243 let mut had = dc;
244 forward_hadamard_2x2(&mut had);
245 let mut scan = [0i32; 16];
246 quant_chroma_dc(&had, qp, true, &mut scan);
247 let mut c: [i32; 4] = [scan[0], scan[1], scan[2], scan[3]];
248 chroma_dc_transform_420(&mut c, &ls, qp);
249 let recon = (c[0] + 32) >> 6;
250 let step = 1 << (qp / 6);
251 assert!(
252 (recon - x).abs() <= 2 + 2 * step,
253 "qp {qp} x {x}: recon {recon}"
254 );
255 }
256 }
257 }
258}