forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

range.rs472 lines, 15.2 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 self.nbits_total * 8 - lg
260 }
261}
262
263#[cfg(test)]
264mod tests {
265 use super::*;
266
267 /// A minimal range *encoder* (RFC 6716, Section 5.1), test-only: it exists
268 /// so the decoder can be checked against something other than itself on
269 /// symbol shapes the test vectors reach only rarely. The vectors, not this,
270 /// are the real oracle.
271 struct RangeEncoder {
272 buf: Vec<u8>,
273 low: u32,
274 rng: u32,
275 rem: i32,
276 ext: u32,
277 // raw bits, packed backwards
278 end_bits: Vec<bool>,
279 }
280
281 impl RangeEncoder {
282 fn new() -> Self {
283 RangeEncoder {
284 buf: Vec::new(),
285 low: 0,
286 rng: 0x8000_0000,
287 rem: -1,
288 ext: 0,
289 end_bits: Vec::new(),
290 }
291 }
292
293 fn carry_out(&mut self, c: i32) {
294 if c != 0xFF {
295 let carry = c >> 8;
296 if self.rem >= 0 {
297 let v = (self.rem + carry) as u8;
298 self.buf.push(v);
299 }
300 while self.ext > 0 {
301 self.buf.push(((0xFF + carry) & 0xFF) as u8);
302 self.ext -= 1;
303 }
304 self.rem = c & 0xFF;
305 } else {
306 self.ext += 1;
307 }
308 }
309
310 fn normalize(&mut self) {
311 while self.rng <= CODE_TOP {
312 self.carry_out((self.low >> 23) as i32);
313 self.low = (self.low << 8) & 0x7FFF_FFFF;
314 self.rng <<= 8;
315 }
316 }
317
318 fn encode(&mut self, fl: u32, fh: u32, ft: u32) {
319 let r = self.rng / ft;
320 if fl > 0 {
321 self.low = self.low.wrapping_add(self.rng - r * (ft - fl));
322 self.rng = r * (fh - fl);
323 } else {
324 self.rng -= r * (ft - fh);
325 }
326 self.normalize();
327 }
328
329 fn enc_bit_logp(&mut self, bit: bool, logp: u32) {
330 let s = self.rng >> logp;
331 if bit {
332 self.low = self.low.wrapping_add(self.rng - s);
333 self.rng = s;
334 } else {
335 self.rng -= s;
336 }
337 self.normalize();
338 }
339
340 fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) {
341 let r = self.rng >> ftb;
342 if k > 0 {
343 self.low = self.low.wrapping_add(self.rng - r * icdf[k - 1] as u32);
344 self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32);
345 } else {
346 self.rng -= r * icdf[k] as u32;
347 }
348 self.normalize();
349 }
350
351 fn enc_uint(&mut self, value: u32, ft: u32) {
352 let ftb = ilog(ft - 1);
353 if ftb <= 8 {
354 self.encode(value, value + 1, ft);
355 } else {
356 let ftb = ftb - 8;
357 let hi = value >> ftb;
358 self.encode(hi, hi + 1, ((ft - 1) >> ftb) + 1);
359 self.enc_bits(value & ((1 << ftb) - 1), ftb);
360 }
361 }
362
363 fn enc_bits(&mut self, value: u32, bits: u32) {
364 for i in 0..bits {
365 self.end_bits.push((value >> i) & 1 == 1);
366 }
367 }
368
369 /// Terminates the stream and returns the frame bytes.
370 fn finish(mut self) -> Vec<u8> {
371 // Output the value in [low, low+rng) with the most trailing zero
372 // bits, so the raw bits may overwrite them (Section 5.1.5).
373 let mut l = (32 - ilog(self.rng)) as i32;
374 let mut msk = 0x7FFF_FFFFu32 >> l;
375 let mut end = self.low.wrapping_add(msk) & !msk;
376 if (end | msk) as u64 >= self.low as u64 + self.rng as u64 {
377 l += 1;
378 msk >>= 1;
379 end = self.low.wrapping_add(msk) & !msk;
380 }
381 while l > 0 {
382 self.carry_out((end >> 23) as i32);
383 end = (end << 8) & 0x7FFF_FFFF;
384 l -= 8;
385 }
386 if self.rem >= 0 || self.ext > 0 {
387 self.carry_out(0);
388 }
389 // Append the raw bits, packed backwards from the end.
390 let raw_bytes = self.end_bits.len().div_ceil(8);
391 let mut tail = vec![0u8; raw_bytes];
392 for (i, &b) in self.end_bits.iter().enumerate() {
393 if b {
394 let byte = raw_bytes - 1 - i / 8;
395 tail[byte] |= 1 << (i % 8);
396 }
397 }
398 // Pad so the range data and raw data never collide in this test.
399 self.buf.resize(self.buf.len() + 8, 0);
400 self.buf.extend_from_slice(&tail);
401 self.buf
402 }
403 }
404
405 #[test]
406 fn roundtrip_mixed_symbols() {
407 // {4,4,4,4}/16 uniform context, as icdf and as raw PDF.
408 const ICDF: &[u8] = &[12, 8, 4, 0];
409 const PDF: &[u16] = &[4, 4, 4, 4];
410 let syms: Vec<usize> = (0..200).map(|i| (i * 7 + i / 3) % 4).collect();
411 let bits: Vec<bool> = (0..64).map(|i| i % 3 == 0).collect();
412 let uints: Vec<u32> = vec![0, 1, 5, 1000, 65535, 70000, 3];
413
414 let mut enc = RangeEncoder::new();
415 for &s in &syms {
416 enc.enc_icdf(s, ICDF, 4);
417 }
418 for (i, &b) in bits.iter().enumerate() {
419 enc.enc_bit_logp(b, (i % 5) as u32 + 1);
420 }
421 for &u in &uints {
422 enc.enc_uint(u, 1 << 17);
423 }
424 for &s in &syms {
425 let fl = (s as u32) * 4;
426 enc.encode(fl, fl + 4, 16);
427 }
428 enc.enc_bits(0b1011, 4);
429 let frame = enc.finish();
430
431 let mut dec = RangeDecoder::new(&frame);
432 for &s in &syms {
433 assert_eq!(dec.dec_icdf(ICDF, 4), s);
434 }
435 for (i, &b) in bits.iter().enumerate() {
436 assert_eq!(dec.dec_bit_logp((i % 5) as u32 + 1), b);
437 }
438 for &u in &uints {
439 assert_eq!(dec.dec_uint(1 << 17), u);
440 }
441 for &s in &syms {
442 assert_eq!(dec.dec_pdf(PDF, 4), s);
443 }
444 assert_eq!(dec.dec_bits(4), 0b1011);
445 }
446
447 #[test]
448 fn tell_agrees_with_tell_frac() {
449 let data: Vec<u8> = (0..64u8)
450 .map(|i| i.wrapping_mul(37).wrapping_add(11))
451 .collect();
452 let mut dec = RangeDecoder::new(&data);
453 assert_eq!(dec.tell(), 1, "a fresh decoder reports the termination bit");
454 for i in 0..100 {
455 let _ = dec.dec_icdf(&[128, 0], 8);
456 if i % 7 == 0 {
457 let _ = dec.dec_bits(3);
458 }
459 assert_eq!(dec.tell(), dec.tell_frac().div_ceil(8));
460 }
461 }
462
463 #[test]
464 fn empty_frame_never_panics() {
465 let mut dec = RangeDecoder::new(&[]);
466 for _ in 0..50 {
467 let _ = dec.dec_icdf(&[128, 0], 8);
468 let _ = dec.dec_bits(8);
469 let _ = dec.dec_uint(1 << 20);
470 }
471 }
472}