Skip to main content

active_call/media/track/
track_codec.rs

1use crate::{media::AudioFrame, media::PcmBuf, media::Samples};
2use audio_codec::{
3    BoxedResampler, CodecType, Decoder, Encoder, bytes_to_samples,
4    g722::{G722Decoder, G722Encoder},
5    pcma::{PcmaDecoder, PcmaEncoder},
6    pcmu::{PcmuDecoder, PcmuEncoder},
7    samples_to_bytes,
8};
9use std::collections::HashMap;
10use std::sync::{Arc, RwLock};
11use std::time::Duration;
12use tracing::warn;
13
14use audio_codec::g729::{G729Decoder, G729Encoder};
15use audio_codec::opus::{OpusDecoder, OpusEncoder};
16
17/// Opus bitrate when the receiver sets no lower `maxaveragebitrate`: speech
18/// to fullband, with room for in-band FEC.
19const OPUS_BITRATE: u32 = 64000;
20
21/// The packet loss to tell the Opus encoder to expect, from the receiver's
22/// reports of the loss it sees (RTCP `fraction lost`), as libwebrtc does:
23/// smoothed over ~10 s, then snapped to 0, 1, 5, 10 or 20% with hysteresis
24/// so it doesn't flip the encoder on every report. It sets how robust the
25/// encoding is, and gates in-band FEC: none is coded at 0%, and at 32 kbit/s
26/// none up to 5%.
27#[derive(Debug, Default)]
28pub struct OpusLossEstimate {
29    smoothed: Option<f32>,
30    level: f32,
31}
32
33impl OpusLossEstimate {
34    /// libwebrtc's smoothing, per millisecond
35    const ALPHA_PER_MS: f32 = 0.9999;
36
37    /// Takes the loss reported (0-1) over `elapsed`; returns the loss for
38    /// the encoder, in percent.
39    pub fn update(&mut self, fraction_lost: f32, elapsed: Duration) -> i32 {
40        let fraction_lost = fraction_lost.clamp(0.0, 1.0);
41        let smoothed = match self.smoothed {
42            Some(smoothed) => {
43                let alpha = Self::ALPHA_PER_MS.powf(elapsed.as_millis() as f32);
44                alpha * smoothed + (1.0 - alpha) * fraction_lost
45            }
46            None => fraction_lost,
47        };
48        self.smoothed = Some(smoothed);
49        self.level = Self::level(smoothed, self.level);
50        (self.level * 100.0).round() as i32
51    }
52
53    /// libwebrtc's `OptimizePacketLossRate`: a level is entered past its
54    /// value plus a margin, and left below its value minus it.
55    fn level(loss: f32, level: f32) -> f32 {
56        let past =
57            |rate: f32, margin: f32| loss >= rate + if rate > level { margin } else { -margin };
58        if past(0.20, 0.02) {
59            0.20
60        } else if past(0.10, 0.01) {
61            0.10
62        } else if past(0.05, 0.01) {
63            0.05
64        } else if loss >= 0.01 {
65            0.01
66        } else {
67            0.0
68        }
69    }
70}
71
72/// How to encode Opus for a receiver, from the `a=fmtp` of its description
73/// (RFC 7587 6.1). Always mono: `stereo=1` is only a preference, and the
74/// audio sent is mono.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct OpusParams {
77    /// Highest audio rate the receiver will play, in Hz.
78    pub max_playback_rate: u32,
79    /// Highest average bitrate the receiver takes, in bit/s.
80    pub max_average_bitrate: Option<u32>,
81    /// The receiver decodes in-band FEC.
82    pub inband_fec: bool,
83}
84
85impl Default for OpusParams {
86    fn default() -> Self {
87        Self {
88            max_playback_rate: 48000,
89            max_average_bitrate: None,
90            inband_fec: false,
91        }
92    }
93}
94
95impl OpusParams {
96    /// Parameters from `a=fmtp` (without its `<pt> ` prefix); unknown or
97    /// malformed ones are left at their defaults.
98    pub fn from_fmtp(fmtp: &str) -> Self {
99        let mut params = Self::default();
100        for (key, value) in fmtp
101            .split(';')
102            .filter_map(|p| p.split_once('='))
103            .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim()))
104        {
105            match key.as_str() {
106                "maxplaybackrate" => {
107                    if let Ok(rate) = value.parse() {
108                        params.max_playback_rate = rate;
109                    }
110                }
111                "maxaveragebitrate" => params.max_average_bitrate = value.parse().ok(),
112                "useinbandfec" => params.inband_fec = value == "1",
113                _ => {}
114            }
115        }
116        params
117    }
118
119    /// Encoder input rate: the highest Opus rate the receiver plays, which
120    /// also caps the audio bandwidth coded.
121    pub fn sample_rate(&self) -> u32 {
122        [48000, 24000, 16000, 12000]
123            .into_iter()
124            .find(|r| *r <= self.max_playback_rate)
125            .unwrap_or(8000)
126    }
127
128    pub fn bitrate(&self) -> u32 {
129        // 6-510 kbit/s is what Opus codes
130        self.max_average_bitrate
131            .map_or(OPUS_BITRATE, |max| max.min(OPUS_BITRATE))
132            .clamp(6000, 510_000)
133    }
134
135    fn encoder(&self, packet_loss_perc: i32) -> OpusEncoder {
136        let mut encoder = OpusEncoder::new(self.sample_rate(), 1);
137        encoder.set_bitrate(self.bitrate() as i32);
138        encoder.set_inband_fec(self.inband_fec);
139        encoder.set_packet_loss_perc(packet_loss_perc);
140        encoder
141    }
142}
143
144/// Convert an audio duration to RTP clock ticks.
145pub fn duration_to_rtp_ticks(duration: Duration, clock_rate: u32) -> u32 {
146    (duration.as_nanos() * clock_rate as u128 / 1_000_000_000) as u32
147}
148
149pub struct TrackCodec {
150    pcmu_encoder: PcmuEncoder,
151    pcmu_decoder: PcmuDecoder,
152    pcma_encoder: PcmaEncoder,
153    pcma_decoder: PcmaDecoder,
154
155    g722_encoder: Option<Box<G722Encoder>>,
156    g722_decoder: Option<Box<G722Decoder>>,
157
158    g729_encoder: Option<Box<G729Encoder>>,
159    g729_decoder: Option<Box<G729Decoder>>,
160
161    opus_encoder: Option<OpusEncoder>,
162    /// What the receiver takes, for `opus_encoder`.
163    opus_params: OpusParams,
164    /// Packet loss `opus_encoder` expects, in percent.
165    opus_packet_loss: i32,
166    opus_decoder: Option<OpusDecoder>,
167
168    resampler: Option<BoxedResampler>,
169    resampler_in_rate: u32,
170    resampler_out_rate: u32,
171    pub payload_type_map: Arc<RwLock<HashMap<u8, CodecType>>>,
172    /// Decoders conceal lost packets (see `conceal`); off by default, as it
173    /// costs a history copy per decoded packet for G.711 and G.722.
174    concealment: bool,
175    /// Payload type of the last packet decoded, whose decoder conceals.
176    last_payload_type: Option<u8>,
177}
178
179/// The codec for an RTP payload type in a payload type map (as shared by
180/// [`TrackCodec::payload_type_map`]), falling back to the static payload
181/// type registry.
182pub fn codec_for_pt(map: &RwLock<HashMap<u8, CodecType>>, pt: u8) -> Option<CodecType> {
183    map.read()
184        .unwrap()
185        .get(&pt)
186        .cloned()
187        .or_else(|| CodecType::try_from(pt).ok())
188}
189
190impl Clone for TrackCodec {
191    fn clone(&self) -> Self {
192        let mut new = Self::new();
193        // Share the same underlying map so reinvite PT updates are visible to all clones.
194        new.payload_type_map = Arc::clone(&self.payload_type_map);
195        new.opus_params = self.opus_params;
196        if self.concealment {
197            new.enable_concealment();
198        }
199        new
200    }
201}
202
203impl TrackCodec {
204    pub fn new() -> Self {
205        let mut map = HashMap::new();
206        map.insert(0, CodecType::PCMU);
207        map.insert(8, CodecType::PCMA);
208        map.insert(9, CodecType::G722);
209        map.insert(18, CodecType::G729);
210        map.insert(101, CodecType::TelephoneEvent);
211        map.insert(111, CodecType::Opus);
212        let payload_type_map = Arc::new(RwLock::new(map));
213
214        Self {
215            pcmu_encoder: PcmuEncoder::new(),
216            pcmu_decoder: PcmuDecoder::new(),
217            pcma_encoder: PcmaEncoder::new(),
218            pcma_decoder: PcmaDecoder::new(),
219            g722_encoder: None,
220            g722_decoder: None,
221            g729_encoder: None,
222            g729_decoder: None,
223            opus_encoder: None,
224            opus_params: OpusParams::default(),
225            opus_packet_loss: 0,
226            opus_decoder: None,
227            resampler: None,
228            resampler_in_rate: 0,
229            resampler_out_rate: 0,
230            payload_type_map,
231            concealment: false,
232            last_payload_type: None,
233        }
234    }
235
236    /// Have the decoders conceal lost packets, for [`Self::conceal`].
237    pub fn enable_concealment(&mut self) {
238        self.concealment = true;
239        self.pcmu_decoder.enable_concealment();
240        self.pcma_decoder.enable_concealment();
241        for decoder in [
242            self.g722_decoder
243                .as_deref_mut()
244                .map(|d| d as &mut dyn Decoder),
245            self.g729_decoder
246                .as_deref_mut()
247                .map(|d| d as &mut dyn Decoder),
248            self.opus_decoder.as_mut().map(|d| d as &mut dyn Decoder),
249        ]
250        .into_iter()
251        .flatten()
252        {
253            decoder.enable_concealment();
254        }
255    }
256
257    fn codec_for_pt(&self, payload_type: u8) -> CodecType {
258        self.payload_type_map
259            .read()
260            .unwrap()
261            .get(&payload_type)
262            .cloned()
263            .unwrap_or_else(|| match payload_type {
264                0 => CodecType::PCMU,
265                8 => CodecType::PCMA,
266                9 => CodecType::G722,
267                18 => CodecType::G729,
268                111 => CodecType::Opus,
269                _ => CodecType::PCMU,
270            })
271    }
272
273    /// The decoder for an audio codec, created on first use.
274    fn decoder(&mut self, codec: CodecType) -> Option<&mut dyn Decoder> {
275        let concealment = self.concealment;
276        let decoder: &mut dyn Decoder = match codec {
277            CodecType::PCMU => &mut self.pcmu_decoder,
278            CodecType::PCMA => &mut self.pcma_decoder,
279            CodecType::G722 => self
280                .g722_decoder
281                .get_or_insert_with(|| {
282                    let mut d = Box::new(G722Decoder::new());
283                    if concealment {
284                        d.enable_concealment();
285                    }
286                    d
287                })
288                .as_mut(),
289            CodecType::G729 => self
290                .g729_decoder
291                .get_or_insert_with(|| {
292                    let mut d = Box::new(G729Decoder::new());
293                    if concealment {
294                        d.enable_concealment();
295                    }
296                    d
297                })
298                .as_mut(),
299            CodecType::Opus => self.opus_decoder.get_or_insert_with(|| {
300                let mut d = OpusDecoder::new_default();
301                if concealment {
302                    d.enable_concealment();
303                }
304                d
305            }),
306            _ => return None,
307        };
308        Some(decoder)
309    }
310
311    /// Native `(sample_rate, channels)` of decoded audio, given the decoded
312    /// sample count for Opus, whose channel count follows the packets.
313    fn native_format(codec: CodecType, samples: usize) -> (u32, u16) {
314        match codec {
315            CodecType::PCMU | CodecType::PCMA | CodecType::G729 => (8000, 1),
316            CodecType::G722 => (16000, 1),
317            CodecType::Opus if samples >= 1920 => (48000, 2),
318            CodecType::Opus => (48000, 1),
319            _ => (8000, 1),
320        }
321    }
322
323    /// Audio for one lost packet of `ptime`, from the decoder of the last
324    /// packet decoded, as `(native_sample_rate, channels, samples)` like
325    /// [`Self::decode`], and whether `next` was used. With `next`, the
326    /// payload type and payload of the packet right after the loss, Opus
327    /// rebuilds the lost one from its in-band FEC (where the sender coded
328    /// any, else it conceals); other codecs conceal. `None` when concealment
329    /// is off, nothing was decoded yet, or the codec has no concealment.
330    pub fn conceal(
331        &mut self,
332        ptime: Duration,
333        next: Option<(u8, &[u8])>,
334    ) -> Option<(u32, u16, PcmBuf, bool)> {
335        if !self.concealment {
336            return None;
337        }
338        let payload_type = self.last_payload_type?;
339        let codec = self.codec_for_pt(payload_type);
340        let (rate, _) = Self::native_format(codec, 0);
341        let samples = (rate as u128 * ptime.as_nanos() / 1_000_000_000) as usize;
342        let next = next
343            .filter(|(pt, _)| *pt == payload_type && codec == CodecType::Opus)
344            .map(|(_, p)| p);
345        let used_next = next.is_some();
346        let decoder = self.decoder(codec)?;
347        let pcm = match next {
348            Some(next) => decoder.recover(next, samples),
349            None => decoder.conceal(samples),
350        };
351        if pcm.is_empty() {
352            return None;
353        }
354        let (rate, channels) = Self::native_format(codec, pcm.len());
355        Some((rate, channels, pcm, used_next))
356    }
357
358    /// Encode Opus as the receiver's `a=fmtp` asks (see [`OpusParams`]).
359    pub fn set_opus_params(&mut self, params: OpusParams) {
360        if params != self.opus_params {
361            self.opus_params = params;
362            self.opus_encoder = None;
363        }
364    }
365
366    /// Have Opus expect this packet loss, in percent (see
367    /// [`OpusLossEstimate`]).
368    pub fn set_opus_packet_loss(&mut self, percent: i32) {
369        if percent != self.opus_packet_loss {
370            self.opus_packet_loss = percent;
371            if let Some(encoder) = self.opus_encoder.as_mut() {
372                encoder.set_packet_loss_perc(percent);
373            }
374        }
375    }
376
377    pub fn opus_params(&self) -> OpusParams {
378        self.opus_params
379    }
380
381    pub fn set_payload_type(&mut self, pt: u8, codec: CodecType) {
382        self.payload_type_map.write().unwrap().insert(pt, codec);
383    }
384
385    /// Look up the codec for a given RTP payload type, consulting the negotiated map first
386    /// and falling back to the static payload type registry.
387    pub fn get_codec_for_pt(&self, pt: u8) -> Option<CodecType> {
388        codec_for_pt(&self.payload_type_map, pt)
389    }
390
391    /// Decode an RTP payload into PCM at the codec's native sample rate.
392    /// Returns `(native_sample_rate, channels, samples)`; resampling to the
393    /// pipeline rate is the caller's responsibility (see ProcessorChain).
394    pub fn decode(&mut self, payload_type: u8, payload: &[u8]) -> (u32, u16, PcmBuf) {
395        let codec = self.codec_for_pt(payload_type);
396        let pcm = match self.decoder(codec) {
397            Some(decoder) => {
398                let pcm = decoder.decode(payload);
399                self.last_payload_type = Some(payload_type);
400                pcm
401            }
402            None => bytes_to_samples(payload),
403        };
404        let (in_rate, channels) = Self::native_format(codec, pcm.len());
405        (in_rate, channels, pcm)
406    }
407
408    pub fn resample(&mut self, pcm: PcmBuf, in_rate: u32, out_rate: u32) -> PcmBuf {
409        // A zero rate means the caller has no valid source rate (e.g. a
410        // media-pass track created without an explicit input sample rate).
411        // There is nothing sensible to resample from, so pass the samples
412        // through instead of panicking: `BoxedResampler::new` rejects zero
413        // rates, and unwinding here poisons the `ProcessorChain` mutex,
414        // permanently breaking every subsequent frame on the track.
415        if in_rate == 0 || out_rate == 0 || in_rate == out_rate {
416            return pcm;
417        }
418
419        if self.resampler.is_none()
420            || self.resampler_in_rate != in_rate
421            || self.resampler_out_rate != out_rate
422        {
423            match BoxedResampler::new(in_rate as usize, out_rate as usize) {
424                Ok(resampler) => {
425                    self.resampler = Some(resampler);
426                    self.resampler_in_rate = in_rate;
427                    self.resampler_out_rate = out_rate;
428                }
429                Err(e) => {
430                    warn!(in_rate, out_rate, "failed to build resampler: {e}");
431                    self.resampler = None;
432                    self.resampler_in_rate = 0;
433                    self.resampler_out_rate = 0;
434                    return pcm;
435                }
436            }
437        }
438        self.resampler.as_mut().unwrap().resample(&pcm)
439    }
440
441    pub fn encode(&mut self, payload_type: u8, frame: AudioFrame) -> (u8, Vec<u8>) {
442        match frame.samples {
443            Samples::PCM { samples: mut pcm } => {
444                let codec = self
445                    .payload_type_map
446                    .read()
447                    .unwrap()
448                    .get(&payload_type)
449                    .cloned()
450                    .or_else(|| CodecType::try_from(payload_type).ok());
451
452                let target_samplerate = match codec {
453                    Some(CodecType::Opus) => self.opus_params.sample_rate(),
454                    Some(c) => c.samplerate(),
455                    None => 8000,
456                };
457                if frame.sample_rate != target_samplerate {
458                    pcm = self.resample(pcm, frame.sample_rate, target_samplerate);
459                }
460
461                let payload = match codec {
462                    Some(CodecType::PCMU) => self.pcmu_encoder.encode(&pcm),
463                    Some(CodecType::PCMA) => self.pcma_encoder.encode(&pcm),
464                    Some(CodecType::G722) => self
465                        .g722_encoder
466                        .get_or_insert_with(|| Box::new(G722Encoder::new()))
467                        .encode(&pcm),
468                    Some(CodecType::G729) => self
469                        .g729_encoder
470                        .get_or_insert_with(|| Box::new(G729Encoder::new()))
471                        .encode(&pcm),
472                    Some(CodecType::Opus) => {
473                        let (params, loss) = (self.opus_params, self.opus_packet_loss);
474                        self.opus_encoder
475                            .get_or_insert_with(|| params.encoder(loss))
476                            .encode(&pcm)
477                    }
478                    _ => samples_to_bytes(&pcm),
479                };
480                (payload_type, payload)
481            }
482            Samples::RTP {
483                payload_type,
484                payload,
485                ..
486            } => (payload_type, payload),
487            _ => (payload_type, vec![]),
488        }
489    }
490}
491
492#[cfg(test)]
493mod tests {
494    use super::*;
495
496    #[test]
497    fn test_encode_dynamic_opus_payload_type_uses_opus_encoder() {
498        let mut codec = TrackCodec::new();
499        codec.set_payload_type(96, CodecType::Opus);
500
501        let frame = AudioFrame {
502            samples: Samples::PCM {
503                // 20ms @ 16k mono
504                samples: vec![0; 320],
505            },
506            sample_rate: 16000,
507            channels: 1,
508            ..Default::default()
509        };
510
511        let (pt, payload) = codec.encode(96, frame);
512        assert_eq!(pt, 96);
513        assert!(!payload.is_empty());
514        // If this were raw PCM bytes, it would be 640 bytes.
515        assert!(payload.len() < 640);
516    }
517
518    #[test]
519    fn test_resample_zero_rate_passes_through_without_panic() {
520        let mut codec = TrackCodec::new();
521        let samples = vec![1000i16; 160];
522
523        assert_eq!(codec.resample(samples.clone(), 0, 16000), samples);
524        assert_eq!(codec.resample(samples.clone(), 16000, 0), samples);
525        assert_eq!(codec.resample(samples.clone(), 0, 0), samples);
526    }
527}
528
529#[cfg(test)]
530mod conceal_tests {
531    use super::*;
532    use audio_codec::Encoder;
533
534    const PTIME: Duration = Duration::from_millis(20);
535
536    /// Speech-like: 8 harmonics of a pitch gliding up, under an envelope.
537    fn voice(rate: u32, frames: usize) -> Vec<Vec<i16>> {
538        let frame = (rate / 50) as usize;
539        let mut phase = 0f32;
540        let pcm: Vec<i16> = (0..frames * frame)
541            .map(|i| {
542                let t = i as f32 / rate as f32;
543                let f0 = 120.0 + 60.0 * (t / 0.6).min(1.0);
544                phase += 2.0 * std::f32::consts::PI * f0 / rate as f32;
545                let env = 0.6 + 0.4 * (2.0 * std::f32::consts::PI * 2.0 * t).sin();
546                let v: f32 = (1..=8).map(|k| (k as f32 * phase).sin() / k as f32).sum();
547                (6000.0 * env * v) as i16
548            })
549            .collect();
550        pcm.chunks(frame).map(<[i16]>::to_vec).collect()
551    }
552
553    #[test]
554    fn nothing_to_conceal_with_until_enabled_and_decoded() {
555        let mut codec = TrackCodec::new();
556        let payload = PcmaEncoder::new().encode(&voice(8000, 1)[0]);
557        codec.decode(8, &payload);
558        assert!(codec.conceal(PTIME, None).is_none(), "concealment is off");
559        let mut codec = TrackCodec::new();
560        codec.enable_concealment();
561        assert!(codec.conceal(PTIME, None).is_none(), "nothing decoded yet");
562    }
563
564    #[test]
565    fn pcma_conceals_in_its_native_format() {
566        let mut codec = TrackCodec::new();
567        codec.enable_concealment();
568        let mut enc = PcmaEncoder::new();
569        for frame in voice(8000, 6) {
570            codec.decode(8, &enc.encode(&frame));
571        }
572        let (rate, channels, pcm, used_next) = codec.conceal(PTIME, None).unwrap();
573        assert_eq!(
574            (rate, channels, pcm.len(), used_next),
575            (8000, 1, 160, false)
576        );
577        assert!(pcm.iter().any(|s| *s != 0));
578    }
579
580    #[test]
581    fn g729_conceals_in_its_native_format() {
582        let mut codec = TrackCodec::new();
583        codec.enable_concealment();
584        let mut enc = G729Encoder::new();
585        for frame in voice(8000, 6) {
586            codec.decode(18, &enc.encode(&frame));
587        }
588        let (rate, channels, pcm, used_next) = codec.conceal(PTIME, None).unwrap();
589        assert_eq!(
590            (rate, channels, pcm.len(), used_next),
591            (8000, 1, 160, false)
592        );
593        assert!(pcm.iter().any(|s| *s != 0));
594    }
595
596    #[test]
597    fn opus_rebuilds_a_lost_packet_from_the_next_ones_fec() {
598        let mut enc = OpusEncoder::new(48000, 1);
599        enc.set_bitrate(32000);
600        enc.set_inband_fec(true);
601        enc.set_packet_loss_perc(20);
602        let packets: Vec<Vec<u8>> = voice(48000, 30).iter().map(|f| enc.encode(f)).collect();
603        let mut reference = TrackCodec::new();
604        let clean: Vec<PcmBuf> = packets.iter().map(|p| reference.decode(111, p).2).collect();
605
606        let error_db = |out: &[i16], clean: &[i16]| {
607            let err: f64 = out
608                .iter()
609                .zip(clean)
610                .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
611                .sum();
612            let sig: f64 = clean.iter().map(|b| (*b as f64).powi(2)).sum();
613            10.0 * (err / sig).log10()
614        };
615        // the encoder codes FEC frame by frame (here not into the quietest
616        // stretch, frames 14-21): lose frames it protected
617        let losses = [6, 9, 12, 24];
618        let (mut fec_db, mut plc_db) = (0f64, 0f64);
619        for lost in losses {
620            let mut recovering = TrackCodec::new();
621            let mut concealing = TrackCodec::new();
622            for codec in [&mut recovering, &mut concealing] {
623                codec.enable_concealment();
624                for p in &packets[..lost] {
625                    codec.decode(111, p);
626                }
627            }
628            let (rate, _, recovered, used_next) = recovering
629                .conceal(PTIME, Some((111, &packets[lost + 1])))
630                .unwrap();
631            assert_eq!((rate, recovered.len(), used_next), (48000, 960, true));
632            let (_, _, concealed, used_next) = concealing.conceal(PTIME, None).unwrap();
633            assert!(!used_next);
634            fec_db += error_db(&recovered, &clean[lost]);
635            plc_db += error_db(&concealed, &clean[lost]);
636        }
637        let (fec_db, plc_db) = (fec_db / losses.len() as f64, plc_db / losses.len() as f64);
638        // measured: FEC -29.8 dB, concealment -7.5 dB
639        assert!(
640            fec_db < plc_db - 10.0,
641            "FEC {fec_db:.1} dB vs concealment {plc_db:.1} dB"
642        );
643        let mut recovering = TrackCodec::new();
644        recovering.enable_concealment();
645        recovering.decode(111, &packets[0]);
646        // a next packet of another payload type is no use
647        let (_, _, _, used_next) = recovering.conceal(PTIME, Some((0, &packets[1]))).unwrap();
648        assert!(!used_next);
649    }
650
651    #[test]
652    fn opus_params_from_fmtp() {
653        // Firefox's offer
654        let firefox = OpusParams::from_fmtp("maxplaybackrate=48000;stereo=1;useinbandfec=1");
655        assert_eq!(
656            firefox,
657            OpusParams {
658                max_playback_rate: 48000,
659                max_average_bitrate: None,
660                inband_fec: true,
661            }
662        );
663        assert_eq!((firefox.sample_rate(), firefox.bitrate()), (48000, 64000));
664        let capped = OpusParams::from_fmtp("maxplaybackrate=16000; maxaveragebitrate=20000");
665        assert_eq!(
666            (capped.sample_rate(), capped.bitrate(), capped.inband_fec),
667            (16000, 20000, false)
668        );
669        // rates between Opus's go down to one, bitrates above ours stay ours
670        assert_eq!(
671            OpusParams::from_fmtp("maxplaybackrate=22050").sample_rate(),
672            16000
673        );
674        assert_eq!(
675            OpusParams::from_fmtp("maxaveragebitrate=128000").bitrate(),
676            64000
677        );
678        assert_eq!(
679            OpusParams::from_fmtp("useinbandfec=0"),
680            OpusParams::default()
681        );
682    }
683
684    #[test]
685    fn opus_loss_estimate_follows_reports_like_libwebrtc() {
686        let every = Duration::from_secs(5);
687        let mut estimate = OpusLossEstimate::default();
688        // the first report is taken as is
689        assert_eq!(estimate.update(0.0, every), 0);
690        // 12% loss is smoothed in over reports (4.7, 7.6, 9.3, 10.4, 11.0,
691        // 11.4%); 10% is entered past 11%
692        let rising: Vec<i32> = (0..6).map(|_| estimate.update(0.12, every)).collect();
693        assert_eq!(rising, [1, 5, 5, 5, 10, 10]);
694        // and left only below 9% (10.7%, then 6.5, 3.9, 2.4, 1.4, 0.9%)
695        assert_eq!(estimate.update(0.095, every), 10);
696        let falling: Vec<i32> = (0..6).map(|_| estimate.update(0.0, every)).collect();
697        assert_eq!(falling, [5, 1, 1, 1, 0, 0]);
698    }
699
700    #[test]
701    fn opus_encoded_for_a_fec_receiver_carries_fec() {
702        let mut sender = TrackCodec::new();
703        sender.set_opus_params(OpusParams::from_fmtp(
704            "maxplaybackrate=48000;stereo=1;useinbandfec=1",
705        ));
706        // the receiver reports 10% loss
707        sender.set_opus_packet_loss(10);
708        // the pipeline's 16 kHz audio
709        let packets: Vec<Vec<u8>> = voice(16000, 30)
710            .into_iter()
711            .map(|samples| {
712                let frame = AudioFrame {
713                    samples: Samples::PCM { samples },
714                    sample_rate: 16000,
715                    channels: 1,
716                    ..Default::default()
717                };
718                sender.encode(111, frame).1
719            })
720            .collect();
721        // mono, at the bitrate
722        assert!(packets.iter().all(|p| p[0] & 0x04 == 0), "stereo packets");
723        let bitrate = packets.iter().map(Vec::len).sum::<usize>() * 8 * 50 / packets.len();
724        assert!((58000..=66000).contains(&bitrate), "{bitrate} bit/s");
725
726        let mut reference = TrackCodec::new();
727        let clean: Vec<PcmBuf> = packets.iter().map(|p| reference.decode(111, p).2).collect();
728        let error_db = |out: &[i16], clean: &[i16]| {
729            let err: f64 = out
730                .iter()
731                .zip(clean)
732                .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
733                .sum();
734            let sig: f64 = clean.iter().map(|b| (*b as f64).powi(2)).sum();
735            10.0 * (err / sig).log10()
736        };
737        let losses = [6, 9, 12, 24];
738        let (mut fec_db, mut plc_db) = (0f64, 0f64);
739        for lost in losses {
740            let mut recovering = TrackCodec::new();
741            let mut concealing = TrackCodec::new();
742            for codec in [&mut recovering, &mut concealing] {
743                codec.enable_concealment();
744                for p in &packets[..lost] {
745                    codec.decode(111, p);
746                }
747            }
748            let (_, _, recovered, used_next) = recovering
749                .conceal(PTIME, Some((111, &packets[lost + 1])))
750                .unwrap();
751            assert!(used_next);
752            let (_, _, concealed, _) = concealing.conceal(PTIME, None).unwrap();
753            fec_db += error_db(&recovered, &clean[lost]);
754            plc_db += error_db(&concealed, &clean[lost]);
755        }
756        let (fec_db, plc_db) = (fec_db / losses.len() as f64, plc_db / losses.len() as f64);
757        // measured: FEC -15.8 dB, concealment -7.1 dB
758        assert!(
759            fec_db < plc_db - 6.0,
760            "FEC {fec_db:.1} dB vs concealment {plc_db:.1} dB"
761        );
762    }
763
764    fn rms(pcm: &[i16]) -> f64 {
765        (pcm.iter().map(|s| (*s as f64).powi(2)).sum::<f64>() / pcm.len() as f64).sqrt()
766    }
767
768    #[test]
769    fn opus_concealment_fades_to_silence() {
770        // audio-codec fades Opus's concealment, which on its own carries on
771        // near the level of the speech before the loss
772        let mut enc = OpusEncoder::new(48000, 1);
773        let packets: Vec<Vec<u8>> = voice(48000, 20).iter().map(|f| enc.encode(f)).collect();
774        let mut codec = TrackCodec::new();
775        codec.enable_concealment();
776        for p in &packets[..10] {
777            codec.decode(111, p);
778        }
779        let levels: Vec<f64> = (0..5)
780            .map(|_| rms(&codec.conceal(PTIME, None).unwrap().2))
781            .collect();
782        assert!(
783            levels[0] > 300.0,
784            "first frame of a loss is audible: {levels:?}"
785        );
786        assert!(levels[1] < levels[0] * 0.8, "not fading: {levels:?}");
787        assert!(
788            levels[3..].iter().all(|l| *l == 0.0),
789            "not silent at 60 ms: {levels:?}"
790        );
791    }
792}
793
794#[cfg(test)]
795mod duration_tests {
796    use super::*;
797
798    #[test]
799    fn test_duration_to_rtp_ticks() {
800        assert_eq!(duration_to_rtp_ticks(Duration::from_millis(20), 8000), 160);
801        assert_eq!(duration_to_rtp_ticks(Duration::from_millis(20), 48000), 960);
802        assert_eq!(
803            duration_to_rtp_ticks(Duration::from_micros(2_500), 48000),
804            120
805        );
806    }
807}