rtci-interceptor 0.4.1

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
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
//! A loss-driven FEC rate, shared by the FEC senders (FlexFEC draft-03, RFC 8627 FlexFEC,
//! ULPFEC), and the FEC overhead taken out of the target the application encodes at.
//!
//! * draft-ietf-payload-flexible-fec-scheme-03 section 8: repair flows "SHOULD" not be sent
//!   when they would not help recover anything, and the amount of FEC is adjusted to the loss
//!   observed; RFC 8627 section 8 likewise ("SHOULD [...] adjust the amount [...] of FEC from
//!   the observed loss rate"); RFC 5109 section 12: users of the format "MUST" monitor packet
//!   loss, and FEC "MUST NOT substantially increase the total bandwidth (media and FEC) as
//!   network loss increases".
//! * The loss is the protected stream's, as its receiver reports it (RFC 3550 6.4.1 fraction
//!   lost, which counts what the path lost, not what FEC rebuilt), smoothed over reports.
//! * The repair packets per block follow it: enough for twice the measured loss
//!   (`ceil(2 * loss * media packets)`), none under [`MIN_LOSS`], at most [`FecRate::max`]
//!   (half the block by default). Before any report the configured amount is sent.
//! * The FEC sent is taken out of the congestion controller's target on its way to the
//!   application ([`FecRate::media_target`]): the bit rate of the repair packets of the last
//!   second is subtracted, so media and FEC together stay at the target however the loss
//!   moves (RFC 5109 section 12), and the controller, which counts the repair packets on the
//!   wire, is not overrun.
//! * RFC 8854 section 8: "WebRTC implementations SHOULD prefer using RTX or Flexible FEC
//!   retransmissions instead of FEC when the connection RTT is within the application's latency
//!   budget, and otherwise SHOULD only transmit the amount of FEC needed to protect against the
//!   observed packet loss [...] unless the application indicates it is willing to pay a quality
//!   penalty to proactively avoid losses". The round trip is the one the RTCP session measured
//!   for a protected stream ([`RtcpSessionEvent::RoundTripTime`](crate::RtcpSessionEvent));
//!   while it is within the latency budget ([`FEC_DEFAULT_LATENCY_BUDGET`] unless the sender's
//!   builder names another) a stream that can be repaired by retransmission (RTX: `nack` and an
//!   RTX stream negotiated; or FlexFEC retransmissions on) gets no FEC
//!   ([`FecRate::fec_packets_with`]). No budget ([`FecRate::with_latency_budget`] `None`) is the
//!   application paying for proactive FEC: the amount then follows the loss whatever the round
//!   trip, as does a fixed amount (`adaptive` false).
//! * RFC 8627 section 8: "It is RECOMMENDED that the amount and type (row, column, or both) of
//!   FEC protection is adjusted dynamically based on the packet loss rate and burst loss length
//!   observed". The runs of lost packets are read from the per-packet congestion control
//!   feedback (transport-wide feedback, and RFC 8888 reports of the protected streams):
//!   [`FecRate::loss_pattern`] says whether the recent losses were isolated, in bursts, or both
//!   (section 1.1.3: rows recover random losses, columns bursts; section 1.1.4: both for mixed
//!   patterns).

use crate::rtpfb::acknowledgement::Acknowledgement;
use crate::{Attribute, Packet, TaggedPacket};
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

/// Smoothed loss under which no repair packet is sent: it would not help recover anything.
pub const MIN_LOSS: f64 = 0.005;
/// Weight of a new report in the smoothed loss.
const LOSS_WEIGHT: f64 = 0.3;
/// The window the FEC bit rate is measured over.
const RATE_WINDOW: Duration = Duration::from_secs(1);

/// The latency budget a FEC sender assumes when its builder names none: the round trip within
/// which a retransmission is preferred to FEC (RFC 8854 section 8). ITU-T G.114 (05/2003)
/// takes a one-way delay of up to 150 ms as acceptable to most interactive applications; a
/// retransmission delays the packet it repairs by about one round trip.
pub const FEC_DEFAULT_LATENCY_BUDGET: Duration = Duration::from_millis(150);

/// How many of the most recent runs of lost packets [`FecRate::loss_pattern`] reads.
const LOSS_RUN_WINDOW: usize = 32;
/// Runs of lost packets needed before a pattern is named.
const MIN_LOSS_RUNS: usize = 4;

