forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7cdaf34Tahinli3 months ago29 commits

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