forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7947774Tahinli1 month ago3899 commits

range.rs810 lines, 26.5 KiBHistoryRawDownload
1//! The Opus range decoder (RFC 6716, Section 4.1).
2//!
3//! Every symbol in an Opus frame — SILK and CELT alike — comes out of this
4//! one object, so its arithmetic is exact integer arithmetic on `u32`, not an
5//! approximation that happens to agree most of the time. A single ULP of drift
6//! here desynchronises the whole frame, which is why the RFC test vectors ship
7//! the encoder's final `rng` value per packet: [`RangeDecoder::range`] against
8//! that value is a bit-exact check of the entire decode path.
9//!
10//! Two streams share the frame: range coder bytes read forward from the start,
11//! and CELT "raw bits" read backward from the end. They are allowed to overlap
12//! (Section 4.1.4) — reading past the end of either simply yields zero bits,
13//! so a truncated or malformed frame decodes to noise rather than panicking.
14
15/// Number of bits in the code value, `EC_CODE_BITS` in the reference.
16const CODE_BITS: u32 = 32;
17/// The renormalisation threshold: `rng` is kept above `2**23`.
18const CODE_TOP: u32 = 1 << (CODE_BITS - 8 - 1); // 2**23
19
20/// `ilog(x)`: one plus the index of the most significant set bit, `0` for `0`.
21#[inline]
22fn ilog(x: u32) -> u32 {
23 32 - x.leading_zeros()
24}
25
26/// A range decoder over one Opus frame.
27#[derive(Clone, Debug)]
28pub struct RangeDecoder<'a> {
29 buf: &'a [u8],
30 /// Next byte the range coder reads, from the front.
31 offs: usize,
32 /// Bytes already consumed by the raw-bit reader, from the back.
33 end_offs: usize,
34 /// Bits buffered by the raw-bit reader (LSB first).
35 end_window: u32,
36 end_bits: u32,
37 /// Difference between the high end of the range and the coded value.
38 val: u32,
39 /// Size of the current range.
40 rng: u32,
41 /// The bit left over from the last byte read by the range coder.
42 rem: u32,
43 /// Whole bits consumed so far, including what is buffered in `rng`.
44 nbits_total: u32,
45}
46
47impl<'a> RangeDecoder<'a> {
48 /// Starts decoding `buf`, an Opus frame body (Section 4.1.1).
49 pub fn new(buf: &'a [u8]) -> RangeDecoder<'a> {
50 let b0 = buf.first().copied().unwrap_or(0) as u32;
51 let mut dec = RangeDecoder {
52 buf,
53 offs: 1.min(buf.len()),
54 end_offs: 0,
55 end_window: 0,
56 end_bits: 0,
57 val: 127 - (b0 >> 1),
58 rng: 128,
59 rem: b0 & 1,
60 // 9 here becomes 33 once the initial renormalisation runs.
61 nbits_total: 9,
62 };
63 dec.normalize();
64 dec
65 }
66
67 /// The encoder's `rng` after the same symbols — the test-vector oracle.
68 pub fn range(&self) -> u32 {
69 self.rng
70 }
71
72 /// Bytes in the frame.
73 pub fn len(&self) -> usize {
74 self.buf.len()
75 }
76
77 /// True for a zero-length frame (DTX).
78 pub fn is_empty(&self) -> bool {
79 self.buf.is_empty()
80 }
81
82 #[inline]
83 fn next_byte(&mut self) -> u32 {
84 let b = self.buf.get(self.offs).copied().unwrap_or(0) as u32;
85 // Past the end the decoder keeps feeding zeros (Section 4.1.2.1).
86 self.offs = (self.offs + 1).min(self.buf.len() + 1);
87 b
88 }
89
90 #[inline]
91 fn normalize(&mut self) {
92 while self.rng <= CODE_TOP {
93 self.nbits_total += 8;
94 self.rng <<= 8;
95 let b = self.next_byte();
96 let sym = (self.rem << 7) | (b >> 1);
97 self.rem = b & 1;
98 self.val = ((self.val << 8) + (255 - sym)) & 0x7FFF_FFFF;
99 }
100 }
101
102 /// `ec_decode()`: the frequency `fs` of the symbol about to be decoded.
103 ///
104 /// Must be followed by [`RangeDecoder::update`] with that symbol's
105 /// `(fl, fh, ft)` before any other decode call.
106 #[inline]
107 pub fn decode(&mut self, ft: u32) -> u32 {
108 let r = self.rng / ft;
109 ft - (self.val / r + 1).min(ft)
110 }
111
112 /// `ec_decode_bin()`: [`RangeDecoder::decode`] with `ft = 1<<ftb`.
113 #[inline]
114 pub fn decode_bin(&mut self, ftb: u32) -> u32 {
115 let r = self.rng >> ftb;
116 (1 << ftb) - (self.val / r + 1).min(1 << ftb)
117 }
118
119 /// `ec_dec_update()`: consumes the symbol spanning `[fl, fh)` of `ft`.
120 #[inline]
121 pub fn update(&mut self, fl: u32, fh: u32, ft: u32) {
122 let r = self.rng / ft;
123 let s = r * (ft - fh);
124 self.val -= s;
125 self.rng = if fl > 0 { r * (fh - fl) } else { self.rng - s };
126 self.normalize();
127 }
128
129 /// `ec_dec_bit_logp()`: one bit whose probability of being 1 is
130 /// `2**-logp`.
131 #[inline]
132 pub fn dec_bit_logp(&mut self, logp: u32) -> bool {
133 let s = self.rng >> logp;
134 let bit = self.val < s;
135 if !bit {
136 self.val -= s;
137 self.rng -= s;
138 } else {
139 self.rng = s;
140 }
141 self.normalize();
142 bit
143 }
144
145 /// `ec_dec_icdf()`: one symbol from an inverse-CDF table, `ft = 1<<ftb`.
146 ///
147 /// `icdf[k]` holds `(1<<ftb) - fh[k]` and the table ends with `0`.
148 #[inline]
149 pub fn dec_icdf(&mut self, icdf: &[u8], ftb: u32) -> usize {
150 let r = self.rng >> ftb;
151 let mut k = 0usize;
152 let mut t = self.rng;
153 let mut s = r * icdf[0] as u32;
154 while self.val < s {
155 t = s;
156 k += 1;
157 s = r * icdf[k] as u32;
158 }
159 self.val -= s;
160 self.rng = t - s;
161 self.normalize();
162 k
163 }
164
165 /// Decodes a symbol from a PDF given as frequency counts (the form the
166 /// RFC tables are written in), summing to `1<<ftb`.
167 #[inline]
168 pub fn dec_pdf(&mut self, pdf: &[u16], ftb: u32) -> usize {
169 let fs = self.decode_bin(ftb);
170 let mut fl = 0u32;
171 let mut k = 0usize;
172 loop {
173 let fh = fl + pdf[k] as u32;
174 if fs < fh {
175 self.update(fl, fh, 1 << ftb);
176 return k;
177 }
178 fl = fh;
179 k += 1;
180 }
181 }
182
183 /// `ec_dec_bits()`: `bits` raw bits, read backwards from the end of the
184 /// frame (Section 4.1.4).
185 pub fn dec_bits(&mut self, bits: u32) -> u32 {
186 if bits == 0 {
187 return 0;
188 }
189 while self.end_bits < bits {
190 let b = if self.end_offs < self.buf.len() {
191 self.end_offs += 1;
192 self.buf[self.buf.len() - self.end_offs] as u32
193 } else {
194 0
195 };
196 self.end_window |= b << self.end_bits;
197 self.end_bits += 8;
198 }
199 let ret = self.end_window & ((1u32 << bits) - 1);
200 self.end_window >>= bits;
201 self.end_bits -= bits;
202 self.nbits_total += bits;
203 ret
204 }
205
206 /// `ec_dec_uint()`: one of `ft` equiprobable values, `0..ft`
207 /// (Section 4.1.5). `ft` must be at least 1.
208 pub fn dec_uint(&mut self, ft: u32) -> u32 {
209 debug_assert!(ft > 1);
210 let ftb = ilog(ft - 1);
211 if ftb <= 8 {
212 let t = self.decode(ft);
213 self.update(t, t + 1, ft);
214 t
215 } else {
216 let ftb = ftb - 8;
217 let ft1 = ((ft - 1) >> ftb) + 1;
218 let t = self.decode(ft1);
219 self.update(t, t + 1, ft1);
220 let t = (t << ftb) | self.dec_bits(ftb);
221 // A corrupt frame can code out of range; saturate rather than
222 // hand a caller an out-of-bounds index (Section 4.1.5).
223 t.min(ft - 1)
224 }
225 }
226
227 /// Shrinks the frame to `len` bytes, which is what the redundancy framing
228 /// does when it reserves the tail of a packet for a second CELT frame
229 /// (RFC 6716, Section 4.5.1). Bytes already read are unaffected.
230 pub fn shrink(&mut self, len: usize) {
231 if len <= self.buf.len() {
232 self.buf = &self.buf[..len];
233 }
234 }
235
236 /// Declares the rest of the frame consumed, so [`RangeDecoder::tell`]
237 /// reports the whole frame. CELT does this for a silent frame, whose
238 /// remaining bits carry nothing (RFC 6716, Section 4.3).
239 pub fn skip_to_end(&mut self) {
240 self.nbits_total = (self.buf.len() as u32) * 8 + ilog(self.rng);
241 }
242
243 /// `ec_tell()`: a conservative upper bound on whole bits used so far.
244 #[inline]
245 pub fn tell(&self) -> u32 {
246 self.nbits_total - ilog(self.rng)
247 }
248
249 /// `ec_tell_frac()`: the same bound in 1/8th bits (Section 4.1.6.2).
250 pub fn tell_frac(&self) -> u32 {
251 let mut lg = ilog(self.rng);
252 let mut r_q15 = self.rng >> (lg - 16);
253 for _ in 0..3 {
254 r_q15 = (r_q15 * r_q15) >> 15;
255 let bit = r_q15 >> 16;
256 lg = 2 * lg + bit;
257 r_q15 >>= bit;
258 }
259 // libopus returns a signed value that can dip below zero after `skip_to_end` on a
260 // frame of a few bytes. Clamp at 0: the plain subtraction panicked in debug builds
261 // and wrapped in release (fuzz finding, ec-opus decode_packet).
262 self.nbits_total.saturating_mul(8).saturating_sub(lg)
263 }
264}
265
266/// Scalar state of a [`RangeEncoder`], saved and restored around a trial
267/// encode (the coarse-energy two-pass search).
268#[derive(Clone, Copy)]
269pub struct EncSnapshot {
270 offs: usize,
271 end_offs: usize,
272 end_window: u32,
273 nend_bits: u32,
274 nbits_total: u32,
275 val: u32,
276 rng: u32,
277 rem: i32,
278 ext: u32,
279 error: bool,
280}
281
282/// The Opus range *encoder* (RFC 6716, Section 5.1) — the exact mirror of
283/// [`RangeDecoder`], over a fixed-size buffer.
284///
285/// Range-coded bytes grow from the front of the buffer, raw bits from the
286/// back, exactly as the decoder reads them; the two meeting is a bust, which
287/// [`RangeEncoder::error`] reports rather than corrupting either stream. The
288/// buffer is owned and reused across frames — [`RangeEncoder::reset`] costs a
289/// `fill(0)` of the frame, so a steady-state encoder never allocates here.
290#[derive(Clone, Debug)]
291pub struct RangeEncoder {
292 buf: Vec<u8>,
293 /// Logical frame size: the decoder will be handed `buf[..storage]`.
294 storage: usize,
295 /// Next byte the range coder writes, from the front.
296 offs: usize,
297 /// Bytes already written by the raw-bit writer, from the back.
298 end_offs: usize,
299 /// Bits buffered by the raw-bit writer (LSB first).
300 end_window: u32,
301 nend_bits: u32,
302 /// Whole bits written so far, including what is buffered in `rng`.
303 nbits_total: u32,
304 /// Low end of the current range.
305 val: u32,
306 /// Size of the current range.
307 rng: u32,
308 /// A buffered byte awaiting carry propagation, `-1` before the first.
309 rem: i32,
310 /// Count of buffered `0xFF` bytes that a carry would turn into `0x00`.
311 ext: u32,
312 error: bool,
313}
314
315impl RangeEncoder {
316 /// An encoder with no buffer; call [`RangeEncoder::reset`] before use.
317 pub fn new() -> RangeEncoder {
318 RangeEncoder {
319 buf: Vec::new(),
320 storage: 0,
321 offs: 0,
322 end_offs: 0,
323 end_window: 0,
324 nend_bits: 0,
325 nbits_total: CODE_BITS + 1,
326 val: 0,
327 rng: 1 << (CODE_BITS - 1),
328 rem: -1,
329 ext: 0,
330 error: false,
331 }
332 }
333
334 /// Starts a fresh frame of exactly `size` bytes.
335 pub fn reset(&mut self, size: usize) {
336 if self.buf.len() < size {
337 self.buf.resize(size, 0);
338 }
339 self.buf[..size].fill(0);
340 self.storage = size;
341 self.offs = 0;
342 self.end_offs = 0;
343 self.end_window = 0;
344 self.nend_bits = 0;
345 self.nbits_total = CODE_BITS + 1;
346 self.val = 0;
347 self.rng = 1 << (CODE_BITS - 1);
348 self.rem = -1;
349 self.ext = 0;
350 self.error = false;
351 }
352
353 /// The encoder's current range state — what the decoder's
354 /// [`RangeDecoder::range`] must equal after the same symbols.
355 pub fn range(&self) -> u32 {
356 self.rng
357 }
358
359 /// True when the frame busted its budget; the frame is unusable.
360 pub fn error(&self) -> bool {
361 self.error
362 }
363
364 /// The frame size in bytes.
365 pub fn storage(&self) -> usize {
366 self.storage
367 }
368
369 /// Bytes the range coder has finalised so far (`ec_range_bytes`).
370 pub fn range_bytes(&self) -> usize {
371 self.offs
372 }
373
374 /// The finished frame; call only after [`RangeEncoder::done`].
375 pub fn data(&self) -> &[u8] {
376 &self.buf[..self.storage]
377 }
378
379 fn write_byte(&mut self, value: u32) {
380 if self.offs + self.end_offs >= self.storage {
381 self.error = true;
382 return;
383 }
384 self.buf[self.offs] = value as u8;
385 self.offs += 1;
386 }
387
388 fn write_byte_at_end(&mut self, value: u32) {
389 if self.offs + self.end_offs >= self.storage {
390 self.error = true;
391 return;
392 }
393 self.end_offs += 1;
394 self.buf[self.storage - self.end_offs] = value as u8;
395 }
396
397 fn carry_out(&mut self, c: i32) {
398 if c != 0xFF {
399 let carry = c >> 8;
400 if self.rem >= 0 {
401 self.write_byte((self.rem + carry) as u32);
402 }
403 while self.ext > 0 {
404 self.write_byte(((0xFF + carry) & 0xFF) as u32);
405 self.ext -= 1;
406 }
407 self.rem = c & 0xFF;
408 } else {
409 self.ext += 1;
410 }
411 }
412
413 fn normalize(&mut self) {
414 while self.rng <= CODE_TOP {
415 self.carry_out((self.val >> 23) as i32);
416 self.val = (self.val << 8) & 0x7FFF_FFFF;
417 self.rng <<= 8;
418 self.nbits_total += 8;
419 }
420 }
421
422 /// `ec_encode()`: one symbol spanning `[fl, fh)` of `ft`.
423 #[inline]
424 pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) {
425 let r = self.rng / ft;
426 if fl > 0 {
427 self.val = self.val.wrapping_add(self.rng - r * (ft - fl));
428 self.rng = r * (fh - fl);
429 } else {
430 self.rng -= r * (ft - fh);
431 }
432 self.normalize();
433 }
434
435 /// `ec_encode_bin()`: [`RangeEncoder::encode`] with `ft = 1<<bits`.
436 #[inline]
437 pub fn encode_bin(&mut self, fl: u32, fh: u32, bits: u32) {
438 let r = self.rng >> bits;
439 if fl > 0 {
440 self.val = self.val.wrapping_add(self.rng - r * ((1 << bits) - fl));
441 self.rng = r * (fh - fl);
442 } else {
443 self.rng -= r * ((1 << bits) - fh);
444 }
445 self.normalize();
446 }
447
448 /// `ec_enc_bit_logp()`: one bit whose probability of being 1 is `2**-logp`.
449 #[inline]
450 pub fn enc_bit_logp(&mut self, bit: bool, logp: u32) {
451 let r = self.rng;
452 let l = self.val;
453 let s = r >> logp;
454 let r = r - s;
455 if bit {
456 self.val = l.wrapping_add(r);
457 }
458 self.rng = if bit { s } else { r };
459 self.normalize();
460 }
461
462 /// `ec_enc_icdf()`: symbol `k` of an inverse-CDF table, `ft = 1<<ftb`.
463 #[inline]
464 pub fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) {
465 let r = self.rng >> ftb;
466 if k > 0 {
467 self.val = self.val.wrapping_add(self.rng - r * icdf[k - 1] as u32);
468 self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32);
469 } else {
470 self.rng -= r * icdf[k] as u32;
471 }
472 self.normalize();
473 }
474
475 /// `ec_enc_uint()`: `value` as one of `ft` equiprobable values
476 /// (Section 5.1.4). `ft` must be at least 2.
477 pub fn enc_uint(&mut self, value: u32, ft: u32) {
478 debug_assert!(ft > 1);
479 let ft = ft - 1;
480 let ftb = ilog(ft);
481 if ftb > 8 {
482 let ftb = ftb - 8;
483 let ft1 = (ft >> ftb) + 1;
484 let hi = value >> ftb;
485 self.encode(hi, hi + 1, ft1);
486 self.enc_bits(value & ((1u32 << ftb) - 1), ftb);
487 } else {
488 self.encode(value, value + 1, ft + 1);
489 }
490 }
491
492 /// `ec_enc_bits()`: `bits` raw bits, written backwards from the end of the
493 /// frame.
494 pub fn enc_bits(&mut self, fl: u32, bits: u32) {
495 debug_assert!(bits > 0);
496 let mut window = self.end_window;
497 let mut used = self.nend_bits;
498 if used + bits > 32 {
499 while used >= 8 {
500 self.write_byte_at_end(window & 0xFF);
501 window >>= 8;
502 used -= 8;
503 }
504 }
505 window |= fl << used;
506 used += bits;
507 self.end_window = window;
508 self.nend_bits = used;
509 self.nbits_total += bits;
510 }
511
512 /// `ec_enc_shrink()`: reduces the frame to `size` bytes, moving raw bits
513 /// already written so they still end the frame. Only legal while
514 /// `range_bytes()` plus the raw-bit bytes fit in `size`.
515 pub fn shrink(&mut self, size: usize) {
516 debug_assert!(self.offs + self.end_offs <= size);
517 self.buf.copy_within(
518 self.storage - self.end_offs..self.storage,
519 size - self.end_offs,
520 );
521 self.storage = size;
522 // The abandoned tail must be zero for the "rest is zeros" guarantee.
523 if size > self.offs + self.end_offs {
524 self.buf[self.offs..size - self.end_offs].fill(0);
525 }
526 }
527
528 /// `ec_tell()`: a conservative upper bound on whole bits used so far.
529 #[inline]
530 pub fn tell(&self) -> u32 {
531 self.nbits_total - ilog(self.rng)
532 }
533
534 /// Snapshot of the coder's scalar state for the two-pass coarse-energy
535 /// search (libopus `enc_start_state`/`enc_intra_state`). Restoring also
536 /// needs the front bytes written since the snapshot; the caller keeps
537 /// those (libopus's `intra_bits` copy).
538 pub fn snapshot(&self) -> EncSnapshot {
539 EncSnapshot {
540 offs: self.offs,
541 end_offs: self.end_offs,
542 end_window: self.end_window,
543 nend_bits: self.nend_bits,
544 nbits_total: self.nbits_total,
545 val: self.val,
546 rng: self.rng,
547 rem: self.rem,
548 ext: self.ext,
549 error: self.error,
550 }
551 }
552
553 /// Restores a [`RangeEncoder::snapshot`]; the caller must also put back
554 /// the front bytes with [`RangeEncoder::front_write`].
555 pub fn restore(&mut self, s: &EncSnapshot) {
556 self.offs = s.offs;
557 self.end_offs = s.end_offs;
558 self.end_window = s.end_window;
559 self.nend_bits = s.nend_bits;
560 self.nbits_total = s.nbits_total;
561 self.val = s.val;
562 self.rng = s.rng;
563 self.rem = s.rem;
564 self.ext = s.ext;
565 self.error = s.error;
566 }
567
568 /// Bytes the range coder has written from the front so far.
569 pub fn front(&self) -> &[u8] {
570 &self.buf[..self.offs]
571 }
572
573 /// Where the range coder will write next, from the front.
574 pub fn front_offs(&self) -> usize {
575 self.offs
576 }
577
578 /// Puts saved front bytes back at `from` (pairs with [`RangeEncoder::restore`]).
579 pub fn front_write(&mut self, from: usize, bytes: &[u8]) {
580 self.buf[from..from + bytes.len()].copy_from_slice(bytes);
581 }
582
583 /// `ec_tell_frac()`: the same bound in 1/8th bits.
584 pub fn tell_frac(&self) -> u32 {
585 let mut lg = ilog(self.rng);
586 let mut r_q15 = self.rng >> (lg - 16);
587 for _ in 0..3 {
588 r_q15 = (r_q15 * r_q15) >> 15;
589 let bit = r_q15 >> 16;
590 lg = 2 * lg + bit;
591 r_q15 >>= bit;
592 }
593 // libopus returns a signed value that can dip below zero after `skip_to_end` on a
594 // frame of a few bytes. Clamp at 0: the plain subtraction panicked in debug builds
595 // and wrapped in release (fuzz finding, ec-opus decode_packet).
596 self.nbits_total.saturating_mul(8).saturating_sub(lg)
597 }
598
599 /// Declares the rest of the frame used, so [`RangeEncoder::tell`] reports
600 /// the whole frame — the encoder side of the decoder's `skip_to_end`,
601 /// which is what a silent CELT frame does with its remaining bits.
602 pub fn pad_to_end(&mut self) {
603 self.nbits_total = (self.storage as u32) * 8 + ilog(self.rng);
604 }
605
606 /// `ec_enc_done()`: terminates the frame. Everything between the range
607 /// bytes and the raw bits is left as zeros, which the decoder reads as
608 /// zeros — a CBR frame is therefore always exactly `storage` bytes.
609 pub fn done(&mut self) {
610 // Output the value in [val, val+rng) with the most trailing zeros.
611 let mut l = CODE_BITS as i32 - ilog(self.rng) as i32;
612 let mut msk = 0x7FFF_FFFFu32 >> l;
613 let mut end = self.val.wrapping_add(msk) & !msk;
614 if (end | msk) as u64 >= self.val as u64 + self.rng as u64 {
615 l += 1;
616 msk >>= 1;
617 end = self.val.wrapping_add(msk) & !msk;
618 }
619 while l > 0 {
620 self.carry_out((end >> 23) as i32);
621 end = (end << 8) & 0x7FFF_FFFF;
622 l -= 8;
623 }
624 if self.rem >= 0 || self.ext > 0 {
625 self.carry_out(0);
626 }
627 let mut window = self.end_window;
628 let mut used = self.nend_bits;
629 while used >= 8 {
630 self.write_byte_at_end(window & 0xFF);
631 window >>= 8;
632 used -= 8;
633 }
634 if !self.error && used > 0 {
635 // Anything not written is already zero (reset cleared the frame).
636 if self.end_offs >= self.storage {
637 self.error = true;
638 } else {
639 let l = -l;
640 if self.offs + self.end_offs >= self.storage && (l as u32) < used {
641 window &= (1u32 << l) - 1;
642 self.error = true;
643 }
644 self.buf[self.storage - self.end_offs - 1] |= window as u8;
645 }
646 }
647 }
648}
649
650impl Default for RangeEncoder {
651 fn default() -> Self {
652 RangeEncoder::new()
653 }
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659
660 #[test]
661 fn roundtrip_mixed_symbols() {
662 // {4,4,4,4}/16 uniform context, as icdf and as raw PDF.
663 const ICDF: &[u8] = &[12, 8, 4, 0];
664 const PDF: &[u16] = &[4, 4, 4, 4];
665 let syms: Vec<usize> = (0..200).map(|i| (i * 7 + i / 3) % 4).collect();
666 let bits: Vec<bool> = (0..64).map(|i| i % 3 == 0).collect();
667 let uints: Vec<u32> = vec![0, 1, 5, 1000, 65535, 70000, 3];
668
669 let mut enc = RangeEncoder::new();
670 enc.reset(512);
671 for &s in &syms {
672 enc.enc_icdf(s, ICDF, 4);
673 }
674 for (i, &b) in bits.iter().enumerate() {
675 enc.enc_bit_logp(b, (i % 5) as u32 + 1);
676 }
677 for &u in &uints {
678 enc.enc_uint(u, 1 << 17);
679 }
680 for &s in &syms {
681 let fl = (s as u32) * 4;
682 enc.encode(fl, fl + 4, 16);
683 }
684 enc.enc_bits(0b1011, 4);
685 enc.done();
686 assert!(!enc.error());
687 let frame = enc.data().to_vec();
688
689 let mut dec = RangeDecoder::new(&frame);
690 for &s in &syms {
691 assert_eq!(dec.dec_icdf(ICDF, 4), s);
692 }
693 for (i, &b) in bits.iter().enumerate() {
694 assert_eq!(dec.dec_bit_logp((i % 5) as u32 + 1), b);
695 }
696 for &u in &uints {
697 assert_eq!(dec.dec_uint(1 << 17), u);
698 }
699 for &s in &syms {
700 assert_eq!(dec.dec_pdf(PDF, 4), s);
701 }
702 assert_eq!(dec.dec_bits(4), 0b1011);
703 }
704
705 /// The bit allocation is derived from `tell()`/`tell_frac()` on *both*
706 /// sides, so the encoder's accounting must match the decoder's after every
707 /// symbol — one bit of drift desynchronises the whole frame.
708 #[test]
709 fn encoder_and_decoder_tell_identically() {
710 const ICDF: &[u8] = &[100, 60, 30, 10, 0];
711 let mut enc = RangeEncoder::new();
712 enc.reset(256);
713 let mut log = Vec::new();
714 let mut x = 7u32;
715 for i in 0..300 {
716 x = x.wrapping_mul(1664525).wrapping_add(1013904223);
717 match i % 4 {
718 0 => enc.enc_icdf((x % 5) as usize, ICDF, 7),
719 1 => enc.enc_bit_logp(x & 1 == 0, (x % 6) + 1),
720 2 => enc.enc_uint(x % 500, 700),
721 _ => enc.enc_bits(x & 0x1F, 5),
722 }
723 log.push((i % 4, x, enc.tell(), enc.tell_frac(), enc.range()));
724 }
725 enc.done();
726 assert!(!enc.error());
727 let data = enc.data().to_vec();
728 let mut dec = RangeDecoder::new(&data);
729 for (kind, x, tell, tell_frac, rng) in log {
730 match kind {
731 0 => assert_eq!(dec.dec_icdf(ICDF, 7), (x % 5) as usize),
732 1 => assert_eq!(dec.dec_bit_logp((x % 6) + 1), x & 1 == 0),
733 2 => assert_eq!(dec.dec_uint(700), x % 500),
734 _ => assert_eq!(dec.dec_bits(5), x & 0x1F),
735 }
736 assert_eq!(dec.tell(), tell, "tell drifted");
737 assert_eq!(dec.tell_frac(), tell_frac, "tell_frac drifted");
738 assert_eq!(dec.range(), rng, "range state drifted");
739 }
740 }
741
742 /// A CBR frame stays exactly `storage` bytes: whatever the symbols leave
743 /// unused decodes as zeros, which is what the encoder assumed.
744 #[test]
745 fn fixed_size_frame_decodes_past_the_coded_symbols() {
746 let mut enc = RangeEncoder::new();
747 enc.reset(40);
748 enc.enc_icdf(1, &[100, 50, 0], 7);
749 enc.enc_bits(0b101, 3);
750 enc.done();
751 assert!(!enc.error());
752 assert_eq!(enc.data().len(), 40);
753 let data = enc.data().to_vec();
754 let mut dec = RangeDecoder::new(&data);
755 assert_eq!(dec.dec_icdf(&[100, 50, 0], 7), 1);
756 assert_eq!(dec.dec_bits(3), 0b101);
757 // The rest of the frame reads as zero symbols, not garbage.
758 for _ in 0..50 {
759 let _ = dec.dec_bit_logp(4);
760 }
761 }
762
763 /// `shrink` moves the raw-bit tail; symbols written before and after the
764 /// shrink must both survive.
765 #[test]
766 fn shrink_preserves_both_streams() {
767 let mut enc = RangeEncoder::new();
768 enc.reset(200);
769 enc.enc_uint(1234, 5000);
770 enc.enc_bits(0xAB, 8);
771 enc.shrink(50);
772 enc.enc_uint(999, 5000);
773 enc.enc_bits(0x5, 4);
774 enc.done();
775 assert!(!enc.error());
776 assert_eq!(enc.data().len(), 50);
777 let data = enc.data().to_vec();
778 let mut dec = RangeDecoder::new(&data);
779 assert_eq!(dec.dec_uint(5000), 1234);
780 assert_eq!(dec.dec_bits(8), 0xAB);
781 assert_eq!(dec.dec_uint(5000), 999);
782 assert_eq!(dec.dec_bits(4), 0x5);
783 }
784
785 #[test]
786 fn tell_agrees_with_tell_frac() {
787 let data: Vec<u8> = (0..64u8)
788 .map(|i| i.wrapping_mul(37).wrapping_add(11))
789 .collect();
790 let mut dec = RangeDecoder::new(&data);
791 assert_eq!(dec.tell(), 1, "a fresh decoder reports the termination bit");
792 for i in 0..100 {
793 let _ = dec.dec_icdf(&[128, 0], 8);
794 if i % 7 == 0 {
795 let _ = dec.dec_bits(3);
796 }
797 assert_eq!(dec.tell(), dec.tell_frac().div_ceil(8));
798 }
799 }
800
801 #[test]
802 fn empty_frame_never_panics() {
803 let mut dec = RangeDecoder::new(&[]);
804 for _ in 0..50 {
805 let _ = dec.dec_icdf(&[128, 0], 8);
806 let _ = dec.dec_bits(8);
807 let _ = dec.dec_uint(1 << 20);
808 }
809 }
810}