forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBabd41b6Tahinli3 months ago75 commits

lib.rs403 lines, 14.7 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 FFT is never optional.** CELT synthesis runs an `N/4`-point FFT
12//! through [`ec_dsp`], 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. (CELT's transform sizes are `15*2^k`, so [`ec_dsp::Mdct`]
16//! itself — power-of-two only — cannot serve them; [`celt`] wraps
17//! [`ec_dsp::Fft`] with one radix-3/radix-5 stage instead.)
18//! - **Malformed input is an error, never a panic.** Framing rules `[R1]`..`[R7]`
19//! are checked in [`packet`], and the range decoder feeds zeros past the end
20//! of a truncated frame exactly as Section 4.1.2.1 requires.
21//! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16,
22//! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the
23//! normative resampler in [`silk`]) and CELT decimates on the way out.
24//! - **There is no packet loss concealment.** A frame of one byte or none —
25//! a dropped or DTX frame — decodes to silence, where the reference
26//! extrapolates from the previous frame. This decoder is fed whole packets by
27//! a container, never a gap, so the concealment would be dead weight; a
28//! caller that needs it (an RTP receiver) has to add it.
29//!
30//! No unsafe, no allocation on the per-frame path beyond the decoder's own
31//! buffers, no dependencies outside the family.
32
33#![forbid(unsafe_code)]
34#![warn(missing_docs)]
35
36pub mod celt;
37pub mod multistream;
38pub mod packet;
39pub mod range;
40pub mod silk;
41
42pub use celt::CeltDecoder;
43pub use multistream::MultistreamDecoder;
44pub use packet::{Bandwidth, Mode, Packet, Toc};
45pub use range::RangeDecoder;
46pub use silk::SilkDecoder;
47
48use ec_core::{Error, Result};
49
50/// One Opus stream: mono or stereo, any mode, any frame size.
51///
52/// Feed whole Opus packets to [`Decoder::decode_float`]; the decoder tracks the
53/// inter-frame state (energy history, MDCT overlap, LPC memory) that Opus needs
54/// across packets, so packets must be delivered in order.
55#[derive(Clone, Debug)]
56pub struct Decoder {
57 sample_rate: u32,
58 /// Output channels, which may exceed what a given packet codes.
59 channels: usize,
60 downsample: usize,
61 celt: CeltDecoder,
62 silk: SilkDecoder,
63 /// The CELT overlap window, reused for redundancy cross-fades.
64 celt_window: Vec<f32>,
65 /// Per-frame scratch, allocated once: the SILK layer's output and the
66 /// redundancy frame.
67 silk_pcm: Vec<i16>,
68 redundant: Vec<f32>,
69 prev_mode: Option<Mode>,
70 prev_redundancy: bool,
71 range_final: u32,
72}
73
74impl Decoder {
75 /// A decoder for `channels` channels at `sample_rate`, which must be one of
76 /// 8000, 12000, 16000, 24000 or 48000 Hz.
77 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
78 let downsample = match sample_rate {
79 48000 => 1,
80 24000 => 2,
81 16000 => 3,
82 12000 => 4,
83 8000 => 6,
84 _ => {
85 return Err(Error::unsupported(
86 format!("opus output rate {sample_rate}"),
87 "Opus decodes to 8, 12, 16, 24 or 48 kHz only",
88 ));
89 }
90 };
91 if !(1..=2).contains(&channels) {
92 return Err(Error::unsupported(
93 format!("{channels}-channel Opus stream"),
94 "one stream carries at most two channels; use MultistreamDecoder",
95 ));
96 }
97 Ok(Decoder {
98 sample_rate,
99 channels,
100 downsample,
101 celt: CeltDecoder::new(channels, downsample),
102 silk: SilkDecoder::new(sample_rate, channels),
103 celt_window: celt::overlap_window(),
104 silk_pcm: vec![0; 5760 * channels],
105 redundant: vec![0.0; 240 * channels],
106 prev_mode: None,
107 prev_redundancy: false,
108 range_final: 0,
109 })
110 }
111
112 /// Output sample rate.
113 pub fn sample_rate(&self) -> u32 {
114 self.sample_rate
115 }
116
117 /// Output channels.
118 pub fn channels(&self) -> usize {
119 self.channels
120 }
121
122 /// The range coder state after the last packet. The RFC 6716 test vectors
123 /// carry this value per packet, which makes it a bit-exact conformance
124 /// check on everything the decoder read.
125 pub fn final_range(&self) -> u32 {
126 self.range_final
127 }
128
129 /// Drops all inter-packet state; call after a seek.
130 pub fn reset(&mut self) {
131 self.celt.reset();
132 self.silk.reset();
133 self.prev_mode = None;
134 self.prev_redundancy = false;
135 self.range_final = 0;
136 }
137
138 /// Decodes one packet into interleaved `f32`, returning samples per channel.
139 ///
140 /// `out` must hold `channels * 120 ms` worth of samples for the general
141 /// case (5760 per channel at 48 kHz).
142 pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> {
143 let (samples, _) = self.decode_impl(packet, out, false)?;
144 Ok(samples)
145 }
146
147 /// Decodes one self-delimited packet (RFC 6716, Appendix B), returning the
148 /// samples per channel and the bytes the packet occupied. This is what the
149 /// multistream framing needs for every stream but the last.
150 pub fn decode_self_delimited(
151 &mut self,
152 data: &[u8],
153 out: &mut [f32],
154 ) -> Result<(usize, usize)> {
155 self.decode_impl(data, out, true)
156 }
157
158 fn decode_impl(
159 &mut self,
160 data: &[u8],
161 out: &mut [f32],
162 self_delimited: bool,
163 ) -> Result<(usize, usize)> {
164 let parsed = Packet::parse(data, self_delimited)?;
165 let toc = parsed.toc;
166 let frame_48k = toc.frame_size_48k();
167 let frame_out = frame_48k / self.downsample;
168 let needed = parsed.frames.len() * frame_out * self.channels;
169 if out.len() < needed {
170 return Err(Error::corrupt(format!(
171 "opus: output buffer holds {} samples, packet needs {needed}",
172 out.len()
173 )));
174 }
175 let mut done = 0usize;
176 let mut range = 0u32;
177 for frame in &parsed.frames {
178 let dst = &mut out[done * self.channels..(done + frame_out) * self.channels];
179 range = self.decode_frame(frame, dst, toc, frame_48k)?;
180 done += frame_out;
181 }
182 self.range_final = range;
183 Ok((done, parsed.consumed))
184 }
185
186 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
187 ///
188 /// The three modes share this path: SILK fills the low band, CELT the high
189 /// one, and a hybrid frame is their sum. The order of everything read from
190 /// the range decoder here is normative — SILK, then the redundancy flags,
191 /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3).
192 fn decode_frame(
193 &mut self,
194 data: &[u8],
195 out: &mut [f32],
196 toc: Toc,
197 frame_48k: usize,
198 ) -> Result<u32> {
199 let mode = toc.mode();
200 let stream_channels = toc.channels();
201 if data.len() <= 1 {
202 // DTX or a dropped frame. There is no PLC here (the container
203 // layer feeds this decoder whole packets), so the frame is silent.
204 out.fill(0.0);
205 self.prev_mode = None;
206 return Ok(0);
207 }
208 let mut dec = RangeDecoder::new(data);
209 let mut len = data.len();
210 let frame_out = frame_48k / self.downsample;
211 let f5 = 240 / self.downsample;
212 let f2_5 = 120 / self.downsample;
213
214 // --- SILK layer -----------------------------------------------------
215 let mut silk_pcm = core::mem::take(&mut self.silk_pcm);
216 silk_pcm.clear();
217 silk_pcm.resize(frame_out * self.channels, 0);
218 if mode != Mode::Celt {
219 if self.prev_mode == Some(Mode::Celt) {
220 self.silk.reset();
221 }
222 let internal_rate = if mode == Mode::Hybrid {
223 16000
224 } else {
225 match toc.bandwidth() {
226 Bandwidth::Narrow => 8000,
227 Bandwidth::Medium => 12000,
228 _ => 16000,
229 }
230 };
231 let payload_ms = (frame_48k / 48).max(10);
232 let mut done = 0usize;
233 let mut first = true;
234 while done < frame_out {
235 let n = self.silk.decode(
236 &mut dec,
237 &mut silk_pcm[done * self.channels..],
238 payload_ms,
239 internal_rate,
240 stream_channels,
241 first,
242 )?;
243 if n == 0 {
244 break;
245 }
246 done += n;
247 first = false;
248 }
249 }
250
251 // --- Redundancy (Section 4.5.1) -------------------------------------
252 let mut redundancy = false;
253 let mut celt_to_silk = false;
254 let mut redundancy_bytes = 0usize;
255 if mode != Mode::Celt
256 && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len
257 {
258 redundancy = if mode == Mode::Hybrid {
259 dec.dec_bit_logp(12)
260 } else {
261 true
262 };
263 if redundancy {
264 celt_to_silk = dec.dec_bit_logp(1);
265 redundancy_bytes = if mode == Mode::Hybrid {
266 dec.dec_uint(256) as usize + 2
267 } else {
268 len - ((dec.tell() as usize + 7) >> 3)
269 };
270 if redundancy_bytes > len {
271 redundancy_bytes = 0;
272 redundancy = false;
273 } else {
274 len -= redundancy_bytes;
275 if len * 8 < dec.tell() as usize {
276 len = 0;
277 redundancy_bytes = 0;
278 redundancy = false;
279 }
280 dec.shrink(len);
281 }
282 }
283 }
284
285 let end_band = toc.bandwidth().celt_end_band();
286 let start_band = if mode == Mode::Celt { 0 } else { 17 };
287 let mut redundant = core::mem::take(&mut self.redundant);
288 redundant.clear();
289 redundant.resize(f5 * self.channels, 0.0);
290
291 // A redundancy frame that precedes the main one is decoded first.
292 let mut redundant_rng = 0u32;
293 if redundancy && celt_to_silk {
294 let tail = &data[len..len + redundancy_bytes];
295 let mut rdec = RangeDecoder::new(tail);
296 self.celt
297 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
298 redundant_rng = rdec.range();
299 }
300
301 // --- CELT layer -----------------------------------------------------
302 if mode != Mode::Silk {
303 // A mode switch invalidates the MDCT overlap and energy history.
304 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
305 self.celt.reset();
306 }
307 self.celt.decode(
308 &mut dec,
309 out,
310 frame_48k.min(960),
311 start_band,
312 end_band,
313 stream_channels,
314 )?;
315 } else {
316 out.fill(0.0);
317 // Fade the CELT layer out when leaving hybrid, as the reference
318 // does, by decoding one silent 2.5 ms frame.
319 if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) {
320 let silence = [0xFFu8, 0xFF];
321 let mut sdec = RangeDecoder::new(&silence);
322 let mut tmp = vec![0.0f32; f2_5 * self.channels];
323 self.celt
324 .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?;
325 }
326 }
327
328 // Sum the two layers.
329 if mode != Mode::Celt {
330 for (o, s) in out.iter_mut().zip(silk_pcm.iter()) {
331 *o += *s as f32 * (1.0 / 32768.0);
332 }
333 }
334
335 // A redundancy frame that follows the main one is cross-faded in.
336 if redundancy && !celt_to_silk {
337 self.celt.reset();
338 let tail = &data[len..len + redundancy_bytes];
339 let mut rdec = RangeDecoder::new(tail);
340 self.celt
341 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
342 redundant_rng = rdec.range();
343 let base = (frame_out - f2_5) * self.channels;
344 smooth_fade(
345 &mut out[base..],
346 &redundant[f2_5 * self.channels..],
347 f2_5,
348 self.channels,
349 &self.celt_window,
350 self.downsample,
351 );
352 }
353 if redundancy && celt_to_silk {
354 for c in 0..self.channels {
355 for i in 0..f2_5 {
356 out[self.channels * i + c] = redundant[self.channels * i + c];
357 }
358 }
359 // Then fade from the redundancy frame into the frame proper.
360 let split = f2_5 * self.channels;
361 for c in 0..self.channels {
362 for i in 0..f2_5 {
363 let w = {
364 let x = self.celt_window[i * self.downsample];
365 x * x
366 };
367 let idx = split + i * self.channels + c;
368 if idx < out.len() && idx < redundant.len() {
369 out[idx] = w * out[idx] + (1.0 - w) * redundant[idx];
370 }
371 }
372 }
373 }
374
375 self.prev_mode = Some(mode);
376 self.prev_redundancy = redundancy && !celt_to_silk;
377 self.silk_pcm = silk_pcm;
378 self.redundant = redundant;
379 Ok(dec.range() ^ redundant_rng)
380 }
381}
382
383/// Cross-fades `b` over `a` across `overlap` samples using the CELT window,
384/// the shape the reference uses for redundancy and mode transitions.
385fn smooth_fade(
386 a: &mut [f32],
387 b: &[f32],
388 overlap: usize,
389 channels: usize,
390 window: &[f32],
391 downsample: usize,
392) {
393 let inc = downsample;
394 for c in 0..channels {
395 for i in 0..overlap {
396 let w = window[i * inc] * window[i * inc];
397 let idx = i * channels + c;
398 if idx < a.len() && idx < b.len() {
399 a[idx] = w * b[idx] + (1.0 - w) * a[idx];
400 }
401 }
402 }
403}