active-call 0.3.121

A SIP/WebRTC voice agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
use crate::{media::AudioFrame, media::PcmBuf, media::Samples};
use audio_codec::{
    BoxedResampler, CodecType, Decoder, Encoder, bytes_to_samples,
    g722::{G722Decoder, G722Encoder},
    pcma::{PcmaDecoder, PcmaEncoder},
    pcmu::{PcmuDecoder, PcmuEncoder},
    samples_to_bytes,
};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tracing::warn;

use audio_codec::g729::{G729Decoder, G729Encoder};
use audio_codec::opus::{OpusDecoder, OpusEncoder};

/// Opus bitrate when the receiver sets no lower `maxaveragebitrate`: speech
/// to fullband, with room for in-band FEC.
const OPUS_BITRATE: u32 = 64000;

/// The packet loss to tell the Opus encoder to expect, from the receiver's
/// reports of the loss it sees (RTCP `fraction lost`), as libwebrtc does:
/// smoothed over ~10 s, then snapped to 0, 1, 5, 10 or 20% with hysteresis
/// so it doesn't flip the encoder on every report. It sets how robust the
/// encoding is, and gates in-band FEC: none is coded at 0%, and at 32 kbit/s
/// none up to 5%.
#[derive(Debug, Default)]
pub struct OpusLossEstimate {
    smoothed: Option<f32>,
    level: f32,
}

impl OpusLossEstimate {
    /// libwebrtc's smoothing, per millisecond
    const ALPHA_PER_MS: f32 = 0.9999;

    /// Takes the loss reported (0-1) over `elapsed`; returns the loss for
    /// the encoder, in percent.
    pub fn update(&mut self, fraction_lost: f32, elapsed: Duration) -> i32 {
        let fraction_lost = fraction_lost.clamp(0.0, 1.0);
        let smoothed = match self.smoothed {
            Some(smoothed) => {
                let alpha = Self::ALPHA_PER_MS.powf(elapsed.as_millis() as f32);
                alpha * smoothed + (1.0 - alpha) * fraction_lost
            }
            None => fraction_lost,
        };
        self.smoothed = Some(smoothed);
        self.level = Self::level(smoothed, self.level);
        (self.level * 100.0).round() as i32
    }

    /// libwebrtc's `OptimizePacketLossRate`: a level is entered past its
    /// value plus a margin, and left below its value minus it.
    fn level(loss: f32, level: f32) -> f32 {
        let past =
            |rate: f32, margin: f32| loss >= rate + if rate > level { margin } else { -margin };
        if past(0.20, 0.02) {
            0.20
        } else if past(0.10, 0.01) {
            0.10
        } else if past(0.05, 0.01) {
            0.05
        } else if loss >= 0.01 {
            0.01
        } else {
            0.0
        }
    }
}

/// How to encode Opus for a receiver, from the `a=fmtp` of its description
/// (RFC 7587 6.1). Always mono: `stereo=1` is only a preference, and the
/// audio sent is mono.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OpusParams {
    /// Highest audio rate the receiver will play, in Hz.
    pub max_playback_rate: u32,
    /// Highest average bitrate the receiver takes, in bit/s.
    pub max_average_bitrate: Option<u32>,
    /// The receiver decodes in-band FEC.
    pub inband_fec: bool,
}

impl Default for OpusParams {
    fn default() -> Self {
        Self {
            max_playback_rate: 48000,
            max_average_bitrate: None,
            inband_fec: false,
        }
    }
}

impl OpusParams {
    /// Parameters from `a=fmtp` (without its `<pt> ` prefix); unknown or
    /// malformed ones are left at their defaults.
    pub fn from_fmtp(fmtp: &str) -> Self {
        let mut params = Self::default();
        for (key, value) in fmtp
            .split(';')
            .filter_map(|p| p.split_once('='))
            .map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim()))
        {
            match key.as_str() {
                "maxplaybackrate" => {
                    if let Ok(rate) = value.parse() {
                        params.max_playback_rate = rate;
                    }
                }
                "maxaveragebitrate" => params.max_average_bitrate = value.parse().ok(),
                "useinbandfec" => params.inband_fec = value == "1",
                _ => {}
            }
        }
        params
    }

    /// Encoder input rate: the highest Opus rate the receiver plays, which
    /// also caps the audio bandwidth coded.
    pub fn sample_rate(&self) -> u32 {
        [48000, 24000, 16000, 12000]
            .into_iter()
            .find(|r| *r <= self.max_playback_rate)
            .unwrap_or(8000)
    }

    pub fn bitrate(&self) -> u32 {
        // 6-510 kbit/s is what Opus codes
        self.max_average_bitrate
            .map_or(OPUS_BITRATE, |max| max.min(OPUS_BITRATE))
            .clamp(6000, 510_000)
    }

    fn encoder(&self, packet_loss_perc: i32) -> OpusEncoder {
        let mut encoder = OpusEncoder::new(self.sample_rate(), 1);
        encoder.set_bitrate(self.bitrate() as i32);
        encoder.set_inband_fec(self.inband_fec);
        encoder.set_packet_loss_perc(packet_loss_perc);
        encoder
    }
}

