forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7cdaf34Tahinli3 months ago29 commits

lib.rs198 lines, 6.8 KiBHistoryRawDownload
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
29pub mod celt;
30pub mod packet;
31pub mod range;
32
33pub use celt::CeltDecoder;
34pub use packet::{Bandwidth, Mode, Packet, Toc};
35pub use range::RangeDecoder;
36
37use ec_core::{Error, Result};
38
39/// One Opus stream: mono or stereo, any mode, any frame size.
40///
41/// Feed whole Opus packets to [`Decoder::decode_float`]; the decoder tracks the
42/// inter-frame state (energy history, MDCT overlap, LPC memory) that Opus needs
43/// across packets, so packets must be delivered in order.
44#[derive(Clone, Debug)]
45pub struct Decoder {
46 sample_rate: u32,
47 /// Output channels, which may exceed what a given packet codes.
48 channels: usize,
49 downsample: usize,
50 celt: CeltDecoder,
51 prev_mode: Option<Mode>,
52 prev_redundancy: bool,
53 range_final: u32,
54}
55
56impl Decoder {
57 /// A decoder for `channels` channels at `sample_rate`, which must be one of
58 /// 8000, 12000, 16000, 24000 or 48000 Hz.
59 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
60 let downsample = match sample_rate {
61 48000 => 1,
62 24000 => 2,
63 16000 => 3,
64 12000 => 4,
65 8000 => 6,
66 _ => {
67 return Err(Error::unsupported(
68 format!("opus output rate {sample_rate}"),
69 "Opus decodes to 8, 12, 16, 24 or 48 kHz only",
70 ));
71 }
72 };
73 if !(1..=2).contains(&channels) {
74 return Err(Error::unsupported(
75 format!("{channels}-channel Opus stream"),
76 "one stream carries at most two channels; use MultistreamDecoder",
77 ));
78 }
79 Ok(Decoder {
80 sample_rate,
81 channels,
82 downsample,
83 celt: CeltDecoder::new(channels, downsample),
84 prev_mode: None,
85 prev_redundancy: false,
86 range_final: 0,
87 })
88 }
89
90 /// Output sample rate.
91 pub fn sample_rate(&self) -> u32 {
92 self.sample_rate
93 }
94
95 /// Output channels.
96 pub fn channels(&self) -> usize {
97 self.channels
98 }
99
100 /// The range coder state after the last packet. The RFC 6716 test vectors
101 /// carry this value per packet, which makes it a bit-exact conformance
102 /// check on everything the decoder read.
103 pub fn final_range(&self) -> u32 {
104 self.range_final
105 }
106
107 /// Drops all inter-packet state; call after a seek.
108 pub fn reset(&mut self) {
109 self.celt.reset();
110 self.prev_mode = None;
111 self.prev_redundancy = false;
112 self.range_final = 0;
113 }
114
115 /// Decodes one packet into interleaved `f32`, returning samples per channel.
116 ///
117 /// `out` must hold `channels * 120 ms` worth of samples for the general
118 /// case (5760 per channel at 48 kHz).
119 pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> {
120 let (samples, _) = self.decode_impl(packet, out, false)?;
121 Ok(samples)
122 }
123
124 /// Decodes one self-delimited packet (RFC 6716, Appendix B), returning the
125 /// samples per channel and the bytes the packet occupied. This is what the
126 /// multistream framing needs for every stream but the last.
127 pub fn decode_self_delimited(
128 &mut self,
129 data: &[u8],
130 out: &mut [f32],
131 ) -> Result<(usize, usize)> {
132 self.decode_impl(data, out, true)
133 }
134
135 fn decode_impl(
136 &mut self,
137 data: &[u8],
138 out: &mut [f32],
139 self_delimited: bool,
140 ) -> Result<(usize, usize)> {
141 let parsed = Packet::parse(data, self_delimited)?;
142 let toc = parsed.toc;
143 let frame_48k = toc.frame_size_48k();
144 let frame_out = frame_48k / self.downsample;
145 let needed = parsed.frames.len() * frame_out * self.channels;
146 if out.len() < needed {
147 return Err(Error::corrupt(format!(
148 "opus: output buffer holds {} samples, packet needs {needed}",
149 out.len()
150 )));
151 }
152 let mut done = 0usize;
153 let mut range = 0u32;
154 for frame in &parsed.frames {
155 let dst = &mut out[done * self.channels..(done + frame_out) * self.channels];
156 range = self.decode_frame(frame, dst, toc, frame_48k)?;
157 done += frame_out;
158 }
159 self.range_final = range;
160 Ok((done, parsed.consumed))
161 }
162
163 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
164 fn decode_frame(
165 &mut self,
166 data: &[u8],
167 out: &mut [f32],
168 toc: Toc,
169 frame_48k: usize,
170 ) -> Result<u32> {
171 let mode = toc.mode();
172 let stream_channels = toc.channels();
173 if data.len() <= 1 {
174 // DTX or a dropped frame: no PLC in this decoder, so emit silence.
175 out.fill(0.0);
176 return Ok(0);
177 }
178 let mut dec = RangeDecoder::new(data);
179
180 if mode != Mode::Celt {
181 return Err(Error::unsupported(
182 "Opus SILK layer",
183 "only the CELT layer is implemented in this build",
184 ));
185 }
186
187 // A mode switch invalidates the MDCT overlap and energy history.
188 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
189 self.celt.reset();
190 }
191 let end_band = toc.bandwidth().celt_end_band();
192 self.celt
193 .decode(&mut dec, out, frame_48k, 0, end_band, stream_channels)?;
194 self.prev_mode = Some(mode);
195 self.prev_redundancy = false;
196 Ok(dec.range())
197 }
198}