forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB70849e0Tahinli2 months ago3122 commits

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