/// Convert an audio duration to RTP clock ticks.
pub fn duration_to_rtp_ticks(duration: Duration, clock_rate: u32) -> u32 {
    (duration.as_nanos() * clock_rate as u128 / 1_000_000_000) as u32
}

pub struct TrackCodec {
    pcmu_encoder: PcmuEncoder,
    pcmu_decoder: PcmuDecoder,
    pcma_encoder: PcmaEncoder,
    pcma_decoder: PcmaDecoder,

    g722_encoder: Option<Box<G722Encoder>>,
    g722_decoder: Option<Box<G722Decoder>>,

    g729_encoder: Option<Box<G729Encoder>>,
    g729_decoder: Option<Box<G729Decoder>>,

    opus_encoder: Option<OpusEncoder>,
    /// What the receiver takes, for `opus_encoder`.
    opus_params: OpusParams,
    /// Packet loss `opus_encoder` expects, in percent.
    opus_packet_loss: i32,
    opus_decoder: Option<OpusDecoder>,

    resampler: Option<BoxedResampler>,
    resampler_in_rate: u32,
    resampler_out_rate: u32,
    pub payload_type_map: Arc<RwLock<HashMap<u8, CodecType>>>,
    /// Decoders conceal lost packets (see `conceal`); off by default, as it
    /// costs a history copy per decoded packet for G.711 and G.722.
    concealment: bool,
    /// Payload type of the last packet decoded, whose decoder conceals.
    last_payload_type: Option<u8>,
}

/// The codec for an RTP payload type in a payload type map (as shared by
/// [`TrackCodec::payload_type_map`]), falling back to the static payload
/// type registry.
pub fn codec_for_pt(map: &RwLock<HashMap<u8, CodecType>>, pt: u8) -> Option<CodecType> {
    map.read()
        .unwrap()
        .get(&pt)
        .cloned()
        .or_else(|| CodecType::try_from(pt).ok())
}

impl Clone for TrackCodec {
    fn clone(&self) -> Self {
        let mut new = Self::new();
        // Share the same underlying map so reinvite PT updates are visible to all clones.
        new.payload_type_map = Arc::clone(&self.payload_type_map);
        new.opus_params = self.opus_params;
        if self.concealment {
            new.enable_concealment();
        }
        new
    }
}

impl TrackCodec {
    pub fn new() -> Self {
        let mut map = HashMap::new();
        map.insert(0, CodecType::PCMU);
        map.insert(8, CodecType::PCMA);
        map.insert(9, CodecType::G722);
        map.insert(18, CodecType::G729);
        map.insert(101, CodecType::TelephoneEvent);
        map.insert(111, CodecType::Opus);
        let payload_type_map = Arc::new(RwLock::new(map));

        Self {
            pcmu_encoder: PcmuEncoder::new(),
            pcmu_decoder: PcmuDecoder::new(),
            pcma_encoder: PcmaEncoder::new(),
            pcma_decoder: PcmaDecoder::new(),
            g722_encoder: None,
            g722_decoder: None,
            g729_encoder: None,
            g729_decoder: None,
            opus_encoder: None,
            opus_params: OpusParams::default(),
            opus_packet_loss: 0,
            opus_decoder: None,
            resampler: None,
            resampler_in_rate: 0,
            resampler_out_rate: 0,
            payload_type_map,
            concealment: false,
            last_payload_type: None,
        }
    }

