forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdd00c7cTahinli3 months ago169 commits

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