forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

transform.rs639 lines, 24.0 KiBHistoryRawDownload
1//! Inverse transforms (inverse DCT, inverse Walsh-Hadamard) and dequant
2//! factor computation for VP8 (RFC 6386 §14).
3//!
4//! Every function here is a bit-exact transcription of the normative
5//! reference implementation in libvpx (`vp8/common/idctllm.c` and
6//! `vp8/common/quant_common.c`), which is also what RFC 6386 §§14.3–14.5
7//! print as pseudocode. Bit-level fidelity of the rounding is a hard
8//! requirement: arithmetic right shifts (`>>` on `i32` in Rust, as in C)
9//! round toward negative infinity, and both implementations rely on that
10//! floor behavior for negative operands.
11//!
12//! Fidelity details reproduced verbatim from the oracle:
13//! - The 16-bit fixed-point constants `cospi8sqrt2minus1 = 20091` and
14//! `sinpi8sqrt2 = 35468` (§14.4). The `>> 16` multiplies carry **no**
15//! rounding constant; the `+4` before the final `>> 3` appears only in
16//! the second DCT pass.
17//! - `short output[16]` intermediates: libvpx stores the first-pass
18//! results into a `short` array, truncating `i32` arithmetic to `i16`
19//! between passes. We reproduce those truncation points with `as i16`
20//! (wrapping two's-complement truncation, identical to the de facto C
21//! behavior) so results stay oracle-exact even for adversarial inputs.
22//! - The inverse WHT rounds with `(x + 3) >> 3` (§14.3); the DC-only
23//! shortcut uses the same constant on `input[0]` alone.
24//!
25//! All functions are pure, allocation-free, and carry no SIMD code.
26
27
28/// 16-bit fixed-point `sqrt(2) * cos(pi/8) - 1` (RFC 6386 §14.4). The
29/// product `x * sqrt(2) * cos(pi/8)` is computed as `x + ((x * K) >> 16)`
30/// because the constant exceeds 1.0 and would otherwise lose precision.
31const COSPI8SQRT2MINUS1: i32 = 20091;
32
33/// 16-bit fixed-point `sqrt(2) * sin(pi/8)` (RFC 6386 §14.4).
34const SINPI8SQRT2: i32 = 35468;
35
36/// DC quantizer lookup, `dc_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1),
37/// transcribed mechanically from libvpx `vp8/common/quant_common.c`.
38const DC_QLOOKUP: [i16; 128] = [
39 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13, 14, 15, 16, 17, 17, 18, 19, 20, 20, 21, 21, 22, 22, 23,
40 23, 24, 25, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44,
41 45, 46, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
42 68, 69, 70, 71, 72, 73, 74, 75, 76, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91,
43 93, 95, 96, 98, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 122, 124, 126, 128, 130,
44 132, 134, 136, 138, 140, 143, 145, 148, 151, 154, 157,
45];
46
47/// AC quantizer lookup, `ac_qlookup[QINDEX_RANGE]` (RFC 6386 §14.1),
48/// transcribed mechanically from libvpx `vp8/common/quant_common.c`.
49const AC_QLOOKUP: [i16; 128] = [
50 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
51 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
52 53, 54, 55, 56, 57, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94,
53 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 119, 122, 125, 128, 131, 134, 137, 140,
54 143, 146, 149, 152, 155, 158, 161, 164, 167, 170, 173, 177, 181, 185, 189, 193, 197, 201, 205,
55 209, 213, 217, 221, 225, 229, 234, 239, 245, 249, 254, 259, 264, 269, 274, 279, 284,
56];
57
58/// Clamps a (possibly delta-adjusted) quantizer index to the valid
59/// qindex range `[0, 127]` — dixie `clamp_q` / libvpx bounds in
60/// `quant_common.c` (RFC 6386 §14.1).
61#[inline]
62fn clamp_q(q: i32) -> i32 {
63 q.clamp(0, 127)
64}
65
66/// `dc_qlookup[clamp(q + delta)]` — Y-after-second / per-plane DC factor
67/// lookup with delta adjustment (RFC 6386 §14.1 `dc_q`).
68#[inline]
69fn dc_factor(q: i32, delta: i32) -> i16 {
70 DC_QLOOKUP[clamp_q(q + delta) as usize]
71}
72
73/// `ac_qlookup[clamp(q + delta)]` — AC factor lookup with delta
74/// adjustment (RFC 6386 §14.1 `ac_q`).
75#[inline]
76fn ac_factor(q: i32, delta: i32) -> i16 {
77 AC_QLOOKUP[clamp_q(q + delta) as usize]
78}
79
80/// Inverse Walsh-Hadamard transform of the 16 dequantized Y2 DC
81/// coefficients into the 16 Y-subblock DC residuals
82/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_c`, oracle
83/// `vp8_short_inv_walsh4x4_c` in `idctllm.c`).
84///
85/// `input` is the row-major 4x4 block of dequantized Y2 DCs; the returned
86/// array holds the 16 Y-subblock DC values in the same row-major order
87/// (the reference scatters `output[i]` to `mb_dqcoeff[i * 16]`, i.e. the
88/// DC slot of the i-th Y subblock — the caller places them). Two passes
89/// of the exact 4-point Hadamard butterfly, with `short` truncation of
90/// the first-pass results and `(x + 3) >> 3` rounding in the second.
91#[inline]
92pub fn iwht4x4(input: &[i16; 16]) -> [i16; 16] {
93 let mut tmp = [0i16; 16];
94
95 // First pass: transform columns; results are stored transposed into
96 // rows of `tmp` (ip walks input[i], input[4+i], input[8+i],
97 // input[12+i]). libvpx stores into `short`: truncate to i16.
98 for i in 0..4 {
99 let a1 = input[i] as i32 + input[12 + i] as i32;
100 let b1 = input[4 + i] as i32 + input[8 + i] as i32;
101 let c1 = input[4 + i] as i32 - input[8 + i] as i32;
102 let d1 = input[i] as i32 - input[12 + i] as i32;
103
104 tmp[i] = (a1 + b1) as i16;
105 tmp[4 + i] = (c1 + d1) as i16;
106 tmp[8 + i] = (a1 - b1) as i16;
107 tmp[12 + i] = (d1 - c1) as i16;
108 }
109
110 let mut output = [0i16; 16];
111
112 // Second pass: transform rows in place, rounding with (x + 3) >> 3.
113 for r in 0..4 {
114 let i = 4 * r;
115 let a1 = tmp[i] as i32 + tmp[i + 3] as i32;
116 let b1 = tmp[i + 1] as i32 + tmp[i + 2] as i32;
117 let c1 = tmp[i + 1] as i32 - tmp[i + 2] as i32;
118 let d1 = tmp[i] as i32 - tmp[i + 3] as i32;
119
120 let a2 = a1 + b1;
121 let b2 = c1 + d1;
122 let c2 = a1 - b1;
123 let d2 = d1 - c1;
124
125 output[i] = ((a2 + 3) >> 3) as i16;
126 output[i + 1] = ((b2 + 3) >> 3) as i16;
127 output[i + 2] = ((c2 + 3) >> 3) as i16;
128 output[i + 3] = ((d2 + 3) >> 3) as i16;
129 }
130
131 output
132}
133
134/// One-nonzero-DC shortcut of the inverse WHT
135/// (RFC 6386 §14.3 `vp8_short_inv_walsh4x4_1_c`, oracle
136/// `vp8_short_inv_walsh4x4_1_c` in `idctllm.c`).
137///
138/// When only `input[0]` is non-zero, every Y-subblock DC equals
139/// `(input[0] + 3) >> 3`. Bit-identical to `iwht4x4` for such inputs.
140#[inline]
141pub fn iwht4x4_dc(input: &[i16; 16]) -> [i16; 16] {
142 let a1 = ((input[0] as i32 + 3) >> 3) as i16;
143 [a1; 16]
144}
145
146/// Full inverse DCT of one dequantized 4x4 coefficient block
147/// (RFC 6386 §14.4; oracle `short_idct4x4llm_c` in `idctllm.c`).
148///
149/// `coeffs` is a row-major 4x4 block of **already dequantized**
150/// coefficients (dequantization happens before the transform, RFC 6386
151/// §14.5). Two passes of the 4-point inverse DCT with the §14.4
152/// fixed-point constants; the `>> 16` multiplies carry no rounding
153/// constant and the `(x + 4) >> 3` rounding is applied only in the
154/// second pass. First-pass results are truncated to `i16` exactly where
155/// the oracle stores into its `short output[16]` scratch.
156///
157/// Returns the row-major 4x4 residual. Not clamped, not added to the
158/// prediction — see [`idct4x4_add`] for the combined form.
159#[inline]
160pub fn idct4x4(coeffs: &[i16; 16]) -> [i16; 16] {
161 let mut tmp = [0i16; 16];
162
163 // First pass: transform columns; results land transposed in rows of
164 // `tmp` (ip walks coeffs[i], coeffs[4+i], coeffs[8+i], coeffs[12+i]).
165 for i in 0..4 {
166 let a1 = coeffs[i] as i32 + coeffs[8 + i] as i32;
167 let b1 = coeffs[i] as i32 - coeffs[8 + i] as i32;
168
169 let temp1 = (coeffs[4 + i] as i32 * SINPI8SQRT2) >> 16;
170 let temp2 = coeffs[12 + i] as i32 + ((coeffs[12 + i] as i32 * COSPI8SQRT2MINUS1) >> 16);
171 let c1 = temp1 - temp2;
172
173 let temp1 = coeffs[4 + i] as i32 + ((coeffs[4 + i] as i32 * COSPI8SQRT2MINUS1) >> 16);
174 let temp2 = (coeffs[12 + i] as i32 * SINPI8SQRT2) >> 16;
175 let d1 = temp1 + temp2;
176
177 // libvpx stores into `short`: truncate to i16.
178 tmp[i] = (a1 + d1) as i16;
179 tmp[12 + i] = (a1 - d1) as i16;
180 tmp[4 + i] = (b1 + c1) as i16;
181 tmp[8 + i] = (b1 - c1) as i16;
182 }
183
184 let mut output = [0i16; 16];
185
186 // Second pass: transform rows, rounding with (x + 4) >> 3.
187 for r in 0..4 {
188 let i = 4 * r;
189 let ip0 = tmp[i] as i32;
190 let ip1 = tmp[i + 1] as i32;
191 let ip2 = tmp[i + 2] as i32;
192 let ip3 = tmp[i + 3] as i32;
193
194 let a1 = ip0 + ip2;
195 let b1 = ip0 - ip2;
196
197 let temp1 = (ip1 * SINPI8SQRT2) >> 16;
198 let temp2 = ip3 + ((ip3 * COSPI8SQRT2MINUS1) >> 16);
199 let c1 = temp1 - temp2;
200
201 let temp1 = ip1 + ((ip1 * COSPI8SQRT2MINUS1) >> 16);
202 let temp2 = (ip3 * SINPI8SQRT2) >> 16;
203 let d1 = temp1 + temp2;
204
205 output[i] = ((a1 + d1 + 4) >> 3) as i16;
206 output[i + 3] = ((a1 - d1 + 4) >> 3) as i16;
207 output[i + 1] = ((b1 + c1 + 4) >> 3) as i16;
208 output[i + 2] = ((b1 - c1 + 4) >> 3) as i16;
209 }
210
211 output
212}
213
214/// DC-only inverse DCT shortcut (RFC 6386 §14.4
215/// `vp8_dc_only_idct_add_c` math; oracle `idctllm.c`): when position 0 is
216/// the sole non-zero coefficient, every residual pixel is `(dc + 4) >> 3`.
217///
218/// Bit-identical to `idct4x4` on such inputs. Not clamped; the caller
219/// adds and clamps (or uses [`idct4x4_add`]).
220#[inline]
221pub fn idct4x4_dc(dc: i16) -> [i16; 16] {
222 let a1 = ((dc as i32 + 4) >> 3) as i16;
223 [a1; 16]
224}
225
226/// Combined per-block reconstruction kernel (RFC 6386 §14.4/§14.5; oracle
227/// `short_idct4x4llm_c` final loop in `idctllm.c`): inverse-transforms
228/// `coeffs` and writes `clamp(predict + residual)` into `recon`.
229///
230/// `coeffs` must already be dequantized (dequantization is applied before
231/// the transform; for intra Y macroblocks the DC positions already hold
232/// the [`iwht4x4`] output). `predict` and `recon` are row-major 4x4
233/// blocks of exactly 16 bytes each. Residuals are fully computed before
234/// any output byte is written.
235#[inline]
236pub fn idct4x4_add(coeffs: &[i16; 16], predict: &[u8], recon: &mut [u8]) {
237 let residual = idct4x4(coeffs);
238 for i in 0..16 {
239 let a = residual[i] as i32 + predict[i] as i32;
240 recon[i] = a.clamp(0, 255) as u8;
241 }
242}
243
244/// Dequantization factors for one macroblock, indexed by plane and
245/// coefficient type (RFC 6386 §14.1; dixie `struct dequant_factors`).
246#[derive(Clone, Copy, Debug, PartialEq, Eq)]
247pub struct Dequant {
248 /// Y plane, DC coefficient (after inverse WHT for intra Y2 rows).
249 pub y1_dc: i16,
250 /// Y plane, AC coefficients.
251 pub y1_ac: i16,
252 /// Y2 plane (second-order) DC coefficient: `dc_qlookup[...] * 2`.
253 pub y2_dc: i16,
254 /// Y2 plane AC coefficient: `ac_qlookup[...] * 155 / 100`, floored at 8.
255 pub y2_ac: i16,
256 /// Chroma DC coefficient, capped at 132 after lookup.
257 pub uv_dc: i16,
258 /// Chroma AC coefficient.
259 pub uv_ac: i16,
260}
261
262/// Computes the six dequantization factors for quantizer index `q` with
263/// the per-frame delta updates (RFC 6386 §9.6 header fields applied per
264/// §14.1; dixie `dequant_init`, oracle `vp8cx_init_quantizer` in
265/// libvpx `decodframe.c` / `quant_common.c`).
266///
267/// `q` is the per-macroblock segment-adjusted base qindex (already
268/// absolute or offset by the segment level per the segment header); the
269/// delta arguments are the frame-header updates. Each lookup clamps its
270/// `q + delta` sum to `[0, 127]`. Semantics transcribed exactly:
271/// - `y1_dc = dc_qlookup[clamp(q + y1_dc_delta)]`,
272/// `y1_ac = ac_qlookup[clamp(q)]` (no delta exists for Y AC),
273/// - `y2_dc = dc_qlookup[clamp(q + y2_dc_delta)] * 2`,
274/// - `y2_ac = ac_qlookup[clamp(q + y2_ac_delta)] * 155 / 100` (integer
275/// division), floored at 8,
276/// - `uv_dc = min(dc_qlookup[clamp(q + uv_dc_delta)], 132)` (cap applied
277/// after the lookup),
278/// - `uv_ac = ac_qlookup[clamp(q + uv_ac_delta)]`.
279#[must_use]
280pub fn dequant(
281 q: i32,
282 y1_dc_delta: i32,
283 y2_dc_delta: i32,
284 y2_ac_delta: i32,
285 uv_dc_delta: i32,
286 uv_ac_delta: i32,
287) -> Dequant {
288 Dequant {
289 y1_dc: dc_factor(q, y1_dc_delta),
290 y1_ac: ac_factor(q, 0),
291 y2_dc: dc_factor(q, y2_dc_delta) * 2,
292 y2_ac: {
293 let v = (ac_factor(q, y2_ac_delta) as i32 * 155) / 100;
294 (if v < 8 { 8 } else { v }) as i16
295 },
296 uv_dc: {
297 let v = dc_factor(q, uv_dc_delta);
298 if v > 132 { 132 } else { v }
299 },
300 uv_ac: ac_factor(q, uv_ac_delta),
301 }
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 /// Hand-derived: impulse `input[0] = 8`, all else 0. First pass, the
309 /// only touched column (0) reads (8,0,0,0): a1 = 8+0 = 8, b1 = 0,
310 /// c1 = 0, d1 = 8, giving intermediate column 0 = [8,8,8,8]. Second
311 /// pass, every row reads (8,0,0,0): a2 = b2 = c2 = d2 = 8, and
312 /// (8 + 3) >> 3 = 1. Expected: all 16 outputs are 1.
313 #[test]
314 fn iwht_unit_impulse_yields_all_ones() {
315 let mut input = [0i16; 16];
316 input[0] = 8;
317 assert_eq!(iwht4x4(&input), [1i16; 16]);
318 }
319
320 /// Hand-derived: impulse `input[5] = 8` (row 1, col 1). First pass,
321 /// column 1 reads (0,8,0,0): a1 = 0, b1 = 8, c1 = 8, d1 = 0, giving
322 /// intermediate column 1 = [8, 8, -8, -8]. Second pass, rows 0-1 read
323 /// (0,8,0,0) → outputs (1, 1, -1, -1); rows 2-3 read (0,-8,0,0) →
324 /// (-1, -1, 1, 1) — the Hadamard basis pattern for position (1,1).
325 #[test]
326 fn iwht_impulse_at_row1_col1_yields_hadamard_pattern() {
327 let mut input = [0i16; 16];
328 input[5] = 8;
329 assert_eq!(
330 iwht4x4(&input),
331 [
332 1, 1, -1, -1, //
333 1, 1, -1, -1, //
334 -1, -1, 1, 1, //
335 -1, -1, 1, 1,
336 ]
337 );
338 }
339
340 /// Mixed-coefficient oracle: expected values computed with a Python
341 /// model of the exact libvpx integer algorithm (see the model in
342 /// `idct_mixed_block_matches_oracle` below — the WHT variant is the
343 /// same structure with §14.3 butterflies and `(x + 3) >> 3`).
344 #[test]
345 fn iwht_mixed_block_matches_oracle() {
346 let input = [
347 40, -13, 0, 7, 222, 5, -40, 1, 0, 0, 17, -9, 300, -250, 88, 3,
348 ];
349 assert_eq!(
350 iwht4x4(&input),
351 [
352 46, 30, 95, 110, //
353 9, 42, -15, -55, //
354 -3, -35, 37, 60, //
355 -36, -27, -86, -92,
356 ]
357 );
358 }
359
360 /// The `_dc` shortcut must agree with the full transform whenever
361 /// only `input[0]` is non-zero — across the whole practical range,
362 /// including negatives and both i16 extremes (arithmetic shifts are
363 /// floor rounding for negatives in both C and Rust).
364 #[test]
365 fn iwht_dc_shortcut_matches_full_transform() {
366 for v in [
367 0,
368 1,
369 -1,
370 3,
371 -3,
372 8,
373 -8,
374 100,
375 -100,
376 1234,
377 -4321,
378 i16::MAX,
379 i16::MIN,
380 ] {
381 let input = {
382 let mut i = [0i16; 16];
383 i[0] = v;
384 i
385 };
386 assert_eq!(iwht4x4(&input), iwht4x4_dc(&input), "mismatch at dc={v}");
387 }
388 }
389
390 /// §14.4 DC-only math: input [40, 0, ...] gives every pixel
391 /// (40 + 4) >> 3 = 5.
392 #[test]
393 fn idct_dc_only_40_yields_five() {
394 let coeffs = {
395 let mut c = [0i16; 16];
396 c[0] = 40;
397 c
398 };
399 assert_eq!(idct4x4(&coeffs), [5i16; 16]);
400 assert_eq!(idct4x4_dc(40), [5i16; 16]);
401 }
402
403 /// Mixed-coefficient oracle. The Python model below is a line-for-line
404 /// transcription of libvpx `short_idct4x4llm_c` (same integer math,
405 /// `short` truncation between passes via `s16`); running it on
406 /// `coeffs` prints the expected block embedded in the assertion.
407 ///
408 /// ```python
409 /// COS, SIN = 20091, 35468
410 /// def s16(x):
411 /// x &= 0xFFFF
412 /// return x - 0x10000 if x >= 0x8000 else x
413 /// def idct(inp):
414 /// out = [0] * 16
415 /// for i in range(4): # pass 1: columns, transposed into rows
416 /// a1 = inp[i] + inp[8+i]; b1 = inp[i] - inp[8+i]
417 /// c1 = ((inp[4+i]*SIN) >> 16) - (inp[12+i] + ((inp[12+i]*COS) >> 16))
418 /// d1 = (inp[4+i] + ((inp[4+i]*COS) >> 16)) + ((inp[12+i]*SIN) >> 16)
419 /// out[i] = s16(a1 + d1); out[12+i] = s16(a1 - d1)
420 /// out[4+i] = s16(b1 + c1); out[8+i] = s16(b1 - c1)
421 /// res = [0] * 16
422 /// for i in range(4): # pass 2: rows, rounding (x + 4) >> 3
423 /// ip = out[4*i:4*i+4]
424 /// a1 = ip[0] + ip[2]; b1 = ip[0] - ip[2]
425 /// c1 = ((ip[1]*SIN) >> 16) - (ip[3] + ((ip[3]*COS) >> 16))
426 /// d1 = (ip[1] + ((ip[1]*COS) >> 16)) + ((ip[3]*SIN) >> 16)
427 /// res[4*i+0] = s16((a1 + d1 + 4) >> 3)
428 /// res[4*i+3] = s16((a1 - d1 + 4) >> 3)
429 /// res[4*i+1] = s16((b1 + c1 + 4) >> 3)
430 /// res[4*i+2] = s16((b1 - c1 + 4) >> 3)
431 /// return res
432 /// ```
433 #[test]
434 fn idct_mixed_block_matches_oracle() {
435 let coeffs = [
436 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55,
437 ];
438 assert_eq!(
439 idct4x4(&coeffs),
440 [
441 305, 108, 139, 72, //
442 -508, -228, -88, 303, //
443 372, 85, -443, -640, //
444 -48, -41, 345, 441,
445 ]
446 );
447 }
448
449 /// The DC-only shortcut must equal the full transform for any value
450 /// at coefficient position 0 (with the rest zero), including the i16
451 /// extremes where the intermediate still fits.
452 #[test]
453 fn idct_dc_shortcut_matches_full_transform() {
454 for v in [
455 0,
456 1,
457 -1,
458 8,
459 -8,
460 40,
461 -40,
462 100,
463 -100,
464 4088,
465 i16::MAX,
466 i16::MIN,
467 ] {
468 let coeffs = {
469 let mut c = [0i16; 16];
470 c[0] = v;
471 c
472 };
473 assert_eq!(idct4x4(&coeffs), idct4x4_dc(v), "mismatch at dc={v}");
474 }
475 }
476
477 /// §14.5: `idct4x4_add` is `clamp255(predict + idct4x4(coeffs))`
478 /// pixelwise. With a flat prediction of 100, every output byte must
479 /// be the saturated sum; extreme residuals clamp to 0 and 255.
480 #[test]
481 fn idct_add_equals_clamped_predict_plus_residual() {
482 let coeffs = [
483 87, -43, 210, 5, -19, 0, 33, -77, 1234, -517, 9, 401, -88, 2100, -3, 55,
484 ];
485 let residual = idct4x4(&coeffs);
486 let predict = [100u8; 16];
487 let mut recon = [0u8; 16];
488 idct4x4_add(&coeffs, &predict, &mut recon);
489 for i in 0..16 {
490 let expected = (residual[i] as i32 + 100).clamp(0, 255) as u8;
491 assert_eq!(recon[i], expected, "pixel {i}");
492 }
493
494 // Saturation: DC 4088 → residual (4088 + 4) >> 3 = 511; 100 + 511
495 // clamps to 255. Negative DC -32768 → residual (-32764) >> 3 =
496 // -4096; clamps to 0.
497 let mut hi = [0i16; 16];
498 hi[0] = 4088;
499 let mut lo = [0i16; 16];
500 lo[0] = i16::MIN;
501 let mut recon = [0u8; 16];
502 idct4x4_add(&hi, &predict, &mut recon);
503 assert_eq!(recon, [255u8; 16]);
504 idct4x4_add(&lo, &predict, &mut recon);
505 assert_eq!(recon, [0u8; 16]);
506 }
507
508 /// `idct4x4_add` over an existing recon block that already holds the
509 /// prediction (the common libvpx dst/pred shape). The `&[u8]` /
510 /// `&mut [u8]` signature statically excludes predict/recon aliasing.
511 #[test]
512 fn idct_add_updates_existing_recon_buffer() {
513 let coeffs = {
514 let mut c = [0i16; 16];
515 c[0] = 40;
516 c
517 };
518 let predict = [100u8; 16];
519 let mut recon = [100u8; 16];
520 idct4x4_add(&coeffs, &predict, &mut recon);
521 assert_eq!(recon, [105u8; 16]);
522 }
523
524 /// §14.1 tables, transcribed from libvpx `quant_common.c`: exact
525 /// length plus boundary and known-trap entries (the duplicated 10 at
526 /// dc[6..7], the >89 acceleration at dc[95..96] and dc[111..112], and
527 /// the ac[54..55] and ac[84..85] jumps).
528 #[test]
529 fn quant_lookup_tables_match_libvpx() {
530 assert_eq!(DC_QLOOKUP.len(), 128);
531 assert_eq!(AC_QLOOKUP.len(), 128);
532 assert_eq!(&DC_QLOOKUP[..3], &[4, 5, 6]);
533 assert_eq!(DC_QLOOKUP[127], 157);
534 assert_eq!(AC_QLOOKUP[0], 4);
535 assert_eq!(AC_QLOOKUP[127], 284);
536 assert_eq!(&DC_QLOOKUP[6..=8], &[10, 10, 11]);
537 assert_eq!(&DC_QLOOKUP[95..=97], &[89, 91, 93]);
538 assert_eq!(&DC_QLOOKUP[111..=112], &[118, 122]);
539 assert_eq!(&AC_QLOOKUP[53..=55], &[57, 58, 60]);
540 assert_eq!(&AC_QLOOKUP[83..=85], &[116, 119, 122]);
541 }
542
543 /// §14.1 boundary qindices: q=0 gives the minimum factors (with the
544 /// Y2 AC floor of 8 already active), q=127 gives the maxima including
545 /// the chroma DC cap at 132.
546 #[test]
547 fn dequant_at_qindex_boundaries() {
548 assert_eq!(
549 dequant(0, 0, 0, 0, 0, 0),
550 Dequant {
551 y1_dc: 4,
552 y1_ac: 4,
553 y2_dc: 8,
554 y2_ac: 8,
555 uv_dc: 4,
556 uv_ac: 4
557 }
558 );
559 assert_eq!(
560 dequant(127, 0, 0, 0, 0, 0),
561 Dequant {
562 y1_dc: 157,
563 y1_ac: 284,
564 y2_dc: 314,
565 y2_ac: 440, // 284 * 155 / 100
566 uv_dc: 132, // 157 capped at 132
567 uv_ac: 284,
568 }
569 );
570 }
571
572 /// Delta-adjusted qindices clamp to [0, 127] before each lookup, for
573 /// every delta channel (RFC 6386 §14.1 dixie `clamp_q`).
574 #[test]
575 fn dequant_delta_indices_clamp_to_qindex_range() {
576 let lo = dequant(0, -1000, -1000, -1000, -1000, -1000);
577 assert_eq!(lo.y1_dc, 4);
578 assert_eq!(lo.y2_dc, 8); // 4 * 2
579 assert_eq!(lo.y2_ac, 8); // floor
580 assert_eq!(lo.uv_dc, 4);
581 assert_eq!(lo.uv_ac, 4);
582
583 let hi = dequant(127, 1000, 1000, 1000, 1000, 1000);
584 assert_eq!(hi.y1_dc, 157);
585 assert_eq!(hi.y2_dc, 314);
586 assert_eq!(hi.y2_ac, 440);
587 assert_eq!(hi.uv_dc, 132);
588 assert_eq!(hi.uv_ac, 284);
589
590 // A base q of 0 with positive deltas reaches mid-table: q=60 has
591 // dc_qlookup[60] = 55, ac_qlookup[60] = 70.
592 let mid = dequant(0, 60, 60, 60, 60, 60);
593 assert_eq!(mid.y1_dc, 55);
594 assert_eq!(mid.y1_ac, 4); // Y AC has no delta channel
595 assert_eq!(mid.y2_dc, 110);
596 assert_eq!(mid.y2_ac, 70 * 155 / 100); // 108
597 assert_eq!(mid.uv_dc, 55);
598 assert_eq!(mid.uv_ac, 70);
599 }
600
601 /// The Y2 AC floor: `x * 155 / 100 < 8` becomes 8. At q=0..4
602 /// (ac = 4..8) the scaled values are 6, 7, 9, 10, 12 — only the first
603 /// two floor up.
604 #[test]
605 fn dequant_y2_ac_floor_at_eight() {
606 for q in 0..=4i32 {
607 let ac = AC_QLOOKUP[q as usize] as i32;
608 let scaled = ac * 155 / 100;
609 assert_eq!(
610 dequant(q, 0, 0, 0, 0, 0).y2_ac as i32,
611 scaled.max(8),
612 "q={q}"
613 );
614 }
615 assert_eq!(dequant(0, 0, 0, 0, 0, 0).y2_ac, 8); // 4*155/100 = 6 → 8
616 assert_eq!(dequant(1, 0, 0, 0, 0, 0).y2_ac, 8); // 5*155/100 = 7 → 8
617 assert_eq!(dequant(2, 0, 0, 0, 0, 0).y2_ac, 9); // 6*155/100 = 9
618 }
619
620 /// libvpx computes the Y2 AC factor as `(x * 101581) >> 16` and its
621 /// comment asserts bitwise equality with `x * 155 / 100` for all
622 /// table entries; our transcription of dixie uses `* 155 / 100`, so
623 /// sweep the whole qindex range and prove the two agree through the
624 /// public API (with a matching delta for the Y2 AC channel).
625 #[test]
626 fn dequant_y2_ac_matches_libvpx_fixed_point_over_all_q() {
627 for q in 0..=127i32 {
628 for delta in [0, -q - 1, 127 - q] {
629 let x = AC_QLOOKUP[clamp_q(q + delta) as usize] as i32;
630 let expected = (((x * 101581) >> 16).max(8)) as i16;
631 assert_eq!(
632 dequant(q, 0, 0, delta, 0, 0).y2_ac,
633 expected,
634 "q={q}, delta={delta}"
635 );
636 }
637 }
638 }
639}