    /// Have the decoders conceal lost packets, for [`Self::conceal`].
    pub fn enable_concealment(&mut self) {
        self.concealment = true;
        self.pcmu_decoder.enable_concealment();
        self.pcma_decoder.enable_concealment();
        for decoder in [
            self.g722_decoder
                .as_deref_mut()
                .map(|d| d as &mut dyn Decoder),
            self.g729_decoder
                .as_deref_mut()
                .map(|d| d as &mut dyn Decoder),
            self.opus_decoder.as_mut().map(|d| d as &mut dyn Decoder),
        ]
        .into_iter()
        .flatten()
        {
            decoder.enable_concealment();
        }
    }

    fn codec_for_pt(&self, payload_type: u8) -> CodecType {
        self.payload_type_map
            .read()
            .unwrap()
            .get(&payload_type)
            .cloned()
            .unwrap_or_else(|| match payload_type {
                0 => CodecType::PCMU,
                8 => CodecType::PCMA,
                9 => CodecType::G722,
                18 => CodecType::G729,
                111 => CodecType::Opus,
                _ => CodecType::PCMU,
            })
    }

    /// The decoder for an audio codec, created on first use.
    fn decoder(&mut self, codec: CodecType) -> Option<&mut dyn Decoder> {
        let concealment = self.concealment;
        let decoder: &mut dyn Decoder = match codec {
            CodecType::PCMU => &mut self.pcmu_decoder,
            CodecType::PCMA => &mut self.pcma_decoder,
            CodecType::G722 => self
                .g722_decoder
                .get_or_insert_with(|| {
                    let mut d = Box::new(G722Decoder::new());
                    if concealment {
                        d.enable_concealment();
                    }
                    d
                })
                .as_mut(),
            CodecType::G729 => self
                .g729_decoder
                .get_or_insert_with(|| {
                    let mut d = Box::new(G729Decoder::new());
                    if concealment {
                        d.enable_concealment();
                    }
                    d
                })
                .as_mut(),
            CodecType::Opus => self.opus_decoder.get_or_insert_with(|| {
                let mut d = OpusDecoder::new_default();
                if concealment {
                    d.enable_concealment();
                }
                d
            }),
            _ => return None,
        };
        Some(decoder)
    }

    /// Native `(sample_rate, channels)` of decoded audio, given the decoded
    /// sample count for Opus, whose channel count follows the packets.
    fn native_format(codec: CodecType, samples: usize) -> (u32, u16) {
        match codec {
            CodecType::PCMU | CodecType::PCMA | CodecType::G729 => (8000, 1),
            CodecType::G722 => (16000, 1),
            CodecType::Opus if samples >= 1920 => (48000, 2),
            CodecType::Opus => (48000, 1),
            _ => (8000, 1),
        }
    }

    /// Audio for one lost packet of `ptime`, from the decoder of the last
    /// packet decoded, as `(native_sample_rate, channels, samples)` like
    /// [`Self::decode`], and whether `next` was used. With `next`, the
    /// payload type and payload of the packet right after the loss, Opus
    /// rebuilds the lost one from its in-band FEC (where the sender coded
    /// any, else it conceals); other codecs conceal. `None` when concealment
    /// is off, nothing was decoded yet, or the codec has no concealment.
    pub fn conceal(
        &mut self,
        ptime: Duration,
        next: Option<(u8, &[u8])>,
    ) -> Option<(u32, u16, PcmBuf, bool)> {
        if !self.concealment {
            return None;
        }
        let payload_type = self.last_payload_type?;
        let codec = self.codec_for_pt(payload_type);
        let (rate, _) = Self::native_format(codec, 0);
        let samples = (rate as u128 * ptime.as_nanos() / 1_000_000_000) as usize;
        let next = next
            .filter(|(pt, _)| *pt == payload_type && codec == CodecType::Opus)
            .map(|(_, p)| p);
        let used_next = next.is_some();
        let decoder = self.decoder(codec)?;
        let pcm = match next {
            Some(next) => decoder.recover(next, samples),
            None => decoder.conceal(samples),
        };
        if pcm.is_empty() {
            return None;
        }
        let (rate, channels) = Self::native_format(codec, pcm.len());
        Some((rate, channels, pcm, used_next))
    }

    /// Encode Opus as the receiver's `a=fmtp` asks (see [`OpusParams`]).
    pub fn set_opus_params(&mut self, params: OpusParams) {
        if params != self.opus_params {
            self.opus_params = params;
            self.opus_encoder = None;
        }
    }

