forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bool.rs408 lines, 13.0 KiBHistoryRawDownload
1//! The bool decoder (spec 8.3.2), VP9's arithmetic range coder over one
2//! data partition (the compressed header, and each tile of tile data).
3//!
4//! Every syntax element below the uncompressed header is coded as a
5//! sequence of bools, each written at an 8-bit zero-probability `p`
6//! (meaning `p/256`). The decoder mirrors the encoder's interval state
7//! with two numbers — `range` (128..=255) and `value` (the encoded
8//! number minus the interval's left endpoint) — and renormalises one
9//! bit at a time, shifting a fresh input byte into `value` for every 8
10//! bits consumed (spec 8.3.2, `read_bool` / libvpx `vpx_reader`).
11//!
12//! The tests drive the decoder against a test-only implementation of the
13//! spec's reference encoder (8.3.3, the carry-propagating writer) and
14//! assert bit-exact round-trips.
15
16use ec_core::{Error, Result};
17
18/// Boolean arithmetic decoder over one data partition (spec 8.3.2).
19pub struct BoolDecoder<'a> {
20 data: &'a [u8],
21 /// Index of the next byte to shift into `value`.
22 pos: usize,
23 /// 128..=255; identical to the encoder's range.
24 range: u32,
25 /// Encoded number minus the current interval's left endpoint; the top
26 /// bits hold what has been read, bytes shift in at the bottom.
27 value: u32,
28 /// Bits shifted out of `value` since the last byte was shifted in.
29 bit_count: u32,
30 /// Bytes consumed past the end of the partition (read as 0, per the
31 /// spec's zero-extension of x). A healthy partition stays at 0.
32 overreads: u32,
33}
34
35impl<'a> BoolDecoder<'a> {
36 /// Start decoding the partition `data` (spec 8.3.2 `init_bool`): the
37 /// first two bytes are read into `value`, big-endian. A partition
38 /// shorter than two bytes is zero-extended like the reference
39 /// decoder does, and the shortfall shows up in [`Self::overreads`].
40 pub fn new(data: &'a [u8]) -> Result<Self> {
41 if data.is_empty() {
42 return Ok(Self {
43 data,
44 pos: 0,
45 range: 255,
46 value: 0,
47 bit_count: 0,
48 overreads: 0,
49 });
50 }
51 let mut value = u32::from(data[0]) << 8;
52 if data.len() > 1 {
53 value |= u32::from(data[1]);
54 }
55 let mut dec = Self {
56 data,
57 pos: data.len().min(2),
58 range: 255,
59 value,
60 bit_count: 0,
61 overreads: 0,
62 };
63 // libvpx 1.15 consumes one marker bit per partition right after the
64 // initial fill (bitreader.c `vpx_reader_init`:
65 // `return vpx_read_bit(r) != 0; // marker bit`); the matching writer
66 // (`vpx_start_encode`) emits a leading 0 bit per partition. A 1 here
67 // means the partition is not a libvpx bool stream.
68 if dec.read_bool(128) {
69 return Err(Error::corrupt("bool decoder marker bit is set"));
70 }
71 Ok(dec)
72 }
73
74 /// Bytes consumed past the end of the partition, read as zero. Any
75 /// non-zero value on a complete, valid partition is a desync symptom.
76 pub fn overreads(&self) -> u32 {
77 self.overreads
78 }
79
80 /// Offset of the next unread input byte, for desync diagnostics.
81 pub fn byte_offset(&self) -> usize {
82 self.pos
83 }
84
85 fn next_byte(&mut self) -> u32 {
86 match self.data.get(self.pos) {
87 Some(&b) => {
88 self.pos += 1;
89 u32::from(b)
90 }
91 None => {
92 self.overreads += 1;
93 0
94 }
95 }
96 }
97
98 /// Decode one bool whose zero-probability is `prob`/256 (spec 8.3.2
99 /// `read_bool`; libvpx `vpx_read`). Under `EC_VP9_TRACE`, prints the
100 /// decoder state after the read — `B <pos> <bit_count> <prob> <bit>`.
101 pub fn read_bool(&mut self, prob: u8) -> bool {
102 let prob = u32::from(prob);
103 let split = 1 + (((self.range - 1) * prob) >> 8);
104 let bigsplit = split << 8;
105 let bit = if self.value >= bigsplit {
106 self.range -= split;
107 self.value -= bigsplit;
108 true
109 } else {
110 self.range = split;
111 false
112 };
113 while self.range < 128 {
114 self.value <<= 1;
115 self.range <<= 1;
116 self.bit_count += 1;
117 if self.bit_count == 8 {
118 self.bit_count = 0;
119 self.value |= self.next_byte();
120 }
121 }
122 if crate::trace_enabled() {
123 eprintln!("B {} {} {} {}", self.pos, self.bit_count, prob, u8::from(bit));
124 }
125 bit
126 }
127
128 /// Unsigned `n`-bit literal, bits high- to low-order, each at
129 /// probability 128 (spec `read_literal`).
130 pub fn read_literal(&mut self, n: u32) -> u32 {
131 let mut v = 0;
132 for _ in 0..n {
133 v = (v << 1) + u32::from(self.read_bool(128));
134 }
135 v
136 }
137
138 /// Signed `n`-bit literal (spec `s(n)`, 4.10): an `n`-bit magnitude
139 /// followed by a sign flag, 1 meaning negative. `n = 0` yields 0.
140 pub fn read_signed_literal(&mut self, n: u32) -> i32 {
141 if n == 0 {
142 return 0;
143 }
144 let mut v: i32 = self.read_literal(n) as i32;
145 if self.read_bool(128) {
146 v = -v;
147 }
148 v
149 }
150
151 /// Decode a tree-coded value (spec 8.3.2 `read_tree`; libvpx
152 /// `vpx_read_tree`): `tree` holds the left/right branch entries
153 /// (positive = interior node index, negative = `-leaf`), `probs[i]`
154 /// is the probability of interior node `i` (the tree position
155 /// halved).
156 pub fn read_tree(&mut self, tree: &[i8], probs: &[u8]) -> u8 {
157 let mut i: i32 = 0;
158 loop {
159 let b = self.read_bool(probs[(i >> 1) as usize]);
160 i = i32::from(tree[(i + i32::from(b as i8)) as usize]);
161 if i <= 0 {
162 return (-i) as u8;
163 }
164 }
165 }
166}
167
168/// The spec 8.3.3 reference bool encoder (the carry-propagating writer
169/// libvpx ships as `vpx_writer`), test-only: it lets the tests drive
170/// [`BoolDecoder`] against known bitstreams instead of trusting the
171/// decoder to decode its own idea of the format.
172#[cfg(test)]
173struct BoolEncoder {
174 out: Vec<u8>,
175 range: u32,
176 bottom: u32,
177 bit_count: u32,
178}
179
180#[cfg(test)]
181impl BoolEncoder {
182 fn new() -> Self {
183 let mut e = Self {
184 out: Vec::new(),
185 range: 255,
186 bottom: 0,
187 bit_count: 24,
188 };
189 // `vpx_start_encode` parity: the writer emits a leading 0 bit per
190 // partition, which the decoder consumes as its marker bit.
191 e.write_bool(false, 128);
192 e
193 }
194
195 fn add_one_to_output(out: &mut [u8]) {
196 for b in out.iter_mut().rev() {
197 if *b == 255 {
198 *b = 0;
199 } else {
200 *b += 1;
201 return;
202 }
203 }
204 // Carry out of the beginning cannot happen: x < 1 always.
205 unreachable!("bool encoder carry propagated past the first byte");
206 }
207
208 fn write_bool(&mut self, val: bool, prob: u8) {
209 let prob = u32::from(prob);
210 let split = 1 + (((self.range - 1) * prob) >> 8);
211 if val {
212 self.bottom += split;
213 self.range -= split;
214 } else {
215 self.range = split;
216 }
217 while self.range < 128 {
218 self.range <<= 1;
219 if self.bottom & (1 << 31) != 0 {
220 Self::add_one_to_output(&mut self.out);
221 }
222 self.bottom <<= 1;
223 self.bit_count -= 1;
224 if self.bit_count == 0 {
225 self.out.push((self.bottom >> 24) as u8);
226 self.bottom &= (1 << 24) - 1;
227 self.bit_count = 8;
228 }
229 }
230 }
231
232 fn write_literal(&mut self, v: u32, n: u32) {
233 for i in (0..n).rev() {
234 self.write_bool((v >> i) & 1 != 0, 128);
235 }
236 }
237
238 /// Spec `flush_bool_encoder`.
239 fn flush(mut self) -> Vec<u8> {
240 let c = self.bit_count;
241 let mut v = self.bottom;
242 if v & (1 << (32 - c)) != 0 {
243 Self::add_one_to_output(&mut self.out);
244 }
245 v <<= c & 7;
246 let mut c = c >> 3;
247 while c > 0 {
248 v <<= 8;
249 c -= 1;
250 }
251 for _ in 0..4 {
252 self.out.push((v >> 24) as u8);
253 v <<= 8;
254 }
255 self.out
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 fn roundtrip_bools(pattern: &[(&[bool], u8)]) {
264 let mut e = BoolEncoder::new();
265 for (vals, p) in pattern {
266 for &v in *vals {
267 e.write_bool(v, *p);
268 }
269 }
270 let data = e.flush();
271 let mut d = BoolDecoder::new(&data).unwrap();
272 for (vals, p) in pattern {
273 for &v in *vals {
274 assert_eq!(d.read_bool(*p), v, "desync at prob {:?}", p);
275 }
276 }
277 assert_eq!(d.overreads(), 0);
278 }
279
280 #[test]
281 fn roundtrips_bools_at_every_extreme() {
282 // p = 1 (all zeros essentially free) through p = 255, with 1s at
283 // the most improbable settings to force carry propagation.
284 roundtrip_bools(&[
285 (&[false; 64], 1),
286 (&[true], 1),
287 (&[false, true, false, true], 128),
288 (&[true; 3], 255),
289 (&[false; 32], 255),
290 (&[true; 16], 1),
291 ]);
292 }
293
294 #[test]
295 fn roundtrips_long_random_streams() {
296 // Deterministic LCG so failures reproduce.
297 let mut state: u64 = 0x9E3779B97F4A7C15;
298 let mut next = move || {
299 state ^= state << 13;
300 state ^= state >> 7;
301 state ^= state << 17;
302 state
303 };
304 let probs = [1u8, 2, 32, 128, 200, 254, 255];
305 let mut e = BoolEncoder::new();
306 let mut expected = Vec::new();
307 for &p in &probs {
308 for _ in 0..200 {
309 let v = next() & 1 == 1;
310 e.write_bool(v, p);
311 expected.push((v, p));
312 }
313 }
314 let data = e.flush();
315 let mut d = BoolDecoder::new(&data).unwrap();
316 for (v, p) in expected {
317 assert_eq!(d.read_bool(p), v);
318 }
319 assert_eq!(d.overreads(), 0);
320 }
321
322 #[test]
323 fn roundtrips_literals() {
324 let mut e = BoolEncoder::new();
325 for n in 1..=19u32 {
326 let ones = (1 << n) - 1;
327 e.write_literal(ones, n);
328 e.write_literal(0, n);
329 e.write_literal(0x15 & ones, n); // 0b10101 truncated
330 }
331 let data = e.flush();
332 let mut d = BoolDecoder::new(&data).unwrap();
333 for n in 1..=19u32 {
334 let ones = (1 << n) - 1;
335 assert_eq!(d.read_literal(n), ones);
336 assert_eq!(d.read_literal(n), 0);
337 assert_eq!(d.read_literal(n), 0x15 & ones);
338 }
339 assert_eq!(d.overreads(), 0);
340 }
341
342 #[test]
343 fn roundtrips_signed_literals() {
344 // Spec s(5): 5-bit magnitude then sign flag.
345 let mut e = BoolEncoder::new();
346 for mag in 0..=15u32 {
347 e.write_literal(mag, 4);
348 e.write_bool(false, 128);
349 e.write_literal(mag, 4);
350 e.write_bool(true, 128);
351 }
352 let data = e.flush();
353 let mut d = BoolDecoder::new(&data).unwrap();
354 for mag in 0..=15i32 {
355 assert_eq!(d.read_signed_literal(4), mag);
356 assert_eq!(d.read_signed_literal(4), -mag);
357 }
358 assert_eq!(d.overreads(), 0);
359 }
360
361 #[test]
362 fn roundtrips_tree_values() {
363 // The spec's intra mode tree (8.2 `read_intra_mode`).
364 let intra: [i8; 18] = [
365 -0, 2, -9, 4, -1, 6, 8, 12, -2, 10, -5, -6, -3, 14, -7, 16, -8, -4,
366 ];
367 let probs = [159u8; 9];
368 // Bit paths per the tree above: DC="0", TM="100", V="101",
369 // H="1100 00"? — walk a few leaves via the decoder itself, then
370 // verify against the encoder paths.
371 let leaves: [(&[bool], u8); 4] = [
372 (&[false], 0),
373 (&[true, false], 9),
374 (&[true, true, false], 1),
375 (&[true, true, true, false, false, false], 2),
376 ];
377 for (path, val) in leaves {
378 let mut e = BoolEncoder::new();
379 for (i, &b) in path.iter().enumerate() {
380 e.write_bool(b, probs[(i + i) >> 1]);
381 }
382 let data = e.flush();
383 let mut d = BoolDecoder::new(&data).unwrap();
384 assert_eq!(d.read_tree(&intra, &probs), val, "path {path:?}");
385 }
386 }
387
388 #[test]
389 fn short_partitions_zero_extend() {
390 // An empty partition is legal (a degenerate tile); init reads
391 // zeros and the shortfall shows in overreads.
392 let mut d = BoolDecoder::new(&[]).unwrap();
393 assert!(!d.read_bool(128));
394 let mut d = BoolDecoder::new(&[0]).unwrap();
395 assert!(!d.read_bool(128));
396 }
397
398 #[test]
399 fn overreads_are_counted_not_panicked() {
400 // Two bytes of init, then nothing: any read shifts in zeros.
401 let data = [0u8, 0];
402 let mut d = BoolDecoder::new(&data).unwrap();
403 for _ in 0..100 {
404 d.read_bool(128);
405 }
406 assert!(d.overreads() > 0);
407 }
408}