forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

bool.rs443 lines, 14.5 KiBHistoryRawDownload
1//! The boolean arithmetic decoder (RFC 6386 §7).
2//!
3//! VP8 codes almost the entire frame as a sequence of bools, each written
4//! at an 8-bit zero-probability `p` (meaning `p/256`). The decoder mirrors
5//! the encoder's interval state with two numbers — `range` (128..=255) and
6//! `value` (the encoded number x minus the interval's left endpoint) — and
7//! renormalises one bit at a time, shifting a fresh input byte into
8//! `value` for every 8 bits consumed.
9//!
10//! Every function here is the direct inverse of the RFC's reference
11//! `bool_encoder`; the tests drive them against a test-only re-implementation
12//! of that encoder and assert bit-exact round-trips.
13
14use ec_core::Result;
15
16/// Boolean arithmetic decoder over one data partition (RFC 6386 §7.3).
17pub struct BoolDecoder<'a> {
18 data: &'a [u8],
19 /// Index of the next byte to shift into `value`.
20 pos: usize,
21 /// 128..=255; identical to the encoder's range.
22 range: u32,
23 /// Encoded number minus the current interval's left endpoint; the top
24 /// bits hold what has been read, bytes shift in at the bottom.
25 value: u32,
26 /// Bits shifted out of `value` since the last byte was shifted in.
27 bit_count: u32,
28 /// Bytes consumed past the end of the partition (read as 0, per the
29 /// spec's zero-extension of x). A healthy partition stays at 0.
30 overreads: u32,
31}
32
33impl<'a> BoolDecoder<'a> {
34 /// Start decoding the partition `data` (RFC `init_bool_decoder`): the
35 /// first two bytes are read into `value`, big-endian. A partition
36 /// shorter than two bytes (legal for unused token partitions of
37 /// multi-partition frames) is zero-extended like the reference
38 /// decoder does, and the shortfall shows up in [`Self::overreads`].
39 pub fn new(data: &'a [u8]) -> Result<Self> {
40 if data.is_empty() {
41 return Ok(Self {
42 data,
43 pos: 0,
44 range: 255,
45 value: 0,
46 bit_count: 0,
47 overreads: 0,
48 });
49 }
50 let mut value = u32::from(data[0]) << 8;
51 if data.len() > 1 {
52 value |= u32::from(data[1]);
53 }
54 Ok(Self {
55 data,
56 pos: data.len().min(2),
57 range: 255,
58 value,
59 bit_count: 0,
60 overreads: 0,
61 })
62 }
63
64 /// Bytes consumed past the end of the partition, read as zero. Any
65 /// non-zero value on a complete, valid partition is a desync symptom.
66 pub fn overreads(&self) -> u32 {
67 self.overreads
68 }
69
70 /// Offset of the next unread input byte, for desync diagnostics.
71 pub fn byte_offset(&self) -> usize {
72 self.pos
73 }
74
75 fn next_byte(&mut self) -> u32 {
76 match self.data.get(self.pos) {
77 Some(&b) => {
78 self.pos += 1;
79 u32::from(b)
80 }
81 None => {
82 self.overreads += 1;
83 0
84 }
85 }
86 }
87
88 /// Decode one bool whose zero-probability is `prob`/256
89 /// (RFC `read_bool`). Under EC_VP8_TRACE, prints the decoder state
90 /// after the read — `B <pos> <bit_count> <prob> <bit>`, byte-exact
91 /// the same line scripts/vp8ref_model.py prints — so the two
92 /// decoders can be diffed read-for-read.
93 pub fn read_bool(&mut self, prob: u8) -> bool {
94 let prob = u32::from(prob);
95 let split = 1 + (((self.range - 1) * prob) >> 8);
96 let bigsplit = split << 8;
97 let bit = if self.value >= bigsplit {
98 self.range -= split;
99 self.value -= bigsplit;
100 true
101 } else {
102 self.range = split;
103 false
104 };
105 while self.range < 128 {
106 self.value <<= 1;
107 self.range <<= 1;
108 self.bit_count += 1;
109 if self.bit_count == 8 {
110 self.bit_count = 0;
111 self.value |= self.next_byte();
112 }
113 }
114 if crate::trace_enabled() {
115 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
116 }
117 bit
118 }
119
120 /// Unsigned `n`-bit literal, bits high- to low-order, each at
121 /// probability 128 (RFC `read_literal`).
122 pub fn read_literal(&mut self, n: u32) -> u32 {
123 let mut v = 0;
124 for _ in 0..n {
125 v = (v << 1) + u32::from(self.read_bool(128));
126 }
127 v
128 }
129
130 /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude
131 /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0.
132 pub fn read_signed_literal(&mut self, n: u32) -> i32 {
133 if n == 0 {
134 return 0;
135 }
136 let mut v: i32 = if self.read_bool(128) { -1 } else { 0 };
137 for _ in 0..n - 1 {
138 v = (v << 1) + i32::from(self.read_bool(128));
139 }
140 v
141 }
142 /// Presence-gated signed integer in the frame-header shape (RFC §9.3,
143 /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an
144 /// `n`-bit magnitude followed by a sign flag (1 = negative). This is
145 /// every segment/quantizer/loop-filter delta in the frame header.
146 pub fn read_maybe_signed(&mut self, n: u32) -> i32 {
147 if !self.read_bool(128) {
148 return 0;
149 }
150 let v = self.read_literal(n) as i32;
151 if self.read_bool(128) { -v } else { v }
152 }
153
154 /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1
155 /// : 1` (RFC §8, MV probability updates use exactly this shape).
156 pub fn read_prob7(&mut self) -> u8 {
157 let x = self.read_literal(7);
158 if x == 0 { 1 } else { (x << 1) as u8 }
159 }
160
161 /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the
162 /// left/right branch entries (positive = interior node index, negative
163 /// `-leaf`), `probs[i]` is the probability of interior node `i` (the
164 /// tree position halved).
165 pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
166 let mut i: i32 = 0;
167 loop {
168 let b = self.read_bool(probs[(i >> 1) as usize]);
169 i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
170 if i <= 0 {
171 return (-i) as u8;
172 }
173 }
174 }
175
176 /// Decode a tree-coded value, skipping the root's `dct_eob` branch —
177 /// used for every token after a `DCT_0`, since EOB cannot follow a
178 /// zero token (RFC §13.2). `tree` must be the full coefficient tree;
179 /// decoding starts at interior node 1.
180 pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
181 // The coefficient tree's layout puts the EOB leaf at the root's
182 // left branch; descending the right branch first is exactly
183 // "start at the root with a read 1".
184 let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch
185 while {
186 let b = self.read_bool(probs[(i >> 1) as usize]);
187 i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
188 i > 0
189 } {}
190 (-i) as u8
191 }
192}
193
194/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests
195/// drive [`BoolDecoder`] against known bitstreams instead of trusting the
196/// decoder to decode its own idea of the format.
197#[cfg(test)]
198pub(crate) struct BoolEncoder {
199 out: Vec<u8>,
200 range: u32,
201 bottom: u32,
202 bit_count: i32,
203}
204
205#[cfg(test)]
206impl BoolEncoder {
207 pub(crate) fn new() -> Self {
208 Self {
209 out: Vec::new(),
210 range: 255,
211 bottom: 0,
212 bit_count: 24,
213 }
214 }
215
216 pub(crate) fn write_bool(&mut self, val: bool, prob: u8) {
217 let prob = u32::from(prob);
218 let split = 1 + (((self.range - 1) * prob) >> 8);
219 if val {
220 self.bottom += split;
221 self.range -= split;
222 } else {
223 self.range = split;
224 }
225 while self.range < 128 {
226 self.range <<= 1;
227 if self.bottom & (1 << 31) != 0 {
228 Self::add_one_to_output(&mut self.out);
229 }
230 self.bottom <<= 1;
231 self.bit_count -= 1;
232 if self.bit_count == 0 {
233 self.out.push((self.bottom >> 24) as u8);
234 self.bottom &= (1 << 24) - 1;
235 self.bit_count = 8;
236 }
237 }
238 }
239
240 pub(crate) fn write_literal(&mut self, v: u32, n: u32) {
241 for i in (0..n).rev() {
242 self.write_bool((v >> i) & 1 != 0, 128);
243 }
244 }
245
246 fn add_one_to_output(out: &mut [u8]) {
247 for b in out.iter_mut().rev() {
248 if *b == 255 {
249 *b = 0;
250 } else {
251 *b += 1;
252 return;
253 }
254 }
255 // Carry out of the beginning cannot happen: x < 1 always (RFC).
256 unreachable!("bool encoder carry propagated past the first byte");
257 }
258
259 /// RFC `flush_bool_encoder`.
260 pub(crate) fn flush(mut self) -> Vec<u8> {
261 let c = self.bit_count;
262 let mut v = self.bottom;
263 if v & (1 << (32 - c)) != 0 {
264 Self::add_one_to_output(&mut self.out);
265 }
266 v <<= c & 7;
267 let mut c = c >> 3;
268 while c > 0 {
269 v <<= 8;
270 c -= 1;
271 }
272 for _ in 0..4 {
273 self.out.push((v >> 24) as u8);
274 v <<= 8;
275 }
276 self.out
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 fn roundtrip_bools(pattern: &[(&[bool], u8)]) {
285 let mut e = BoolEncoder::new();
286 for (vals, p) in pattern {
287 for &v in *vals {
288 e.write_bool(v, *p);
289 }
290 }
291 let data = e.flush();
292 let mut d = BoolDecoder::new(&data).unwrap();
293 for (vals, p) in pattern {
294 for &v in *vals {
295 assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p);
296 }
297 }
298 assert_eq!(d.overreads(), 0);
299 }
300
301 #[test]
302 fn roundtrips_bools_at_every_extreme() {
303 // p = 1 (all zeros essentially free) through p = 255, with 1s at
304 // the most improbable settings to force carry propagation.
305 roundtrip_bools(&[
306 (&[false; 64], 1),
307 (&[true], 1),
308 (&[false, true, false, true], 128),
309 (&[true; 3], 255),
310 (&[false; 32], 255),
311 (&[true; 16], 1),
312 ]);
313 }
314
315 #[test]
316 fn roundtrips_long_random_streams() {
317 // Deterministic LCG so failures reproduce.
318 let mut state: u64 = 0x9E3779B97F4A7C15;
319 let mut next = move || {
320 state ^= state << 13;
321 state ^= state >> 7;
322 state ^= state << 17;
323 state
324 };
325 let probs = [1u8, 2, 32, 128, 200, 254, 255];
326 let mut e = BoolEncoder::new();
327 let mut expected = Vec::new();
328 for &p in &probs {
329 for _ in 0..200 {
330 let v = next() & 1 == 1;
331 e.write_bool(v, p);
332 expected.push((v, p));
333 }
334 }
335 let data = e.flush();
336 let mut d = BoolDecoder::new(&data).unwrap();
337 for (v, p) in expected {
338 assert_eq!(d.read_bool(p), v);
339 }
340 assert_eq!(d.overreads(), 0);
341 }
342
343 #[test]
344 fn roundtrips_literals() {
345 let mut e = BoolEncoder::new();
346 for n in 1..=19u32 {
347 let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
348 e.write_literal(ones, n);
349 e.write_literal(0, n);
350 e.write_literal(0x15 & ones, n); // 0b10101 truncated
351 }
352 let data = e.flush();
353 let mut d = BoolDecoder::new(&data).unwrap();
354 for n in 1..=19u32 {
355 let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
356 assert_eq!(d.read_literal(n), ones);
357 assert_eq!(d.read_literal(n), 0);
358 assert_eq!(d.read_literal(n), 0x15 & ones);
359 }
360 assert_eq!(d.overreads(), 0);
361 }
362
363 #[test]
364 fn roundtrips_signed_literals() {
365 let mut e = BoolEncoder::new();
366 // sign flag then 4 magnitude bits: the two's-complement value in
367 // -16..=15 (RFC read_signed_literal shifts the sign-extended -1).
368 for mag in 0..=15u32 {
369 e.write_bool(true, 128);
370 e.write_literal(mag, 4);
371 e.write_bool(false, 128);
372 e.write_literal(mag, 4);
373 }
374 let data = e.flush();
375 let mut d = BoolDecoder::new(&data).unwrap();
376 for mag in 0..=15i32 {
377 assert_eq!(d.read_signed_literal(5), mag - 16);
378 assert_eq!(d.read_signed_literal(5), mag);
379 }
380 assert_eq!(d.overreads(), 0);
381 }
382
383 #[test]
384 fn roundtrips_prob7() {
385 let mut e = BoolEncoder::new();
386 for x in 0..=127u32 {
387 e.write_literal(x, 7);
388 }
389 let data = e.flush();
390 let mut d = BoolDecoder::new(&data).unwrap();
391 for x in 0..=127u32 {
392 assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 });
393 }
394 }
395
396 #[test]
397 fn roundtrips_tree_values() {
398 // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2:
399 // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}.
400 let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3];
401 let probs = [145u8, 156, 163, 128];
402 // (bit path, leaf value) pairs of the kf ymode tree (§11.2):
403 // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110",
404 // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics.
405 let leaves: [(&[bool], u8); 5] = [
406 (&[false], 4),
407 (&[true, false, false], 0),
408 (&[true, false, true], 1),
409 (&[true, true, false], 2),
410 (&[true, true, true], 3),
411 ];
412 for (path, val) in leaves {
413 let mut e = BoolEncoder::new();
414 for (i, &b) in path.iter().enumerate() {
415 e.write_bool(b, probs[i]);
416 }
417 let data = e.flush();
418 let mut d = BoolDecoder::new(&data).unwrap();
419 assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}");
420 }
421 }
422
423 #[test]
424 fn short_partitions_zero_extend() {
425 // Empty/1-byte partitions are legal for unused token partitions;
426 // the init shortfall counts as overreads.
427 let mut d = BoolDecoder::new(&[]).unwrap();
428 assert_eq!(d.read_bool(128), false);
429 let mut d = BoolDecoder::new(&[0]).unwrap();
430 assert_eq!(d.read_bool(128), false);
431 }
432
433 #[test]
434 fn overreads_are_counted_not_panicked() {
435 // Two bytes of init, then nothing: any read shifts in zeros.
436 let data = [0u8, 0];
437 let mut d = BoolDecoder::new(&data).unwrap();
438 for _ in 0..100 {
439 d.read_bool(128);
440 }
441 assert!(d.overreads() > 0);
442 }
443}