    /// Have Opus expect this packet loss, in percent (see
    /// [`OpusLossEstimate`]).
    pub fn set_opus_packet_loss(&mut self, percent: i32) {
        if percent != self.opus_packet_loss {
            self.opus_packet_loss = percent;
            if let Some(encoder) = self.opus_encoder.as_mut() {
                encoder.set_packet_loss_perc(percent);
            }
        }
    }

    pub fn opus_params(&self) -> OpusParams {
        self.opus_params
    }

    pub fn set_payload_type(&mut self, pt: u8, codec: CodecType) {
        self.payload_type_map.write().unwrap().insert(pt, codec);
    }

    /// Look up the codec for a given RTP payload type, consulting the negotiated map first
    /// and falling back to the static payload type registry.
    pub fn get_codec_for_pt(&self, pt: u8) -> Option<CodecType> {
        codec_for_pt(&self.payload_type_map, pt)
    }

    /// Decode an RTP payload into PCM at the codec's native sample rate.
    /// Returns `(native_sample_rate, channels, samples)`; resampling to the
    /// pipeline rate is the caller's responsibility (see ProcessorChain).
    pub fn decode(&mut self, payload_type: u8, payload: &[u8]) -> (u32, u16, PcmBuf) {
        let codec = self.codec_for_pt(payload_type);
        let pcm = match self.decoder(codec) {
            Some(decoder) => {
                let pcm = decoder.decode(payload);
                self.last_payload_type = Some(payload_type);
                pcm
            }
            None => bytes_to_samples(payload),
        };
        let (in_rate, channels) = Self::native_format(codec, pcm.len());
        (in_rate, channels, pcm)
    }

    pub fn resample(&mut self, pcm: PcmBuf, in_rate: u32, out_rate: u32) -> PcmBuf {
        // A zero rate means the caller has no valid source rate (e.g. a
        // media-pass track created without an explicit input sample rate).
        // There is nothing sensible to resample from, so pass the samples
        // through instead of panicking: `BoxedResampler::new` rejects zero
        // rates, and unwinding here poisons the `ProcessorChain` mutex,
        // permanently breaking every subsequent frame on the track.
        if in_rate == 0 || out_rate == 0 || in_rate == out_rate {
            return pcm;
        }

        if self.resampler.is_none()
            || self.resampler_in_rate != in_rate
            || self.resampler_out_rate != out_rate
        {
            match BoxedResampler::new(in_rate as usize, out_rate as usize) {
                Ok(resampler) => {
                    self.resampler = Some(resampler);
                    self.resampler_in_rate = in_rate;
                    self.resampler_out_rate = out_rate;
                }
                Err(e) => {
                    warn!(in_rate, out_rate, "failed to build resampler: {e}");
                    self.resampler = None;
                    self.resampler_in_rate = 0;
                    self.resampler_out_rate = 0;
                    return pcm;
                }
            }
        }
        self.resampler.as_mut().unwrap().resample(&pcm)
    }

