Skip to main content

audio_codec/
opus.rs

1#[cfg(feature = "std")]
2use super::PcmBuf;
3use super::{CodecError, Decoder, Encoder, Sample};
4use crate::fade;
5#[cfg(test)]
6use crate::fade::RECOVER_MS;
7// `Box` lives in the std prelude; under `no_std` it comes from `alloc`.
8#[cfg(not(feature = "std"))]
9use alloc::boxed::Box;
10pub use opus_rs::Application as OpusApplication;
11use opus_rs::{Application, OpusDecoder as OpusDecoderRaw, OpusEncoder as OpusEncoderRaw};
12
13// Heap-free scratch-buffer caps (worst case: 48 kHz, stereo, 20 ms frame).
14const OPUS_MAX_FRAME: usize = 960; // 20 ms @ 48 kHz per channel
15const OPUS_MAX_CHANNELS: usize = 2;
16const OPUS_MAX_SAMPLES: usize = OPUS_MAX_FRAME * OPUS_MAX_CHANNELS; // 1920
17// RFC 6716: a single Opus packet carries at most 1276 bytes. Used by the
18// std-only `encode` helper's scratch packet buffer.
19#[cfg(feature = "std")]
20const OPUS_MAX_PACKET: usize = 1276;
21
22pub struct OpusDecoder {
23    decoder: Box<OpusDecoderRaw>,
24    sample_rate: u32,
25    channels: u16,
26    w_output_f32: [f32; OPUS_MAX_SAMPLES],
27    w_pcm_i16: [i16; OPUS_MAX_SAMPLES],
28    /// Opus's concealment carries on near the level of the audio before
29    /// the loss, so it's faded here (see [`crate::fade`]).
30    loss: fade::LossFade,
31}
32
33impl OpusDecoder {
34    /// Create a new Opus decoder instance
35    pub fn new(sample_rate: u32, channels: u16) -> Self {
36        let decoder = Box::new(
37            OpusDecoderRaw::new(sample_rate as i32, channels as usize)
38                .expect("Failed to create Opus decoder"),
39        );
40
41        Self {
42            decoder,
43            sample_rate,
44            channels,
45            w_output_f32: [0.0; OPUS_MAX_SAMPLES],
46            w_pcm_i16: [0; OPUS_MAX_SAMPLES],
47            loss: fade::LossFade::default(),
48        }
49    }
50
51    /// Create a default Opus decoder (48kHz, stereo)
52    pub fn new_default() -> Self {
53        Self::new(48000, 2)
54    }
55
56    /// Lower-level decode that does not perform the stereo→mono downmix.
57    /// Used internally by both the trait impl and the back-comat `decode`.
58    pub fn decode_into_raw(&mut self, data: &[u8], output: &mut [i16]) -> usize {
59        if data.is_empty() {
60            return 0;
61        }
62
63        // Detect the actual channel count from the Opus packet's TOC byte
64        // (bit 2 is the stereo flag per RFC 6716). opus-rs 0.1.19+ rejects
65        // decoding when the packet channel count doesn't match the decoder's,
66        // so we adapt the decoder here to avoid returning empty PCM.
67        let packet_channels = if data[0] & 0x04 != 0 { 2usize } else { 1 };
68        if self.channels as usize != packet_channels {
69            self.channels = packet_channels as u16;
70            // Reuse the existing heap allocation (see `clippy::replace_box`).
71            *self.decoder = OpusDecoderRaw::new(self.sample_rate as i32, packet_channels)
72                .expect("Failed to create Opus decoder");
73            self.loss.clear();
74        }
75
76        let channels = usize::from(self.channels);
77        let frame_size = (self.sample_rate as usize * 20) / 1000;
78        let max_samples = frame_size * channels;
79
80        match self
81            .decoder
82            .decode(data, frame_size, &mut self.w_output_f32[..max_samples])
83        {
84            Ok(len) => {
85                let total_samples = len * channels;
86                if total_samples == 0 {
87                    return 0;
88                }
89
90                for i in 0..total_samples {
91                    self.w_pcm_i16[i] =
92                        (self.w_output_f32[i] * 32768.0).clamp(-32768.0, 32767.0) as i16;
93                }
94
95                let n = total_samples.min(output.len());
96                output[..n].copy_from_slice(&self.w_pcm_i16[..n]);
97                // a DTX frame (the TOC byte alone) is the decoder's comfort
98                // noise, not the end of a loss
99                if data.len() > 1 {
100                    self.loss
101                        .end_loss(&mut output[..n], channels, self.sample_rate);
102                }
103                n
104            }
105            Err(_) => 0,
106        }
107    }
108}
109
110impl OpusDecoder {
111    /// Conceal a lost frame of `samples` samples per channel with Opus's own
112    /// packet loss concealment or, given `next`, rebuild it from the in-band
113    /// FEC of the packet after it; without the stereo→mono downmix.
114    fn conceal_into_raw(
115        &mut self,
116        next: Option<&[u8]>,
117        samples: usize,
118        out: &mut [Sample],
119    ) -> Result<usize, CodecError> {
120        let channels = usize::from(self.channels);
121        let total = samples * channels;
122        if total > OPUS_MAX_SAMPLES {
123            return Err(CodecError::InvalidInput);
124        }
125        if out.len() < total {
126            return Err(CodecError::BufferTooSmall);
127        }
128        let pcm = &mut self.w_output_f32[..total];
129        let len = match next {
130            Some(next) => self.decoder.decode_fec(next, samples, pcm),
131            // opus-rs conceals a packet of 0 or 1 bytes, as libopus does
132            // with `data == NULL`
133            None => self.decoder.decode(&[], samples, pcm),
134        }
135        .map_err(|_| CodecError::DecodeFailed)?;
136        let n = len * channels;
137        for (o, f) in out[..n].iter_mut().zip(&self.w_output_f32[..n]) {
138            *o = (f * 32768.0).clamp(-32768.0, 32767.0) as i16;
139        }
140        match next {
141            // rebuilt from the sender's own data: audio like a decoded
142            // packet's (where `next` carried no FEC, the frame is concealed
143            // at full level, as the first of a loss would be)
144            Some(_) => self
145                .loss
146                .end_loss(&mut out[..n], channels, self.sample_rate),
147            None => self.loss.fade(&mut out[..n], channels, self.sample_rate),
148        }
149        Ok(n)
150    }
151
152    /// `conceal_into_raw` with the stereo→mono downmix `decode` does.
153    #[cfg(feature = "std")]
154    fn conceal_downmixed(&mut self, next: Option<&[u8]>, samples: usize) -> PcmBuf {
155        let mut pcm = vec![0i16; samples * usize::from(self.channels)];
156        match self.conceal_into_raw(next, samples, &mut pcm) {
157            Ok(n) => pcm.truncate(n),
158            Err(_) => return Vec::new(),
159        }
160        if usize::from(self.channels) == 2 {
161            pcm = pcm
162                .chunks_exact(2)
163                .map(|chunk| ((chunk[0] as i32 + chunk[1] as i32) / 2) as i16)
164                .collect();
165        }
166        pcm
167    }
168}
169
170impl Decoder for OpusDecoder {
171    /// Opus's concealment is part of the decoder: always on.
172    fn enable_concealment(&mut self) -> bool {
173        true
174    }
175
176    /// Conceals with Opus's own packet loss concealment, faded through a
177    /// long loss as G.711 and G.722's is: full level for 10 ms, silence at
178    /// 60 ms. `samples` must be an Opus frame size (a multiple of 2.5 ms, at
179    /// most 20 ms); others fail with `DecodeFailed`.
180    fn conceal_into(&mut self, samples: usize, out: &mut [Sample]) -> Result<usize, CodecError> {
181        self.conceal_into_raw(None, samples, out)
182    }
183
184    /// Override the default to downmix stereo to mono, as `decode` does.
185    #[cfg(feature = "std")]
186    fn conceal(&mut self, samples: usize) -> PcmBuf {
187        self.conceal_downmixed(None, samples)
188    }
189
190    /// Rebuilds the lost frame from `next`'s in-band FEC (libopus's
191    /// `decode_fec`), concealing what it doesn't cover. `samples` as for
192    /// `conceal_into`.
193    fn recover_into(
194        &mut self,
195        next: &[u8],
196        samples: usize,
197        out: &mut [Sample],
198    ) -> Result<usize, CodecError> {
199        self.conceal_into_raw(Some(next), samples, out)
200    }
201
202    /// Override the default to downmix stereo to mono, as `decode` does.
203    #[cfg(feature = "std")]
204    fn recover(&mut self, next: &[u8], samples: usize) -> PcmBuf {
205        self.conceal_downmixed(Some(next), samples)
206    }
207
208    fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
209        if data.is_empty() {
210            return Ok(0);
211        }
212        let n = self.decode_into_raw(data, out);
213        if n == 0 {
214            Err(CodecError::DecodeFailed)
215        } else {
216            Ok(n)
217        }
218    }
219
220    fn max_decode_samples(&self, n_bytes: usize) -> usize {
221        // One 20ms frame per packet is the typical case; size for stereo
222        // to cover the worst case (caller may downmix afterwards).
223        let frame_size = (self.sample_rate as usize * 20) / 1000;
224        let _ = n_bytes;
225        frame_size * 2
226    }
227
228    fn sample_rate(&self) -> u32 {
229        self.sample_rate
230    }
231
232    fn channels(&self) -> u16 {
233        self.channels
234    }
235
236    /// Override the default to preserve back-comat stereo→mono downmix
237    /// when the decoder was configured with `channels == 2`.
238    #[cfg(feature = "std")]
239    fn decode(&mut self, data: &[u8]) -> PcmBuf {
240        if data.is_empty() {
241            return Vec::new();
242        }
243        let packet_channels = if data[0] & 0x04 != 0 { 2usize } else { 1 };
244
245        let frame_size = (self.sample_rate as usize * 20) / 1000;
246        let max_samples = frame_size * packet_channels;
247        let mut pcm = vec![0i16; max_samples];
248        let n = self.decode_into_raw(data, &mut pcm);
249        pcm.truncate(n);
250        if usize::from(self.channels) == 2 {
251            pcm = pcm
252                .chunks_exact(2)
253                .map(|chunk| ((chunk[0] as i32 + chunk[1] as i32) / 2) as i16)
254                .collect();
255        }
256        pcm
257    }
258}
259
260pub struct OpusEncoder {
261    encoder: Box<OpusEncoderRaw>,
262    sample_rate: u32,
263    channels: u16,
264    w_input_f32: [f32; OPUS_MAX_SAMPLES],
265}
266
267impl OpusEncoder {
268    pub fn new_with_application(sample_rate: u32, channels: u16, application: Application) -> Self {
269        let encoder = Box::new(
270            OpusEncoderRaw::new(sample_rate as i32, channels as usize, application)
271                .expect("Failed to create Opus encoder"),
272        );
273
274        Self {
275            encoder,
276            sample_rate,
277            channels,
278            w_input_f32: [0.0; OPUS_MAX_SAMPLES],
279        }
280    }
281
282    /// Create a new Opus encoder instance.
283    ///
284    /// Keep backward-compatible defaults with pre-0.3.31 behavior:
285    /// - VoIP application
286    /// - caller can provide mono PCM even when encoder is configured as stereo;
287    ///   `encode()` duplicates mono samples to stereo.
288    pub fn new(sample_rate: u32, channels: u16) -> Self {
289        let mut enc = Self::new_with_application(sample_rate, channels, Application::Voip);
290        enc.encoder.bitrate_bps = if channels == 2 { 64000 } else { 48000 };
291        enc.encoder.complexity = 5;
292        enc.encoder.use_cbr = true;
293        enc
294    }
295
296    /// Create a default Opus encoder (48kHz, stereo)
297    pub fn new_default() -> Self {
298        Self::new(48000, 2)
299    }
300
301    /// Set the encoder bitrate in bits per second.
302    pub fn set_bitrate(&mut self, bitrate_bps: i32) {
303        self.encoder.bitrate_bps = bitrate_bps;
304    }
305
306    /// Set the encoder complexity (0-10).
307    pub fn set_complexity(&mut self, complexity: i32) {
308        self.encoder.complexity = complexity;
309    }
310
311    /// Enable or disable constant bitrate (CBR) mode.
312    pub fn set_cbr(&mut self, cbr: bool) {
313        self.encoder.use_cbr = cbr;
314    }
315
316    /// Enable or disable in-band FEC: SILK frames also carry a low-bitrate
317    /// copy of the previous frame, which a decoder can rebuild a lost packet
318    /// from (`Decoder::recover_into`). Only coded when the expected packet
319    /// loss (`set_packet_loss_perc`) is above zero and the bitrate leaves
320    /// room for it (e.g. 32 kb/s for wideband speech).
321    pub fn set_inband_fec(&mut self, enabled: bool) {
322        self.encoder.use_inband_fec = enabled;
323    }
324
325    /// Set the packet loss the encoder expects, in percent (0-100). It
326    /// trades bitrate for robustness, and gates in-band FEC.
327    pub fn set_packet_loss_perc(&mut self, percent: i32) {
328        self.encoder.packet_loss_perc = percent.clamp(0, 100);
329    }
330
331    /// Encode into a caller-provided packet buffer.
332    ///
333    /// Returns `Some(bytes_written)` on success. Expects `samples` to match
334    /// the encoder's channel count (interleaved stereo when `channels == 2`).
335    pub fn encode_into_raw(&mut self, samples: &[Sample], output: &mut [u8]) -> Option<usize> {
336        let channels = usize::from(self.channels);
337        if samples.is_empty() || channels == 0 || !samples.len().is_multiple_of(channels) {
338            return None;
339        }
340        // Fixed scratch cap (heap-free build).
341        if samples.len() > OPUS_MAX_SAMPLES {
342            return None;
343        }
344
345        let frame_size = samples.len() / channels;
346
347        for (dst, &s) in self.w_input_f32[..samples.len()]
348            .iter_mut()
349            .zip(samples.iter())
350        {
351            *dst = s as f32 / 32768.0;
352        }
353
354        self.encoder
355            .encode(&self.w_input_f32[..samples.len()], frame_size, output)
356            .ok()
357    }
358
359    #[cfg(feature = "std")]
360    fn encode_raw(&mut self, samples: &[Sample]) -> Vec<u8> {
361        let channels = usize::from(self.channels);
362        if samples.is_empty()
363            || channels == 0
364            || !samples.len().is_multiple_of(channels)
365            || samples.len() > OPUS_MAX_SAMPLES
366        {
367            return Vec::new();
368        }
369
370        let frame_size = samples.len() / channels;
371
372        for (dst, &s) in self.w_input_f32[..samples.len()]
373            .iter_mut()
374            .zip(samples.iter())
375        {
376            *dst = s as f32 / 32768.0;
377        }
378
379        let mut packet = [0u8; OPUS_MAX_PACKET];
380        match self
381            .encoder
382            .encode(&self.w_input_f32[..samples.len()], frame_size, &mut packet)
383        {
384            Ok(len) => packet[..len].to_vec(),
385            Err(_) => Vec::new(),
386        }
387    }
388}
389
390impl Encoder for OpusEncoder {
391    fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
392        if samples.is_empty() {
393            return Ok(0);
394        }
395        // Note: this expects `samples` to already match the encoder's channel
396        // count (interleaved stereo if `channels == 2`). For the legacy
397        // mono→stereo upmix behavior, use the std-only `encode` method.
398        match self.encode_into_raw(samples, out) {
399            Some(n) => Ok(n),
400            None => Err(CodecError::EncodeFailed),
401        }
402    }
403
404    fn max_encode_bytes(&self, _n_samples: usize) -> usize {
405        // Per RFC 6716 the maximum Opus packet size is 1275 bytes.
406        1275
407    }
408
409    fn sample_rate(&self) -> u32 {
410        self.sample_rate
411    }
412
413    fn channels(&self) -> u16 {
414        self.channels
415    }
416
417    /// Override the default to preserve back-comat mono→stereo upmix
418    /// when the encoder was configured with `channels == 2`.
419    #[cfg(feature = "std")]
420    fn encode(&mut self, samples: &[Sample]) -> Vec<u8> {
421        if self.channels == 2 {
422            // mono→stereo upmix into a local scratch buffer (no allocation).
423            if samples.len() > OPUS_MAX_FRAME {
424                return Vec::new();
425            }
426            let mut stereo = [0i16; OPUS_MAX_SAMPLES];
427            for (i, &sample) in samples.iter().enumerate() {
428                stereo[2 * i] = sample;
429                stereo[2 * i + 1] = sample;
430            }
431            return self.encode_raw(&stereo[..samples.len() * 2]);
432        }
433        self.encode_raw(samples)
434    }
435}
436
437// The tests below exercise the std-only allocating `encode`/`decode`
438// conveniences (including the stereo-downmix handling), so they only compile
439// with `std`. The `*_into` trait API is covered portably by
440// `test_opus_into_roundtrip` at the bottom, which also runs in `no_std`.
441#[cfg(all(test, feature = "std"))]
442mod tests {
443    use super::*;
444
445    fn make_mono_pcm_20ms() -> Vec<i16> {
446        (0..960).map(|i| ((i * 100) % 32767) as i16).collect()
447    }
448
449    /// 20 ms frames of a continuous 220 Hz tone at 48 kHz.
450    fn tone_frame(frame: usize) -> Vec<i16> {
451        (0..960)
452            .map(|i| {
453                let t = (frame * 960 + i) as f32 / 48000.0;
454                (8000.0 * (2.0 * core::f32::consts::PI * 220.0 * t).sin()) as i16
455            })
456            .collect()
457    }
458
459    fn rms(s: &[i16]) -> f64 {
460        (s.iter().map(|x| (*x as f64).powi(2)).sum::<f64>() / s.len() as f64).sqrt()
461    }
462
463    #[test]
464    fn test_opus_conceals_a_lost_frame_with_its_own_plc() {
465        let mut enc = OpusEncoder::new_default();
466        let mut dec = OpusDecoder::new_default();
467        for f in 0..10 {
468            dec.decode(&enc.encode(&tone_frame(f)));
469        }
470        // frame 10 is lost
471        let concealed = dec.conceal(960);
472        assert_eq!(concealed.len(), 960, "downmixed like decode");
473        assert!(
474            rms(&concealed) > 1000.0,
475            "concealment is silent: rms {}",
476            rms(&concealed)
477        );
478        // the stream carries on after the loss
479        enc.encode(&tone_frame(10));
480        let next = dec.decode(&enc.encode(&tone_frame(11)));
481        assert_eq!(next.len(), 960);
482        assert!(rms(&next) > 1000.0);
483    }
484
485    /// Voiced, speech-like 48 kHz mono: 8 harmonics of a pitch gliding
486    /// 120 → 180 Hz under a slow envelope.
487    fn voice(frames: usize) -> Vec<Vec<i16>> {
488        let mut phase = 0f32;
489        let pcm: Vec<i16> = (0..frames * 960)
490            .map(|i| {
491                let t = i as f32 / 48000.0;
492                let f0 = 120.0 + 60.0 * (t / 0.6).min(1.0);
493                phase += 2.0 * core::f32::consts::PI * f0 / 48000.0;
494                let env = 0.6 + 0.4 * (2.0 * core::f32::consts::PI * 2.0 * t).sin();
495                let v: f32 = (1..=8).map(|k| (k as f32 * phase).sin() / k as f32).sum();
496                (6000.0 * env * v) as i16
497            })
498            .collect();
499        pcm.chunks(960).map(<[i16]>::to_vec).collect()
500    }
501
502    #[test]
503    fn test_opus_recovers_a_lost_frame_from_inband_fec() {
504        // speech at 32 kb/s (SILK or Hybrid), told to expect loss so it codes
505        // FEC; at 16 kb/s fullband Hybrid it codes none
506        let mut enc = OpusEncoder::new(48000, 1);
507        enc.set_bitrate(32000);
508        enc.set_inband_fec(true);
509        enc.set_packet_loss_perc(20);
510        let packets: Vec<Vec<u8>> = voice(40).iter().map(|f| enc.encode(f)).collect();
511        // SILK or Hybrid: FEC lives in the SILK layer (TOC configs 0-15)
512        let has_silk = |p: &[u8]| p[0] >> 3 < 16;
513        assert!(packets.iter().all(|p| has_silk(p)), "coded without SILK");
514
515        let mut reference = OpusDecoder::new(48000, 1);
516        let clean: Vec<Vec<i16>> = packets.iter().map(|p| reference.decode(p)).collect();
517        let error_db = |out: &[i16], clean: &[i16]| {
518            let err: f64 = out
519                .iter()
520                .zip(clean)
521                .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
522                .sum();
523            let sig: f64 = clean.iter().map(|b| (*b as f64).powi(2)).sum();
524            10.0 * (err / sig).log10()
525        };
526        let (mut recovered_db, mut concealed_db) = (0f64, 0f64);
527        let losses = [10, 17, 23, 31];
528        for &lost in &losses {
529            let mut recovering = OpusDecoder::new(48000, 1);
530            let mut concealing = OpusDecoder::new(48000, 1);
531            for p in &packets[..lost] {
532                recovering.decode(p);
533                concealing.decode(p);
534            }
535            let recovered = recovering.recover(&packets[lost + 1], 960);
536            let concealed = concealing.conceal(960);
537            assert_eq!(recovered.len(), 960);
538            recovered_db += error_db(&recovered, &clean[lost]);
539            concealed_db += error_db(&concealed, &clean[lost]);
540            // `next` is not consumed: it decodes as usual afterwards
541            assert_eq!(recovering.decode(&packets[lost + 1]).len(), 960);
542        }
543        let n = losses.len() as f64;
544        let (recovered_db, concealed_db) = (recovered_db / n, concealed_db / n);
545        println!(
546            "lost frame error: recovered {recovered_db:.1} dB, concealed {concealed_db:.1} dB"
547        );
548        // measured: recovered -11.7 dB, concealed -5.0 dB
549        assert!(
550            recovered_db < concealed_db - 4.0,
551            "FEC no better than concealment: {recovered_db:.1} vs {concealed_db:.1} dB"
552        );
553    }
554
555    #[test]
556    fn test_opus_concealment_fades_through_a_long_loss() {
557        let mut enc = OpusEncoder::new(48000, 1);
558        let packets: Vec<Vec<u8>> = voice(12).iter().map(|f| enc.encode(f)).collect();
559        let mut dec = OpusDecoder::new(48000, 1);
560        for p in &packets[..10] {
561            dec.decode(p);
562        }
563        let levels: Vec<f64> = (0..5).map(|_| rms(&dec.conceal(960))).collect();
564        // full for 10 ms, then 20% per 10 ms: silent from 60 ms
565        assert!(
566            levels[0] > 500.0,
567            "first frame of a loss is audible: {levels:?}"
568        );
569        assert!(
570            levels[1] < levels[0] && levels[2] < levels[1],
571            "not fading: {levels:?}"
572        );
573        assert_eq!(levels[3..], [0.0, 0.0], "not silent from 60 ms: {levels:?}");
574    }
575
576    #[test]
577    fn test_opus_decoding_after_a_faded_loss_ramps_in() {
578        let mut enc = OpusEncoder::new(48000, 1);
579        let packets: Vec<Vec<u8>> = voice(12).iter().map(|f| enc.encode(f)).collect();
580        let mut dec = OpusDecoder::new(48000, 1);
581        // opus-rs on its own, given the same calls
582        let mut raw = OpusDecoderRaw::new(48000, 1).unwrap();
583        let mut raw_out = [0f32; 960];
584        for p in &packets[..10] {
585            dec.decode(p);
586            raw.decode(p, 960, &mut raw_out).unwrap();
587        }
588        for _ in 0..5 {
589            dec.conceal(960);
590            raw.decode(&[], 960, &mut raw_out).unwrap();
591        }
592        let resumed = dec.decode(&packets[10]);
593        raw.decode(&packets[10], 960, &mut raw_out).unwrap();
594        let expected: Vec<i16> = raw_out
595            .iter()
596            .map(|f| (f * 32768.0).clamp(-32768.0, 32767.0) as i16)
597            .collect();
598        // from silence over 4 ms, then as decoded
599        let ramp = 48000 * RECOVER_MS as usize / 1000;
600        assert!(resumed[0].unsigned_abs() <= expected[0].unsigned_abs() / 100 + 1);
601        assert_eq!(resumed[ramp..], expected[ramp..]);
602        // the loss is over: the next one starts at full level
603        dec.conceal(960);
604        assert_eq!(dec.loss.concealed(), 960);
605    }
606
607    #[test]
608    fn test_opus_recover_without_fec_conceals() {
609        let mut enc = OpusEncoder::new(48000, 1);
610        let packets: Vec<Vec<u8>> = voice(12).iter().map(|f| enc.encode(f)).collect();
611        let mut dec = OpusDecoder::new(48000, 1);
612        for p in &packets[..10] {
613            dec.decode(p);
614        }
615        // no FEC coded: the lost frame is concealed, still audible
616        let recovered = dec.recover(&packets[11], 960);
617        assert_eq!(recovered.len(), 960);
618        assert!(rms(&recovered) > 500.0, "rms {}", rms(&recovered));
619    }
620
621    #[test]
622    fn test_opus_conceal_into_is_interleaved_and_checks_the_buffer() {
623        let mut enc = OpusEncoder::new_default();
624        let mut dec = OpusDecoder::new_default();
625        dec.decode(&enc.encode(&tone_frame(0)));
626        let mut out = [0i16; 1920];
627        // stereo decoder: 960 samples per channel, interleaved
628        assert_eq!(dec.conceal_into(960, &mut out), Ok(1920));
629        let mut small = [0i16; 100];
630        assert_eq!(
631            dec.conceal_into(960, &mut small),
632            Err(CodecError::BufferTooSmall)
633        );
634    }
635
636    #[test]
637    fn test_opus_encode_decode_20ms_produces_960_mono_samples() {
638        let mut enc = OpusEncoder::new_default();
639        let pcm = make_mono_pcm_20ms();
640        let opus_pkt = enc.encode(&pcm);
641        assert!(!opus_pkt.is_empty(), "encoder should produce output");
642
643        // TOC byte bit 2 should be set (stereo flag from mono→stereo upmix)
644        assert!(opus_pkt[0] & 0x04 != 0, "packet should be stereo");
645
646        let mut dec = OpusDecoder::new_default();
647        let decoded = dec.decode(&opus_pkt);
648
649        // 20ms at 48kHz mono = 960 samples
650        assert_eq!(
651            decoded.len(),
652            960,
653            "decoder should downmix stereo→mono and output 960 samples, got {}",
654            decoded.len()
655        );
656    }
657
658    #[test]
659    fn test_opus_consecutive_frames_all_produce_960() {
660        let mut enc = OpusEncoder::new_default();
661        let pcm = make_mono_pcm_20ms();
662        let opus_pkt = enc.encode(&pcm);
663
664        let mut dec = OpusDecoder::new_default();
665        for i in 0..5 {
666            let decoded = dec.decode(&opus_pkt);
667            assert_eq!(
668                decoded.len(),
669                960,
670                "frame {} should produce 960 mono samples, got {}",
671                i,
672                decoded.len()
673            );
674        }
675    }
676
677    #[test]
678    fn test_opus_decoder_output_has_reasonable_energy() {
679        let mut enc = OpusEncoder::new_default();
680        // 440Hz sine at 48kHz, 20ms
681        let pcm: Vec<i16> = (0..960)
682            .map(|i| {
683                let t = i as f64 / 48000.0;
684                (16384.0 * (2.0 * std::f64::consts::PI * 440.0 * t).sin()) as i16
685            })
686            .collect();
687        let opus_pkt = enc.encode(&pcm);
688
689        let mut dec = OpusDecoder::new_default();
690        let decoded = dec.decode(&opus_pkt);
691        assert_eq!(decoded.len(), 960);
692
693        let energy: f64 =
694            decoded.iter().map(|&s| (s as f64).powi(2)).sum::<f64>() / decoded.len() as f64;
695        let rms = energy.sqrt();
696        assert!(
697            rms > 100.0 && rms < 20000.0,
698            "decoded audio RMS {} should be in reasonable range",
699            rms
700        );
701    }
702
703    #[test]
704    fn test_opus_decoder_handles_mono_packet_gracefully() {
705        // Create a mono Opus encoder, encode PCM → mono Opus packet
706        let mut mono_enc = OpusEncoder::new(48000, 1);
707        let pcm = make_mono_pcm_20ms();
708        let mono_pkt = mono_enc.encode(&pcm);
709        assert!(!mono_pkt.is_empty());
710        // Mono packet TOC bit 2 should be 0
711        assert!(
712            mono_pkt[0] & 0x04 == 0,
713            "mono encoder should produce mono packet"
714        );
715
716        // Decode with default stereo decoder — should handle mono→stereo transition
717        let mut dec = OpusDecoder::new_default();
718        let decoded = dec.decode(&mono_pkt);
719        assert_eq!(
720            decoded.len(),
721            960,
722            "first mono packet should produce exactly 960 mono samples, got {}",
723            decoded.len()
724        );
725
726        // Second mono packet should also be 960
727        let decoded2 = dec.decode(&mono_pkt);
728        assert_eq!(
729            decoded2.len(),
730            960,
731            "second mono packet should also produce 960 mono samples, got {}",
732            decoded2.len()
733        );
734    }
735
736    #[test]
737    fn test_opus_stereo_packet_downmix_produces_960() {
738        let mut enc = OpusEncoder::new_default();
739        let pcm = make_mono_pcm_20ms();
740        let stereo_pkt = enc.encode(&pcm);
741        assert!(stereo_pkt[0] & 0x04 != 0);
742
743        let mut dec = OpusDecoder::new_default();
744        let decoded = dec.decode(&stereo_pkt);
745        assert_eq!(
746            decoded.len(),
747            960,
748            "stereo packet should downmix to 960 mono samples"
749        );
750    }
751}
752
753/// Portable roundtrip through the trait `encode_into`/`decode_into` API
754/// (compiles with or without `std`; the no_std opus path).
755#[cfg(all(test, feature = "opus"))]
756mod no_std_tests {
757    use super::*;
758    use alloc::vec::Vec;
759
760    #[test]
761    fn test_opus_into_roundtrip() {
762        let mut enc = OpusEncoder::new_default();
763        let mut dec = OpusDecoder::new(48000, 1);
764        let pcm: Vec<i16> = (0..960).map(|i| ((i * 100) % 32767) as i16).collect();
765
766        let mut packet = alloc::vec![0u8; enc.max_encode_bytes(pcm.len())];
767        let n = enc
768            .encode_into(&pcm, &mut packet)
769            .expect("packet sized by max_encode_bytes");
770        packet.truncate(n);
771        assert!(!packet.is_empty(), "encoder should produce output");
772
773        let mut out = alloc::vec![0i16; dec.max_decode_samples(packet.len())];
774        let samples = dec
775            .decode_into(&packet, &mut out)
776            .expect("out sized by max_decode_samples");
777        assert_eq!(samples, 960, "20 ms at 48 kHz must decode to 960 samples");
778        let rms: f64 = out[..samples]
779            .iter()
780            .map(|&s| (s as f64) * (s as f64))
781            .sum::<f64>()
782            / samples as f64;
783        assert!(rms.sqrt() > 1000.0, "decoded signal should keep energy");
784    }
785}