forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tokens.rs315 lines, 11.1 KiBHistoryRawDownload
1//! DCT coefficient (token) decoding — RFC 6386 §13.
2//!
3//! Per 4x4 block: tokens are tree-decoded at
4//! `probs[type][band[position]][ctx]` where `ctx` (0..2) is the zero-
5//! neighbour count — sum of the above/left block contexts for the first
6//! coded coefficient, then derived from the magnitude of the previous
7//! coefficient within the block (§13.3). Coefficients are written in
8//! natural (de-zigzagged) order and dequantized on the fly (the first
9//! coded position takes the DC factor, all others the AC factor — the
10//! same arithmetic dixie applies inline and libvpx applies in
11//! `vp8_dequantize_b`).
12//!
13//! After an EOB the block ends; after a `DCT_0` token the tree decode of
14//! the next coefficient skips the EOB branch (§13.2). A block whose
15//! coefficients fill all 16 positions cannot take an EOB (the decoder
16//! stops at 16 exactly like the reference decoder, down to the sentinel
17//! band entry).
18
19use crate::bool::BoolDecoder;
20use crate::tables::{PCAT3, PCAT4, PCAT5, PCAT6};
21
22/// De-zigzag: coefficient scan position -> natural order index
23/// (RFC 6386 §13, dixie/libvpx `zigzag`).
24const ZIGZAG: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
25
26/// Band per coefficient position, with the reference decoder's sentinel
27/// entry at 16 (band 0 on the malformed no-EOB path — libvpx `kBands`).
28const BANDS: [u8; 17] = [0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0];
29
30/// Extra-bit probability tables per category (cat3..cat6, RFC 6386
31/// §13.2; the cat1/cat2 probabilities 159/165+145 are inlined in the
32/// tree decode exactly as the reference does). Trailing 0 is the
33/// DCTextra sentinel.
34const CAT_EXTRA: [&[u8]; 4] = [&PCAT3, &PCAT4, &PCAT5, &PCAT6];
35
36/// Dequantization factors for one macroblock (already scaled: Y2 AC has
37/// the ×155/100 min-8 rule applied, Y2 DC ×2, UV DC capped at 132).
38#[derive(Debug, Clone, Copy)]
39pub(crate) struct Dq {
40 pub y1_dc: i16,
41 pub y1_ac: i16,
42 pub uv_dc: i16,
43 pub uv_ac: i16,
44 pub y2_dc: i16,
45 pub y2_ac: i16,
46}
47
48/// The 25 blocks of one macroblock, dequantized, in natural coefficient
49/// order. `eobs[b]` is the number of significant coefficients (position
50/// of the last non-zero + 1); `eob_mask` mirrors dixie's: bit b set iff
51/// block b ended with more than one significant coefficient, bit 31 set
52/// iff ANY block had a non-zero coefficient.
53pub(crate) struct MbCoeffs {
54 pub y: [[i16; 16]; 16],
55 pub u: [[i16; 16]; 4],
56 pub v: [[i16; 16]; 4],
57 pub y2: [i16; 16],
58 pub has_y2: bool,
59 pub eobs: [u8; 25],
60 pub eob_mask: u32,
61}
62
63impl MbCoeffs {
64 pub(crate) fn empty(has_y2: bool) -> Self {
65 Self {
66 y: [[0; 16]; 16],
67 u: [[0; 16]; 4],
68 v: [[0; 16]; 4],
69 y2: [0; 16],
70 has_y2,
71 eobs: [0; 25],
72 eob_mask: 0,
73 }
74 }
75
76 /// Whether any block carries a non-zero coefficient (the loop
77 /// filter's interior-edge condition, §15.1).
78 pub fn has_nonzero(&self) -> bool {
79 self.eob_mask & (1 << 31) != 0
80 }
81}
82
83/// Left/above context slot of each block (dixie `left_context_index` /
84/// `above_context_index`).
85const LEFT_INDEX: [usize; 25] = [
86 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8,
87];
88const ABOVE_INDEX: [usize; 25] = [
89 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8,
90];
91
92/// Token entropy contexts (dixie/libvpx layout): indices 0-3 are the Y
93/// subblock columns, 4-5 U, 6-7 V, 8 the Y2 block. `left` is the running
94/// one-MB-wide column state; `above` is the per-MB-column state for the
95/// current row (9 slots per MB column).
96pub(crate) struct TokenContexts {
97 pub above: Vec<u8>,
98 pub left: [u8; 9],
99}
100
101impl TokenContexts {
102 /// `mb_cols` entries of 9 slots for the above state.
103 pub fn new(mb_cols: usize) -> Self {
104 Self {
105 above: vec![0u8; mb_cols * 9],
106 left: [0; 9],
107 }
108 }
109
110 /// Reset the above state at the start of a row (§13.3: non-existent
111 /// neighbours are empty).
112 pub fn reset_above_row(&mut self) {
113 self.above.iter_mut().for_each(|s| *s = 0);
114 }
115
116 /// Reset the left state at the start of a row (the caller MUST call
117 /// this once per MB row before decoding its tokens).
118 pub fn reset_left(&mut self) {
119 self.left = [0; 9];
120 }
121
122 /// Skip-MB context reset (dixie `reset_mb_context`): everything to 0
123 /// except the Y2 slots, which survive iff this MB has no Y2 block.
124 pub fn reset_mb(&mut self, mb_col: usize, has_y2: bool) {
125 let a = &mut self.above[mb_col * 9..mb_col * 9 + 9];
126 a[..8].fill(0);
127 self.left[..8].fill(0);
128 if has_y2 {
129 a[8] = 0;
130 self.left[8] = 0;
131 }
132 }
133
134 fn ctx_pair(&self, mb_col: usize, block: usize) -> (u8, u8) {
135 let a = &self.above[mb_col * 9..mb_col * 9 + 9];
136 (self.left[LEFT_INDEX[block]], a[ABOVE_INDEX[block]])
137 }
138
139 fn set_ctx(&mut self, mb_col: usize, block: usize, v: u8) {
140 self.left[LEFT_INDEX[block]] = v;
141 self.above[mb_col * 9 + ABOVE_INDEX[block]] = v;
142 }
143}
144
145/// Decode one 4x4 block's tokens (libvpx `GetCoeffs` / RFC §13.2-13.3
146/// verbatim). `probs_t` is `[band][ctx][node]` for the block's plane
147/// type; `n0` the first coded position (1 for Y blocks after a Y2).
148/// Returns the number of significant coefficients. Coefficients are
149/// written dequantized into `out` (natural order).
150fn get_coeffs(
151 bc: &mut BoolDecoder<'_>,
152 probs_t: &[[[u8; 11]; 3]; 8],
153 ctx: usize,
154 n0: usize,
155 dc_factor: i16,
156 ac_factor: i16,
157 out: &mut [i16; 16],
158) -> usize {
159 let trace = crate::trace_enabled();
160 // One token decision: decode the bool, then — under EC_VP8_TRACE —
161 // print the consulted (n, band, ctx, prob) and the decoded bit so the
162 // stream can be diffed read-for-read against scripts/vp8ref_model.py.
163 macro_rules! g {
164 ($n:expr, $band:expr, $c:expr, $prob:expr) => {{
165 let bit = bc.read_bool($prob);
166 if trace {
167 eprintln!(
168 "G n={} band={} ctx={} prob={} bit={}",
169 $n, $band, $c, $prob, u8::from(bit)
170 );
171 }
172 bit
173 }};
174 }
175 let mut n = n0;
176 let mut band = BANDS[n0];
177 let mut c = ctx;
178 let mut p = &probs_t[band as usize][c];
179 if !g!(n, band, c, p[0]) {
180 return 0; // immediate EOB
181 }
182 loop {
183 n += 1;
184 let mut v: i32;
185 if !g!(n, band, c, p[1]) {
186 // DCT_0: the next decision skips the EOB branch (§13.2) and
187 // libvpx forces the context to 0 after a zero token.
188 c = 0;
189 band = BANDS[n];
190 p = &probs_t[band as usize][0];
191 } else {
192 if !g!(n, band, c, p[2]) {
193 c = 1;
194 band = BANDS[n];
195 p = &probs_t[band as usize][1];
196 v = 1;
197 } else {
198 if !g!(n, band, c, p[3]) {
199 if !g!(n, band, c, p[4]) {
200 v = 2;
201 } else {
202 v = 3 + i32::from(g!(n, band, c, p[5]));
203 }
204 } else {
205 if !g!(n, band, c, p[6]) {
206 if !g!(n, band, c, p[7]) {
207 v = 5 + i32::from(g!(n, band, c, 159u8));
208 } else {
209 v = 7 + 2 * i32::from(g!(n, band, c, 165u8));
210 v += i32::from(g!(n, band, c, 145u8));
211 }
212 } else {
213 let bit1 = usize::from(g!(n, band, c, p[8]));
214 let bit0 = usize::from(g!(n, band, c, p[9 + bit1]));
215 let cat = 2 * bit1 + bit0;
216 v = 0;
217 for &prob in CAT_EXTRA[cat].iter() {
218 if prob == 0 {
219 break;
220 }
221 let g = i32::from(g!(n, band, c, prob));
222 v = v + v + g;
223 }
224 v += 3 + (8 << cat);
225 }
226 }
227 c = 2;
228 band = BANDS[n];
229 p = &probs_t[band as usize][2];
230 }
231
232 // Sign flag, then dequantize (first coded position is DC).
233 // Shared by the ONE and magnitude paths, exactly like the
234 // reference walk (libvpx detokenize.c GetCoeffs).
235 let neg = g!(n, band, c, 128u8);
236 let mag = if neg { -v } else { v };
237 out[ZIGZAG[n - 1]] = if n - 1 == 0 {
238 (mag * i32::from(dc_factor)) as i16
239 } else {
240 (mag * i32::from(ac_factor)) as i16
241 };
242 if n < 16 && !g!(n, band, c, p[0]) {
243 return n; // EOB
244 }
245 }
246 if n == 16 {
247 return 16; // malformed without EOB: stop like the reference
248 }
249 }
250}
251
252/// Decode all 25 blocks of one macroblock (dixie `decode_mb_tokens`):
253/// Y2 first when present, then the 16 Y, then U, then V. A skipped MB
254/// must not be run through here — call [`skip_mb_tokens`] instead.
255pub(crate) fn decode_mb_tokens(
256 bc: &mut BoolDecoder<'_>,
257 probs: &[[[[u8; 11]; 3]; 8]; 4],
258 dq: &Dq,
259 has_y2: bool,
260 ctxs: &mut TokenContexts,
261 mb_col: usize,
262) -> MbCoeffs {
263 let mut out = MbCoeffs::empty(has_y2);
264 let mut eob_mask = 0u32;
265
266 // Decode one block and fold its contexts/mask in.
267 macro_rules! block {
268 ($idx:expr, $ptype:expr, $dc:expr, $ac:expr, $slot:expr) => {{
269 let n0 = usize::from($ptype == 0);
270 let (l, a) = ctxs.ctx_pair(mb_col, $idx);
271 let ctx = (usize::from(l) + usize::from(a)).min(2);
272 if crate::trace_enabled() {
273 eprintln!("TB {} ctx={} l={} a={}", $idx, ctx, l, a);
274 }
275 let eob = get_coeffs(bc, &probs[$ptype], ctx, n0, $dc, $ac, $slot);
276 if crate::trace_enabled() {
277 eprintln!("TBE {} eob={}", $idx, eob);
278 }
279 out.eobs[$idx] = eob as u8;
280 let t = u8::from(eob > 0);
281 ctxs.set_ctx(mb_col, $idx, t);
282 eob_mask |= (u32::from(eob > 1)) << $idx;
283 eob_mask |= u32::from(t != 0) << 31;
284 }};
285 }
286
287 if has_y2 {
288 block!(24, 1, dq.y2_dc, dq.y2_ac, &mut out.y2);
289 for b in 0..16 {
290 block!(b, 0, dq.y1_dc, dq.y1_ac, &mut out.y[b]);
291 }
292 } else {
293 for b in 0..16 {
294 block!(b, 3, dq.y1_dc, dq.y1_ac, &mut out.y[b]);
295 }
296 }
297 for b in 0..4 {
298 block!(16 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.u[b]);
299 }
300 for b in 0..4 {
301 block!(20 + b, 2, dq.uv_dc, dq.uv_ac, &mut out.v[b]);
302 }
303
304 out.eob_mask = eob_mask;
305 out
306}
307
308/// The context reset a skipped MB applies (dixie `reset_mb_context`):
309/// the returned [`MbCoeffs`] is all-zero and the contexts look like a
310/// fully-empty MB — except the Y2 slots survive when the skipped MB has
311/// no Y2 block.
312pub(crate) fn skip_mb_tokens(ctxs: &mut TokenContexts, mb_col: usize, has_y2: bool) -> MbCoeffs {
313 ctxs.reset_mb(mb_col, has_y2);
314 MbCoeffs::empty(has_y2)
315}