forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeee0a69Tahinli3 months ago415 commits

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