    pub fn encode(&mut self, payload_type: u8, frame: AudioFrame) -> (u8, Vec<u8>) {
        match frame.samples {
            Samples::PCM { samples: mut pcm } => {
                let codec = self
                    .payload_type_map
                    .read()
                    .unwrap()
                    .get(&payload_type)
                    .cloned()
                    .or_else(|| CodecType::try_from(payload_type).ok());

                let target_samplerate = match codec {
                    Some(CodecType::Opus) => self.opus_params.sample_rate(),
                    Some(c) => c.samplerate(),
                    None => 8000,
                };
                if frame.sample_rate != target_samplerate {
                    pcm = self.resample(pcm, frame.sample_rate, target_samplerate);
                }

                let payload = match codec {
                    Some(CodecType::PCMU) => self.pcmu_encoder.encode(&pcm),
                    Some(CodecType::PCMA) => self.pcma_encoder.encode(&pcm),
                    Some(CodecType::G722) => self
                        .g722_encoder
                        .get_or_insert_with(|| Box::new(G722Encoder::new()))
                        .encode(&pcm),
                    Some(CodecType::G729) => self
                        .g729_encoder
                        .get_or_insert_with(|| Box::new(G729Encoder::new()))
                        .encode(&pcm),
                    Some(CodecType::Opus) => {
                        let (params, loss) = (self.opus_params, self.opus_packet_loss);
                        self.opus_encoder
                            .get_or_insert_with(|| params.encoder(loss))
                            .encode(&pcm)
                    }
                    _ => samples_to_bytes(&pcm),
                };
                (payload_type, payload)
            }
            Samples::RTP {
                payload_type,
                payload,
                ..
            } => (payload_type, payload),
            _ => (payload_type, vec![]),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_dynamic_opus_payload_type_uses_opus_encoder() {
        let mut codec = TrackCodec::new();
        codec.set_payload_type(96, CodecType::Opus);

        let frame = AudioFrame {
            samples: Samples::PCM {
                // 20ms @ 16k mono
                samples: vec![0; 320],
            },
            sample_rate: 16000,
            channels: 1,
            ..Default::default()
        };

        let (pt, payload) = codec.encode(96, frame);
        assert_eq!(pt, 96);
        assert!(!payload.is_empty());
        // If this were raw PCM bytes, it would be 640 bytes.
        assert!(payload.len() < 640);
    }

    #[test]
    fn test_resample_zero_rate_passes_through_without_panic() {
        let mut codec = TrackCodec::new();
        let samples = vec![1000i16; 160];

        assert_eq!(codec.resample(samples.clone(), 0, 16000), samples);
        assert_eq!(codec.resample(samples.clone(), 16000, 0), samples);
        assert_eq!(codec.resample(samples.clone(), 0, 0), samples);
    }
}

#[cfg(test)]
mod conceal_tests {
    use super::*;
    use audio_codec::Encoder;

    const PTIME: Duration = Duration::from_millis(20);

    /// Speech-like: 8 harmonics of a pitch gliding up, under an envelope.
    fn voice(rate: u32, frames: usize) -> Vec<Vec<i16>> {
        let frame = (rate / 50) as usize;
        let mut phase = 0f32;
        let pcm: Vec<i16> = (0..frames * frame)
            .map(|i| {
                let t = i as f32 / rate as f32;
                let f0 = 120.0 + 60.0 * (t / 0.6).min(1.0);
                phase += 2.0 * std::f32::consts::PI * f0 / rate as f32;
                let env = 0.6 + 0.4 * (2.0 * std::f32::consts::PI * 2.0 * t).sin();
                let v: f32 = (1..=8).map(|k| (k as f32 * phase).sin() / k as f32).sum();
                (6000.0 * env * v) as i16
            })
            .collect();
        pcm.chunks(frame).map(<[i16]>::to_vec).collect()
    }

    #[test]
    fn nothing_to_conceal_with_until_enabled_and_decoded() {
        let mut codec = TrackCodec::new();
        let payload = PcmaEncoder::new().encode(&voice(8000, 1)[0]);
        codec.decode(8, &payload);
        assert!(codec.conceal(PTIME, None).is_none(), "concealment is off");
        let mut codec = TrackCodec::new();
        codec.enable_concealment();
        assert!(codec.conceal(PTIME, None).is_none(), "nothing decoded yet");
    }

    #[test]
    fn pcma_conceals_in_its_native_format() {
        let mut codec = TrackCodec::new();
        codec.enable_concealment();
        let mut enc = PcmaEncoder::new();
        for frame in voice(8000, 6) {
            codec.decode(8, &enc.encode(&frame));
        }
        let (rate, channels, pcm, used_next) = codec.conceal(PTIME, None).unwrap();
        assert_eq!(
            (rate, channels, pcm.len(), used_next),
            (8000, 1, 160, false)
        );
        assert!(pcm.iter().any(|s| *s != 0));
    }

    #[test]
    fn g729_conceals_in_its_native_format() {
        let mut codec = TrackCodec::new();
        codec.enable_concealment();
        let mut enc = G729Encoder::new();
        for frame in voice(8000, 6) {
            codec.decode(18, &enc.encode(&frame));
        }
        let (rate, channels, pcm, used_next) = codec.conceal(PTIME, None).unwrap();
        assert_eq!(
            (rate, channels, pcm.len(), used_next),
            (8000, 1, 160, false)
        );
        assert!(pcm.iter().any(|s| *s != 0));
    }

    #[test]
    fn opus_rebuilds_a_lost_packet_from_the_next_ones_fec() {
        let mut enc = OpusEncoder::new(48000, 1);
        enc.set_bitrate(32000);
        enc.set_inband_fec(true);
        enc.set_packet_loss_perc(20);
        let packets: Vec<Vec<u8>> = voice(48000, 30).iter().map(|f| enc.encode(f)).collect();
        let mut reference = TrackCodec::new();
        let clean: Vec<PcmBuf> = packets.iter().map(|p| reference.decode(111, p).2).collect();

        let error_db = |out: &[i16], clean: &[i16]| {
            let err: f64 = out
                .iter()
                .zip(clean)
                .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
                .sum();
            let sig: f64 = clean.iter().map(|b| (*b as f64).powi(2)).sum();
            10.0 * (err / sig).log10()
        };
        // the encoder codes FEC frame by frame (here not into the quietest
        // stretch, frames 14-21): lose frames it protected
        let losses = [6, 9, 12, 24];
        let (mut fec_db, mut plc_db) = (0f64, 0f64);
        for lost in losses {
            let mut recovering = TrackCodec::new();
            let mut concealing = TrackCodec::new();
            for codec in [&mut recovering, &mut concealing] {
                codec.enable_concealment();
                for p in &packets[..lost] {
                    codec.decode(111, p);
                }
            }
            let (rate, _, recovered, used_next) = recovering
                .conceal(PTIME, Some((111, &packets[lost + 1])))
                .unwrap();
            assert_eq!((rate, recovered.len(), used_next), (48000, 960, true));
            let (_, _, concealed, used_next) = concealing.conceal(PTIME, None).unwrap();
            assert!(!used_next);
            fec_db += error_db(&recovered, &clean[lost]);
            plc_db += error_db(&concealed, &clean[lost]);
        }
        let (fec_db, plc_db) = (fec_db / losses.len() as f64, plc_db / losses.len() as f64);
        // measured: FEC -29.8 dB, concealment -7.5 dB
        assert!(
            fec_db < plc_db - 10.0,
            "FEC {fec_db:.1} dB vs concealment {plc_db:.1} dB"
        );
        let mut recovering = TrackCodec::new();
        recovering.enable_concealment();
        recovering.decode(111, &packets[0]);
        // a next packet of another payload type is no use
        let (_, _, _, used_next) = recovering.conceal(PTIME, Some((0, &packets[1]))).unwrap();
        assert!(!used_next);
    }

    #[test]
    fn opus_params_from_fmtp() {
        // Firefox's offer
        let firefox = OpusParams::from_fmtp("maxplaybackrate=48000;stereo=1;useinbandfec=1");
        assert_eq!(
            firefox,
            OpusParams {
                max_playback_rate: 48000,
                max_average_bitrate: None,
                inband_fec: true,
            }
        );
        assert_eq!((firefox.sample_rate(), firefox.bitrate()), (48000, 64000));
        let capped = OpusParams::from_fmtp("maxplaybackrate=16000; maxaveragebitrate=20000");
        assert_eq!(
            (capped.sample_rate(), capped.bitrate(), capped.inband_fec),
            (16000, 20000, false)
        );
        // rates between Opus's go down to one, bitrates above ours stay ours
        assert_eq!(
            OpusParams::from_fmtp("maxplaybackrate=22050").sample_rate(),
            16000
        );
        assert_eq!(
            OpusParams::from_fmtp("maxaveragebitrate=128000").bitrate(),
            64000
        );
        assert_eq!(
            OpusParams::from_fmtp("useinbandfec=0"),
            OpusParams::default()
        );
    }

    #[test]
    fn opus_loss_estimate_follows_reports_like_libwebrtc() {
        let every = Duration::from_secs(5);
        let mut estimate = OpusLossEstimate::default();
        // the first report is taken as is
        assert_eq!(estimate.update(0.0, every), 0);
        // 12% loss is smoothed in over reports (4.7, 7.6, 9.3, 10.4, 11.0,
        // 11.4%); 10% is entered past 11%
        let rising: Vec<i32> = (0..6).map(|_| estimate.update(0.12, every)).collect();
        assert_eq!(rising, [1, 5, 5, 5, 10, 10]);
        // and left only below 9% (10.7%, then 6.5, 3.9, 2.4, 1.4, 0.9%)
        assert_eq!(estimate.update(0.095, every), 10);
        let falling: Vec<i32> = (0..6).map(|_| estimate.update(0.0, every)).collect();
        assert_eq!(falling, [5, 1, 1, 1, 0, 0]);
    }

    #[test]
    fn opus_encoded_for_a_fec_receiver_carries_fec() {
        let mut sender = TrackCodec::new();
        sender.set_opus_params(OpusParams::from_fmtp(
            "maxplaybackrate=48000;stereo=1;useinbandfec=1",
        ));
        // the receiver reports 10% loss
        sender.set_opus_packet_loss(10);
        // the pipeline's 16 kHz audio
        let packets: Vec<Vec<u8>> = voice(16000, 30)
            .into_iter()
            .map(|samples| {
                let frame = AudioFrame {
                    samples: Samples::PCM { samples },
                    sample_rate: 16000,
                    channels: 1,
                    ..Default::default()
                };
                sender.encode(111, frame).1
            })
            .collect();
        // mono, at the bitrate
        assert!(packets.iter().all(|p| p[0] & 0x04 == 0), "stereo packets");
        let bitrate = packets.iter().map(Vec::len).sum::<usize>() * 8 * 50 / packets.len();
        assert!((58000..=66000).contains(&bitrate), "{bitrate} bit/s");

        let mut reference = TrackCodec::new();
        let clean: Vec<PcmBuf> = packets.iter().map(|p| reference.decode(111, p).2).collect();
        let error_db = |out: &[i16], clean: &[i16]| {
            let err: f64 = out
                .iter()
                .zip(clean)
                .map(|(a, b)| (*a as f64 - *b as f64).powi(2))
                .sum();
            let sig: f64 = clean.iter().map(|b| (*b as f64).powi(2)).sum();
            10.0 * (err / sig).log10()
        };
        let losses = [6, 9, 12, 24];
        let (mut fec_db, mut plc_db) = (0f64, 0f64);
        for lost in losses {
            let mut recovering = TrackCodec::new();
            let mut concealing = TrackCodec::new();
            for codec in [&mut recovering, &mut concealing] {
                codec.enable_concealment();
                for p in &packets[..lost] {
                    codec.decode(111, p);
                }
            }
            let (_, _, recovered, used_next) = recovering
                .conceal(PTIME, Some((111, &packets[lost + 1])))
                .unwrap();
            assert!(used_next);
            let (_, _, concealed, _) = concealing.conceal(PTIME, None).unwrap();
            fec_db += error_db(&recovered, &clean[lost]);
            plc_db += error_db(&concealed, &clean[lost]);
        }
        let (fec_db, plc_db) = (fec_db / losses.len() as f64, plc_db / losses.len() as f64);
        // measured: FEC -15.8 dB, concealment -7.1 dB
        assert!(
            fec_db < plc_db - 6.0,
            "FEC {fec_db:.1} dB vs concealment {plc_db:.1} dB"
        );
    }

    fn rms(pcm: &[i16]) -> f64 {
        (pcm.iter().map(|s| (*s as f64).powi(2)).sum::<f64>() / pcm.len() as f64).sqrt()
    }

    #[test]
    fn opus_concealment_fades_to_silence() {
        // audio-codec fades Opus's concealment, which on its own carries on
        // near the level of the speech before the loss
        let mut enc = OpusEncoder::new(48000, 1);
        let packets: Vec<Vec<u8>> = voice(48000, 20).iter().map(|f| enc.encode(f)).collect();
        let mut codec = TrackCodec::new();
        codec.enable_concealment();
        for p in &packets[..10] {
            codec.decode(111, p);
        }
        let levels: Vec<f64> = (0..5)
            .map(|_| rms(&codec.conceal(PTIME, None).unwrap().2))
            .collect();
        assert!(
            levels[0] > 300.0,
            "first frame of a loss is audible: {levels:?}"
        );
        assert!(levels[1] < levels[0] * 0.8, "not fading: {levels:?}");
        assert!(
            levels[3..].iter().all(|l| *l == 0.0),
            "not silent at 60 ms: {levels:?}"
        );
    }
}

#[cfg(test)]
mod duration_tests {
    use super::*;

    #[test]
    fn test_duration_to_rtp_ticks() {
        assert_eq!(duration_to_rtp_ticks(Duration::from_millis(20), 8000), 160);
        assert_eq!(duration_to_rtp_ticks(Duration::from_millis(20), 48000), 960);
        assert_eq!(
            duration_to_rtp_ticks(Duration::from_micros(2_500), 48000),
            120
        );
    }
}