/// What the recent losses of the path looked like (RFC 8627 sections 1.1.3, 1.1.4 and 8).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LossPattern {
    /// Isolated losses (fewer than a quarter of the runs of lost packets are longer than one):
    /// row (non-interleaved) protection recovers them.
    Random,
    /// Losses in bursts (more than three quarters of the runs are longer than one): column
    /// (interleaved) protection recovers a burst no longer than a row.
    Bursty,
    /// Both: rows and columns.
    Mixed,
}

/// Runs of consecutive lost packets, read from per-packet feedback, each sequence number space
/// (transport-wide, or one stream's RTP sequence numbers) on its own.
#[derive(Debug, Clone, Default)]
struct LossRuns {
    /// By space (`None`: transport-wide): the newest sequence number read and the length of the
    /// run of lost packets it ends, if it was lost.
    spaces: HashMap<Option<u32>, (u16, u32)>,
    /// The lengths of the most recent runs that ended, oldest first.
    runs: VecDeque<u32>,
}

impl LossRuns {
    fn close(&mut self, run: u32) {
        if run == 0 {
            return;
        }
        if self.runs.len() == LOSS_RUN_WINDOW {
            self.runs.pop_front();
        }
        self.runs.push_back(run);
    }

    fn on_acknowledgements(&mut self, space: Option<u32>, acknowledgements: &[Acknowledgement]) {
        for acknowledgement in acknowledgements {
            let sequence_number = acknowledgement.sequence_number;
            let open = match self.spaces.get(&space).copied() {
                Some((newest, open)) => {
                    let step = sequence_number.wrapping_sub(newest);
                    // Reported before (feedback ranges may overlap), or older.
                    if step == 0 || step >= 0x8000 {
                        continue;
                    }
                    // Packets no feedback reported: the run cannot be known to go on.
                    if step > 1 {
                        self.close(open);
                        0
                    } else {
                        open
                    }
                }
                None => 0,
            };
            let open = if acknowledgement.arrived {
                self.close(open);
                0
            } else {
                open + 1
            };
            self.spaces.insert(space, (sequence_number, open));
        }
    }

    fn pattern(&self) -> Option<LossPattern> {
        if self.runs.len() < MIN_LOSS_RUNS {
            return None;
        }
        let bursts = self.runs.iter().filter(|run| **run > 1).count();
        Some(if bursts * 4 < self.runs.len() {
            LossPattern::Random
        } else if bursts * 4 > self.runs.len() * 3 {
            LossPattern::Bursty
        } else {
            LossPattern::Mixed
        })
    }
}

/// The loss-driven amount of FEC for one sender. See the module documentation.
#[derive(Debug, Clone)]
pub struct FecRate {
    media_packets: u32,
    configured: u32,
    max: u32,
    adaptive: bool,
    loss: Option<f64>,
    /// Repair packets sent in the last [`RATE_WINDOW`]: when and how many octets.
    sent: VecDeque<(Instant, usize)>,
    /// The round trip within which retransmission is preferred to FEC; `None`: FEC whatever
    /// the round trip.
    latency_budget: Option<Duration>,
    /// The newest round trip measured to the receiver of a protected stream.
    round_trip_time: Option<Duration>,
    /// The runs of lost packets the feedback reported.
    loss_runs: LossRuns,
}

