forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB68cf7a6Tahinli2 months ago2975 commits

bool.rs444 lines, 14.6 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 trace = std::env::var_os("EC_VP8_TRACE").is_some();
95 let prob = u32::from(prob);
96 let split = 1 + (((self.range - 1) * prob) >> 8);
97 let bigsplit = split << 8;
98 let bit = if self.value >= bigsplit {
99 self.range -= split;
100 self.value -= bigsplit;
101 true
102 } else {
103 self.range = split;
104 false
105 };
106 while self.range < 128 {
107 self.value <<= 1;
108 self.range <<= 1;
109 self.bit_count += 1;
110 if self.bit_count == 8 {
111 self.bit_count = 0;
112 self.value |= self.next_byte();
113 }
114 }
115 if trace {
116 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
117 }
118 bit
119 }
120
121 /// Unsigned `n`-bit literal, bits high- to low-order, each at
122 /// probability 128 (RFC `read_literal`).
123 pub fn read_literal(&mut self, n: u32) -> u32 {
124 let mut v = 0;
125 for _ in 0..n {
126 v = (v << 1) + u32::from(self.read_bool(128));
127 }
128 v
129 }
130
131 /// Signed `n`-bit literal: a sign flag followed by `n - 1` magnitude
132 /// bits (RFC `read_signed_literal`). `n = 0` reads nothing and yields 0.
133 pub fn read_signed_literal(&mut self, n: u32) -> i32 {
134 if n == 0 {
135 return 0;
136 }
137 let mut v: i32 = if self.read_bool(128) { -1 } else { 0 };
138 for _ in 0..n - 1 {
139 v = (v << 1) + i32::from(self.read_bool(128));
140 }
141 v
142 }
143 /// Presence-gated signed integer in the frame-header shape (RFC §9.3,
144 /// §9.6; dixie `bool_maybe_get_int`): a presence flag, then, if set, an
145 /// `n`-bit magnitude followed by a sign flag (1 = negative). This is
146 /// every segment/quantizer/loop-filter delta in the frame header.
147 pub fn read_maybe_signed(&mut self, n: u32) -> i32 {
148 if !self.read_bool(128) {
149 return 0;
150 }
151 let v = self.read_literal(n) as i32;
152 if self.read_bool(128) { -v } else { v }
153 }
154
155 /// P(7): a 7-bit specification of an 8-bit probability — `x ? x << 1
156 /// : 1` (RFC §8, MV probability updates use exactly this shape).
157 pub fn read_prob7(&mut self) -> u8 {
158 let x = self.read_literal(7);
159 if x == 0 { 1 } else { (x << 1) as u8 }
160 }
161
162 /// Decode a tree-coded value (RFC §8.1 `treed_read`): `tree` holds the
163 /// left/right branch entries (positive = interior node index, negative
164 /// `-leaf`), `probs[i]` is the probability of interior node `i` (the
165 /// tree position halved).
166 pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
167 let mut i: i32 = 0;
168 loop {
169 let b = self.read_bool(probs[(i >> 1) as usize]);
170 i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
171 if i <= 0 {
172 return (-i) as u8;
173 }
174 }
175 }
176
177 /// Decode a tree-coded value, skipping the root's `dct_eob` branch —
178 /// used for every token after a `DCT_0`, since EOB cannot follow a
179 /// zero token (RFC §13.2). `tree` must be the full coefficient tree;
180 /// decoding starts at interior node 1.
181 pub fn read_tree_no_root_eob(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
182 // The coefficient tree's layout puts the EOB leaf at the root's
183 // left branch; descending the right branch first is exactly
184 // "start at the root with a read 1".
185 let mut i: i32 = i32::from(tree[1]); // interior node reached on the "1" branch
186 while {
187 let b = self.read_bool(probs[(i >> 1) as usize]);
188 i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
189 i > 0
190 } {}
191 (-i) as u8
192 }
193}
194
195/// The RFC 6386 §7.3 reference `bool_encoder`, test-only: it lets the tests
196/// drive [`BoolDecoder`] against known bitstreams instead of trusting the
197/// decoder to decode its own idea of the format.
198#[cfg(test)]
199pub(crate) struct BoolEncoder {
200 out: Vec<u8>,
201 range: u32,
202 bottom: u32,
203 bit_count: i32,
204}
205
206#[cfg(test)]
207impl BoolEncoder {
208 pub(crate) fn new() -> Self {
209 Self {
210 out: Vec::new(),
211 range: 255,
212 bottom: 0,
213 bit_count: 24,
214 }
215 }
216
217 pub(crate) fn write_bool(&mut self, val: bool, prob: u8) {
218 let prob = u32::from(prob);
219 let split = 1 + (((self.range - 1) * prob) >> 8);
220 if val {
221 self.bottom += split;
222 self.range -= split;
223 } else {
224 self.range = split;
225 }
226 while self.range < 128 {
227 self.range <<= 1;
228 if self.bottom & (1 << 31) != 0 {
229 Self::add_one_to_output(&mut self.out);
230 }
231 self.bottom <<= 1;
232 self.bit_count -= 1;
233 if self.bit_count == 0 {
234 self.out.push((self.bottom >> 24) as u8);
235 self.bottom &= (1 << 24) - 1;
236 self.bit_count = 8;
237 }
238 }
239 }
240
241 pub(crate) fn write_literal(&mut self, v: u32, n: u32) {
242 for i in (0..n).rev() {
243 self.write_bool((v >> i) & 1 != 0, 128);
244 }
245 }
246
247 fn add_one_to_output(out: &mut [u8]) {
248 for b in out.iter_mut().rev() {
249 if *b == 255 {
250 *b = 0;
251 } else {
252 *b += 1;
253 return;
254 }
255 }
256 // Carry out of the beginning cannot happen: x < 1 always (RFC).
257 unreachable!("bool encoder carry propagated past the first byte");
258 }
259
260 /// RFC `flush_bool_encoder`.
261 pub(crate) fn flush(mut self) -> Vec<u8> {
262 let c = self.bit_count;
263 let mut v = self.bottom;
264 if v & (1 << (32 - c)) != 0 {
265 Self::add_one_to_output(&mut self.out);
266 }
267 v <<= c & 7;
268 let mut c = c >> 3;
269 while c > 0 {
270 v <<= 8;
271 c -= 1;
272 }
273 for _ in 0..4 {
274 self.out.push((v >> 24) as u8);
275 v <<= 8;
276 }
277 self.out
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 fn roundtrip_bools(pattern: &[(&[bool], u8)]) {
286 let mut e = BoolEncoder::new();
287 for (vals, p) in pattern {
288 for &v in *vals {
289 e.write_bool(v, *p);
290 }
291 }
292 let data = e.flush();
293 let mut d = BoolDecoder::new(&data).unwrap();
294 for (vals, p) in pattern {
295 for &v in *vals {
296 assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p);
297 }
298 }
299 assert_eq!(d.overreads(), 0);
300 }
301
302 #[test]
303 fn roundtrips_bools_at_every_extreme() {
304 // p = 1 (all zeros essentially free) through p = 255, with 1s at
305 // the most improbable settings to force carry propagation.
306 roundtrip_bools(&[
307 (&[false; 64], 1),
308 (&[true], 1),
309 (&[false, true, false, true], 128),
310 (&[true; 3], 255),
311 (&[false; 32], 255),
312 (&[true; 16], 1),
313 ]);
314 }
315
316 #[test]
317 fn roundtrips_long_random_streams() {
318 // Deterministic LCG so failures reproduce.
319 let mut state: u64 = 0x9E3779B97F4A7C15;
320 let mut next = move || {
321 state ^= state << 13;
322 state ^= state >> 7;
323 state ^= state << 17;
324 state
325 };
326 let probs = [1u8, 2, 32, 128, 200, 254, 255];
327 let mut e = BoolEncoder::new();
328 let mut expected = Vec::new();
329 for &p in &probs {
330 for _ in 0..200 {
331 let v = next() & 1 == 1;
332 e.write_bool(v, p);
333 expected.push((v, p));
334 }
335 }
336 let data = e.flush();
337 let mut d = BoolDecoder::new(&data).unwrap();
338 for (v, p) in expected {
339 assert_eq!(d.read_bool(p), v);
340 }
341 assert_eq!(d.overreads(), 0);
342 }
343
344 #[test]
345 fn roundtrips_literals() {
346 let mut e = BoolEncoder::new();
347 for n in 1..=19u32 {
348 let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
349 e.write_literal(ones, n);
350 e.write_literal(0, n);
351 e.write_literal(0x15 & ones, n); // 0b10101 truncated
352 }
353 let data = e.flush();
354 let mut d = BoolDecoder::new(&data).unwrap();
355 for n in 1..=19u32 {
356 let ones = if n >= 32 { u32::MAX } else { (1 << n) - 1 };
357 assert_eq!(d.read_literal(n), ones);
358 assert_eq!(d.read_literal(n), 0);
359 assert_eq!(d.read_literal(n), 0x15 & ones);
360 }
361 assert_eq!(d.overreads(), 0);
362 }
363
364 #[test]
365 fn roundtrips_signed_literals() {
366 let mut e = BoolEncoder::new();
367 // sign flag then 4 magnitude bits: the two's-complement value in
368 // -16..=15 (RFC read_signed_literal shifts the sign-extended -1).
369 for mag in 0..=15u32 {
370 e.write_bool(true, 128);
371 e.write_literal(mag, 4);
372 e.write_bool(false, 128);
373 e.write_literal(mag, 4);
374 }
375 let data = e.flush();
376 let mut d = BoolDecoder::new(&data).unwrap();
377 for mag in 0..=15i32 {
378 assert_eq!(d.read_signed_literal(5), mag - 16);
379 assert_eq!(d.read_signed_literal(5), mag);
380 }
381 assert_eq!(d.overreads(), 0);
382 }
383
384 #[test]
385 fn roundtrips_prob7() {
386 let mut e = BoolEncoder::new();
387 for x in 0..=127u32 {
388 e.write_literal(x, 7);
389 }
390 let data = e.flush();
391 let mut d = BoolDecoder::new(&data).unwrap();
392 for x in 0..=127u32 {
393 assert_eq!(d.read_prob7(), if x == 0 { 1 } else { (x << 1) as u8 });
394 }
395 }
396
397 #[test]
398 fn roundtrips_tree_values() {
399 // kf_ymode_tree: B_PRED=0, DC=4? -- RFC 6386 §8.2/§11.2:
400 // {-B_PRED,2, 4,6, -DC_PRED,-V_PRED, -H_PRED,-TM_PRED}.
401 let tree: [i8; 8] = [-4, 2, 4, 6, 0, -1, -2, -3];
402 let probs = [145u8, 156, 163, 128];
403 // (bit path, leaf value) pairs of the kf ymode tree (§11.2):
404 // B_PRED="0", DC_PRED="100", V_PRED="101", H_PRED="110",
405 // TM_PRED="111". The 0 leaf relies on `i <= 0` semantics.
406 let leaves: [(&[bool], u8); 5] = [
407 (&[false], 4),
408 (&[true, false, false], 0),
409 (&[true, false, true], 1),
410 (&[true, true, false], 2),
411 (&[true, true, true], 3),
412 ];
413 for (path, val) in leaves {
414 let mut e = BoolEncoder::new();
415 for (i, &b) in path.iter().enumerate() {
416 e.write_bool(b, probs[i]);
417 }
418 let data = e.flush();
419 let mut d = BoolDecoder::new(&data).unwrap();
420 assert_eq!(d.read_tree(&tree, &probs), val, "path {path:?}");
421 }
422 }
423
424 #[test]
425 fn short_partitions_zero_extend() {
426 // Empty/1-byte partitions are legal for unused token partitions;
427 // the init shortfall counts as overreads.
428 let mut d = BoolDecoder::new(&[]).unwrap();
429 assert_eq!(d.read_bool(128), false);
430 let mut d = BoolDecoder::new(&[0]).unwrap();
431 assert_eq!(d.read_bool(128), false);
432 }
433
434 #[test]
435 fn overreads_are_counted_not_panicked() {
436 // Two bytes of init, then nothing: any read shifts in zeros.
437 let data = [0u8, 0];
438 let mut d = BoolDecoder::new(&data).unwrap();
439 for _ in 0..100 {
440 d.read_bool(128);
441 }
442 assert!(d.overreads() > 0);
443 }
444}