oxideav_vp8/dct_tokens.rs
1//! VP8 DCT-coefficient token decoding per RFC 6386 §13.
2//!
3//! This module walks the `coeff_tree` of §13.2 against the
4//! `coeff_probs[4][8][3][11]` probability table to recover the sixteen
5//! quantised DCT coefficients of a single 4×4 sub-block. Encoded
6//! coefficients are written into a caller-supplied `[i16; 16]` in the
7//! spec's "implicit position" order — i.e. positions `firstCoeff ..
8//! firstCoeff + n` of the (already-zig-zagged) sub-block array. After
9//! a `dct_eob` token the remaining positions are left at zero.
10//!
11//! **What is in this module:**
12//!
13//! * The §13.2 token-tree walk, with the §13.2 "skip the dct_eob
14//! branch when the previous coefficient was a DCT_0" optimisation.
15//! The tree is fixed (`COEFF_TREE` transcribes the §13.2 listing),
16//! so the production descent in `decode_block_core` is written out
17//! branch-by-branch — each internal node reads `probs[node >> 1]`
18//! exactly as the generic §8.1 `treed_read` walk would, but without
19//! the per-step tree-table loads, and each leaf flows straight into
20//! its §13.2 consequence (zero / small value / `DCTextra` category /
21//! end-of-block). The "skip dct_eob" rule becomes the inner
22//! zero-run loop re-entering at the DCT_0 node. Bit-equivalence
23//! against a generic table-driven walker over the same `COEFF_TREE`
24//! is enforced by `fused_descent_matches_generic_tree_walk`.
25//! * The §13.2 `DCTextra` extra-bits decoder over the six fixed
26//! probability tables `Pcat1..Pcat6`.
27//! * The §13.2 sign bit (read at probability 128).
28//! * The §13.3 `coeff_bands[16]` position-to-band mapping that selects
29//! the second probability-table index.
30//! * The §13.3 "previous-token class" `ctx3` rollover that selects the
31//! third probability-table index (0 if previous was zero, 1 if its
32//! absolute value was 1, 2 if its absolute value was > 1).
33//! * The §13.3 plane-type discriminator: 0 = Y after Y2, 1 = Y2,
34//! 2 = U or V, 3 = Y in the absence of Y2.
35//! * The §13.5 default token-probability table (transcribed verbatim).
36//! * A `merge_default_token_probs` helper that overlays a
37//! `TokenProbUpdates` (from `coded_header::Vp8CodedHeader`) onto the
38//! default table, producing a complete `coeff_probs[4][8][3][11]`
39//! ready for `decode_block` calls.
40//! * The §13.3 per-macroblock token walk (`decode_mb_coeffs`): it
41//! aggregates the 24/25 blocks of one macroblock — the §14.2 Y2 (WHT)
42//! block first when present, then the sixteen Y DCT blocks, then the
43//! four U and four V chroma blocks — threading the above / left
44//! non-zero predictor context through the §20.16
45//! `left_context_index` / `above_context_index` slot tables, honouring
46//! the §13.1 `mb_skip_coeff` short-circuit (with the §20.16
47//! `reset_mb_context` Y2-preserving rule), selecting the
48//! `YAfterY2` / `YNoY2` plane per `has_y2`, and reordering each block
49//! into raster order via the §20.16 `zigzag[16]` table. It produces a
50//! [`crate::frame::MbCoeffs`].
51//!
52//! **What is NOT in this module yet:**
53//!
54//! * Dequantisation — multiplying the recovered `i16` coefficients by
55//! the §14.1 `dc_qlookup` / `ac_qlookup` table values. `decode_mb_coeffs`
56//! emits the **raw quantized** token coefficients (in raster order);
57//! the §14.1 Y2 / chroma dequant scaling remains a documented spec gap
58//! (§14.1 page 77 defers it to `dixie.c` §20.4).
59//! * The inverse WHT / IDCT (§14.2 / §14.3).
60//!
61//! # Spec-pseudocode caveat
62//!
63//! RFC 6386 §13.3 page 67's pseudocode ends each iteration with the
64//! literal statement `prevCoeffWasZero = true;` — i.e. *unconditionally
65//! true*. That is plainly a transcription error: the field is named
66//! `prevCoeffWasZero` and is used at the next iteration's tree entry
67//! to decide whether to skip the `dct_eob` branch (which is illegal
68//! after a zero). Setting it unconditionally true would mean **every
69//! coefficient after the first** allows EOB-after-non-zero, which
70//! contradicts §13.2's "if the preceding coefficient is a DCT_0,
71//! decoding will skip the first branch" statement. We treat the
72//! correct semantics as `prevCoeffWasZero = (token == DCT_0)`. The
73//! `prev_token_skips_eob_branch` test exercises both directions to
74//! prove this branch decision matters.
75
76use crate::bool_decoder::{BoolDecoder, BoolDecoderError};
77use crate::coded_header::TokenProbUpdates;
78
79/// Twelve DCT-token alphabet symbols per RFC 6386 §13.2. Order is
80/// fixed to match the spec; the integer discriminants are also the
81/// `dct_token` enum values.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum DctToken {
84 /// Coefficient value 0.
85 Dct0 = 0,
86 /// Coefficient value 1.
87 Dct1 = 1,
88 /// Coefficient value 2.
89 Dct2 = 2,
90 /// Coefficient value 3.
91 Dct3 = 3,
92 /// Coefficient value 4.
93 Dct4 = 4,
94 /// Range `5..=6` (size 2; 1 extra bit).
95 Cat1 = 5,
96 /// Range `7..=10` (size 4; 2 extra bits).
97 Cat2 = 6,
98 /// Range `11..=18` (size 8; 3 extra bits).
99 Cat3 = 7,
100 /// Range `19..=34` (size 16; 4 extra bits).
101 Cat4 = 8,
102 /// Range `35..=66` (size 32; 5 extra bits).
103 Cat5 = 9,
104 /// Range `67..=2048` (size 1982; 11 extra bits).
105 Cat6 = 10,
106 /// End of block — the remaining coefficients of this sub-block
107 /// are zero.
108 Eob = 11,
109}
110
111/// The §13.3 "plane type" — the outermost index into
112/// `coeff_probs[4][8][3][11]`.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum BlockType {
115 /// Y luma block when the macroblock also has a Y2 block — i.e.
116 /// the DC slot is part of Y2 and Y DCT starts at coefficient 1.
117 YAfterY2 = 0,
118 /// The Y2 block itself (one per macroblock, holds the 16 Y DCs).
119 Y2 = 1,
120 /// U or V chroma block.
121 UV = 2,
122 /// Y luma block in a macroblock without Y2 (B_PRED / SPLITMV) —
123 /// Y DCT starts at coefficient 0.
124 YNoY2 = 3,
125}
126
127impl BlockType {
128 /// The §13.3 `firstCoeff` index — the first coefficient position
129 /// the token loop visits. `1` for [`BlockType::YAfterY2`], `0` for
130 /// every other plane.
131 pub const fn first_coeff(self) -> usize {
132 match self {
133 BlockType::YAfterY2 => 1,
134 BlockType::Y2 | BlockType::UV | BlockType::YNoY2 => 0,
135 }
136 }
137
138 /// The numeric `coeff_probs` outermost index per §13.3.
139 pub const fn plane_index(self) -> usize {
140 self as usize
141 }
142}
143
144/// Out-of-band conditions surfaced by [`decode_block`].
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146#[non_exhaustive]
147pub enum DctTokenError {
148 /// Underlying bool-decoder ran out of bytes mid-token.
149 BoolDecoder(BoolDecoderError),
150 /// Historical variant: a generic tree walk stepped to a leaf index
151 /// outside `0..=11`. The production descent is now written out
152 /// branch-by-branch over the fixed §13.2 tree, so this can no
153 /// longer occur; the variant is retained for API compatibility
154 /// (it is part of the public error surface).
155 InvalidTokenIndex,
156}
157
158impl From<BoolDecoderError> for DctTokenError {
159 fn from(e: BoolDecoderError) -> Self {
160 DctTokenError::BoolDecoder(e)
161 }
162}
163
164impl core::fmt::Display for DctTokenError {
165 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
166 match self {
167 DctTokenError::BoolDecoder(e) => write!(f, "vp8 dct token: bool decoder: {e}"),
168 DctTokenError::InvalidTokenIndex => {
169 write!(f, "vp8 dct token: token tree leaf index out of range")
170 }
171 }
172 }
173}
174
175impl std::error::Error for DctTokenError {}
176
177/// §13.2 `coeff_tree` — the eleven-internal-node, twelve-leaf token
178/// tree. Entry `2*i` is the left child of internal node `i`; entry
179/// `2*i + 1` is the right child. Non-negative entries point to the
180/// next internal node; non-positive entries `-t` denote the leaf
181/// `DctToken::from(t as u8)`.
182///
183/// Encoded verbatim from the §13.2 listing. The leading `-Eob` entry
184/// is at index 0; when the previous coefficient was zero the walker
185/// starts at index 2 (skipping the EOB branch) — see [`decode_block`].
186///
187/// The production descent (`decode_block_core`) writes this fixed tree
188/// out branch-by-branch instead of walking the table, so the constant
189/// is no longer loaded on the hot path. It stays as the §13.2
190/// transcription anchor: the test-side token encoder and the generic
191/// reference walker (`fused_descent_matches_generic_tree_walk`) both
192/// consume it to prove the fused descent agrees with the listing.
193#[allow(dead_code)] // production reads are fused; tests consume the table.
194const COEFF_TREE: [i8; 22] = [
195 -(DctToken::Eob as i8),
196 2, // eob = "0"
197 -(DctToken::Dct0 as i8),
198 4, // 0 = "10"
199 -(DctToken::Dct1 as i8),
200 6, // 1 = "110"
201 8,
202 12,
203 -(DctToken::Dct2 as i8),
204 10, // 2 = "11100"
205 -(DctToken::Dct3 as i8),
206 -(DctToken::Dct4 as i8),
207 14,
208 16,
209 -(DctToken::Cat1 as i8),
210 -(DctToken::Cat2 as i8),
211 18,
212 20,
213 -(DctToken::Cat3 as i8),
214 -(DctToken::Cat4 as i8),
215 -(DctToken::Cat5 as i8),
216 -(DctToken::Cat6 as i8),
217];
218
219/// §13.2 `Pcat1` extra-bits probability list (terminator removed).
220const PCAT1: &[u8] = &[159];
221/// §13.2 `Pcat2`.
222const PCAT2: &[u8] = &[165, 145];
223/// §13.2 `Pcat3`.
224const PCAT3: &[u8] = &[173, 148, 140];
225/// §13.2 `Pcat4`.
226const PCAT4: &[u8] = &[176, 155, 140, 135];
227/// §13.2 `Pcat5`.
228const PCAT5: &[u8] = &[180, 157, 141, 134, 130];
229/// §13.2 `Pcat6` — eleven probabilities for the wide cat6 range.
230const PCAT6: &[u8] = &[254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129];
231
232/// §13.2 base values for cat1..cat6 (`categoryBase[6]`).
233const CAT_BASE: [u16; 6] = [5, 7, 11, 19, 35, 67];
234
235/// §13.3 `coeff_bands[16]` — position-to-band lookup for the second
236/// probability-table dimension.
237pub const COEFF_BANDS: [usize; 16] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7];
238
239/// Complete `coeff_probs[plane][band][prev_ctx][position]` table.
240/// The four outer dimensions match RFC 6386 §13.3's `Prob
241/// coeff_probs[4][8][3][num_dct_tokens - 1]` declaration.
242pub type CoeffProbs = [[[[u8; 11]; 3]; 8]; 4];
243
244/// §13.5 default token-probability table (`default_coeff_probs[4][8][3][11]`),
245/// transcribed verbatim from RFC 6386.
246pub const DEFAULT_COEFF_PROBS: CoeffProbs = [
247 // plane 0 — Y after Y2 (DCT starts at coefficient 1)
248 [
249 [
250 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
251 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
252 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
253 ],
254 [
255 [253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128],
256 [189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128],
257 [106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128],
258 ],
259 [
260 [1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128],
261 [181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128],
262 [78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128],
263 ],
264 [
265 [1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128],
266 [184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128],
267 [77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128],
268 ],
269 [
270 [1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128],
271 [170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128],
272 [37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128],
273 ],
274 [
275 [1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128],
276 [207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128],
277 [102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128],
278 ],
279 [
280 [1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128],
281 [177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128],
282 [80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128],
283 ],
284 [
285 [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
286 [246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
287 [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
288 ],
289 ],
290 // plane 1 — Y2
291 [
292 [
293 [198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62],
294 [131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1],
295 [68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128],
296 ],
297 [
298 [1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128],
299 [184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128],
300 [81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128],
301 ],
302 [
303 [1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128],
304 [99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128],
305 [23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128],
306 ],
307 [
308 [1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128],
309 [109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128],
310 [44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128],
311 ],
312 [
313 [1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128],
314 [94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128],
315 [22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128],
316 ],
317 [
318 [1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128],
319 [124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128],
320 [35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128],
321 ],
322 [
323 [1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128],
324 [121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128],
325 [45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128],
326 ],
327 [
328 [1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128],
329 [203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128],
330 [137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128],
331 ],
332 ],
333 // plane 2 — U or V
334 [
335 [
336 [253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128],
337 [175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128],
338 [73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128],
339 ],
340 [
341 [1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128],
342 [239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128],
343 [155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128],
344 ],
345 [
346 [1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128],
347 [201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128],
348 [69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128],
349 ],
350 [
351 [1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128],
352 [223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128],
353 [141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128],
354 ],
355 [
356 [1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128],
357 [190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128],
358 [149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
359 ],
360 [
361 [1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128],
362 [247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128],
363 [240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128],
364 ],
365 [
366 [1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128],
367 [213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128],
368 [55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128],
369 ],
370 [
371 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
372 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
373 [128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128],
374 ],
375 ],
376 // plane 3 — Y in the absence of Y2 (DCT starts at coefficient 0)
377 [
378 [
379 [202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255],
380 [126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128],
381 [61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128],
382 ],
383 [
384 [1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128],
385 [166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128],
386 [39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128],
387 ],
388 [
389 [1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128],
390 [124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128],
391 [24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128],
392 ],
393 [
394 [1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128],
395 [149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128],
396 [28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128],
397 ],
398 [
399 [1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128],
400 [123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128],
401 [20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128],
402 ],
403 [
404 [1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128],
405 [168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128],
406 [47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128],
407 ],
408 [
409 [1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128],
410 [141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128],
411 [42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128],
412 ],
413 [
414 [1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
415 [244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
416 [238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128],
417 ],
418 ],
419];
420
421/// Overlay an in-frame `token_prob_update()` block onto the §13.5
422/// default token-probability table. The output is the resolved
423/// `coeff_probs[4][8][3][11]` used by the per-frame DCT decode loop.
424///
425/// Each entry of `updates` that is `Some(p)` replaces the
426/// corresponding default position; `None` leaves the default in
427/// place. The on-the-wire ordering of `updates` matches RFC 6386
428/// §19.2's `token_prob_update()` four-nested-loop sweep, so the
429/// `[plane][band][prev_ctx][pos]` indexing on the type alias is
430/// already aligned.
431pub fn merge_default_token_probs(updates: &TokenProbUpdates) -> CoeffProbs {
432 let mut out = DEFAULT_COEFF_PROBS;
433 for (plane_idx, plane) in updates.iter().enumerate() {
434 for (band_idx, band) in plane.iter().enumerate() {
435 for (prev_idx, ctx) in band.iter().enumerate() {
436 for (pos_idx, slot) in ctx.iter().enumerate() {
437 if let Some(p) = *slot {
438 out[plane_idx][band_idx][prev_idx][pos_idx] = p;
439 }
440 }
441 }
442 }
443 }
444 out
445}
446
447/// Decode the variable-length "extra bits" trailing a `Cat1..Cat6`
448/// token (RFC 6386 §13.2 `DCTextra`). `cat_probs` is the cat's
449/// fixed probability list (`Pcat1..Pcat6`, terminator omitted).
450#[inline]
451fn read_extra_bits(dec: &mut BoolDecoder<'_>, cat_probs: &[u8]) -> Result<u16, BoolDecoderError> {
452 let mut v: u16 = 0;
453 for &p in cat_probs {
454 let bit = dec.read_bool(p)? as u16;
455 v = (v << 1) | bit;
456 }
457 Ok(v)
458}
459
460/// Identity write-order table — [`decode_block`]'s public contract is
461/// scan-order output, so its core invocation writes position `c` to
462/// slot `c`. The per-macroblock walk passes [`ZIGZAG`] instead and
463/// gets raster-order output without a separate reorder pass.
464const SCAN_IDENTITY: [usize; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
465
466/// The §13.3 token loop with the §13.2 `coeff_tree` descent written
467/// out branch-by-branch.
468///
469/// Each `read_bool` below sits at one internal node of the §13.2
470/// `coeff_tree` and reads `probs[node >> 1]`, exactly as the generic
471/// §8.1 `treed_read` walk over [`COEFF_TREE`] would — the node-by-node
472/// mapping is: `probs[0]` eob-vs-rest (node 0), `probs[1]` DCT_0
473/// (node 2), `probs[2]` DCT_1 (node 4), `probs[3]` small-vs-category
474/// (node 6), `probs[4]`/`probs[5]` DCT_2/3/4 (nodes 8/10),
475/// `probs[6]`..`probs[10]` the cat1..cat6 fan-out (nodes 12..20).
476/// Flattening the walk removes the per-step tree-table loads and lets
477/// every leaf flow directly into its consequence — the §13.2 "skip
478/// the dct_eob branch after a DCT_0" rule becomes the inner zero-run
479/// loop re-entering at the DCT_0 node (with the §13.3 zero-class
480/// `ctx3 = 0` row), so the `prevCoeffWasZero` flag disappears
481/// entirely. The bit-read sequence is identical to the generic walk:
482/// tree bits, then `DCTextra` bits, then the sign bit at probability
483/// 128 (`fused_descent_matches_generic_tree_walk` proves it).
484///
485/// `plane_probs` is the resolved per-plane `[band][prev_ctx][11]`
486/// slice of [`CoeffProbs`]; `seed_ctx3` the §13.3 neighbour-count
487/// context for the first coefficient; `write_order[c]` the output
488/// slot for scan position `c` ([`SCAN_IDENTITY`] or [`ZIGZAG`]).
489/// Returns the number of non-zero coefficients written.
490///
491/// When the `DQ` const parameter is `true` the §14.1 dequant multiply
492/// is fused into the coefficient write: each non-zero value is scaled
493/// by `dc_factor` (raster slot 0) or `ac_factor` (raster slots 1..=15)
494/// — the identical `i32` product / `i16` truncation
495/// [`crate::dequant`]'s per-block apply performs — at the moment it is
496/// produced, so the all-lanes second pass over the macroblock (400
497/// occupancy-independent multiplies plus an 800-byte re-walk) never
498/// runs. Zero coefficients need no scaling (`0 × factor` truncates to
499/// `0`, exactly what the second pass stored), which is what makes the
500/// fusion bit-identical by construction; the equivalence is pinned
501/// stream-for-stream by `fused_dequant_walk_matches_decode_then_dequantize`.
502/// With `DQ = false` the factors are ignored and the generated code is
503/// the raw-coefficient walk, unchanged.
504#[inline]
505#[allow(clippy::too_many_arguments)]
506fn decode_block_core<const DQ: bool>(
507 dec: &mut BoolDecoder<'_>,
508 plane_probs: &[[[u8; 11]; 3]; 8],
509 first_coeff: usize,
510 seed_ctx3: usize,
511 write_order: &[usize; 16],
512 coeffs: &mut [i16; 16],
513 dc_factor: i16,
514 ac_factor: i16,
515) -> Result<usize, DctTokenError> {
516 let mut ctx3 = seed_ctx3;
517 let mut non_zero_count = 0usize;
518 let mut i = first_coeff;
519 'position: while i < 16 {
520 let mut probs = &plane_probs[COEFF_BANDS[i]][ctx3];
521 // Node 0 — dct_eob vs everything else. Only reachable when the
522 // previous token was not a DCT_0 (or at the first coefficient).
523 if !dec.read_bool(probs[0])? {
524 break;
525 }
526 // Node 2 — DCT_0 vs non-zero. A DCT_0 forbids dct_eob at the
527 // next position (§13.2), so a run of zeros loops here directly,
528 // each subsequent position using the §13.3 zero-class row.
529 while !dec.read_bool(probs[1])? {
530 coeffs[write_order[i]] = 0;
531 i += 1;
532 if i == 16 {
533 break 'position;
534 }
535 probs = &plane_probs[COEFF_BANDS[i]][0];
536 }
537 // Non-zero magnitude. §13.3: the next position's context class
538 // is 1 for |value| == 1, 2 for |value| > 1.
539 let abs_value: u16 = if !dec.read_bool(probs[2])? {
540 // Node 4 — DCT_1.
541 ctx3 = 1;
542 1
543 } else {
544 ctx3 = 2;
545 if !dec.read_bool(probs[3])? {
546 // Node 6 left — DCT_2 / DCT_3 / DCT_4 (nodes 8, 10).
547 if !dec.read_bool(probs[4])? {
548 2
549 } else if !dec.read_bool(probs[5])? {
550 3
551 } else {
552 4
553 }
554 } else if !dec.read_bool(probs[6])? {
555 // Node 12 left — cat1 / cat2 (node 14).
556 if !dec.read_bool(probs[7])? {
557 CAT_BASE[0] + read_extra_bits(dec, PCAT1)?
558 } else {
559 CAT_BASE[1] + read_extra_bits(dec, PCAT2)?
560 }
561 } else if !dec.read_bool(probs[8])? {
562 // Node 16 left — cat3 / cat4 (node 18).
563 if !dec.read_bool(probs[9])? {
564 CAT_BASE[2] + read_extra_bits(dec, PCAT3)?
565 } else {
566 CAT_BASE[3] + read_extra_bits(dec, PCAT4)?
567 }
568 } else if !dec.read_bool(probs[10])? {
569 // Node 20 — cat5 / cat6.
570 CAT_BASE[4] + read_extra_bits(dec, PCAT5)?
571 } else {
572 CAT_BASE[5] + read_extra_bits(dec, PCAT6)?
573 }
574 };
575 // Non-zero coefficients carry a sign bit at fixed probability
576 // 128 (§13.2 page 62). §13.2 cat6 max value is 67 + (2^11 - 1)
577 // = 2114, which still fits in i16 with sign.
578 let sign = dec.read_bool(128)?;
579 let signed = abs_value as i16;
580 let slot = write_order[i];
581 let mut value = if sign { -signed } else { signed };
582 if DQ {
583 // Fused §14.1 apply: DC factor for raster slot 0, AC for
584 // slots 1..=15, product in i32 truncated to i16 — the exact
585 // arithmetic of the per-block second pass this replaces.
586 let factor = if slot == 0 { dc_factor } else { ac_factor };
587 value = ((value as i32) * (factor as i32)) as i16;
588 }
589 coeffs[slot] = value;
590 non_zero_count += 1;
591 i += 1;
592 }
593 Ok(non_zero_count)
594}
595
596/// Decode one DCT-token sub-block per RFC 6386 §13.3 and return the
597/// number of non-zero coefficients written. The recovered values are
598/// written into `coeffs[firstCoeff..16]` (positions in the
599/// already-zig-zagged sub-block order); positions past the implicit
600/// `dct_eob` are left untouched (caller is expected to pre-zero
601/// `coeffs`).
602///
603/// * `block_type` selects the §13.3 plane index and the
604/// `firstCoeff` value.
605/// * `coeff_probs` is the resolved `coeff_probs[4][8][3][11]`
606/// produced by [`merge_default_token_probs`].
607/// * `above_has_nonzero` / `left_has_nonzero` are the §13.3
608/// "neighbour block has at least one non-zero coefficient"
609/// predictors for the *first* coefficient only. Off-frame
610/// neighbours are passed as `false` per §13.3 page 64.
611/// * Returns `Ok(non_zero_count)` — the number of non-zero
612/// coefficients decoded. `coeffs` is updated in place. A return
613/// value of 0 means the block was all-zero (either an immediate
614/// EOB at `firstCoeff` or a sequence of `DCT_0` tokens followed
615/// by EOB).
616pub fn decode_block(
617 dec: &mut BoolDecoder<'_>,
618 block_type: BlockType,
619 coeff_probs: &CoeffProbs,
620 above_has_nonzero: bool,
621 left_has_nonzero: bool,
622 coeffs: &mut [i16; 16],
623) -> Result<usize, DctTokenError> {
624 // §13.3 page 65: the third context-index (`ctx3`) is seeded by
625 // the count of non-zero neighbours for the very first coefficient
626 // only. After the first coefficient the field rolls over to the
627 // class of the last decoded coefficient (handled inside the core).
628 //
629 // §13.3 page 67 calls the "skip dct_eob branch" flag
630 // `prevCoeffWasZero`. It is `false` for the first coefficient
631 // because there is no previous coefficient at all (i.e. we DO
632 // permit an immediate dct_eob). After that, the spec-typo-corrected
633 // semantics (see the module-level doc comment) — `prevCoeffWasZero
634 // = (token == DCT_0)`, NOT the literal `true` the spec listing
635 // types — are realised structurally by `decode_block_core`'s inner
636 // zero-run loop, which re-enters the tree at the DCT_0 node.
637 let ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
638 decode_block_core::<false>(
639 dec,
640 &coeff_probs[block_type.plane_index()],
641 block_type.first_coeff(),
642 ctx3,
643 &SCAN_IDENTITY,
644 coeffs,
645 0,
646 0,
647 )
648}
649
650// ===========================================================================
651// §13.3 per-macroblock token walk
652// ===========================================================================
653
654/// §13 page 60 zig-zag scan order, transcribed from the §20.16 (tokens.c)
655/// reference annex `zigzag[16]`. `ZIGZAG[c]` is the raster (natural-order)
656/// position of the coefficient at scan position `c`. The per-block token
657/// loop fills coefficients in scan order; this table places each into its
658/// raster slot for the §14 raster-order inverse transforms.
659pub const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
660
661/// Number of per-plane non-zero predictor slots a macroblock maintains in
662/// each direction (above / left): four Y columns/rows, two U, two V, and
663/// one Y2 — the `token_entropy_ctx_t = int[4 + 2 + 2 + 1]` of the §20.16
664/// reference annex.
665pub const MB_ENTROPY_CTX_LEN: usize = 4 + 2 + 2 + 1;
666
667/// The §20.16 `left_context_index[25]` — maps a macroblock's 25 residual
668/// blocks (16 Y, then 4 U, 4 V, then the Y2 block as block 24) to a slot
669/// in the nine-entry "left" non-zero predictor vector. Y subblocks share a
670/// left slot per subblock *row* (slots 0..3); U and V each occupy two slots
671/// (4/5 and 6/7); Y2 is slot 8.
672const LEFT_CONTEXT_INDEX: [usize; 25] = [
673 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, // 16 Y
674 4, 4, 5, 5, // 4 U
675 6, 6, 7, 7, // 4 V
676 8, // Y2
677];
678
679/// The §20.16 `above_context_index[25]` — the companion mapping for the
680/// "above" predictor vector. Y subblocks share an above slot per subblock
681/// *column* (slots 0..3); U/V/Y2 mirror [`LEFT_CONTEXT_INDEX`].
682const ABOVE_CONTEXT_INDEX: [usize; 25] = [
683 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, // 16 Y
684 4, 5, 4, 5, // 4 U
685 6, 7, 6, 7, // 4 V
686 8, // Y2
687];
688
689/// One macroblock's worth of non-zero coefficient predictors for a single
690/// direction (above *or* left), per the §13.3 "aggregate coefficient
691/// predictor" description: a single Y2 predictor, two each for U and V, and
692/// four for Y. A decoder maintains one [`MbEntropyCtx`] per macroblock
693/// column for the "above" row and a single rolling "left" instance.
694///
695/// Each entry is `true` if the most-recently-decoded block mapping to that
696/// slot had at least one non-zero coefficient. Off-frame predictors are
697/// `false` (the §13.3 "non-existent predictors ... taken to be empty"
698/// rule); a freshly [`Default`]-constructed context satisfies that.
699#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
700pub struct MbEntropyCtx {
701 /// The nine non-zero flags, indexed by [`LEFT_CONTEXT_INDEX`] /
702 /// [`ABOVE_CONTEXT_INDEX`]: slots 0..3 = Y, 4..5 = U, 6..7 = V,
703 /// 8 = Y2.
704 pub nonzero: [bool; MB_ENTROPY_CTX_LEN],
705}
706
707impl MbEntropyCtx {
708 /// Apply the §20.16 `reset_mb_context` rule for a skipped macroblock.
709 ///
710 /// The eight Y/U/V slots are always cleared (a skipped macroblock has
711 /// no residue, so every same-plane neighbour predictor it contributes
712 /// is empty). The Y2 slot (8) is cleared **only** when this macroblock
713 /// would have carried a Y2 block (i.e. a non-`B_PRED` / non-`SPLITMV`
714 /// mode); otherwise it is preserved so that the most-recent Y2-bearing
715 /// macroblock in this column / row still drives the Y2 predictor, per
716 /// the §13.3 "most recent macroblock ... that has a Y2 block" rule.
717 fn reset_for_skip(&mut self, has_y2: bool) {
718 for slot in self.nonzero.iter_mut().take(8) {
719 *slot = false;
720 }
721 if has_y2 {
722 self.nonzero[8] = false;
723 }
724 }
725}
726
727/// Out-of-band conditions surfaced by [`decode_mb_coeffs`].
728#[derive(Debug, Clone, Copy, PartialEq, Eq)]
729#[non_exhaustive]
730pub enum MbCoeffError {
731 /// A per-block token decode failed (bool-decoder ran dry, or a
732 /// corrupted tree table). Carries the residual block index
733 /// (`0..=24`, dixie order: 0..15 Y, 16..19 U, 20..23 V, 24 Y2) and
734 /// the underlying error.
735 Block {
736 /// The §20.16 residual block index that failed.
737 index: usize,
738 /// The per-block decode error.
739 source: DctTokenError,
740 },
741}
742
743impl core::fmt::Display for MbCoeffError {
744 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
745 match self {
746 MbCoeffError::Block { index, source } => {
747 write!(f, "vp8 mb coeffs: residual block {index}: {source}")
748 }
749 }
750 }
751}
752
753impl std::error::Error for MbCoeffError {}
754
755/// Reorder a scan-order coefficient block into raster (natural) order via
756/// the §20.16 zig-zag table. `scan[c]` (scan position `c`) is placed at
757/// raster position `ZIGZAG[c]`.
758///
759/// The production per-macroblock walk no longer needs this pass — it
760/// hands [`ZIGZAG`] to `decode_block_core` as the write-order table so
761/// each coefficient lands in its raster slot as it is decoded. Kept as
762/// the test-side reference permutation.
763#[cfg(test)]
764fn scan_to_raster(scan: &[i16; 16]) -> [i16; 16] {
765 let mut raster = [0i16; 16];
766 for (c, &v) in scan.iter().enumerate() {
767 raster[ZIGZAG[c]] = v;
768 }
769 raster
770}
771
772/// Decode one macroblock's worth of DCT/WHT coefficient tokens per RFC
773/// 6386 §13.3, threading the above / left non-zero predictor context the
774/// §13.3 third-dimension probability index requires.
775///
776/// This is the integration layer over [`decode_block`]: it walks all the
777/// residual blocks of one macroblock — the §14.2 Y2 (WHT) block first when
778/// present, then the sixteen Y 4×4 DCT blocks, then the four U and four V
779/// chroma blocks, in the §13 "residual_data()" order — selecting the
780/// correct [`BlockType`] plane and the correct above / left predictor slot
781/// per the §20.16 `left_context_index` / `above_context_index` tables, and
782/// updating those slots with each block's non-zero status for the
783/// macroblocks below and to the right (§13.3 "after each block is decoded,
784/// the two predictors referenced by the block are replaced").
785///
786/// # Inputs
787///
788/// * `dec` — the §13.2 boolean decoder positioned at this macroblock's
789/// residual record in the (second) DCT partition.
790/// * `has_y2` — whether this macroblock carries a Y2 block. `true` for the
791/// four 16×16 luma modes (and inter modes other than `SPLITMV`); `false`
792/// for `B_PRED` / `SPLITMV`, whose Y blocks instead carry their own DC.
793/// The caller derives this from the decoded [`crate::macroblock::IntraYMode`]
794/// (`!= B`).
795/// * `mb_skip_coeff` — the §11.1 / §13.1 skip flag. When `true` no tokens
796/// are read; the returned coefficients are all zero and the predictor
797/// context is updated per the §20.16 `reset_mb_context` rule (clear all
798/// Y/U/V slots; clear Y2 only when `has_y2`).
799/// * `coeff_probs` — the resolved `coeff_probs[4][8][3][11]` from
800/// [`merge_default_token_probs`].
801/// * `above` / `left` — the macroblock's incoming non-zero predictor
802/// contexts. Both are read for the *first* coefficient of each block and
803/// updated in place as blocks are decoded. The caller maintains a row of
804/// `above` contexts (one per macroblock column) and a single rolling
805/// `left` context, clearing both at the appropriate frame / row edges.
806///
807/// # Output
808///
809/// The macroblock's coefficients as an [`crate::frame::MbCoeffs`], with
810/// each 4×4 block placed in **raster (natural) order** (the layout the §14
811/// inverse transforms consume). The coefficients are the **raw quantized
812/// token values** — the §14.1 Y2 / chroma dequant scaling is a documented
813/// spec gap (§14.1 page 77 defers it to `dixie.c` §20.4), so this function
814/// does **not** multiply by any dequant factor. The caller must apply
815/// §14.1 dequantization before the inverse transforms once that gap is
816/// filled.
817pub fn decode_mb_coeffs(
818 dec: &mut BoolDecoder<'_>,
819 has_y2: bool,
820 mb_skip_coeff: bool,
821 coeff_probs: &CoeffProbs,
822 above: &mut MbEntropyCtx,
823 left: &mut MbEntropyCtx,
824) -> Result<crate::frame::MbCoeffs, MbCoeffError> {
825 // Raw walk: the factor pairs are ignored under `DQ = false`.
826 decode_mb_coeffs_inner::<false>(
827 dec,
828 has_y2,
829 mb_skip_coeff,
830 coeff_probs,
831 &MbDequantPairs {
832 y2: (0, 0),
833 y1: (0, 0),
834 uv: (0, 0),
835 },
836 above,
837 left,
838 )
839}
840
841/// Per-plane §14.1 `(DC, AC)` dequant factor pairs for the fused
842/// decode→dequant walk ([`decode_mb_coeffs_dequant`]). A plain
843/// destructuring of [`crate::dequant::MbDequantFactors`] into the three
844/// plane pairs the §13 residual order selects between.
845#[derive(Debug, Clone, Copy, PartialEq, Eq)]
846pub(crate) struct MbDequantPairs {
847 /// Y2 (the 25th, WHT) block factors.
848 pub y2: (i16, i16),
849 /// Y1 (the sixteen luma DCT sub-blocks) factors.
850 pub y1: (i16, i16),
851 /// Chroma (the four U and four V sub-blocks) factors.
852 pub uv: (i16, i16),
853}
854
855/// The fused §13.3 decode → §14.1 dequant walk: identical to
856/// [`decode_mb_coeffs`] except that every non-zero coefficient is
857/// scaled by its plane's DC/AC factor at the moment it is written, so
858/// the caller receives the **dequantized** [`crate::frame::MbCoeffs`]
859/// directly and the per-macroblock second pass
860/// ([`crate::dequant::MbDequantFactors::dequantize`] — 400
861/// occupancy-independent multiplies over all twenty-five blocks) is
862/// never needed. Bit-identical to decode-then-dequantize by
863/// construction (untouched / zero-run lanes hold `0`, and `0 × factor`
864/// truncates to `0`); pinned stream-for-stream by
865/// `fused_dequant_walk_matches_decode_then_dequantize`.
866#[allow(clippy::too_many_arguments)]
867pub(crate) fn decode_mb_coeffs_dequant(
868 dec: &mut BoolDecoder<'_>,
869 has_y2: bool,
870 mb_skip_coeff: bool,
871 coeff_probs: &CoeffProbs,
872 pairs: &MbDequantPairs,
873 above: &mut MbEntropyCtx,
874 left: &mut MbEntropyCtx,
875) -> Result<crate::frame::MbCoeffs, MbCoeffError> {
876 decode_mb_coeffs_inner::<true>(dec, has_y2, mb_skip_coeff, coeff_probs, pairs, above, left)
877}
878
879/// Shared body of [`decode_mb_coeffs`] / [`decode_mb_coeffs_dequant`]:
880/// the §13 / §14.2 residual-order walk, monomorphised on whether the
881/// §14.1 apply is fused into the coefficient writes.
882#[allow(clippy::too_many_arguments)]
883fn decode_mb_coeffs_inner<const DQ: bool>(
884 dec: &mut BoolDecoder<'_>,
885 has_y2: bool,
886 mb_skip_coeff: bool,
887 coeff_probs: &CoeffProbs,
888 pairs: &MbDequantPairs,
889 above: &mut MbEntropyCtx,
890 left: &mut MbEntropyCtx,
891) -> Result<crate::frame::MbCoeffs, MbCoeffError> {
892 let mut out = crate::frame::MbCoeffs::default();
893
894 // §13.1: a skip macroblock reads no tokens. Update the predictor
895 // context per the §20.16 `reset_mb_context` rule and return zeros
896 // (which dequantize to zeros, so the fused walk returns them as-is).
897 if mb_skip_coeff {
898 above.reset_for_skip(has_y2);
899 left.reset_for_skip(has_y2);
900 return Ok(out);
901 }
902
903 // Decode one residual block: select the predictor slots, run the
904 // per-coefficient token loop (writing each coefficient straight
905 // into its raster slot via the §20.16 `ZIGZAG` write order — no
906 // separate reorder pass), and write back the non-zero status into
907 // both predictor vectors. `block_index` is the §20.16 residual
908 // block index (0..=24); `(dc_factor, ac_factor)` the plane's §14.1
909 // pair (ignored under `DQ = false`).
910 let decode_one = |dec: &mut BoolDecoder<'_>,
911 block_index: usize,
912 block_type: BlockType,
913 (dc_factor, ac_factor): (i16, i16),
914 above: &mut MbEntropyCtx,
915 left: &mut MbEntropyCtx,
916 raster: &mut [i16; 16]|
917 -> Result<(), MbCoeffError> {
918 let a_slot = ABOVE_CONTEXT_INDEX[block_index];
919 let l_slot = LEFT_CONTEXT_INDEX[block_index];
920 // §13.3 page 65: ctx3 for the first coefficient is the count
921 // of non-zero neighbours.
922 let ctx3 = (above.nonzero[a_slot] as usize) + (left.nonzero[l_slot] as usize);
923 let nz = decode_block_core::<DQ>(
924 dec,
925 &coeff_probs[block_type.plane_index()],
926 block_type.first_coeff(),
927 ctx3,
928 &ZIGZAG,
929 raster,
930 dc_factor,
931 ac_factor,
932 )
933 .map_err(|source| MbCoeffError::Block {
934 index: block_index,
935 source,
936 })?;
937 // §13.3: replace the two referenced predictors with this
938 // block's (non-)empty state for blocks below and to the right.
939 let has_coeffs = nz != 0;
940 above.nonzero[a_slot] = has_coeffs;
941 left.nonzero[l_slot] = has_coeffs;
942 Ok(())
943 };
944
945 // §13 / §14.2 residual order: Y2 (when present) → 16 Y → 4 U → 4 V.
946 // The Y luma plane type is `YAfterY2` (DCT starts at coefficient 1)
947 // when a Y2 block carries the DCs, else `YNoY2` (DCT starts at 0).
948 if has_y2 {
949 // Y2 is residual block 24 in the §20.16 index tables.
950 decode_one(dec, 24, BlockType::Y2, pairs.y2, above, left, &mut out.y2)?;
951 }
952
953 let y_plane = if has_y2 {
954 BlockType::YAfterY2
955 } else {
956 BlockType::YNoY2
957 };
958 for (i, y_block) in out.y.iter_mut().enumerate() {
959 decode_one(dec, i, y_plane, pairs.y1, above, left, y_block)?;
960 }
961
962 // U occupies residual blocks 16..=19, V occupies 20..=23.
963 for (i, u_block) in out.u.iter_mut().enumerate() {
964 decode_one(dec, 16 + i, BlockType::UV, pairs.uv, above, left, u_block)?;
965 }
966 for (i, v_block) in out.v.iter_mut().enumerate() {
967 decode_one(dec, 20 + i, BlockType::UV, pairs.uv, above, left, v_block)?;
968 }
969
970 Ok(out)
971}
972
973#[cfg(test)]
974mod tests {
975 use super::*;
976
977 // Test-side bool encoder (mirrors the one inside
978 // `bool_decoder::tests`). Lives only in tests; never exported.
979 struct TestEncoder {
980 out: Vec<u8>,
981 range: u32,
982 bottom: u32,
983 bit_count: i32,
984 }
985
986 impl TestEncoder {
987 fn new() -> Self {
988 Self {
989 out: Vec::new(),
990 range: 255,
991 bottom: 0,
992 bit_count: 24,
993 }
994 }
995
996 fn write_bool(&mut self, prob: u8, val: bool) {
997 let split = 1 + (((self.range - 1) * prob as u32) >> 8);
998 if val {
999 self.bottom = self.bottom.wrapping_add(split);
1000 self.range -= split;
1001 } else {
1002 self.range = split;
1003 }
1004 while self.range < 128 {
1005 self.range <<= 1;
1006 if (self.bottom >> 31) & 1 == 1 {
1007 let mut i = self.out.len();
1008 while i > 0 {
1009 i -= 1;
1010 if self.out[i] == 255 {
1011 self.out[i] = 0;
1012 } else {
1013 self.out[i] = self.out[i].wrapping_add(1);
1014 break;
1015 }
1016 }
1017 }
1018 self.bottom <<= 1;
1019 self.bit_count -= 1;
1020 if self.bit_count == 0 {
1021 let byte = (self.bottom >> 24) as u8;
1022 self.out.push(byte);
1023 self.bottom &= (1 << 24) - 1;
1024 self.bit_count = 8;
1025 }
1026 }
1027 }
1028
1029 fn finish(mut self) -> Vec<u8> {
1030 let c = self.bit_count;
1031 let v = self.bottom;
1032 if v & (1u32 << (32 - c)) != 0 {
1033 let mut i = self.out.len();
1034 while i > 0 {
1035 i -= 1;
1036 if self.out[i] == 255 {
1037 self.out[i] = 0;
1038 } else {
1039 self.out[i] = self.out[i].wrapping_add(1);
1040 break;
1041 }
1042 }
1043 }
1044 let mut v = v;
1045 v <<= c & 7;
1046 let mut c_shift = c >> 3;
1047 while c_shift > 0 {
1048 v <<= 8;
1049 c_shift -= 1;
1050 }
1051 for _ in 0..4 {
1052 self.out.push((v >> 24) as u8);
1053 v <<= 8;
1054 }
1055 self.out
1056 }
1057 }
1058
1059 /// Encode a single DctToken against the given probability vector by
1060 /// walking the same tree the decoder will walk. Returns the (start
1061 /// internal node, list of (prob_index, bit) pairs to write).
1062 ///
1063 /// `start_at_index` is `0` if we may emit eob, `2` if not (i.e.
1064 /// when the previous coefficient was a DCT_0).
1065 fn encode_token(token: DctToken, start_at_index: i8) -> Vec<(usize, bool)> {
1066 // We replay the tree-walk and at each step record (i>>1, bit)
1067 // that the decoder would have read. We do this by knowing the
1068 // tree statically.
1069 let target = token as i8;
1070 let mut out = Vec::new();
1071 // Helper: at internal node `i`, the two children are
1072 // COEFF_TREE[i] (left, bit=0) and COEFF_TREE[i+1] (right, bit=1).
1073 fn descend(i: i8, target: i8, path: &mut Vec<(usize, bool)>) -> bool {
1074 for &bit in &[false, true] {
1075 let child = COEFF_TREE[i as usize + bit as usize];
1076 if child <= 0 {
1077 if -child == target {
1078 path.push(((i as usize) >> 1, bit));
1079 return true;
1080 }
1081 } else {
1082 path.push(((i as usize) >> 1, bit));
1083 if descend(child, target, path) {
1084 return true;
1085 }
1086 path.pop();
1087 }
1088 }
1089 false
1090 }
1091 assert!(descend(start_at_index, target, &mut out));
1092 out
1093 }
1094
1095 /// Encode a full block of coefficients against the resolved coeff
1096 /// probability table and return the bool-encoder byte stream that
1097 /// `decode_block` should consume.
1098 fn encode_block(
1099 coeffs: &[i16; 16],
1100 block_type: BlockType,
1101 coeff_probs: &CoeffProbs,
1102 above_has_nonzero: bool,
1103 left_has_nonzero: bool,
1104 ) -> Vec<u8> {
1105 let mut enc = TestEncoder::new();
1106 let plane = block_type.plane_index();
1107 let first_coeff = block_type.first_coeff();
1108 let mut ctx3 = (above_has_nonzero as usize) + (left_has_nonzero as usize);
1109 let mut prev_was_zero = false;
1110
1111 // Find the position of the last non-zero coefficient — we will
1112 // emit an EOB token immediately after that position (or at
1113 // first_coeff if the block is empty).
1114 let mut last_non_zero: i32 = -1;
1115 for (idx, c) in coeffs.iter().enumerate().take(16) {
1116 if idx >= first_coeff && *c != 0 {
1117 last_non_zero = idx as i32;
1118 }
1119 }
1120
1121 let mut i = first_coeff as i32;
1122 while i < 16 {
1123 let band = COEFF_BANDS[i as usize];
1124 let probs = &coeff_probs[plane][band][ctx3];
1125
1126 let emit_eob = i > last_non_zero;
1127 let abs_value: u16;
1128 let sign: bool;
1129 let token: DctToken;
1130 if emit_eob {
1131 token = DctToken::Eob;
1132 abs_value = 0;
1133 sign = false;
1134 } else {
1135 let v = coeffs[i as usize];
1136 sign = v < 0;
1137 abs_value = v.unsigned_abs();
1138 token = if abs_value == 0 {
1139 DctToken::Dct0
1140 } else if abs_value == 1 {
1141 DctToken::Dct1
1142 } else if abs_value == 2 {
1143 DctToken::Dct2
1144 } else if abs_value == 3 {
1145 DctToken::Dct3
1146 } else if abs_value == 4 {
1147 DctToken::Dct4
1148 } else if abs_value <= 6 {
1149 DctToken::Cat1
1150 } else if abs_value <= 10 {
1151 DctToken::Cat2
1152 } else if abs_value <= 18 {
1153 DctToken::Cat3
1154 } else if abs_value <= 34 {
1155 DctToken::Cat4
1156 } else if abs_value <= 66 {
1157 DctToken::Cat5
1158 } else {
1159 DctToken::Cat6
1160 };
1161 }
1162
1163 let start = if prev_was_zero { 2i8 } else { 0i8 };
1164 for (i_half, bit) in encode_token(token, start) {
1165 enc.write_bool(probs[i_half], bit);
1166 }
1167 if token == DctToken::Eob {
1168 break;
1169 }
1170
1171 if let Some((base, plist)) = match token {
1172 DctToken::Cat1 => Some((CAT_BASE[0], PCAT1)),
1173 DctToken::Cat2 => Some((CAT_BASE[1], PCAT2)),
1174 DctToken::Cat3 => Some((CAT_BASE[2], PCAT3)),
1175 DctToken::Cat4 => Some((CAT_BASE[3], PCAT4)),
1176 DctToken::Cat5 => Some((CAT_BASE[4], PCAT5)),
1177 DctToken::Cat6 => Some((CAT_BASE[5], PCAT6)),
1178 _ => None,
1179 } {
1180 let extra = abs_value - base;
1181 let n = plist.len();
1182 for (j, &p) in plist.iter().enumerate() {
1183 let bit = ((extra >> (n - 1 - j)) & 1) == 1;
1184 enc.write_bool(p, bit);
1185 }
1186 }
1187
1188 if abs_value != 0 {
1189 enc.write_bool(128, sign);
1190 }
1191
1192 ctx3 = if abs_value == 0 {
1193 0
1194 } else if abs_value == 1 {
1195 1
1196 } else {
1197 2
1198 };
1199 prev_was_zero = token == DctToken::Dct0;
1200 i += 1;
1201 }
1202
1203 enc.finish()
1204 }
1205
1206 #[test]
1207 fn default_probs_table_shape() {
1208 // Cheap sanity check on the §13.5 transcription: every entry
1209 // is a u8 in the legal range and the table has 4*8*3*11=1056
1210 // probabilities.
1211 let mut count = 0;
1212 for plane in &DEFAULT_COEFF_PROBS {
1213 for band in plane {
1214 for ctx in band {
1215 for &_p in ctx {
1216 count += 1;
1217 }
1218 }
1219 }
1220 }
1221 assert_eq!(count, 4 * 8 * 3 * 11);
1222 }
1223
1224 #[test]
1225 fn default_probs_first_row_is_uniform_128() {
1226 // Plane 0 (Y after Y2) band 0 is all-128 in the RFC listing —
1227 // unused since plane 0 starts at coefficient 1, so band 0
1228 // never reads. Spot-check the first row.
1229 for ctx in &DEFAULT_COEFF_PROBS[0][0] {
1230 for &p in ctx {
1231 assert_eq!(p, 128);
1232 }
1233 }
1234 }
1235
1236 #[test]
1237 fn default_probs_known_values() {
1238 // A handful of specific cells from §13.5 — would catch a
1239 // transcription typo on any of the four touched planes.
1240 assert_eq!(DEFAULT_COEFF_PROBS[0][1][0][0], 253);
1241 assert_eq!(DEFAULT_COEFF_PROBS[1][0][0][10], 62);
1242 assert_eq!(DEFAULT_COEFF_PROBS[2][7][2][0], 128); // chroma plane band 7 all-128
1243 assert_eq!(DEFAULT_COEFF_PROBS[3][0][0][0], 202);
1244 assert_eq!(DEFAULT_COEFF_PROBS[3][7][2][1], 1); // last block: { 238, 1, 255, ... }
1245 }
1246
1247 #[test]
1248 fn coeff_bands_is_spec_listing() {
1249 assert_eq!(
1250 COEFF_BANDS,
1251 [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7]
1252 );
1253 }
1254
1255 #[test]
1256 fn block_type_first_coeff_and_plane_index() {
1257 assert_eq!(BlockType::YAfterY2.first_coeff(), 1);
1258 assert_eq!(BlockType::Y2.first_coeff(), 0);
1259 assert_eq!(BlockType::UV.first_coeff(), 0);
1260 assert_eq!(BlockType::YNoY2.first_coeff(), 0);
1261 assert_eq!(BlockType::YAfterY2.plane_index(), 0);
1262 assert_eq!(BlockType::Y2.plane_index(), 1);
1263 assert_eq!(BlockType::UV.plane_index(), 2);
1264 assert_eq!(BlockType::YNoY2.plane_index(), 3);
1265 }
1266
1267 #[test]
1268 fn merge_no_updates_is_identity() {
1269 let updates: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1270 let merged = merge_default_token_probs(&updates);
1271 assert_eq!(merged, DEFAULT_COEFF_PROBS);
1272 }
1273
1274 #[test]
1275 fn merge_overlays_present_entries() {
1276 let mut updates: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1277 updates[2][3][1][5] = Some(42);
1278 updates[0][0][0][0] = Some(7);
1279 let merged = merge_default_token_probs(&updates);
1280 assert_eq!(merged[2][3][1][5], 42);
1281 assert_eq!(merged[0][0][0][0], 7);
1282 // Untouched cells still match defaults.
1283 assert_eq!(merged[3][5][2][1], DEFAULT_COEFF_PROBS[3][5][2][1]);
1284 }
1285
1286 #[test]
1287 fn decode_immediate_eob_yields_all_zero_block() {
1288 // Block: 16 zeros; first token is dct_eob.
1289 let probs = &DEFAULT_COEFF_PROBS;
1290 let coeffs = [0i16; 16];
1291 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1292 let mut dec = BoolDecoder::init(&buf).unwrap();
1293 let mut out = [0i16; 16];
1294 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1295 assert_eq!(nz, 0);
1296 assert_eq!(out, [0i16; 16]);
1297 }
1298
1299 #[test]
1300 fn decode_roundtrip_single_dct1_at_position_0() {
1301 let probs = &DEFAULT_COEFF_PROBS;
1302 let mut coeffs = [0i16; 16];
1303 coeffs[0] = 1;
1304 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1305 let mut dec = BoolDecoder::init(&buf).unwrap();
1306 let mut out = [0i16; 16];
1307 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1308 assert_eq!(nz, 1);
1309 assert_eq!(out[0], 1);
1310 for &v in out.iter().skip(1) {
1311 assert_eq!(v, 0);
1312 }
1313 }
1314
1315 #[test]
1316 fn decode_roundtrip_negative_value() {
1317 let probs = &DEFAULT_COEFF_PROBS;
1318 let mut coeffs = [0i16; 16];
1319 coeffs[0] = -3;
1320 coeffs[1] = -2;
1321 let buf = encode_block(&coeffs, BlockType::Y2, probs, true, true);
1322 let mut dec = BoolDecoder::init(&buf).unwrap();
1323 let mut out = [0i16; 16];
1324 let nz = decode_block(&mut dec, BlockType::Y2, probs, true, true, &mut out).unwrap();
1325 assert_eq!(nz, 2);
1326 assert_eq!(out[0], -3);
1327 assert_eq!(out[1], -2);
1328 }
1329
1330 #[test]
1331 fn decode_roundtrip_each_cat_range() {
1332 // One value from inside each cat1..cat6 range. Verifies the
1333 // base + extra-bits arithmetic at the cat boundary, halfway
1334 // inside the range, and at the cat ceiling.
1335 for &val in &[5i16, 6, 7, 10, 11, 18, 19, 34, 35, 66, 67, 100, 2048] {
1336 let probs = &DEFAULT_COEFF_PROBS;
1337 let mut coeffs = [0i16; 16];
1338 coeffs[0] = val;
1339 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1340 let mut dec = BoolDecoder::init(&buf).unwrap();
1341 let mut out = [0i16; 16];
1342 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1343 assert_eq!(nz, 1, "val={val}");
1344 assert_eq!(out[0], val, "val={val}");
1345 }
1346 }
1347
1348 #[test]
1349 fn decode_y_after_y2_skips_dc_position() {
1350 // Plane 0 (`YAfterY2`) starts at coefficient 1; position 0
1351 // must stay zero even if the encoded bits would otherwise
1352 // ascribe a token there. Verify by encoding a value at
1353 // position 1.
1354 let probs = &DEFAULT_COEFF_PROBS;
1355 let mut coeffs = [0i16; 16];
1356 coeffs[1] = 7; // cat2
1357 let buf = encode_block(&coeffs, BlockType::YAfterY2, probs, false, false);
1358 let mut dec = BoolDecoder::init(&buf).unwrap();
1359 let mut out = [0i16; 16];
1360 let nz =
1361 decode_block(&mut dec, BlockType::YAfterY2, probs, false, false, &mut out).unwrap();
1362 assert_eq!(nz, 1);
1363 assert_eq!(out[0], 0);
1364 assert_eq!(out[1], 7);
1365 }
1366
1367 #[test]
1368 fn decode_dense_block_zigzag_positions() {
1369 // A non-trivial block with values at multiple positions
1370 // including the rollover from DCT_0 -> non-zero (covering
1371 // the §13.3 `prev_was_zero` / `ctx3` rollover).
1372 let probs = &DEFAULT_COEFF_PROBS;
1373 let mut coeffs = [0i16; 16];
1374 coeffs[0] = 3;
1375 coeffs[1] = 0;
1376 coeffs[2] = -1;
1377 coeffs[3] = 2;
1378 coeffs[5] = 15; // cat3
1379 coeffs[8] = -25; // cat4
1380 let buf = encode_block(&coeffs, BlockType::UV, probs, true, false);
1381 let mut dec = BoolDecoder::init(&buf).unwrap();
1382 let mut out = [0i16; 16];
1383 let nz = decode_block(&mut dec, BlockType::UV, probs, true, false, &mut out).unwrap();
1384 assert_eq!(nz, 5);
1385 assert_eq!(out, coeffs);
1386 }
1387
1388 #[test]
1389 fn decode_under_overlaid_probability_updates() {
1390 // Use a TokenProbUpdates that overrides a handful of entries
1391 // and verify decode still round-trips. Catches a bug where
1392 // `decode_block` accidentally hits `DEFAULT_COEFF_PROBS`
1393 // instead of the caller-supplied table.
1394 let mut updates: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1395 updates[2][1][0][0] = Some(200);
1396 updates[2][1][0][1] = Some(50);
1397 updates[2][2][1][2] = Some(99);
1398 let probs = merge_default_token_probs(&updates);
1399
1400 let mut coeffs = [0i16; 16];
1401 coeffs[0] = 4;
1402 coeffs[1] = -1;
1403 coeffs[3] = 12; // cat3
1404 let buf = encode_block(&coeffs, BlockType::UV, &probs, false, false);
1405 let mut dec = BoolDecoder::init(&buf).unwrap();
1406 let mut out = [0i16; 16];
1407 let nz = decode_block(&mut dec, BlockType::UV, &probs, false, false, &mut out).unwrap();
1408 assert_eq!(nz, 3);
1409 assert_eq!(out, coeffs);
1410 }
1411
1412 #[test]
1413 fn prev_token_skips_eob_branch() {
1414 // Encode a block where the second coefficient is reached
1415 // through the "previous was zero" path. The decoder must
1416 // start the second token's tree-walk at index 2 (skipping
1417 // the dct_eob branch). To prove this matters: emit a long
1418 // run of zeros that would, under the buggy spec literal
1419 // `prev_was_zero = true`, be interpreted as eob.
1420 //
1421 // We rely on the encode helper applying the same "start at
1422 // 2 when prev was zero" rule; if `decode_block` did the
1423 // wrong thing, the round-trip would fail.
1424 let probs = &DEFAULT_COEFF_PROBS;
1425 let mut coeffs = [0i16; 16];
1426 coeffs[0] = 0;
1427 coeffs[1] = 0;
1428 coeffs[2] = 0;
1429 coeffs[3] = 5; // cat1
1430 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1431 let mut dec = BoolDecoder::init(&buf).unwrap();
1432 let mut out = [0i16; 16];
1433 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1434 assert_eq!(nz, 1);
1435 assert_eq!(out, coeffs);
1436 }
1437
1438 #[test]
1439 fn neighbour_predictor_count_seeds_ctx3() {
1440 // The `ctx3` for the very first coefficient is the count
1441 // (0/1/2) of non-zero neighbours. Encoding with all four
1442 // cases (00, 01, 10, 11) and round-tripping makes sure the
1443 // decoder picks the same row.
1444 let probs = &DEFAULT_COEFF_PROBS;
1445 for (above, left) in [(false, false), (true, false), (false, true), (true, true)] {
1446 let mut coeffs = [0i16; 16];
1447 coeffs[0] = -7; // cat2
1448 coeffs[2] = 1;
1449 let buf = encode_block(&coeffs, BlockType::UV, probs, above, left);
1450 let mut dec = BoolDecoder::init(&buf).unwrap();
1451 let mut out = [0i16; 16];
1452 let nz = decode_block(&mut dec, BlockType::UV, probs, above, left, &mut out).unwrap();
1453 assert_eq!(nz, 2, "above={above} left={left}");
1454 assert_eq!(out, coeffs, "above={above} left={left}");
1455 }
1456 }
1457
1458 #[test]
1459 fn block_full_to_position_15_no_eob_emitted() {
1460 // A block that uses all 16 positions emits no EOB at all —
1461 // the §13.3 loop runs to completion with i = 16. Verify
1462 // the decoder handles that termination correctly.
1463 let probs = &DEFAULT_COEFF_PROBS;
1464 let coeffs = [1i16; 16];
1465 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1466 let mut dec = BoolDecoder::init(&buf).unwrap();
1467 let mut out = [0i16; 16];
1468 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1469 assert_eq!(nz, 16);
1470 assert_eq!(out, coeffs);
1471 }
1472
1473 #[test]
1474 fn cat6_high_magnitude_roundtrip() {
1475 // cat6 with the largest legal magnitude (67 + 2047 = 2114).
1476 // Exercises the 11-extra-bit DCTextra path.
1477 let probs = &DEFAULT_COEFF_PROBS;
1478 let mut coeffs = [0i16; 16];
1479 coeffs[0] = 2114;
1480 let buf = encode_block(&coeffs, BlockType::Y2, probs, false, false);
1481 let mut dec = BoolDecoder::init(&buf).unwrap();
1482 let mut out = [0i16; 16];
1483 let nz = decode_block(&mut dec, BlockType::Y2, probs, false, false, &mut out).unwrap();
1484 assert_eq!(nz, 1);
1485 assert_eq!(out[0], 2114);
1486 }
1487
1488 /// Reference §8.1 `treed_read` over [`COEFF_TREE`]: the generic
1489 /// table-driven walk the fused production descent replaced. Ground
1490 /// truth for `fused_descent_matches_generic_tree_walk`.
1491 fn treed_read_coef_reference(
1492 dec: &mut BoolDecoder<'_>,
1493 probs: &[u8; 11],
1494 start_index: i8,
1495 ) -> Result<DctToken, DctTokenError> {
1496 let mut i: i8 = start_index;
1497 loop {
1498 let prob = probs[(i as usize) >> 1];
1499 let bit = dec.read_bool(prob)? as usize;
1500 let next = COEFF_TREE[i as usize + bit];
1501 if next <= 0 {
1502 let leaf = -next as u8;
1503 return Ok(match leaf {
1504 0 => DctToken::Dct0,
1505 1 => DctToken::Dct1,
1506 2 => DctToken::Dct2,
1507 3 => DctToken::Dct3,
1508 4 => DctToken::Dct4,
1509 5 => DctToken::Cat1,
1510 6 => DctToken::Cat2,
1511 7 => DctToken::Cat3,
1512 8 => DctToken::Cat4,
1513 9 => DctToken::Cat5,
1514 10 => DctToken::Cat6,
1515 11 => DctToken::Eob,
1516 _ => return Err(DctTokenError::InvalidTokenIndex),
1517 });
1518 }
1519 i = next;
1520 }
1521 }
1522
1523 /// Reference §13.3 token loop built on the generic tree walk — the
1524 /// pre-fusion `decode_block` body, kept verbatim as ground truth.
1525 fn decode_block_reference(
1526 dec: &mut BoolDecoder<'_>,
1527 block_type: BlockType,
1528 coeff_probs: &CoeffProbs,
1529 above_has_nonzero: bool,
1530 left_has_nonzero: bool,
1531 coeffs: &mut [i16; 16],
1532 ) -> Result<usize, DctTokenError> {
1533 let mut ctx3: usize = (above_has_nonzero as usize) + (left_has_nonzero as usize);
1534 let plane = block_type.plane_index();
1535 let first_coeff = block_type.first_coeff();
1536 let mut prev_was_zero = false;
1537 let mut non_zero_count = 0usize;
1538 let mut i = first_coeff;
1539 while i < 16 {
1540 let band = COEFF_BANDS[i];
1541 let probs = &coeff_probs[plane][band][ctx3];
1542 let start = if prev_was_zero { 2i8 } else { 0i8 };
1543 let token = treed_read_coef_reference(dec, probs, start)?;
1544 if token == DctToken::Eob {
1545 break;
1546 }
1547 let abs_value: u16 = match token {
1548 DctToken::Dct0 => 0,
1549 DctToken::Dct1 => 1,
1550 DctToken::Dct2 => 2,
1551 DctToken::Dct3 => 3,
1552 DctToken::Dct4 => 4,
1553 DctToken::Cat1 => CAT_BASE[0] + read_extra_bits(dec, PCAT1)?,
1554 DctToken::Cat2 => CAT_BASE[1] + read_extra_bits(dec, PCAT2)?,
1555 DctToken::Cat3 => CAT_BASE[2] + read_extra_bits(dec, PCAT3)?,
1556 DctToken::Cat4 => CAT_BASE[3] + read_extra_bits(dec, PCAT4)?,
1557 DctToken::Cat5 => CAT_BASE[4] + read_extra_bits(dec, PCAT5)?,
1558 DctToken::Cat6 => CAT_BASE[5] + read_extra_bits(dec, PCAT6)?,
1559 DctToken::Eob => unreachable!("eob handled above"),
1560 };
1561 if abs_value != 0 {
1562 let sign = dec.read_bool(128)?;
1563 let signed = abs_value as i16;
1564 coeffs[i] = if sign { -signed } else { signed };
1565 non_zero_count += 1;
1566 } else {
1567 coeffs[i] = 0;
1568 }
1569 ctx3 = if abs_value == 0 {
1570 0
1571 } else if abs_value == 1 {
1572 1
1573 } else {
1574 2
1575 };
1576 prev_was_zero = token == DctToken::Dct0;
1577 i += 1;
1578 }
1579 Ok(non_zero_count)
1580 }
1581
1582 #[test]
1583 fn fused_descent_matches_generic_tree_walk() {
1584 // Drive the fused production `decode_block` and the generic
1585 // table-driven reference over a deterministic randomised corpus
1586 // covering every plane type, every neighbour-context seed, and
1587 // a sparsity/magnitude mix that reaches every tree leaf
1588 // (zero runs, DCT_1..4, all six DCTextra categories, immediate
1589 // EOB, and full-16 blocks). Outputs, non-zero counts, and the
1590 // complete bool-decoder end state must agree exactly — proving
1591 // the fused walk consumes the identical bit sequence.
1592 let mut seed = 0x9e3779b9u32;
1593 let mut rng = move || {
1594 seed ^= seed << 13;
1595 seed ^= seed >> 17;
1596 seed ^= seed << 5;
1597 seed
1598 };
1599 let block_types = [
1600 BlockType::YAfterY2,
1601 BlockType::Y2,
1602 BlockType::UV,
1603 BlockType::YNoY2,
1604 ];
1605 // A second probability table with overlays, so the corpus is
1606 // not tied to the defaults.
1607 let mut updates: TokenProbUpdates = [[[[None; 11]; 3]; 8]; 4];
1608 updates[0][1][0][0] = Some(90);
1609 updates[1][0][1][3] = Some(17);
1610 updates[3][6][2][1] = Some(201);
1611 let overlaid = merge_default_token_probs(&updates);
1612 let tables = [&DEFAULT_COEFF_PROBS, &overlaid];
1613
1614 for trial in 0..400 {
1615 let block_type = block_types[(rng() % 4) as usize];
1616 let probs = tables[(trial % 2) as usize];
1617 let above = rng() & 1 == 1;
1618 let left = rng() & 1 == 1;
1619 // Sparsity dial: 0 = empty block, up to dense full blocks.
1620 let density = rng() % 17;
1621 let mut coeffs = [0i16; 16];
1622 for slot in coeffs.iter_mut().skip(block_type.first_coeff()) {
1623 if rng() % 16 < density {
1624 // Magnitude classes hitting every leaf: 1..4 small,
1625 // 5..2114 across cat1..cat6.
1626 let m = match rng() % 8 {
1627 0 => 1,
1628 1 => 2,
1629 2 => 3,
1630 3 => 4,
1631 4 => 5 + (rng() % 6) as i16, // cat1/cat2
1632 5 => 11 + (rng() % 24) as i16, // cat3/cat4
1633 6 => 35 + (rng() % 32) as i16, // cat5
1634 _ => 67 + (rng() % 2048) as i16, // cat6
1635 };
1636 *slot = if rng() & 1 == 1 { -m } else { m };
1637 }
1638 }
1639 let buf = encode_block(&coeffs, block_type, probs, above, left);
1640
1641 let mut dec_fused = BoolDecoder::init(&buf).unwrap();
1642 let mut out_fused = [0i16; 16];
1643 let nz_fused = decode_block(
1644 &mut dec_fused,
1645 block_type,
1646 probs,
1647 above,
1648 left,
1649 &mut out_fused,
1650 )
1651 .unwrap();
1652
1653 let mut dec_ref = BoolDecoder::init(&buf).unwrap();
1654 let mut out_ref = [0i16; 16];
1655 let nz_ref =
1656 decode_block_reference(&mut dec_ref, block_type, probs, above, left, &mut out_ref)
1657 .unwrap();
1658
1659 assert_eq!(nz_fused, nz_ref, "trial {trial}: non-zero count");
1660 assert_eq!(out_fused, out_ref, "trial {trial}: coefficients");
1661 assert_eq!(out_fused, coeffs, "trial {trial}: roundtrip");
1662 assert_eq!(
1663 dec_fused.range(),
1664 dec_ref.range(),
1665 "trial {trial}: range state"
1666 );
1667 assert_eq!(
1668 dec_fused.value(),
1669 dec_ref.value(),
1670 "trial {trial}: value state"
1671 );
1672 assert_eq!(
1673 dec_fused.remaining_input(),
1674 dec_ref.remaining_input(),
1675 "trial {trial}: input cursor"
1676 );
1677 }
1678 }
1679
1680 // -----------------------------------------------------------------
1681 // §13.3 per-macroblock walk tests
1682 // -----------------------------------------------------------------
1683
1684 /// Reorder a raster-order block back into scan order (the inverse of
1685 /// `scan_to_raster`) so a test can specify the expected raster layout
1686 /// and feed `encode_block` (which works in scan order).
1687 fn raster_to_scan(raster: &[i16; 16]) -> [i16; 16] {
1688 let mut scan = [0i16; 16];
1689 for (c, slot) in scan.iter_mut().enumerate() {
1690 *slot = raster[ZIGZAG[c]];
1691 }
1692 scan
1693 }
1694
1695 /// A single shared bool-encoder that emits the whole macroblock
1696 /// residual record contiguously (the per-block `TestEncoder` cannot be
1697 /// concatenated). Mirrors `decode_mb_coeffs` exactly: block order,
1698 /// plane selection, zig-zag, and predictor threading.
1699 struct MbEncoder {
1700 enc: TestEncoder,
1701 }
1702
1703 impl MbEncoder {
1704 fn new() -> Self {
1705 Self {
1706 enc: TestEncoder::new(),
1707 }
1708 }
1709
1710 fn write_block(
1711 &mut self,
1712 block_index: usize,
1713 block_type: BlockType,
1714 raster: &[i16; 16],
1715 coeff_probs: &CoeffProbs,
1716 above: &mut MbEntropyCtx,
1717 left: &mut MbEntropyCtx,
1718 ) {
1719 let a_slot = ABOVE_CONTEXT_INDEX[block_index];
1720 let l_slot = LEFT_CONTEXT_INDEX[block_index];
1721 let above_nz = above.nonzero[a_slot];
1722 let left_nz = left.nonzero[l_slot];
1723 let scan = raster_to_scan(raster);
1724
1725 // Replay the §13.3 token loop, writing bits into the shared
1726 // encoder (this is `encode_block`'s body, inlined to share the
1727 // encoder state across blocks).
1728 let plane = block_type.plane_index();
1729 let first_coeff = block_type.first_coeff();
1730 let mut ctx3 = (above_nz as usize) + (left_nz as usize);
1731 let mut prev_was_zero = false;
1732 let mut last_non_zero: i32 = -1;
1733 for (idx, c) in scan.iter().enumerate().take(16) {
1734 if idx >= first_coeff && *c != 0 {
1735 last_non_zero = idx as i32;
1736 }
1737 }
1738 let mut nonzero_count = 0usize;
1739 let mut i = first_coeff as i32;
1740 while i < 16 {
1741 let band = COEFF_BANDS[i as usize];
1742 let probs = &coeff_probs[plane][band][ctx3];
1743 let emit_eob = i > last_non_zero;
1744 let abs_value: u16;
1745 let sign: bool;
1746 let token: DctToken;
1747 if emit_eob {
1748 token = DctToken::Eob;
1749 abs_value = 0;
1750 sign = false;
1751 } else {
1752 let v = scan[i as usize];
1753 sign = v < 0;
1754 abs_value = v.unsigned_abs();
1755 token = if abs_value == 0 {
1756 DctToken::Dct0
1757 } else if abs_value == 1 {
1758 DctToken::Dct1
1759 } else if abs_value == 2 {
1760 DctToken::Dct2
1761 } else if abs_value == 3 {
1762 DctToken::Dct3
1763 } else if abs_value == 4 {
1764 DctToken::Dct4
1765 } else if abs_value <= 6 {
1766 DctToken::Cat1
1767 } else if abs_value <= 10 {
1768 DctToken::Cat2
1769 } else if abs_value <= 18 {
1770 DctToken::Cat3
1771 } else if abs_value <= 34 {
1772 DctToken::Cat4
1773 } else if abs_value <= 66 {
1774 DctToken::Cat5
1775 } else {
1776 DctToken::Cat6
1777 };
1778 }
1779 let start = if prev_was_zero { 2i8 } else { 0i8 };
1780 for (i_half, bit) in encode_token(token, start) {
1781 self.enc.write_bool(probs[i_half], bit);
1782 }
1783 if token == DctToken::Eob {
1784 break;
1785 }
1786 if let Some((base, plist)) = match token {
1787 DctToken::Cat1 => Some((CAT_BASE[0], PCAT1)),
1788 DctToken::Cat2 => Some((CAT_BASE[1], PCAT2)),
1789 DctToken::Cat3 => Some((CAT_BASE[2], PCAT3)),
1790 DctToken::Cat4 => Some((CAT_BASE[3], PCAT4)),
1791 DctToken::Cat5 => Some((CAT_BASE[4], PCAT5)),
1792 DctToken::Cat6 => Some((CAT_BASE[5], PCAT6)),
1793 _ => None,
1794 } {
1795 let extra = abs_value - base;
1796 let n = plist.len();
1797 for (j, &p) in plist.iter().enumerate() {
1798 let bit = ((extra >> (n - 1 - j)) & 1) == 1;
1799 self.enc.write_bool(p, bit);
1800 }
1801 }
1802 if abs_value != 0 {
1803 self.enc.write_bool(128, sign);
1804 nonzero_count += 1;
1805 }
1806 ctx3 = if abs_value == 0 {
1807 0
1808 } else if abs_value == 1 {
1809 1
1810 } else {
1811 2
1812 };
1813 prev_was_zero = token == DctToken::Dct0;
1814 i += 1;
1815 }
1816 // Mirror the decoder's predictor update.
1817 let has_coeffs = nonzero_count != 0;
1818 above.nonzero[a_slot] = has_coeffs;
1819 left.nonzero[l_slot] = has_coeffs;
1820 }
1821
1822 fn finish(self) -> Vec<u8> {
1823 self.enc.finish()
1824 }
1825 }
1826
1827 /// Encode a whole macroblock contiguously and return the byte stream.
1828 /// `above` / `left` are threaded and left holding the post-MB context.
1829 #[allow(clippy::too_many_arguments)]
1830 fn encode_mb_shared(
1831 has_y2: bool,
1832 coeff_probs: &CoeffProbs,
1833 above: &mut MbEntropyCtx,
1834 left: &mut MbEntropyCtx,
1835 y2_raster: &[i16; 16],
1836 y_raster: &[[i16; 16]; 16],
1837 u_raster: &[[i16; 16]; 4],
1838 v_raster: &[[i16; 16]; 4],
1839 ) -> Vec<u8> {
1840 let mut mb = MbEncoder::new();
1841 if has_y2 {
1842 mb.write_block(24, BlockType::Y2, y2_raster, coeff_probs, above, left);
1843 }
1844 let y_plane = if has_y2 {
1845 BlockType::YAfterY2
1846 } else {
1847 BlockType::YNoY2
1848 };
1849 for (i, b) in y_raster.iter().enumerate() {
1850 mb.write_block(i, y_plane, b, coeff_probs, above, left);
1851 }
1852 for (i, b) in u_raster.iter().enumerate() {
1853 mb.write_block(16 + i, BlockType::UV, b, coeff_probs, above, left);
1854 }
1855 for (i, b) in v_raster.iter().enumerate() {
1856 mb.write_block(20 + i, BlockType::UV, b, coeff_probs, above, left);
1857 }
1858 mb.finish()
1859 }
1860
1861 #[test]
1862 fn zigzag_is_a_permutation_of_0_15() {
1863 // §20.16 zigzag[16] must be a bijection on 0..16 so
1864 // scan_to_raster / raster_to_scan round-trip.
1865 let mut seen = [false; 16];
1866 for &r in &ZIGZAG {
1867 assert!(!seen[r], "duplicate raster index {r}");
1868 seen[r] = true;
1869 }
1870 assert!(seen.iter().all(|&s| s));
1871 // Round-trip a distinct-valued block.
1872 let raster: [i16; 16] = core::array::from_fn(|i| (i as i16) - 8);
1873 assert_eq!(scan_to_raster(&raster_to_scan(&raster)), raster);
1874 }
1875
1876 #[test]
1877 fn context_index_tables_match_section_20_16() {
1878 // Spot-check the §20.16 left/above slot tables against the RFC
1879 // annex listing, including the Y2 (block 24) slot.
1880 assert_eq!(LEFT_CONTEXT_INDEX[0], 0);
1881 assert_eq!(LEFT_CONTEXT_INDEX[4], 1);
1882 assert_eq!(LEFT_CONTEXT_INDEX[15], 3);
1883 assert_eq!(LEFT_CONTEXT_INDEX[16], 4); // first U
1884 assert_eq!(LEFT_CONTEXT_INDEX[20], 6); // first V
1885 assert_eq!(LEFT_CONTEXT_INDEX[24], 8); // Y2
1886 assert_eq!(ABOVE_CONTEXT_INDEX[0], 0);
1887 assert_eq!(ABOVE_CONTEXT_INDEX[4], 0);
1888 assert_eq!(ABOVE_CONTEXT_INDEX[5], 1);
1889 assert_eq!(ABOVE_CONTEXT_INDEX[16], 4);
1890 assert_eq!(ABOVE_CONTEXT_INDEX[24], 8);
1891 }
1892
1893 #[test]
1894 fn mb_skip_yields_zero_coeffs_and_resets_context() {
1895 // A skip MB reads no tokens and zeroes its Y/U/V predictor slots.
1896 // With has_y2 = true the Y2 slot is also cleared.
1897 let probs = &DEFAULT_COEFF_PROBS;
1898 let mut above = MbEntropyCtx {
1899 nonzero: [true; MB_ENTROPY_CTX_LEN],
1900 };
1901 let mut left = MbEntropyCtx {
1902 nonzero: [true; MB_ENTROPY_CTX_LEN],
1903 };
1904 // No bytes are consumed; a trivial buffer suffices.
1905 let buf = [0u8; 8];
1906 let mut dec = BoolDecoder::init(&buf).unwrap();
1907 let mb = decode_mb_coeffs(&mut dec, true, true, probs, &mut above, &mut left).unwrap();
1908 assert_eq!(mb.y2, [0i16; 16]);
1909 assert_eq!(mb.y, [[0i16; 16]; 16]);
1910 assert_eq!(mb.u, [[0i16; 16]; 4]);
1911 assert_eq!(mb.v, [[0i16; 16]; 4]);
1912 assert_eq!(above.nonzero, [false; MB_ENTROPY_CTX_LEN]);
1913 assert_eq!(left.nonzero, [false; MB_ENTROPY_CTX_LEN]);
1914 }
1915
1916 #[test]
1917 fn mb_skip_bpred_preserves_y2_context() {
1918 // §20.16 reset_mb_context: a skipped B_PRED MB (no Y2) clears the
1919 // eight Y/U/V slots but preserves the Y2 slot (8).
1920 let probs = &DEFAULT_COEFF_PROBS;
1921 let mut above = MbEntropyCtx {
1922 nonzero: [true; MB_ENTROPY_CTX_LEN],
1923 };
1924 let mut left = MbEntropyCtx {
1925 nonzero: [true; MB_ENTROPY_CTX_LEN],
1926 };
1927 let buf = [0u8; 8];
1928 let mut dec = BoolDecoder::init(&buf).unwrap();
1929 let _ = decode_mb_coeffs(&mut dec, false, true, probs, &mut above, &mut left).unwrap();
1930 for slot in 0..8 {
1931 assert!(!above.nonzero[slot], "above slot {slot} not cleared");
1932 assert!(!left.nonzero[slot], "left slot {slot} not cleared");
1933 }
1934 assert!(above.nonzero[8], "above Y2 slot must be preserved");
1935 assert!(left.nonzero[8], "left Y2 slot must be preserved");
1936 }
1937
1938 #[test]
1939 fn synthetic_mb_decodes_to_expected_per_block_layout() {
1940 // Build a macroblock with distinctive coefficients in each plane,
1941 // encode it contiguously, and verify decode_mb_coeffs recovers the
1942 // exact per-block raster layout — including the Y2 block, the
1943 // YAfterY2 first-coefficient-1 luma plane, and chroma.
1944 let probs = &DEFAULT_COEFF_PROBS;
1945
1946 let mut y2 = [0i16; 16];
1947 y2[0] = 9;
1948 y2[3] = -4;
1949 y2[15] = 2;
1950
1951 // Each Y block: a recognisable value at raster position 1 (AC,
1952 // since the YAfterY2 plane starts decoding at scan coefficient 1).
1953 // Raster position 0 (the DC) must stay 0 — it is owned by Y2 and
1954 // never decoded for the YAfterY2 plane.
1955 let mut y = [[0i16; 16]; 16];
1956 for (k, blk) in y.iter_mut().enumerate() {
1957 blk[1] = (k as i16) - 8; // distinct per block, some negative
1958 if k % 3 == 0 {
1959 blk[5] = 3;
1960 }
1961 }
1962
1963 let mut u = [[0i16; 16]; 4];
1964 let mut v = [[0i16; 16]; 4];
1965 for (k, blk) in u.iter_mut().enumerate() {
1966 blk[0] = (k as i16) + 1; // DC present (UV plane starts at 0)
1967 }
1968 for (k, blk) in v.iter_mut().enumerate() {
1969 blk[0] = -((k as i16) + 1);
1970 blk[2] = 7;
1971 }
1972
1973 let mut enc_above = MbEntropyCtx::default();
1974 let mut enc_left = MbEntropyCtx::default();
1975 let buf = encode_mb_shared(true, probs, &mut enc_above, &mut enc_left, &y2, &y, &u, &v);
1976
1977 let mut dec_above = MbEntropyCtx::default();
1978 let mut dec_left = MbEntropyCtx::default();
1979 let mut dec = BoolDecoder::init(&buf).unwrap();
1980 let mb =
1981 decode_mb_coeffs(&mut dec, true, false, probs, &mut dec_above, &mut dec_left).unwrap();
1982
1983 assert_eq!(mb.y2, y2, "Y2 block mismatch");
1984 assert_eq!(mb.y, y, "Y blocks mismatch");
1985 assert_eq!(mb.u, u, "U blocks mismatch");
1986 assert_eq!(mb.v, v, "V blocks mismatch");
1987
1988 // The decoder's post-MB context must equal the encoder's.
1989 assert_eq!(dec_above, enc_above, "above context drift");
1990 assert_eq!(dec_left, enc_left, "left context drift");
1991
1992 // Sanity on the resulting context: Y2 had coeffs (slot 8 set);
1993 // every Y column/row slot set (each Y block has a nonzero AC);
1994 // U/V slots set.
1995 assert!(dec_above.nonzero[8], "Y2 above predictor should be set");
1996 for (slot, nonzero) in dec_above.nonzero.iter().enumerate().take(8) {
1997 assert!(nonzero, "above slot {slot} should be set");
1998 }
1999 }
2000
2001 #[test]
2002 fn empty_block_clears_its_predictor_slot() {
2003 // A block that decodes to all-zero (immediate EOB) must clear its
2004 // predictor slot even if it was set on entry, so the slot reflects
2005 // the LAST block mapped to it. We encode a Y MB where Y block 0
2006 // (slots above=0, left=0) is empty while Y block 1 (above=1,
2007 // left=0) is non-empty, then assert the resulting context.
2008 let probs = &DEFAULT_COEFF_PROBS;
2009 let y2 = [0i16; 16];
2010 let mut y = [[0i16; 16]; 16];
2011 // Y block 0 empty; Y block 1 has an AC coeff. Leave the rest empty.
2012 y[1][1] = 5;
2013 let u = [[0i16; 16]; 4];
2014 let v = [[0i16; 16]; 4];
2015
2016 let mut enc_above = MbEntropyCtx::default();
2017 let mut enc_left = MbEntropyCtx::default();
2018 let buf = encode_mb_shared(true, probs, &mut enc_above, &mut enc_left, &y2, &y, &u, &v);
2019 let mut dec_above = MbEntropyCtx::default();
2020 let mut dec_left = MbEntropyCtx::default();
2021 let mut dec = BoolDecoder::init(&buf).unwrap();
2022 let mb =
2023 decode_mb_coeffs(&mut dec, true, false, probs, &mut dec_above, &mut dec_left).unwrap();
2024 assert_eq!(mb.y, y);
2025 // Above slot for Y column 0 (blocks 0,4,8,12): the last decoded
2026 // block touching above-slot 0 is Y block 12 (empty) → false.
2027 assert!(
2028 !dec_above.nonzero[0],
2029 "above slot 0 should be cleared by later empty block"
2030 );
2031 // Above slot for Y column 1 (blocks 1,5,9,13): last is block 13
2032 // (empty) → false; but block 1 was non-empty earlier — confirm the
2033 // slot reflects the *last* block, not the earlier non-empty one.
2034 assert!(
2035 !dec_above.nonzero[1],
2036 "above slot 1 must reflect last (empty) block"
2037 );
2038 assert_eq!(dec_above, enc_above);
2039 assert_eq!(dec_left, enc_left);
2040 }
2041
2042 #[test]
2043 fn two_adjacent_mbs_propagate_left_context() {
2044 // §13.3: the left predictor of MB(col=1) is the right column of
2045 // MB(col=0). Decode two horizontally-adjacent MBs sharing a single
2046 // rolling `left` context (and independent `above` rows), and prove
2047 // the second MB's first-coefficient context depends on the first
2048 // MB's right-edge blocks.
2049 //
2050 // We construct MB0 so that its right-column Y blocks (3,7,11,15 ->
2051 // left slot 3) and right-column U/V are non-empty, then verify the
2052 // identical MB1 token bytes decode correctly only when the carried
2053 // `left` context is used. The strongest proof: decode MB1 with the
2054 // propagated context vs a fresh (all-false) context and show the
2055 // recovered coefficients differ (a context mismatch desyncs the
2056 // bool decoder, corrupting the stream).
2057 let probs = &DEFAULT_COEFF_PROBS;
2058
2059 // MB0: give every block a non-empty residue so all left slots end
2060 // up set (especially the right-column-driven slot 3, and U/V).
2061 let y2_0 = {
2062 let mut b = [0i16; 16];
2063 b[0] = 2;
2064 b
2065 };
2066 let mut y0 = [[0i16; 16]; 16];
2067 for blk in y0.iter_mut() {
2068 blk[1] = 1;
2069 }
2070 let mut u0 = [[0i16; 16]; 4];
2071 let mut v0 = [[0i16; 16]; 4];
2072 for blk in u0.iter_mut() {
2073 blk[0] = 1;
2074 }
2075 for blk in v0.iter_mut() {
2076 blk[0] = 1;
2077 }
2078
2079 // MB1: distinctive coefficients so we can assert exact recovery.
2080 let y2_1 = {
2081 let mut b = [0i16; 16];
2082 b[0] = -5;
2083 b[1] = 2;
2084 b
2085 };
2086 let mut y1 = [[0i16; 16]; 16];
2087 for (k, blk) in y1.iter_mut().enumerate() {
2088 blk[1] = (k as i16) - 5;
2089 }
2090 let mut u1 = [[0i16; 16]; 4];
2091 let mut v1 = [[0i16; 16]; 4];
2092 for (k, blk) in u1.iter_mut().enumerate() {
2093 blk[0] = (k as i16) + 2;
2094 }
2095 for (k, blk) in v1.iter_mut().enumerate() {
2096 blk[0] = -((k as i16) + 2);
2097 }
2098
2099 // Encode both MBs with the shared rolling `left` and a per-column
2100 // `above` row of two contexts (mirroring a 2-wide MB row).
2101 let mut enc_left = MbEntropyCtx::default();
2102 let mut enc_above0 = MbEntropyCtx::default();
2103 let mut enc_above1 = MbEntropyCtx::default();
2104 let buf0 = encode_mb_shared(
2105 true,
2106 probs,
2107 &mut enc_above0,
2108 &mut enc_left,
2109 &y2_0,
2110 &y0,
2111 &u0,
2112 &v0,
2113 );
2114 // After MB0, `enc_left` holds MB0's right-edge context — exactly
2115 // what MB1 must consume. Capture it for the negative control.
2116 let left_after_mb0 = enc_left;
2117 let buf1 = encode_mb_shared(
2118 true,
2119 probs,
2120 &mut enc_above1,
2121 &mut enc_left,
2122 &y2_1,
2123 &y1,
2124 &u1,
2125 &v1,
2126 );
2127
2128 // Decode MB0, then MB1 with the propagated `left`.
2129 let mut dec_left = MbEntropyCtx::default();
2130 let mut dec_above0 = MbEntropyCtx::default();
2131 let mut dec_above1 = MbEntropyCtx::default();
2132 let mut dec0 = BoolDecoder::init(&buf0).unwrap();
2133 let mb0 = decode_mb_coeffs(
2134 &mut dec0,
2135 true,
2136 false,
2137 probs,
2138 &mut dec_above0,
2139 &mut dec_left,
2140 )
2141 .unwrap();
2142 assert_eq!(mb0.y, y0);
2143 assert_eq!(
2144 dec_left, left_after_mb0,
2145 "MB0 must yield MB1's left context"
2146 );
2147
2148 let mut dec1 = BoolDecoder::init(&buf1).unwrap();
2149 let mb1 = decode_mb_coeffs(
2150 &mut dec1,
2151 true,
2152 false,
2153 probs,
2154 &mut dec_above1,
2155 &mut dec_left,
2156 )
2157 .unwrap();
2158 assert_eq!(mb1.y2, y2_1, "MB1 Y2 with propagated left context");
2159 assert_eq!(mb1.y, y1, "MB1 Y with propagated left context");
2160 assert_eq!(mb1.u, u1, "MB1 U with propagated left context");
2161 assert_eq!(mb1.v, v1, "MB1 V with propagated left context");
2162
2163 // Negative control: decoding MB1 with a FRESH (all-false) left
2164 // context picks the wrong probability rows on the first
2165 // coefficient of every block, desyncing the range decoder. The
2166 // recovered coefficients must NOT match the encoded MB1 — proving
2167 // the propagation is load-bearing, not incidental.
2168 let mut wrong_left = MbEntropyCtx::default();
2169 let mut wrong_above = MbEntropyCtx::default();
2170 let mut dec_wrong = BoolDecoder::init(&buf1).unwrap();
2171 let mb_wrong = decode_mb_coeffs(
2172 &mut dec_wrong,
2173 true,
2174 false,
2175 probs,
2176 &mut wrong_above,
2177 &mut wrong_left,
2178 );
2179 // It may decode (to garbage) or error; either way it must not
2180 // reproduce the correct MB1 coefficients.
2181 if let Ok(garbage) = mb_wrong {
2182 assert!(
2183 garbage.y != y1 || garbage.y2 != y2_1 || garbage.u != u1 || garbage.v != v1,
2184 "fresh-left decode unexpectedly matched — propagation not load-bearing?"
2185 );
2186 }
2187 }
2188
2189 #[test]
2190 fn fused_dequant_walk_matches_decode_then_dequantize() {
2191 // The fused §13.3 decode → §14.1 dequant walk
2192 // (`decode_mb_coeffs_dequant`, the `DQ = true` monomorphisation)
2193 // must be stream-for-stream identical to the two-pass form —
2194 // `decode_mb_coeffs` followed by
2195 // `MbDequantFactors::dequantize` — in every §13 shape:
2196 //
2197 // * a dense MB (every lane of every block non-zero, including
2198 // cat6 magnitudes whose product with a large factor overflows
2199 // i16 and must truncate identically);
2200 // * a sparse MB (DC + a few low-frequency AC, long zero runs —
2201 // the common shape, exercising the DCT_0 re-entry loop and
2202 // the untouched-lane invariant);
2203 // * a no-Y2 (B_PRED-shaped) MB where luma starts at coefficient
2204 // 0 and carries its own DC;
2205 // * a skip MB (no tokens; both paths return zeros and apply the
2206 // same context reset).
2207 //
2208 // The two decoders walk physically separate copies of the same
2209 // byte stream with independently threaded above/left contexts;
2210 // afterwards the coefficients, both contexts, and the number of
2211 // consumed input bits must all agree (the trailing literal read
2212 // proves bit-position lockstep).
2213 use crate::coded_header::QuantIndices;
2214 use crate::dequant::MbDequantFactors;
2215
2216 let probs = &DEFAULT_COEFF_PROBS;
2217
2218 // Large factors (high qi + worst-case deltas) so the cat6
2219 // products genuinely overflow i16 and pin the truncation.
2220 let factors = MbDequantFactors::from_quant_indices(&QuantIndices {
2221 y_ac_qi: 120,
2222 y_dc_delta: Some(7),
2223 y2_dc_delta: Some(15),
2224 y2_ac_delta: Some(15),
2225 uv_dc_delta: Some(3),
2226 uv_ac_delta: Some(9),
2227 });
2228 let pairs = MbDequantPairs {
2229 y2: (factors.y2_dc, factors.y2_ac),
2230 y1: (factors.y1_dc, factors.y1_ac),
2231 uv: (factors.uv_dc, factors.uv_ac),
2232 };
2233
2234 // Dense MB: every lane non-zero, cat6 values in every plane.
2235 let dense_block: [i16; 16] = [
2236 900, -3, 1, 70, //
2237 2, -80, 5, 1, //
2238 -1, 4, -2114, 2, //
2239 3, -1, 1, -6,
2240 ];
2241 let dense_y2 = dense_block;
2242 let dense_y = [dense_block; 16];
2243 let dense_uv = [dense_block; 4];
2244
2245 // Sparse MB: DC + two low-frequency ACs, long zero runs.
2246 let sparse_block: [i16; 16] = [
2247 7, -1, 0, 0, //
2248 1, 0, 0, 0, //
2249 0, 0, 0, 0, //
2250 0, 0, 0, 0,
2251 ];
2252 let sparse_y2 = sparse_block;
2253 let sparse_y = [sparse_block; 16];
2254 let sparse_uv = [sparse_block; 4];
2255
2256 // (has_y2, skip, y2, y, u, v) shapes.
2257 let zero_y2 = [0i16; 16];
2258 #[allow(clippy::type_complexity)]
2259 let shapes: [(bool, bool, [i16; 16], [[i16; 16]; 16], [[i16; 16]; 4]); 4] = [
2260 (true, false, dense_y2, dense_y, dense_uv),
2261 (true, false, sparse_y2, sparse_y, sparse_uv),
2262 (false, false, zero_y2, sparse_y, dense_uv),
2263 (true, true, zero_y2, [[0i16; 16]; 16], [[0i16; 16]; 4]),
2264 ];
2265
2266 for (case, &(has_y2, skip, y2, y, uv)) in shapes.iter().enumerate() {
2267 // Encode the MB (skip MBs contribute no tokens; encode an
2268 // empty stream and let both paths take the skip branch).
2269 let mut bytes = if skip {
2270 vec![0u8; 8]
2271 } else {
2272 let mut enc_above = MbEntropyCtx::default();
2273 let mut enc_left = MbEntropyCtx::default();
2274 encode_mb_shared(
2275 has_y2,
2276 probs,
2277 &mut enc_above,
2278 &mut enc_left,
2279 &y2,
2280 &y,
2281 &uv,
2282 &uv,
2283 )
2284 };
2285 // Slack for the trailing lockstep literal read below.
2286 bytes.extend_from_slice(&[0xA5; 8]);
2287
2288 // Path A: two-pass — decode raw, then dequantize.
2289 let mut dec_a = BoolDecoder::init(&bytes).unwrap();
2290 let mut above_a = MbEntropyCtx::default();
2291 let mut left_a = MbEntropyCtx::default();
2292 let mut two_pass =
2293 decode_mb_coeffs(&mut dec_a, has_y2, skip, probs, &mut above_a, &mut left_a)
2294 .unwrap();
2295 factors.dequantize(&mut two_pass);
2296
2297 // Path B: the fused walk.
2298 let mut dec_b = BoolDecoder::init(&bytes).unwrap();
2299 let mut above_b = MbEntropyCtx::default();
2300 let mut left_b = MbEntropyCtx::default();
2301 let fused = decode_mb_coeffs_dequant(
2302 &mut dec_b,
2303 has_y2,
2304 skip,
2305 probs,
2306 &pairs,
2307 &mut above_b,
2308 &mut left_b,
2309 )
2310 .unwrap();
2311
2312 assert_eq!(fused, two_pass, "case {case}: coefficients diverge");
2313 assert_eq!(above_a, above_b, "case {case}: above ctx diverges");
2314 assert_eq!(left_a, left_b, "case {case}: left ctx diverges");
2315 // Bit-position lockstep: the next reads must agree.
2316 assert_eq!(
2317 dec_a.read_literal(16).unwrap(),
2318 dec_b.read_literal(16).unwrap(),
2319 "case {case}: consumed bit counts diverge"
2320 );
2321 }
2322 }
2323}