impl FecRate {
    /// `fec_packets` repair packets per `media_packets` source packets until the loss is known;
    /// `adaptive` false keeps that amount whatever the loss.
    pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
        let media_packets = media_packets.max(1);
        Self {
            media_packets,
            configured: fec_packets,
            max: media_packets.div_ceil(2).max(fec_packets),
            adaptive,
            loss: None,
            sent: VecDeque::new(),
            latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
            round_trip_time: None,
            loss_runs: LossRuns::default(),
        }
    }

    /// The round trip within which a stream that can be repaired by retransmission gets no FEC
    /// (RFC 8854 section 8); [`FEC_DEFAULT_LATENCY_BUDGET`] by default. `None` is the
    /// application paying for proactive FEC: the amount follows the loss whatever the round
    /// trip.
    pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
        self.latency_budget = latency_budget;
        self
    }

    /// The latency budget in force.
    pub fn latency_budget(&self) -> Option<Duration> {
        self.latency_budget
    }

    /// The newest round trip measured to the receiver of a protected stream.
    pub fn round_trip_time(&self) -> Option<Duration> {
        self.round_trip_time
    }

    /// A round trip measured to the receiver of a protected stream.
    pub fn on_round_trip_time(&mut self, round_trip_time: Duration) {
        self.round_trip_time = Some(round_trip_time);
    }

    /// Whether retransmission is to repair a stream that can be retransmitted, rather than FEC:
    /// the amount follows the loss, a latency budget is set, and the round trip measured is
    /// within it.
    pub fn retransmission_preferred(&self) -> bool {
        self.adaptive
            && matches!(
                (self.round_trip_time, self.latency_budget),
                (Some(round_trip_time), Some(budget)) if round_trip_time <= budget
            )
    }

    /// Repair packets for the next block of a stream; `retransmission`: whether the stream can
    /// be repaired by retransmission. None while [`retransmission_preferred`](Self::retransmission_preferred),
    /// otherwise [`fec_packets`](Self::fec_packets).
    pub fn fec_packets_with(&self, retransmission: bool) -> u32 {
        if retransmission && self.retransmission_preferred() {
            0
        } else {
            self.fec_packets()
        }
    }

    /// Repair packets for a block of `media_packets` source packets that closed short (or is
    /// shorter than the configured block), as [`fec_packets_with`](Self::fec_packets_with)
    /// decides for a full one, and never more than the block has packets.
    pub fn fec_packets_for(&self, media_packets: u32, retransmission: bool) -> u32 {
        let media_packets = media_packets.max(1);
        if retransmission && self.retransmission_preferred() {
            return 0;
        }
        match self.loss {
            Some(loss) if self.adaptive => {
                if loss < MIN_LOSS {
                    0
                } else {
                    ((2.0 * loss * f64::from(media_packets)).ceil() as u32)
                        .max(1)
                        .min(self.max)
                        .min(media_packets)
                }
            }
            _ => self.configured.min(media_packets),
        }
    }

    /// Per-packet feedback for one sequence number space: `ssrc` names the stream an RFC 8888
    /// report is about, `None` is transport-wide feedback. Feeds [`loss_pattern`](Self::loss_pattern).
    pub fn on_acknowledgements(&mut self, ssrc: Option<u32>, acknowledgements: &[Acknowledgement]) {
        self.loss_runs.on_acknowledgements(ssrc, acknowledgements);
    }

    /// Whether the recent losses were isolated, in bursts, or both (the last 32 runs of lost
    /// packets; `None` before four runs were seen).
    pub fn loss_pattern(&self) -> Option<LossPattern> {
        self.loss_runs.pattern()
    }

    /// The most repair packets per block, whatever the loss.
    pub fn with_max(mut self, max: u32) -> Self {
        self.max = max;
        self
    }

    /// The most repair packets per block.
    pub fn max(&self) -> u32 {
        self.max
    }

    /// Whether the amount follows the loss (`false`: the configured amount whatever happens).
    pub fn adaptive(&self) -> bool {
        self.adaptive
    }

    /// The smoothed loss fraction, once a report gave one.
    pub fn loss(&self) -> Option<f64> {
        self.loss
    }

    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for a protected stream.
    pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
        let sample = f64::from(fraction_lost) / 256.0;
        self.loss = Some(match self.loss {
            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
            None => sample,
        });
    }

    /// Repair packets for the next block.
    pub fn fec_packets(&self) -> u32 {
        match self.loss {
            Some(loss) if self.adaptive => {
                if loss < MIN_LOSS {
                    0
                } else {
                    // At least one, unless the bound allows none (`clamp` would panic on it).
                    ((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
                        .max(1)
                        .min(self.max)
                }
            }
            _ => self.configured,
        }
    }

    /// Whether any repair is to be sent now (for protection shapes whose amount is fixed:
    /// sent or not).
    pub fn protects(&self) -> bool {
        self.fec_packets() > 0
    }

    /// A repair packet of `size` octets left at `now`.
    pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
        self.sent.push_back((now, size));
        self.expire(now);
    }

    fn expire(&mut self, now: Instant) {
        while self
            .sent
            .front()
            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
        {
            self.sent.pop_front();
        }
    }

    /// The bit rate of the repair packets of the last second at `now`.
    pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
        self.expire(now);
        self.sent
            .iter()
            .map(|(_, size)| *size as f64 * 8.0)
            .sum::<f64>()
            / RATE_WINDOW.as_secs_f64()
    }

    /// The target the application encodes at, out of the congestion controller's `target`:
    /// what is left after the FEC.
    pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
        (target - self.fec_bitrate(now)).max(0.0)
    }

    /// Reads what an inbound packet tells the FEC rate, and takes the FEC out of a target it
    /// carries: the receiver reports of `protected` streams feed the loss, the round trip the
    /// RTCP session measured to one of them the latency rule, per-packet feedback (transport-wide,
    /// and RFC 8888 reports on `protected` streams) the loss pattern, and an
    /// [`Attribute::TargetBitrateChanged`] on the packet is lowered by the FEC bit rate.
    pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
        if let Some(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }) =
            msg.message.custom::<crate::RtcpSessionEvent>()
            && protected(*ssrc)
        {
            self.round_trip_time = Some(*rtt);
        }
        if let Packet::Rtcp(packets) = &msg.message.packet {
            for packet in packets {
                let any = packet.as_any();
                if let Some(feedback) = any
                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc>(
                ) {
                    let acknowledgements = crate::rtpfb::convert::convert_twcc(feedback);
                    self.loss_runs.on_acknowledgements(None, &acknowledgements);
                    continue;
                }
                if let Some(feedback) = any
                    .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>(
                ) {
                    let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
                    for (ssrc, acknowledgements) in per_stream {
                        if protected(ssrc) {
                            self.loss_runs
                                .on_acknowledgements(Some(ssrc), &acknowledgements);
                        }
                    }
                    continue;
                }
                let reports = if let Some(rr) =
                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
                {
                    &rr.reports
                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
                    &sr.reports
                } else {
                    continue;
                };
                for report in reports {
                    if protected(report.ssrc) {
                        self.on_fraction_lost(report.fraction_lost);
                    }
                }
            }
        }
        let now = msg.now;
        let fec = self.fec_bitrate(now);
        if fec > 0.0 {
            for attribute in &mut msg.message.attributes {
                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
                    *bits_per_second = (*bits_per_second - fec).max(0.0);
                }
            }
        }
    }
}

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

    #[test]
    fn before_any_report_the_configured_amount_is_sent() {
        assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
        assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
    }

    #[test]
    fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(0);
        assert_eq!(
            rate.fec_packets(),
            0,
            "repair that helps nothing is not sent"
        );
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(5); // 2%
        assert_eq!(rate.fec_packets(), 1);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(13); // 5%
        assert_eq!(rate.fec_packets(), 2);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51); // 20%
        assert_eq!(rate.fec_packets(), 4);
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(200); // 78%
        assert_eq!(rate.fec_packets(), 5, "at most half the block");
    }

    #[test]
    fn the_loss_is_smoothed_over_reports() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51);
        rate.on_fraction_lost(0);
        let loss = rate.loss().unwrap();
        assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
        assert_eq!(rate.fec_packets(), 3);
    }

    #[test]
    fn a_fixed_rate_ignores_the_loss() {
        let mut rate = FecRate::new(10, 1, false);
        rate.on_fraction_lost(0);
        assert_eq!(rate.fec_packets(), 1);
        rate.on_fraction_lost(128);
        assert_eq!(rate.fec_packets(), 1);
    }

    #[test]
    fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
        let mut rate = FecRate::new(10, 1, true);
        let now = Instant::now();
        for n in 0..10u64 {
            rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
        }
        let at = now + Duration::from_millis(950);
        assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
        assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
        // A second later the repair has aged out.
        assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
    }

    /// RFC 8854 section 8: retransmission is preferred to FEC while the round trip is within
    /// the latency budget, for a stream that can be retransmitted; otherwise the amount
    /// follows the loss.
    #[test]
    fn within_the_latency_budget_a_stream_with_rtx_gets_no_fec() {
        let mut rate = FecRate::new(10, 1, true);
        assert_eq!(rate.latency_budget(), Some(FEC_DEFAULT_LATENCY_BUDGET));
        rate.on_fraction_lost(51); // 20%
        assert_eq!(rate.fec_packets(), 4, "precondition: the loss asks for FEC");
        assert_eq!(rate.fec_packets_with(true), 4, "no round trip measured yet");
        rate.on_round_trip_time(Duration::from_millis(80));
        assert!(rate.retransmission_preferred());
        assert_eq!(
            rate.fec_packets_with(true),
            0,
            "RTX repairs within the budget"
        );
        assert_eq!(rate.fec_packets_for(3, true), 0);
        assert_eq!(
            rate.fec_packets_with(false),
            4,
            "a stream without RTX keeps its FEC"
        );
        rate.on_round_trip_time(FEC_DEFAULT_LATENCY_BUDGET + Duration::from_millis(1));
        assert_eq!(
            rate.fec_packets_with(true),
            4,
            "beyond the budget FEC follows the loss"
        );
        // No budget: the application pays for proactive FEC.
        let mut rate = FecRate::new(10, 1, true).with_latency_budget(None);
        rate.on_fraction_lost(51);
        rate.on_round_trip_time(Duration::from_millis(1));
        assert_eq!(rate.fec_packets_with(true), 4);
        // A fixed amount was asked for explicitly.
        let mut rate = FecRate::new(10, 2, false);
        rate.on_round_trip_time(Duration::from_millis(1));
        assert_eq!(rate.fec_packets_with(true), 2);
    }

    /// A block that closed short gets its share of the repair, never more packets than it has.
    #[test]
    fn a_short_block_gets_its_share_of_the_repair() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_fraction_lost(51); // 20%: 4 for 10 packets
        assert_eq!(rate.fec_packets_for(10, false), 4);
        assert_eq!(rate.fec_packets_for(3, false), 2);
        assert_eq!(rate.fec_packets_for(1, false), 1);
        let rate = FecRate::new(10, 3, false);
        assert_eq!(rate.fec_packets_for(2, false), 2);
    }

    fn session_round_trip(ssrc: u32, rtt: Duration) -> TaggedPacket {
        TaggedPacket {
            now: Instant::now(),
            transport: shared::TransportContext::default(),
            message: crate::AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
                std::sync::Arc::new(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }),
            )),
        }
    }

    /// The round trip the RTCP session measured to the receiver of a protected stream is the
    /// one the latency rule reads; another stream's is not.
    #[test]
    fn the_round_trip_the_rtcp_session_measured_to_a_protected_stream_is_read() {
        let mut rate = FecRate::new(10, 1, true);
        rate.on_read(
            &mut session_round_trip(7, Duration::from_millis(40)),
            |ssrc| ssrc == 9,
        );
        assert_eq!(rate.round_trip_time(), None, "not a protected stream");
        rate.on_read(
            &mut session_round_trip(9, Duration::from_millis(40)),
            |ssrc| ssrc == 9,
        );
        assert_eq!(rate.round_trip_time(), Some(Duration::from_millis(40)));
    }

    fn acks(statuses: &[(u16, bool)]) -> Vec<Acknowledgement> {
        statuses
            .iter()
            .map(|&(sequence_number, arrived)| {
                if arrived {
                    Acknowledgement::received(
                        sequence_number,
                        None,
                        rtcp::transport_feedbacks::cc_feedback_report::Ecn::NotEct,
                    )
                } else {
                    Acknowledgement::lost(sequence_number)
                }
            })
            .collect()
    }

    /// A run of `lost` packets lost then one received, from `first`.
    fn run(first: u16, lost: u16) -> Vec<(u16, bool)> {
        (0..lost)
            .map(|offset| (first.wrapping_add(offset), false))
            .chain(std::iter::once((first.wrapping_add(lost), true)))
            .collect()
    }

    /// RFC 8627 sections 1.1.3, 1.1.4 and 8: isolated losses, bursts, and both, read from the
    /// runs of lost packets.
    #[test]
    fn isolated_losses_bursts_and_both_are_told_apart() {
        let pattern = |runs: &[u16]| {
            let mut rate = FecRate::new(12, 7, true);
            let mut at = 1000u16;
            for lost in runs {
                rate.on_acknowledgements(None, &acks(&run(at, *lost)));
                at = at.wrapping_add(lost + 1);
            }
            rate.loss_pattern()
        };
        assert_eq!(pattern(&[1, 1, 1]), None, "too few runs to tell");
        assert_eq!(pattern(&[1; 8]), Some(LossPattern::Random));
        assert_eq!(
            pattern(&[1, 1, 1, 1, 1, 1, 1, 2]),
            Some(LossPattern::Random)
        );
        assert_eq!(pattern(&[3; 8]), Some(LossPattern::Bursty));
        assert_eq!(pattern(&[1, 4, 1, 4, 1, 4, 1, 4]), Some(LossPattern::Mixed));
        // The window is the last 32 runs: bursts long ago are forgotten.
        let mut runs = vec![3u16; 32];
        runs.extend([1u16; 32]);
        assert_eq!(pattern(&runs), Some(LossPattern::Random));
    }

    /// A packet reported twice (overlapping feedback) is read once, a run cut by packets no
    /// report covered is not taken as going on, and the streams of RFC 8888 reports are runs
    /// of their own.
    #[test]
    fn feedback_is_read_once_per_packet_and_per_sequence_space() {
        let mut rate = FecRate::new(12, 7, true);
        // Four bursts of two, each report repeating the packets of the one before.
        let mut previous: Vec<(u16, bool)> = Vec::new();
        for first in [10u16, 13, 16, 19] {
            let mut report = previous.clone();
            report.extend(run(first, 2));
            rate.on_acknowledgements(None, &acks(&report));
            previous = run(first, 2);
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
        // Isolated losses on two streams, interleaved: neither joins the other's runs.
        let mut rate = FecRate::new(12, 7, true);
        for first in [100u16, 102, 104, 106] {
            rate.on_acknowledgements(Some(1), &acks(&run(first, 1)));
            rate.on_acknowledgements(Some(2), &acks(&run(first, 1)));
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
        // Lost packets on either side of a stretch no report covered are two runs.
        let mut rate = FecRate::new(12, 7, true);
        for first in [200u16, 300, 400, 500] {
            rate.on_acknowledgements(None, &acks(&[(first, false)]));
            rate.on_acknowledgements(None, &acks(&[(first + 50, false), (first + 51, true)]));
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
    }

    /// Transport-wide feedback read through `on_read` feeds the pattern; an RFC 8888 report
    /// only for a protected stream.
    #[test]
    fn per_packet_feedback_on_the_read_path_feeds_the_loss_pattern() {
        use rtcp::transport_feedbacks::transport_layer_cc::{
            PacketStatusChunk, RecvDelta, RunLengthChunk, SymbolTypeTcc, TransportLayerCc,
        };
        let chunk = |symbol, run_length| {
            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
                packet_status_symbol: symbol,
                run_length,
                ..Default::default()
            })
        };
        let mut rate = FecRate::new(12, 7, true);
        let mut base = 500u16;
        for _ in 0..4 {
            // Three lost, then two received.
            let feedback = TransportLayerCc {
                base_sequence_number: base,
                packet_status_count: 5,
                packet_chunks: vec![
                    chunk(SymbolTypeTcc::PacketNotReceived, 3),
                    chunk(SymbolTypeTcc::PacketReceivedSmallDelta, 2),
                ],
                recv_deltas: vec![
                    RecvDelta {
                        delta: 1000,
                        ..Default::default()
                    };
                    2
                ],
                ..Default::default()
            };
            let mut msg = TaggedPacket {
                now: Instant::now(),
                transport: shared::TransportContext::default(),
                message: crate::AttributedPacket::new(Packet::Rtcp(vec![Box::new(feedback)])),
            };
            rate.on_read(&mut msg, |_| true);
            base = base.wrapping_add(5);
        }
        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
    }

    /// A fixed corpus of arbitrary report and send sequences: the repair per block stays
    /// within zero and the bound, the media target never goes negative or above the target it
    /// is cut from, and the FEC bit rate never goes negative.
    #[test]
    fn arbitrary_reports_keep_the_rate_within_its_bounds() {
        let mut state = 0x0FEC_0001u32;
        let mut next = move || {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            state >> 8
        };
        for _ in 0..300 {
            let media = 1 + next() % 48;
            let configured = next() % 8;
            let mut rate = FecRate::new(media, configured, next() % 4 != 0);
            if next() % 3 == 0 {
                rate = rate.with_max(next() % 30);
            }
            let mut at = Instant::now();
            for _ in 0..300 {
                at += Duration::from_millis(u64::from(next() % 200));
                match next() % 3 {
                    0 => rate.on_fraction_lost(next() as u8),
                    1 => rate.on_repair_sent(at, (next() % 1500) as usize),
                    _ => {
                        let k = rate.fec_packets();
                        assert!(k <= rate.max().max(configured), "{k} over the bound");
                        let target = f64::from(next() % 5_000_000);
                        let media_target = rate.media_target(at, target);
                        assert!((0.0..=target).contains(&media_target));
                        assert!(rate.fec_bitrate(at) >= 0.0);
                    }
                }
            }
        }
    }
}