forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB7947774Tahinli1 month ago3899 commits

lib.rs473 lines, 18.3 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//! The crate also carries the family's Opus *encoder* — [`Encoder`] for one
31//! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono
32//! and stereo, every rate from 16 to 510 kbps, CBR and constrained VBR.
33//!
34//! **Why the incumbent encoder collapsed above ~128-165 kbps** (the measured
35//! record this crate replaces; edith `engine/Cargo.toml:124-140` and
36//! `export.rs:1834`): its packets above that rate were decodable only by its
37//! *own* decoder — correlation 0.06 against the reference decoder at 256 kbps while its
38//! internal round trip read 0.999 — and the rate the cliff sat at moved with
39//! the content. That signature — self-consistent, world-divergent, at a
40//! *bits-per-band* threshold — is a shared encode/decode convention error in
41//! exactly the code CELT only exercises when a band's budget is large: the
42//! over-32-bit-codeword band split (RFC 6716 Section 4.3.4.1: a band whose bit
43//! demand exceeds its cache row is halved recursively, with an entropy-coded
44//! angle and a rebalance of the leftover bits). An encoder whose split
45//! bookkeeping (`tell`-derived budgets, rebalance, theta pdf selection)
46//! drifts one bit from the normative derivation still decodes its own output
47//! — both halves share the drift — but a conformant decoder desynchronises,
48//! and the threshold moves with content because the split only triggers on
49//! loud, flat bands. Content-dependence is also why mono broke at *every*
50//! rate: half the coefficients means every band hits the split threshold at
51//! half the bitrate. This encoder mirrors the reference's allocation
52//! arithmetic symbol for symbol, and the tests hold the closed loop to it:
53//! every packet is range-state-exact against this crate's own
54//! RFC-vector-verified decoder, and the reference decoder (via the oracle) plus the reference
55//! `opus_demo` decoder read the same packets at correlation >= 0.99 across
56//! the whole rate table, mono, stereo and 5.1 alike.
57//!
58//! No unsafe, no allocation on the per-frame path beyond the codecs' own
59//! buffers, no dependencies outside the family.
60
61#![forbid(unsafe_code)]
62#![warn(missing_docs)]
63
64pub(crate) mod analysis;
65pub mod celt;
66pub mod celt_enc;
67pub mod encoder;
68pub mod multistream;
69pub mod multistream_enc;
70pub mod ogg;
71pub mod packet;
72pub mod range;
73pub mod silk;
74pub(crate) mod silk_enc;
75pub mod silk_enc_write;
76mod stack_budget;
77
78pub use celt::CeltDecoder;
79pub use celt_enc::CeltFrameDiag;
80pub use encoder::{Application, Encoder};
81pub use multistream::MultistreamDecoder;
82pub use multistream_enc::MultistreamEncoder;
83pub use packet::{Bandwidth, Mode, Packet, Toc};
84pub use range::{RangeDecoder, RangeEncoder};
85pub use silk::{SilkDecIndices, SilkDecoder};
86pub use silk_enc_write::SilkFrameDiag;
87pub use silk_enc_write::{SilkEncoder, SilkStereoEncoder};
88
89use ec_core::{Error, Result};
90
91/// One Opus stream: mono or stereo, any mode, any frame size.
92///
93/// Feed whole Opus packets to [`Decoder::decode_float`]; the decoder tracks the
94/// inter-frame state (energy history, MDCT overlap, LPC memory) that Opus needs
95/// across packets, so packets must be delivered in order.
96#[derive(Clone, Debug)]
97pub struct Decoder {
98 sample_rate: u32,
99 /// Output channels, which may exceed what a given packet codes.
100 channels: usize,
101 downsample: usize,
102 celt: CeltDecoder,
103 /// Boxed because a `SilkDecoder` is 6304 bytes, 83% of what a `Decoder`
104 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
105 /// decoder's largest field and its only large one; `celt` is 1168.
106 /// `Stack`: crate::stack_budget.
107 silk: Box<SilkDecoder>,
108 /// The CELT overlap window, reused for redundancy cross-fades.
109 celt_window: Vec<f32>,
110 /// Per-frame scratch, allocated once: the SILK layer's output and the
111 /// redundancy frame.
112 silk_pcm: Vec<i16>,
113 redundant: Vec<f32>,
114 prev_mode: Option<Mode>,
115 prev_redundancy: bool,
116 range_final: u32,
117 /// Test hook: drop the (CELT, SILK) layer's output before the sum.
118 debug_mute: (bool, bool),
119}
120
121impl Decoder {
122 /// Test hook, not for production use: silences the CELT and/or SILK
123 /// layer's contribution to the output (the decoder state still advances)
124 /// so a hybrid packet's two layers can be measured one at a time.
125 #[doc(hidden)]
126 pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) {
127 self.debug_mute = (celt, silk);
128 }
129
130 /// Decodes with the RFC 6716 reconstruction instead of the RFC 8251 one
131 /// (the default). Needed only to reproduce the RFC 6716 reference vectors.
132 pub fn set_legacy_rfc6716(&mut self, on: bool) {
133 self.celt.set_legacy_rfc6716(on);
134 }
135
136 /// Facts from the last decoded frame's CELT layer (diagnostic).
137 pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag {
138 self.celt.last_diag()
139 }
140
141 /// A decoder for `channels` channels at `sample_rate`, which must be one of
142 /// 8000, 12000, 16000, 24000 or 48000 Hz.
143 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
144 let downsample = match sample_rate {
145 48000 => 1,
146 24000 => 2,
147 16000 => 3,
148 12000 => 4,
149 8000 => 6,
150 _ => {
151 return Err(Error::unsupported(
152 format!("opus output rate {sample_rate}"),
153 "Opus decodes to 8, 12, 16, 24 or 48 kHz only",
154 ));
155 }
156 };
157 if !(1..=2).contains(&channels) {
158 return Err(Error::unsupported(
159 format!("{channels}-channel Opus stream"),
160 "one stream carries at most two channels; use MultistreamDecoder",
161 ));
162 }
163 Ok(Decoder {
164 sample_rate,
165 channels,
166 downsample,
167 celt: CeltDecoder::new(channels, downsample),
168 silk: Box::new(SilkDecoder::new(sample_rate, channels)),
169 celt_window: celt::overlap_window(),
170 silk_pcm: vec![0; 5760 * channels],
171 redundant: vec![0.0; 240 * channels],
172 prev_mode: None,
173 prev_redundancy: false,
174 range_final: 0,
175 debug_mute: (false, false),
176 })
177 }
178
179 /// Output sample rate.
180 pub fn sample_rate(&self) -> u32 {
181 self.sample_rate
182 }
183
184 /// Output channels.
185 pub fn channels(&self) -> usize {
186 self.channels
187 }
188
189 /// The range coder state after the last packet. The RFC 6716 test vectors
190 /// carry this value per packet, which makes it a bit-exact conformance
191 /// check on everything the decoder read.
192 pub fn final_range(&self) -> u32 {
193 self.range_final
194 }
195
196 /// Drops all inter-packet state; call after a seek.
197 pub fn reset(&mut self) {
198 self.celt.reset();
199 self.silk.reset();
200 self.prev_mode = None;
201 self.prev_redundancy = false;
202 self.range_final = 0;
203 }
204
205 /// Decodes one packet into interleaved `f32`, returning samples per channel.
206 ///
207 /// `out` must hold `channels * 120 ms` worth of samples for the general
208 /// case (5760 per channel at 48 kHz).
209 pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> {
210 let (samples, _) = self.decode_impl(packet, out, false)?;
211 Ok(samples)
212 }
213
214 /// Decodes one self-delimited packet (RFC 6716, Appendix B), returning the
215 /// samples per channel and the bytes the packet occupied. This is what the
216 /// multistream framing needs for every stream but the last.
217 pub fn decode_self_delimited(
218 &mut self,
219 data: &[u8],
220 out: &mut [f32],
221 ) -> Result<(usize, usize)> {
222 self.decode_impl(data, out, true)
223 }
224
225 fn decode_impl(
226 &mut self,
227 data: &[u8],
228 out: &mut [f32],
229 self_delimited: bool,
230 ) -> Result<(usize, usize)> {
231 let parsed = Packet::parse(data, self_delimited)?;
232 let toc = parsed.toc;
233 let frame_48k = toc.frame_size_48k();
234 let frame_out = frame_48k / self.downsample;
235 let needed = parsed.frames.len() * frame_out * self.channels;
236 if out.len() < needed {
237 return Err(Error::corrupt(format!(
238 "opus: output buffer holds {} samples, packet needs {needed}",
239 out.len()
240 )));
241 }
242 let mut done = 0usize;
243 let mut range = 0u32;
244 for frame in &parsed.frames {
245 let dst = &mut out[done * self.channels..(done + frame_out) * self.channels];
246 range = self.decode_frame(frame, dst, toc, frame_48k)?;
247 done += frame_out;
248 }
249 self.range_final = range;
250 Ok((done, parsed.consumed))
251 }
252
253 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
254 ///
255 /// The three modes share this path: SILK fills the low band, CELT the high
256 /// one, and a hybrid frame is their sum. The order of everything read from
257 /// the range decoder here is normative — SILK, then the redundancy flags,
258 /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3).
259 fn decode_frame(
260 &mut self,
261 data: &[u8],
262 out: &mut [f32],
263 toc: Toc,
264 frame_48k: usize,
265 ) -> Result<u32> {
266 let mode = toc.mode();
267 let stream_channels = toc.channels();
268 if data.len() <= 1 {
269 // DTX or a dropped frame. There is no PLC here (the container
270 // layer feeds this decoder whole packets), so the frame is silent.
271 out.fill(0.0);
272 self.prev_mode = None;
273 return Ok(0);
274 }
275 let mut dec = RangeDecoder::new(data);
276 let mut len = data.len();
277 let frame_out = frame_48k / self.downsample;
278 let f5 = 240 / self.downsample;
279 let f2_5 = 120 / self.downsample;
280
281 // --- SILK layer -----------------------------------------------------
282 let mut silk_pcm = core::mem::take(&mut self.silk_pcm);
283 silk_pcm.clear();
284 silk_pcm.resize(frame_out * self.channels, 0);
285 if mode != Mode::Celt {
286 if self.prev_mode == Some(Mode::Celt) {
287 self.silk.reset();
288 }
289 let internal_rate = if mode == Mode::Hybrid {
290 16000
291 } else {
292 match toc.bandwidth() {
293 Bandwidth::Narrow => 8000,
294 Bandwidth::Medium => 12000,
295 _ => 16000,
296 }
297 };
298 let payload_ms = (frame_48k / 48).max(10);
299 let mut done = 0usize;
300 let mut first = true;
301 while done < frame_out {
302 let n = self.silk.decode(
303 &mut dec,
304 &mut silk_pcm[done * self.channels..],
305 payload_ms,
306 internal_rate,
307 stream_channels,
308 first,
309 )?;
310 if n == 0 {
311 break;
312 }
313 done += n;
314 first = false;
315 }
316 }
317
318 // --- Redundancy (Section 4.5.1) -------------------------------------
319 let mut redundancy = false;
320 let mut celt_to_silk = false;
321 let mut redundancy_bytes = 0usize;
322 if mode != Mode::Celt
323 && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len
324 {
325 redundancy = if mode == Mode::Hybrid {
326 dec.dec_bit_logp(12)
327 } else {
328 true
329 };
330 if redundancy {
331 celt_to_silk = dec.dec_bit_logp(1);
332 redundancy_bytes = if mode == Mode::Hybrid {
333 dec.dec_uint(256) as usize + 2
334 } else {
335 len - ((dec.tell() as usize + 7) >> 3)
336 };
337 if redundancy_bytes > len {
338 redundancy_bytes = 0;
339 redundancy = false;
340 } else {
341 len -= redundancy_bytes;
342 if len * 8 < dec.tell() as usize {
343 len = 0;
344 redundancy_bytes = 0;
345 redundancy = false;
346 }
347 dec.shrink(len);
348 }
349 }
350 }
351
352 let end_band = toc.bandwidth().celt_end_band();
353 let start_band = if mode == Mode::Celt { 0 } else { 17 };
354 let mut redundant = core::mem::take(&mut self.redundant);
355 redundant.clear();
356 redundant.resize(f5 * self.channels, 0.0);
357
358 // A redundancy frame that precedes the main one is decoded first.
359 let mut redundant_rng = 0u32;
360 if redundancy && celt_to_silk {
361 let tail = &data[len..len + redundancy_bytes];
362 let mut rdec = RangeDecoder::new(tail);
363 self.celt
364 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
365 redundant_rng = rdec.range();
366 }
367
368 // --- CELT layer -----------------------------------------------------
369 if mode != Mode::Silk {
370 // A mode switch invalidates the MDCT overlap and energy history.
371 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
372 self.celt.reset();
373 }
374 self.celt.decode(
375 &mut dec,
376 out,
377 frame_48k.min(960),
378 start_band,
379 end_band,
380 stream_channels,
381 )?;
382 } else {
383 out.fill(0.0);
384 // Fade the CELT layer out when leaving hybrid, as the reference
385 // does, by decoding one silent 2.5 ms frame.
386 if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) {
387 let silence = [0xFFu8, 0xFF];
388 let mut sdec = RangeDecoder::new(&silence);
389 let mut tmp = vec![0.0f32; f2_5 * self.channels];
390 self.celt
391 .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?;
392 }
393 }
394
395 // Sum the two layers.
396 if self.debug_mute.0 {
397 out.fill(0.0);
398 }
399 if mode != Mode::Celt && !self.debug_mute.1 {
400 for (o, s) in out.iter_mut().zip(silk_pcm.iter()) {
401 *o += *s as f32 * (1.0 / 32768.0);
402 }
403 }
404
405 // A redundancy frame that follows the main one is cross-faded in.
406 if redundancy && !celt_to_silk {
407 self.celt.reset();
408 let tail = &data[len..len + redundancy_bytes];
409 let mut rdec = RangeDecoder::new(tail);
410 self.celt
411 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
412 redundant_rng = rdec.range();
413 let base = (frame_out - f2_5) * self.channels;
414 smooth_fade(
415 &mut out[base..],
416 &redundant[f2_5 * self.channels..],
417 f2_5,
418 self.channels,
419 &self.celt_window,
420 self.downsample,
421 );
422 }
423 if redundancy && celt_to_silk {
424 for c in 0..self.channels {
425 for i in 0..f2_5 {
426 out[self.channels * i + c] = redundant[self.channels * i + c];
427 }
428 }
429 // Then fade from the redundancy frame into the frame proper.
430 let split = f2_5 * self.channels;
431 for c in 0..self.channels {
432 for i in 0..f2_5 {
433 let w = {
434 let x = self.celt_window[i * self.downsample];
435 x * x
436 };
437 let idx = split + i * self.channels + c;
438 if idx < out.len() && idx < redundant.len() {
439 out[idx] = w * out[idx] + (1.0 - w) * redundant[idx];
440 }
441 }
442 }
443 }
444
445 self.prev_mode = Some(mode);
446 self.prev_redundancy = redundancy && !celt_to_silk;
447 self.silk_pcm = silk_pcm;
448 self.redundant = redundant;
449 Ok(dec.range() ^ redundant_rng)
450 }
451}
452
453/// Cross-fades `b` over `a` across `overlap` samples using the CELT window,
454/// the shape the reference uses for redundancy and mode transitions.
455fn smooth_fade(
456 a: &mut [f32],
457 b: &[f32],
458 overlap: usize,
459 channels: usize,
460 window: &[f32],
461 downsample: usize,
462) {
463 let inc = downsample;
464 for c in 0..channels {
465 for i in 0..overlap {
466 let w = window[i * inc] * window[i * inc];
467 let idx = i * channels + c;
468 if idx < a.len() && idx < b.len() {
469 a[idx] = w * b[idx] + (1.0 - w) * a[idx];
470 }
471 }
472 }
473}