forge
Explore
Log in

Don't you dare go Hollow

Range decoder and packet framing

Browse files at this commit

b05a16e4e22c4e07d84e599d123140798ab3779aAhmet Kaan GümüşParent: 0eac457
  • feat
    • range decoder and packet framing
Show full message
feat(opus): range decoder and packet framing

RFC 6716 Section 4.1 range decoder (exact u32 arithmetic, raw bits from the
frame end, ec_tell/ec_tell_frac) and Section 3 + Appendix B framing: TOC,
codes 0-3, padding, and the self-delimiting variant multistream needs.

Checks: symbol round-trip against a test-only range encoder written from
Section 5.1, tell/tell_frac agreement, and a malformed-input sweep that must
never panic.
Cargo.tomlmodified+1 -0
@@ -10,6 +10,7 @@ authors = ["Ahmet Kaan Gümüş"]
10 10
11 [workspace.dependencies]11 [workspace.dependencies]
12 ec-core = { path = "crates/ec-core", version = "0.1.0" }12 ec-core = { path = "crates/ec-core", version = "0.1.0" }
13+ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
13 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).14 # Portable SIMD without asm or build-time tooling (family rule: pure Rust only).
14 wide = "1.5"15 wide = "1.5"
15 16
crates/ec-opus/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-opus"
3+description = "Opus decoder (RFC 6716): SILK, CELT, hybrid and multistream, built on the edith_codecs IR."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
11+ec-dsp.workspace = true
crates/ec-opus/src/lib.rsadded+33 -0
@@ -0,0 +1,33 @@
1+//! Opus decoding (RFC 6716, with the RFC 8251 corrections).
2+//!
3+//! Opus is two codecs behind one entropy coder: a linear-prediction layer
4+//! (SILK) for speech up to 8 kHz of bandwidth, and an MDCT layer (CELT) for
5+//! everything above that and for music. A packet's table-of-contents byte picks
6+//! one of them or both, and this crate decodes all three cases plus the
7+//! multistream framing that carries 5.1 and 7.1.
8+//!
9+//! Contracts worth knowing before implementing against this crate:
10+//!
11+//! - **The MDCT is the shared one.** CELT synthesis runs through
12+//! [`ec_dsp::Mdct`], never a direct-form DFT. An incumbent Opus decoder in
13+//! this product shipped its FFT behind a default-off feature and ran at 0.95x
14+//! realtime on 5.1; there is no such switch here, and no code path that could
15+//! answer to one.
16+//! - **Malformed input is an error, never a panic.** Framing rules [R1]..[R7]
17+//! are checked in [`packet`], and the range decoder feeds zeros past the end
18+//! of a truncated frame exactly as Section 4.1.2.1 requires.
19+//! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16,
20+//! 12 and 8 kHz are supported; SILK's internal rate is resampled up and the
21+//! sum of the two layers is resampled down once, at the end.
22+//!
23+//! No unsafe, no allocation on the per-frame path beyond the decoder's own
24+//! buffers, no dependencies outside the family.
25+
26+#![forbid(unsafe_code)]
27+#![warn(missing_docs)]
28+
29+pub mod packet;
30+pub mod range;
31+
32+pub use packet::{Bandwidth, Mode, Packet, Toc};
33+pub use range::RangeDecoder;
crates/ec-opus/src/packet.rsadded+423 -0
@@ -0,0 +1,423 @@
1+//! Opus packet framing: the TOC byte, codes 0-3, and the self-delimiting
2+//! variant (RFC 6716, Section 3 and Appendix B).
3+//!
4+//! Every rule marked [R1]..[R7] in Section 3.4 is enforced here and reported as
5+//! [`Error::Corrupt`] — a malformed packet is rejected at the framing layer, so
6+//! nothing downstream ever sees a frame it cannot account for.
7+//!
8+//! The self-delimiting variant is what makes multichannel work: a multistream
9+//! packet is several ordinary Opus packets concatenated, all but the last
10+//! carrying their own length. [`Packet::parse`] with `self_delimited = true`
11+//! reports how many bytes it consumed so the next stream can start there.
12+
13+use ec_core::{Error, Result};
14+
15+/// Which of the three operating modes a configuration selects.
16+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17+pub enum Mode {
18+ /// SILK only: NB/MB/WB speech, 10-60 ms.
19+ Silk,
20+ /// SILK below 8 kHz plus CELT above it: SWB/FB, 10 or 20 ms.
21+ Hybrid,
22+ /// CELT only: NB..FB, 2.5-20 ms.
23+ Celt,
24+}
25+
26+/// Audio bandwidth, in the RFC's names.
27+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
28+pub enum Bandwidth {
29+ /// Narrowband, 4 kHz.
30+ Narrow,
31+ /// Mediumband, 6 kHz.
32+ Medium,
33+ /// Wideband, 8 kHz.
34+ Wide,
35+ /// Super-wideband, 12 kHz.
36+ SuperWide,
37+ /// Fullband, 20 kHz.
38+ Full,
39+}
40+
41+impl Bandwidth {
42+ /// The CELT band count that covers this bandwidth (Section 4.3).
43+ pub fn celt_end_band(self) -> usize {
44+ match self {
45+ Bandwidth::Narrow => 13,
46+ Bandwidth::Medium | Bandwidth::Wide => 17,
47+ Bandwidth::SuperWide => 19,
48+ Bandwidth::Full => 21,
49+ }
50+ }
51+}
52+
53+/// The parsed TOC byte (Section 3.1).
54+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55+pub struct Toc {
56+ /// Configuration number, 0..32.
57+ pub config: u8,
58+ /// True when the packet carries two channels.
59+ pub stereo: bool,
60+ /// Frame count code, 0..4.
61+ pub code: u8,
62+}
63+
64+impl Toc {
65+ /// Splits a TOC byte into its fields.
66+ pub fn new(byte: u8) -> Toc {
67+ Toc {
68+ config: byte >> 3,
69+ stereo: byte & 0x4 != 0,
70+ code: byte & 0x3,
71+ }
72+ }
73+
74+ /// Operating mode for this configuration.
75+ pub fn mode(self) -> Mode {
76+ match self.config {
77+ 0..=11 => Mode::Silk,
78+ 12..=15 => Mode::Hybrid,
79+ _ => Mode::Celt,
80+ }
81+ }
82+
83+ /// Audio bandwidth for this configuration.
84+ pub fn bandwidth(self) -> Bandwidth {
85+ match self.config {
86+ 0..=3 => Bandwidth::Narrow,
87+ 4..=7 => Bandwidth::Medium,
88+ 8..=11 => Bandwidth::Wide,
89+ 12..=13 => Bandwidth::SuperWide,
90+ 14..=15 => Bandwidth::Full,
91+ 16..=19 => Bandwidth::Narrow,
92+ 20..=23 => Bandwidth::Wide,
93+ 24..=27 => Bandwidth::SuperWide,
94+ _ => Bandwidth::Full,
95+ }
96+ }
97+
98+ /// Samples per frame at 48 kHz.
99+ pub fn frame_size_48k(self) -> usize {
100+ match self.config {
101+ // SILK: 10, 20, 40, 60 ms.
102+ 0..=11 => [480, 960, 1920, 2880][(self.config & 0x3) as usize],
103+ // Hybrid: 10, 20 ms.
104+ 12..=15 => [480, 960][(self.config & 0x1) as usize],
105+ // CELT: 2.5, 5, 10, 20 ms.
106+ _ => [120, 240, 480, 960][(self.config & 0x3) as usize],
107+ }
108+ }
109+
110+ /// Channel count signalled by the stereo flag.
111+ pub fn channels(self) -> usize {
112+ if self.stereo { 2 } else { 1 }
113+ }
114+}
115+
116+/// One parsed Opus packet: its TOC and the byte range of each Opus frame.
117+#[derive(Clone, Debug)]
118+pub struct Packet<'a> {
119+ /// The table-of-contents byte.
120+ pub toc: Toc,
121+ /// Compressed frames, in order. A zero-length frame is DTX.
122+ pub frames: Vec<&'a [u8]>,
123+ /// Bytes of the input this packet occupied — the offset of the next
124+ /// stream when parsing self-delimited packets.
125+ pub consumed: usize,
126+}
127+
128+/// Reads a one- or two-byte frame length (Section 3.2.1).
129+fn frame_length(data: &[u8], pos: &mut usize) -> Result<usize> {
130+ let b0 = *data
131+ .get(*pos)
132+ .ok_or_else(|| Error::corrupt("opus packet: truncated frame length"))?
133+ as usize;
134+ *pos += 1;
135+ if b0 < 252 {
136+ return Ok(b0);
137+ }
138+ let b1 = *data
139+ .get(*pos)
140+ .ok_or_else(|| Error::corrupt("opus packet: truncated two-byte frame length"))?
141+ as usize;
142+ *pos += 1;
143+ Ok(b1 * 4 + b0)
144+}
145+
146+impl<'a> Packet<'a> {
147+ /// Parses one packet. `self_delimited` selects the Appendix B variant, in
148+ /// which one extra length precedes the first frame's data.
149+ ///
150+ /// Rejects every malformed packet listed in Section 3.4 rather than
151+ /// guessing at a repair.
152+ pub fn parse(data: &'a [u8], self_delimited: bool) -> Result<Packet<'a>> {
153+ // [R1] Packets are at least one byte.
154+ if data.is_empty() {
155+ return Err(Error::corrupt("opus packet: empty"));
156+ }
157+ let toc = Toc::new(data[0]);
158+ let mut pos = 1usize;
159+ let mut frames = Vec::new();
160+ // Total duration cap of 120 ms [R5].
161+ let max_frames = 5760 / toc.frame_size_48k();
162+
163+ match toc.code {
164+ 0 => {
165+ let len = if self_delimited {
166+ frame_length(data, &mut pos)?
167+ } else {
168+ data.len() - pos
169+ };
170+ push_frame(data, &mut pos, len, &mut frames)?;
171+ }
172+ 1 => {
173+ let len = if self_delimited {
174+ frame_length(data, &mut pos)?
175+ } else {
176+ // [R3] the payload must split evenly in two.
177+ let rest = data.len() - pos;
178+ if !rest.is_multiple_of(2) {
179+ return Err(Error::corrupt("opus packet: code 1 with odd payload"));
180+ }
181+ rest / 2
182+ };
183+ push_frame(data, &mut pos, len, &mut frames)?;
184+ push_frame(data, &mut pos, len, &mut frames)?;
185+ }
186+ 2 => {
187+ // [R4] first length must fit in what remains.
188+ let n1 = frame_length(data, &mut pos)?;
189+ let n2 = if self_delimited {
190+ frame_length(data, &mut pos)?
191+ } else {
192+ (data.len() - pos)
193+ .checked_sub(n1)
194+ .ok_or_else(|| Error::corrupt("opus packet: code 2 first frame overruns"))?
195+ };
196+ push_frame(data, &mut pos, n1, &mut frames)?;
197+ push_frame(data, &mut pos, n2, &mut frames)?;
198+ }
199+ _ => {
200+ // [R6,R7] code 3 needs the frame count byte.
201+ let fc = *data
202+ .get(pos)
203+ .ok_or_else(|| Error::corrupt("opus packet: code 3 without frame count"))?;
204+ pos += 1;
205+ let vbr = fc & 0x80 != 0;
206+ let padded = fc & 0x40 != 0;
207+ let count = (fc & 0x3F) as usize;
208+ // [R5] at least one frame, at most 120 ms of audio.
209+ if count == 0 || count > max_frames {
210+ return Err(Error::corrupt(format!(
211+ "opus packet: code 3 frame count {count} (max {max_frames})"
212+ )));
213+ }
214+ let mut padding = 0usize;
215+ if padded {
216+ loop {
217+ let p = *data.get(pos).ok_or_else(|| {
218+ Error::corrupt("opus packet: truncated padding length")
219+ })?;
220+ pos += 1;
221+ padding += p as usize;
222+ if p != 255 {
223+ break;
224+ }
225+ padding -= 1;
226+ }
227+ }
228+ // Padding bytes live at the very end of the packet. Where the
229+ // packet end is only known from the frame lengths (Appendix B),
230+ // they are skipped after the frames instead.
231+ let body = if self_delimited {
232+ data
233+ } else {
234+ let end = data
235+ .len()
236+ .checked_sub(padding)
237+ .filter(|end| *end >= pos)
238+ .ok_or_else(|| Error::corrupt("opus packet: padding larger than packet"))?;
239+ &data[..end]
240+ };
241+ if vbr {
242+ let mut lengths = Vec::with_capacity(count);
243+ for _ in 0..count - 1 {
244+ lengths.push(frame_length(body, &mut pos)?);
245+ }
246+ let last = if self_delimited {
247+ frame_length(body, &mut pos)?
248+ } else {
249+ let used: usize = lengths.iter().sum();
250+ (body.len() - pos).checked_sub(used).ok_or_else(|| {
251+ Error::corrupt("opus packet: code 3 VBR lengths overrun")
252+ })?
253+ };
254+ lengths.push(last);
255+ for len in lengths {
256+ push_frame(body, &mut pos, len, &mut frames)?;
257+ }
258+ } else {
259+ let len = if self_delimited {
260+ frame_length(body, &mut pos)?
261+ } else {
262+ // [R6] (N-2-P) must be a multiple of M.
263+ let rest = body.len() - pos;
264+ if !rest.is_multiple_of(count) {
265+ return Err(Error::corrupt(
266+ "opus packet: code 3 CBR payload not a multiple of the frame count",
267+ ));
268+ }
269+ rest / count
270+ };
271+ for _ in 0..count {
272+ push_frame(body, &mut pos, len, &mut frames)?;
273+ }
274+ }
275+ pos += padding;
276+ }
277+ }
278+
279+ // [R2] no frame exceeds 1275 bytes.
280+ if let Some(f) = frames.iter().find(|f| f.len() > 1275) {
281+ return Err(Error::corrupt(format!(
282+ "opus packet: frame of {} bytes exceeds 1275",
283+ f.len()
284+ )));
285+ }
286+ if !self_delimited && pos != data.len() {
287+ return Err(Error::corrupt(format!(
288+ "opus packet: {} trailing bytes",
289+ data.len() - pos
290+ )));
291+ }
292+ Ok(Packet {
293+ toc,
294+ frames,
295+ consumed: pos,
296+ })
297+ }
298+
299+ /// Samples this packet decodes to at 48 kHz.
300+ pub fn samples_48k(&self) -> usize {
301+ self.frames.len() * self.toc.frame_size_48k()
302+ }
303+}
304+
305+fn push_frame<'a>(
306+ data: &'a [u8],
307+ pos: &mut usize,
308+ len: usize,
309+ frames: &mut Vec<&'a [u8]>,
310+) -> Result<()> {
311+ let end = pos
312+ .checked_add(len)
313+ .filter(|end| *end <= data.len())
314+ .ok_or_else(|| Error::corrupt("opus packet: frame runs past the end of the packet"))?;
315+ frames.push(&data[*pos..end]);
316+ *pos = end;
317+ Ok(())
318+}
319+
320+#[cfg(test)]
321+mod tests {
322+ use super::*;
323+
324+ #[test]
325+ fn toc_table_2() {
326+ // Spot-checks of Table 2, one per row plus the frame-size ordering.
327+ assert_eq!(Toc::new(0).mode(), Mode::Silk);
328+ assert_eq!(Toc::new(0).frame_size_48k(), 480);
329+ assert_eq!(Toc::new(3 << 3).frame_size_48k(), 2880);
330+ assert_eq!(Toc::new(4 << 3).bandwidth(), Bandwidth::Medium);
331+ assert_eq!(Toc::new(12 << 3).mode(), Mode::Hybrid);
332+ assert_eq!(Toc::new(12 << 3).bandwidth(), Bandwidth::SuperWide);
333+ assert_eq!(Toc::new(13 << 3).frame_size_48k(), 960);
334+ assert_eq!(Toc::new(15 << 3).bandwidth(), Bandwidth::Full);
335+ assert_eq!(Toc::new(16 << 3).mode(), Mode::Celt);
336+ assert_eq!(Toc::new(16 << 3).frame_size_48k(), 120);
337+ assert_eq!(Toc::new(31 << 3).bandwidth(), Bandwidth::Full);
338+ assert!(Toc::new((31 << 3) | 4).stereo);
339+ assert_eq!(Toc::new((31 << 3) | 4 | 3).code, 3);
340+ }
341+
342+ #[test]
343+ fn code0_to_code3() {
344+ // Code 0: everything after the TOC is one frame.
345+ let p = Packet::parse(&[0, 0xaa, 0xbb], false).unwrap();
346+ assert_eq!(p.frames, vec![&[0xaa, 0xbb][..]]);
347+
348+ // Code 1: two halves.
349+ let p = Packet::parse(&[1, 1, 2, 3, 4], false).unwrap();
350+ assert_eq!(p.frames, vec![&[1, 2][..], &[3, 4][..]]);
351+ assert!(Packet::parse(&[1, 1, 2, 3], false).is_err(), "[R3]");
352+
353+ // Code 2: explicit first length.
354+ let p = Packet::parse(&[2, 1, 0x11, 0x22, 0x33], false).unwrap();
355+ assert_eq!(p.frames, vec![&[0x11][..], &[0x22, 0x33][..]]);
356+ assert!(Packet::parse(&[2, 9, 0x11], false).is_err(), "[R4]");
357+
358+ // Code 3 CBR, 3 frames of 2 bytes.
359+ let p = Packet::parse(&[3, 3, 1, 2, 3, 4, 5, 6], false).unwrap();
360+ assert_eq!(p.frames.len(), 3);
361+ assert_eq!(p.frames[2], &[5, 6][..]);
362+ assert!(
363+ Packet::parse(&[3, 3, 1, 2, 3, 4, 5], false).is_err(),
364+ "[R6]"
365+ );
366+ assert!(Packet::parse(&[3, 0], false).is_err(), "[R5] zero frames");
367+
368+ // Code 3 VBR with padding: lengths 1 and 2, then 2 padding bytes.
369+ let p = Packet::parse(
370+ &[3, 0x80 | 0x40 | 3, 2, 1, 2, 0xa, 0xb, 0xc, 0xd, 0, 0],
371+ false,
372+ )
373+ .unwrap();
374+ assert_eq!(p.frames, vec![&[0xa][..], &[0xb, 0xc][..], &[0xd][..]]);
375+
376+ // [R1]
377+ assert!(Packet::parse(&[], false).is_err());
378+ }
379+
380+ #[test]
381+ fn self_delimited_leaves_the_rest_for_the_next_stream() {
382+ // Two self-delimited code 0 packets back to back, then an undelimited one.
383+ let data = [0, 2, 0xa, 0xb, 0, 1, 0xc, 0, 0xd, 0xe];
384+ let first = Packet::parse(&data, true).unwrap();
385+ assert_eq!(first.frames, vec![&[0xa, 0xb][..]]);
386+ assert_eq!(first.consumed, 4);
387+ let second = Packet::parse(&data[first.consumed..], true).unwrap();
388+ assert_eq!(second.frames, vec![&[0xc][..]]);
389+ assert_eq!(second.consumed, 3);
390+ let last = Packet::parse(&data[first.consumed + second.consumed..], false).unwrap();
391+ assert_eq!(last.frames, vec![&[0xd, 0xe][..]]);
392+
393+ // Code 1 self-delimited: the length applies to both frames.
394+ let p = Packet::parse(&[1, 2, 1, 2, 3, 4, 0xff], true).unwrap();
395+ assert_eq!(p.frames, vec![&[1, 2][..], &[3, 4][..]]);
396+ assert_eq!(p.consumed, 6);
397+
398+ // Code 2 self-delimited: both lengths explicit.
399+ let p = Packet::parse(&[2, 1, 2, 0x11, 0x22, 0x33, 0xff], true).unwrap();
400+ assert_eq!(p.frames, vec![&[0x11][..], &[0x22, 0x33][..]]);
401+ assert_eq!(p.consumed, 6);
402+ }
403+
404+ #[test]
405+ fn malformed_input_is_an_error_not_a_panic() {
406+ // Every prefix of a well-formed packet, and a fuzz of short buffers.
407+ let good = [3u8, 0x80 | 0x40 | 3, 2, 1, 2, 0xa, 0xb, 0xc, 0xd, 0, 0];
408+ for n in 0..good.len() {
409+ let _ = Packet::parse(&good[..n], false);
410+ let _ = Packet::parse(&good[..n], true);
411+ }
412+ let mut x = 1u32;
413+ for _ in 0..5000 {
414+ let mut buf = Vec::new();
415+ for _ in 0..(x % 17) {
416+ x = x.wrapping_mul(1664525).wrapping_add(1013904223);
417+ buf.push((x >> 16) as u8);
418+ }
419+ let _ = Packet::parse(&buf, false);
420+ let _ = Packet::parse(&buf, true);
421+ }
422+ }
423+}
crates/ec-opus/src/range.rsadded+456 -0
@@ -0,0 +1,456 @@
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.
16+const CODE_BITS: u32 = 32;
17+/// The renormalisation threshold: `rng` is kept above `2**23`.
18+const 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]
22+fn ilog(x: u32) -> u32 {
23+ 32 - x.leading_zeros()
24+}
25+
26+/// A range decoder over one Opus frame.
27+#[derive(Clone, Debug)]
28+pub 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+
47+impl<'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+ /// `ec_tell()`: a conservative upper bound on whole bits used so far.
228+ #[inline]
229+ pub fn tell(&self) -> u32 {
230+ self.nbits_total - ilog(self.rng)
231+ }
232+
233+ /// `ec_tell_frac()`: the same bound in 1/8th bits (Section 4.1.6.2).
234+ pub fn tell_frac(&self) -> u32 {
235+ let mut lg = ilog(self.rng);
236+ let mut r_q15 = self.rng >> (lg - 16);
237+ for _ in 0..3 {
238+ r_q15 = (r_q15 * r_q15) >> 15;
239+ let bit = r_q15 >> 16;
240+ lg = 2 * lg + bit;
241+ r_q15 >>= bit;
242+ }
243+ self.nbits_total * 8 - lg
244+ }
245+}
246+
247+#[cfg(test)]
248+mod tests {
249+ use super::*;
250+
251+ /// A minimal range *encoder* (RFC 6716, Section 5.1), test-only: it exists
252+ /// so the decoder can be checked against something other than itself on
253+ /// symbol shapes the test vectors reach only rarely. The vectors, not this,
254+ /// are the real oracle.
255+ struct RangeEncoder {
256+ buf: Vec<u8>,
257+ low: u32,
258+ rng: u32,
259+ rem: i32,
260+ ext: u32,
261+ // raw bits, packed backwards
262+ end_bits: Vec<bool>,
263+ }
264+
265+ impl RangeEncoder {
266+ fn new() -> Self {
267+ RangeEncoder {
268+ buf: Vec::new(),
269+ low: 0,
270+ rng: 0x8000_0000,
271+ rem: -1,
272+ ext: 0,
273+ end_bits: Vec::new(),
274+ }
275+ }
276+
277+ fn carry_out(&mut self, c: i32) {
278+ if c != 0xFF {
279+ let carry = c >> 8;
280+ if self.rem >= 0 {
281+ let v = (self.rem + carry) as u8;
282+ self.buf.push(v);
283+ }
284+ while self.ext > 0 {
285+ self.buf.push(((0xFF + carry) & 0xFF) as u8);
286+ self.ext -= 1;
287+ }
288+ self.rem = c & 0xFF;
289+ } else {
290+ self.ext += 1;
291+ }
292+ }
293+
294+ fn normalize(&mut self) {
295+ while self.rng <= CODE_TOP {
296+ self.carry_out((self.low >> 23) as i32);
297+ self.low = (self.low << 8) & 0x7FFF_FFFF;
298+ self.rng <<= 8;
299+ }
300+ }
301+
302+ fn encode(&mut self, fl: u32, fh: u32, ft: u32) {
303+ let r = self.rng / ft;
304+ if fl > 0 {
305+ self.low = self.low.wrapping_add(self.rng - r * (ft - fl));
306+ self.rng = r * (fh - fl);
307+ } else {
308+ self.rng -= r * (ft - fh);
309+ }
310+ self.normalize();
311+ }
312+
313+ fn enc_bit_logp(&mut self, bit: bool, logp: u32) {
314+ let s = self.rng >> logp;
315+ if bit {
316+ self.low = self.low.wrapping_add(self.rng - s);
317+ self.rng = s;
318+ } else {
319+ self.rng -= s;
320+ }
321+ self.normalize();
322+ }
323+
324+ fn enc_icdf(&mut self, k: usize, icdf: &[u8], ftb: u32) {
325+ let r = self.rng >> ftb;
326+ if k > 0 {
327+ self.low = self.low.wrapping_add(self.rng - r * icdf[k - 1] as u32);
328+ self.rng = r * (icdf[k - 1] as u32 - icdf[k] as u32);
329+ } else {
330+ self.rng -= r * icdf[k] as u32;
331+ }
332+ self.normalize();
333+ }
334+
335+ fn enc_uint(&mut self, value: u32, ft: u32) {
336+ let ftb = ilog(ft - 1);
337+ if ftb <= 8 {
338+ self.encode(value, value + 1, ft);
339+ } else {
340+ let ftb = ftb - 8;
341+ let hi = value >> ftb;
342+ self.encode(hi, hi + 1, ((ft - 1) >> ftb) + 1);
343+ self.enc_bits(value & ((1 << ftb) - 1), ftb);
344+ }
345+ }
346+
347+ fn enc_bits(&mut self, value: u32, bits: u32) {
348+ for i in 0..bits {
349+ self.end_bits.push((value >> i) & 1 == 1);
350+ }
351+ }
352+
353+ /// Terminates the stream and returns the frame bytes.
354+ fn finish(mut self) -> Vec<u8> {
355+ // Output the value in [low, low+rng) with the most trailing zero
356+ // bits, so the raw bits may overwrite them (Section 5.1.5).
357+ let mut l = (32 - ilog(self.rng)) as i32;
358+ let mut msk = 0x7FFF_FFFFu32 >> l;
359+ let mut end = self.low.wrapping_add(msk) & !msk;
360+ if (end | msk) as u64 >= self.low as u64 + self.rng as u64 {
361+ l += 1;
362+ msk >>= 1;
363+ end = self.low.wrapping_add(msk) & !msk;
364+ }
365+ while l > 0 {
366+ self.carry_out((end >> 23) as i32);
367+ end = (end << 8) & 0x7FFF_FFFF;
368+ l -= 8;
369+ }
370+ if self.rem >= 0 || self.ext > 0 {
371+ self.carry_out(0);
372+ }
373+ // Append the raw bits, packed backwards from the end.
374+ let raw_bytes = self.end_bits.len().div_ceil(8);
375+ let mut tail = vec![0u8; raw_bytes];
376+ for (i, &b) in self.end_bits.iter().enumerate() {
377+ if b {
378+ let byte = raw_bytes - 1 - i / 8;
379+ tail[byte] |= 1 << (i % 8);
380+ }
381+ }
382+ // Pad so the range data and raw data never collide in this test.
383+ self.buf.resize(self.buf.len() + 8, 0);
384+ self.buf.extend_from_slice(&tail);
385+ self.buf
386+ }
387+ }
388+
389+ #[test]
390+ fn roundtrip_mixed_symbols() {
391+ // {4,4,4,4}/16 uniform context, as icdf and as raw PDF.
392+ const ICDF: &[u8] = &[12, 8, 4, 0];
393+ const PDF: &[u16] = &[4, 4, 4, 4];
394+ let syms: Vec<usize> = (0..200).map(|i| (i * 7 + i / 3) % 4).collect();
395+ let bits: Vec<bool> = (0..64).map(|i| i % 3 == 0).collect();
396+ let uints: Vec<u32> = vec![0, 1, 5, 1000, 65535, 70000, 3];
397+
398+ let mut enc = RangeEncoder::new();
399+ for &s in &syms {
400+ enc.enc_icdf(s, ICDF, 4);
401+ }
402+ for (i, &b) in bits.iter().enumerate() {
403+ enc.enc_bit_logp(b, (i % 5) as u32 + 1);
404+ }
405+ for &u in &uints {
406+ enc.enc_uint(u, 1 << 17);
407+ }
408+ for &s in &syms {
409+ let fl = (s as u32) * 4;
410+ enc.encode(fl, fl + 4, 16);
411+ }
412+ enc.enc_bits(0b1011, 4);
413+ let frame = enc.finish();
414+
415+ let mut dec = RangeDecoder::new(&frame);
416+ for &s in &syms {
417+ assert_eq!(dec.dec_icdf(ICDF, 4), s);
418+ }
419+ for (i, &b) in bits.iter().enumerate() {
420+ assert_eq!(dec.dec_bit_logp((i % 5) as u32 + 1), b);
421+ }
422+ for &u in &uints {
423+ assert_eq!(dec.dec_uint(1 << 17), u);
424+ }
425+ for &s in &syms {
426+ assert_eq!(dec.dec_pdf(PDF, 4), s);
427+ }
428+ assert_eq!(dec.dec_bits(4), 0b1011);
429+ }
430+
431+ #[test]
432+ fn tell_agrees_with_tell_frac() {
433+ let data: Vec<u8> = (0..64u8)
434+ .map(|i| i.wrapping_mul(37).wrapping_add(11))
435+ .collect();
436+ let mut dec = RangeDecoder::new(&data);
437+ assert_eq!(dec.tell(), 1, "a fresh decoder reports the termination bit");
438+ for i in 0..100 {
439+ let _ = dec.dec_icdf(&[128, 0], 8);
440+ if i % 7 == 0 {
441+ let _ = dec.dec_bits(3);
442+ }
443+ assert_eq!(dec.tell(), dec.tell_frac().div_ceil(8));
444+ }
445+ }
446+
447+ #[test]
448+ fn empty_frame_never_panics() {
449+ let mut dec = RangeDecoder::new(&[]);
450+ for _ in 0..50 {
451+ let _ = dec.dec_icdf(&[128, 0], 8);
452+ let _ = dec.dec_bits(8);
453+ let _ = dec.dec_uint(1 << 20);
454+ }
455+ }
456+}