Skip to main content

rtci_interceptor/cc/
fec_rate.rs

1//! A loss-driven FEC rate, shared by the FEC senders (FlexFEC draft-03, RFC 8627 FlexFEC,
2//! ULPFEC), and the FEC overhead taken out of the target the application encodes at.
3//!
4//! * draft-ietf-payload-flexible-fec-scheme-03 section 8: repair flows "SHOULD" not be sent
5//!   when they would not help recover anything, and the amount of FEC is adjusted to the loss
6//!   observed; RFC 8627 section 8 likewise ("SHOULD [...] adjust the amount [...] of FEC from
7//!   the observed loss rate"); RFC 5109 section 12: users of the format "MUST" monitor packet
8//!   loss, and FEC "MUST NOT substantially increase the total bandwidth (media and FEC) as
9//!   network loss increases".
10//! * The loss is the protected stream's, as its receiver reports it (RFC 3550 6.4.1 fraction
11//!   lost, which counts what the path lost, not what FEC rebuilt), smoothed over reports.
12//! * The repair packets per block follow it: enough for twice the measured loss
13//!   (`ceil(2 * loss * media packets)`), none under [`MIN_LOSS`], at most [`FecRate::max`]
14//!   (half the block by default). Before any report the configured amount is sent.
15//! * The FEC sent is taken out of the congestion controller's target on its way to the
16//!   application ([`FecRate::media_target`]): the bit rate of the repair packets of the last
17//!   second is subtracted, so media and FEC together stay at the target however the loss
18//!   moves (RFC 5109 section 12), and the controller, which counts the repair packets on the
19//!   wire, is not overrun.
20//! * RFC 8854 section 8: "WebRTC implementations SHOULD prefer using RTX or Flexible FEC
21//!   retransmissions instead of FEC when the connection RTT is within the application's latency
22//!   budget, and otherwise SHOULD only transmit the amount of FEC needed to protect against the
23//!   observed packet loss [...] unless the application indicates it is willing to pay a quality
24//!   penalty to proactively avoid losses". The round trip is the one the RTCP session measured
25//!   for a protected stream ([`RtcpSessionEvent::RoundTripTime`](crate::RtcpSessionEvent));
26//!   while it is within the latency budget ([`FEC_DEFAULT_LATENCY_BUDGET`] unless the sender's
27//!   builder names another) a stream that can be repaired by retransmission (RTX: `nack` and an
28//!   RTX stream negotiated; or FlexFEC retransmissions on) gets no FEC
29//!   ([`FecRate::fec_packets_with`]). No budget ([`FecRate::with_latency_budget`] `None`) is the
30//!   application paying for proactive FEC: the amount then follows the loss whatever the round
31//!   trip, as does a fixed amount (`adaptive` false).
32//! * RFC 8627 section 8: "It is RECOMMENDED that the amount and type (row, column, or both) of
33//!   FEC protection is adjusted dynamically based on the packet loss rate and burst loss length
34//!   observed". The runs of lost packets are read from the per-packet congestion control
35//!   feedback (transport-wide feedback, and RFC 8888 reports of the protected streams):
36//!   [`FecRate::loss_pattern`] says whether the recent losses were isolated, in bursts, or both
37//!   (section 1.1.3: rows recover random losses, columns bursts; section 1.1.4: both for mixed
38//!   patterns).
39
40use crate::rtpfb::acknowledgement::Acknowledgement;
41use crate::{Attribute, Packet, TaggedPacket};
42use std::collections::{HashMap, VecDeque};
43use std::time::{Duration, Instant};
44
45/// Smoothed loss under which no repair packet is sent: it would not help recover anything.
46pub const MIN_LOSS: f64 = 0.005;
47/// Weight of a new report in the smoothed loss.
48const LOSS_WEIGHT: f64 = 0.3;
49/// The window the FEC bit rate is measured over.
50const RATE_WINDOW: Duration = Duration::from_secs(1);
51
52/// The latency budget a FEC sender assumes when its builder names none: the round trip within
53/// which a retransmission is preferred to FEC (RFC 8854 section 8). ITU-T G.114 (05/2003)
54/// takes a one-way delay of up to 150 ms as acceptable to most interactive applications; a
55/// retransmission delays the packet it repairs by about one round trip.
56pub const FEC_DEFAULT_LATENCY_BUDGET: Duration = Duration::from_millis(150);
57
58/// How many of the most recent runs of lost packets [`FecRate::loss_pattern`] reads.
59const LOSS_RUN_WINDOW: usize = 32;
60/// Runs of lost packets needed before a pattern is named.
61const MIN_LOSS_RUNS: usize = 4;
62
63/// What the recent losses of the path looked like (RFC 8627 sections 1.1.3, 1.1.4 and 8).
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65#[non_exhaustive]
66pub enum LossPattern {
67    /// Isolated losses (fewer than a quarter of the runs of lost packets are longer than one):
68    /// row (non-interleaved) protection recovers them.
69    Random,
70    /// Losses in bursts (more than three quarters of the runs are longer than one): column
71    /// (interleaved) protection recovers a burst no longer than a row.
72    Bursty,
73    /// Both: rows and columns.
74    Mixed,
75}
76
77/// Runs of consecutive lost packets, read from per-packet feedback, each sequence number space
78/// (transport-wide, or one stream's RTP sequence numbers) on its own.
79#[derive(Debug, Clone, Default)]
80struct LossRuns {
81    /// By space (`None`: transport-wide): the newest sequence number read and the length of the
82    /// run of lost packets it ends, if it was lost.
83    spaces: HashMap<Option<u32>, (u16, u32)>,
84    /// The lengths of the most recent runs that ended, oldest first.
85    runs: VecDeque<u32>,
86}
87
88impl LossRuns {
89    fn close(&mut self, run: u32) {
90        if run == 0 {
91            return;
92        }
93        if self.runs.len() == LOSS_RUN_WINDOW {
94            self.runs.pop_front();
95        }
96        self.runs.push_back(run);
97    }
98
99    fn on_acknowledgements(&mut self, space: Option<u32>, acknowledgements: &[Acknowledgement]) {
100        for acknowledgement in acknowledgements {
101            let sequence_number = acknowledgement.sequence_number;
102            let open = match self.spaces.get(&space).copied() {
103                Some((newest, open)) => {
104                    let step = sequence_number.wrapping_sub(newest);
105                    // Reported before (feedback ranges may overlap), or older.
106                    if step == 0 || step >= 0x8000 {
107                        continue;
108                    }
109                    // Packets no feedback reported: the run cannot be known to go on.
110                    if step > 1 {
111                        self.close(open);
112                        0
113                    } else {
114                        open
115                    }
116                }
117                None => 0,
118            };
119            let open = if acknowledgement.arrived {
120                self.close(open);
121                0
122            } else {
123                open + 1
124            };
125            self.spaces.insert(space, (sequence_number, open));
126        }
127    }
128
129    fn pattern(&self) -> Option<LossPattern> {
130        if self.runs.len() < MIN_LOSS_RUNS {
131            return None;
132        }
133        let bursts = self.runs.iter().filter(|run| **run > 1).count();
134        Some(if bursts * 4 < self.runs.len() {
135            LossPattern::Random
136        } else if bursts * 4 > self.runs.len() * 3 {
137            LossPattern::Bursty
138        } else {
139            LossPattern::Mixed
140        })
141    }
142}
143
144/// The loss-driven amount of FEC for one sender. See the module documentation.
145#[derive(Debug, Clone)]
146pub struct FecRate {
147    media_packets: u32,
148    configured: u32,
149    max: u32,
150    adaptive: bool,
151    loss: Option<f64>,
152    /// Repair packets sent in the last [`RATE_WINDOW`]: when and how many octets.
153    sent: VecDeque<(Instant, usize)>,
154    /// The round trip within which retransmission is preferred to FEC; `None`: FEC whatever
155    /// the round trip.
156    latency_budget: Option<Duration>,
157    /// The newest round trip measured to the receiver of a protected stream.
158    round_trip_time: Option<Duration>,
159    /// The runs of lost packets the feedback reported.
160    loss_runs: LossRuns,
161}
162
163impl FecRate {
164    /// `fec_packets` repair packets per `media_packets` source packets until the loss is known;
165    /// `adaptive` false keeps that amount whatever the loss.
166    pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
167        let media_packets = media_packets.max(1);
168        Self {
169            media_packets,
170            configured: fec_packets,
171            max: media_packets.div_ceil(2).max(fec_packets),
172            adaptive,
173            loss: None,
174            sent: VecDeque::new(),
175            latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
176            round_trip_time: None,
177            loss_runs: LossRuns::default(),
178        }
179    }
180
181    /// The round trip within which a stream that can be repaired by retransmission gets no FEC
182    /// (RFC 8854 section 8); [`FEC_DEFAULT_LATENCY_BUDGET`] by default. `None` is the
183    /// application paying for proactive FEC: the amount follows the loss whatever the round
184    /// trip.
185    pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
186        self.latency_budget = latency_budget;
187        self
188    }
189
190    /// The latency budget in force.
191    pub fn latency_budget(&self) -> Option<Duration> {
192        self.latency_budget
193    }
194
195    /// The newest round trip measured to the receiver of a protected stream.
196    pub fn round_trip_time(&self) -> Option<Duration> {
197        self.round_trip_time
198    }
199
200    /// A round trip measured to the receiver of a protected stream.
201    pub fn on_round_trip_time(&mut self, round_trip_time: Duration) {
202        self.round_trip_time = Some(round_trip_time);
203    }
204
205    /// Whether retransmission is to repair a stream that can be retransmitted, rather than FEC:
206    /// the amount follows the loss, a latency budget is set, and the round trip measured is
207    /// within it.
208    pub fn retransmission_preferred(&self) -> bool {
209        self.adaptive
210            && matches!(
211                (self.round_trip_time, self.latency_budget),
212                (Some(round_trip_time), Some(budget)) if round_trip_time <= budget
213            )
214    }
215
216    /// Repair packets for the next block of a stream; `retransmission`: whether the stream can
217    /// be repaired by retransmission. None while [`retransmission_preferred`](Self::retransmission_preferred),
218    /// otherwise [`fec_packets`](Self::fec_packets).
219    pub fn fec_packets_with(&self, retransmission: bool) -> u32 {
220        if retransmission && self.retransmission_preferred() {
221            0
222        } else {
223            self.fec_packets()
224        }
225    }
226
227    /// Repair packets for a block of `media_packets` source packets that closed short (or is
228    /// shorter than the configured block), as [`fec_packets_with`](Self::fec_packets_with)
229    /// decides for a full one, and never more than the block has packets.
230    pub fn fec_packets_for(&self, media_packets: u32, retransmission: bool) -> u32 {
231        let media_packets = media_packets.max(1);
232        if retransmission && self.retransmission_preferred() {
233            return 0;
234        }
235        match self.loss {
236            Some(loss) if self.adaptive => {
237                if loss < MIN_LOSS {
238                    0
239                } else {
240                    ((2.0 * loss * f64::from(media_packets)).ceil() as u32)
241                        .max(1)
242                        .min(self.max)
243                        .min(media_packets)
244                }
245            }
246            _ => self.configured.min(media_packets),
247        }
248    }
249
250    /// Per-packet feedback for one sequence number space: `ssrc` names the stream an RFC 8888
251    /// report is about, `None` is transport-wide feedback. Feeds [`loss_pattern`](Self::loss_pattern).
252    pub fn on_acknowledgements(&mut self, ssrc: Option<u32>, acknowledgements: &[Acknowledgement]) {
253        self.loss_runs.on_acknowledgements(ssrc, acknowledgements);
254    }
255
256    /// Whether the recent losses were isolated, in bursts, or both (the last 32 runs of lost
257    /// packets; `None` before four runs were seen).
258    pub fn loss_pattern(&self) -> Option<LossPattern> {
259        self.loss_runs.pattern()
260    }
261
262    /// The most repair packets per block, whatever the loss.
263    pub fn with_max(mut self, max: u32) -> Self {
264        self.max = max;
265        self
266    }
267
268    /// The most repair packets per block.
269    pub fn max(&self) -> u32 {
270        self.max
271    }
272
273    /// Whether the amount follows the loss (`false`: the configured amount whatever happens).
274    pub fn adaptive(&self) -> bool {
275        self.adaptive
276    }
277
278    /// The smoothed loss fraction, once a report gave one.
279    pub fn loss(&self) -> Option<f64> {
280        self.loss
281    }
282
283    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for a protected stream.
284    pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
285        let sample = f64::from(fraction_lost) / 256.0;
286        self.loss = Some(match self.loss {
287            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
288            None => sample,
289        });
290    }
291
292    /// Repair packets for the next block.
293    pub fn fec_packets(&self) -> u32 {
294        match self.loss {
295            Some(loss) if self.adaptive => {
296                if loss < MIN_LOSS {
297                    0
298                } else {
299                    // At least one, unless the bound allows none (`clamp` would panic on it).
300                    ((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
301                        .max(1)
302                        .min(self.max)
303                }
304            }
305            _ => self.configured,
306        }
307    }
308
309    /// Whether any repair is to be sent now (for protection shapes whose amount is fixed:
310    /// sent or not).
311    pub fn protects(&self) -> bool {
312        self.fec_packets() > 0
313    }
314
315    /// A repair packet of `size` octets left at `now`.
316    pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
317        self.sent.push_back((now, size));
318        self.expire(now);
319    }
320
321    fn expire(&mut self, now: Instant) {
322        while self
323            .sent
324            .front()
325            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
326        {
327            self.sent.pop_front();
328        }
329    }
330
331    /// The bit rate of the repair packets of the last second at `now`.
332    pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
333        self.expire(now);
334        self.sent
335            .iter()
336            .map(|(_, size)| *size as f64 * 8.0)
337            .sum::<f64>()
338            / RATE_WINDOW.as_secs_f64()
339    }
340
341    /// The target the application encodes at, out of the congestion controller's `target`:
342    /// what is left after the FEC.
343    pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
344        (target - self.fec_bitrate(now)).max(0.0)
345    }
346
347    /// Reads what an inbound packet tells the FEC rate, and takes the FEC out of a target it
348    /// carries: the receiver reports of `protected` streams feed the loss, the round trip the
349    /// RTCP session measured to one of them the latency rule, per-packet feedback (transport-wide,
350    /// and RFC 8888 reports on `protected` streams) the loss pattern, and an
351    /// [`Attribute::TargetBitrateChanged`] on the packet is lowered by the FEC bit rate.
352    pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
353        if let Some(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }) =
354            msg.message.custom::<crate::RtcpSessionEvent>()
355            && protected(*ssrc)
356        {
357            self.round_trip_time = Some(*rtt);
358        }
359        if let Packet::Rtcp(packets) = &msg.message.packet {
360            for packet in packets {
361                let any = packet.as_any();
362                if let Some(feedback) = any
363                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc>(
364                ) {
365                    let acknowledgements = crate::rtpfb::convert::convert_twcc(feedback);
366                    self.loss_runs.on_acknowledgements(None, &acknowledgements);
367                    continue;
368                }
369                if let Some(feedback) = any
370                    .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>(
371                ) {
372                    let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
373                    for (ssrc, acknowledgements) in per_stream {
374                        if protected(ssrc) {
375                            self.loss_runs
376                                .on_acknowledgements(Some(ssrc), &acknowledgements);
377                        }
378                    }
379                    continue;
380                }
381                let reports = if let Some(rr) =
382                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
383                {
384                    &rr.reports
385                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
386                    &sr.reports
387                } else {
388                    continue;
389                };
390                for report in reports {
391                    if protected(report.ssrc) {
392                        self.on_fraction_lost(report.fraction_lost);
393                    }
394                }
395            }
396        }
397        let now = msg.now;
398        let fec = self.fec_bitrate(now);
399        if fec > 0.0 {
400            for attribute in &mut msg.message.attributes {
401                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
402                    *bits_per_second = (*bits_per_second - fec).max(0.0);
403                }
404            }
405        }
406    }
407}
408
409#[cfg(test)]
410mod tests {
411    use super::*;
412
413    #[test]
414    fn before_any_report_the_configured_amount_is_sent() {
415        assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
416        assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
417    }
418
419    #[test]
420    fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
421        let mut rate = FecRate::new(10, 1, true);
422        rate.on_fraction_lost(0);
423        assert_eq!(
424            rate.fec_packets(),
425            0,
426            "repair that helps nothing is not sent"
427        );
428        let mut rate = FecRate::new(10, 1, true);
429        rate.on_fraction_lost(5); // 2%
430        assert_eq!(rate.fec_packets(), 1);
431        let mut rate = FecRate::new(10, 1, true);
432        rate.on_fraction_lost(13); // 5%
433        assert_eq!(rate.fec_packets(), 2);
434        let mut rate = FecRate::new(10, 1, true);
435        rate.on_fraction_lost(51); // 20%
436        assert_eq!(rate.fec_packets(), 4);
437        let mut rate = FecRate::new(10, 1, true);
438        rate.on_fraction_lost(200); // 78%
439        assert_eq!(rate.fec_packets(), 5, "at most half the block");
440    }
441
442    #[test]
443    fn the_loss_is_smoothed_over_reports() {
444        let mut rate = FecRate::new(10, 1, true);
445        rate.on_fraction_lost(51);
446        rate.on_fraction_lost(0);
447        let loss = rate.loss().unwrap();
448        assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
449        assert_eq!(rate.fec_packets(), 3);
450    }
451
452    #[test]
453    fn a_fixed_rate_ignores_the_loss() {
454        let mut rate = FecRate::new(10, 1, false);
455        rate.on_fraction_lost(0);
456        assert_eq!(rate.fec_packets(), 1);
457        rate.on_fraction_lost(128);
458        assert_eq!(rate.fec_packets(), 1);
459    }
460
461    #[test]
462    fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
463        let mut rate = FecRate::new(10, 1, true);
464        let now = Instant::now();
465        for n in 0..10u64 {
466            rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
467        }
468        let at = now + Duration::from_millis(950);
469        assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
470        assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
471        // A second later the repair has aged out.
472        assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
473    }
474
475    /// RFC 8854 section 8: retransmission is preferred to FEC while the round trip is within
476    /// the latency budget, for a stream that can be retransmitted; otherwise the amount
477    /// follows the loss.
478    #[test]
479    fn within_the_latency_budget_a_stream_with_rtx_gets_no_fec() {
480        let mut rate = FecRate::new(10, 1, true);
481        assert_eq!(rate.latency_budget(), Some(FEC_DEFAULT_LATENCY_BUDGET));
482        rate.on_fraction_lost(51); // 20%
483        assert_eq!(rate.fec_packets(), 4, "precondition: the loss asks for FEC");
484        assert_eq!(rate.fec_packets_with(true), 4, "no round trip measured yet");
485        rate.on_round_trip_time(Duration::from_millis(80));
486        assert!(rate.retransmission_preferred());
487        assert_eq!(
488            rate.fec_packets_with(true),
489            0,
490            "RTX repairs within the budget"
491        );
492        assert_eq!(rate.fec_packets_for(3, true), 0);
493        assert_eq!(
494            rate.fec_packets_with(false),
495            4,
496            "a stream without RTX keeps its FEC"
497        );
498        rate.on_round_trip_time(FEC_DEFAULT_LATENCY_BUDGET + Duration::from_millis(1));
499        assert_eq!(
500            rate.fec_packets_with(true),
501            4,
502            "beyond the budget FEC follows the loss"
503        );
504        // No budget: the application pays for proactive FEC.
505        let mut rate = FecRate::new(10, 1, true).with_latency_budget(None);
506        rate.on_fraction_lost(51);
507        rate.on_round_trip_time(Duration::from_millis(1));
508        assert_eq!(rate.fec_packets_with(true), 4);
509        // A fixed amount was asked for explicitly.
510        let mut rate = FecRate::new(10, 2, false);
511        rate.on_round_trip_time(Duration::from_millis(1));
512        assert_eq!(rate.fec_packets_with(true), 2);
513    }
514
515    /// A block that closed short gets its share of the repair, never more packets than it has.
516    #[test]
517    fn a_short_block_gets_its_share_of_the_repair() {
518        let mut rate = FecRate::new(10, 1, true);
519        rate.on_fraction_lost(51); // 20%: 4 for 10 packets
520        assert_eq!(rate.fec_packets_for(10, false), 4);
521        assert_eq!(rate.fec_packets_for(3, false), 2);
522        assert_eq!(rate.fec_packets_for(1, false), 1);
523        let rate = FecRate::new(10, 3, false);
524        assert_eq!(rate.fec_packets_for(2, false), 2);
525    }
526
527    fn session_round_trip(ssrc: u32, rtt: Duration) -> TaggedPacket {
528        TaggedPacket {
529            now: Instant::now(),
530            transport: shared::TransportContext::default(),
531            message: crate::AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
532                std::sync::Arc::new(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }),
533            )),
534        }
535    }
536
537    /// The round trip the RTCP session measured to the receiver of a protected stream is the
538    /// one the latency rule reads; another stream's is not.
539    #[test]
540    fn the_round_trip_the_rtcp_session_measured_to_a_protected_stream_is_read() {
541        let mut rate = FecRate::new(10, 1, true);
542        rate.on_read(
543            &mut session_round_trip(7, Duration::from_millis(40)),
544            |ssrc| ssrc == 9,
545        );
546        assert_eq!(rate.round_trip_time(), None, "not a protected stream");
547        rate.on_read(
548            &mut session_round_trip(9, Duration::from_millis(40)),
549            |ssrc| ssrc == 9,
550        );
551        assert_eq!(rate.round_trip_time(), Some(Duration::from_millis(40)));
552    }
553
554    fn acks(statuses: &[(u16, bool)]) -> Vec<Acknowledgement> {
555        statuses
556            .iter()
557            .map(|&(sequence_number, arrived)| {
558                if arrived {
559                    Acknowledgement::received(
560                        sequence_number,
561                        None,
562                        rtcp::transport_feedbacks::cc_feedback_report::Ecn::NotEct,
563                    )
564                } else {
565                    Acknowledgement::lost(sequence_number)
566                }
567            })
568            .collect()
569    }
570
571    /// A run of `lost` packets lost then one received, from `first`.
572    fn run(first: u16, lost: u16) -> Vec<(u16, bool)> {
573        (0..lost)
574            .map(|offset| (first.wrapping_add(offset), false))
575            .chain(std::iter::once((first.wrapping_add(lost), true)))
576            .collect()
577    }
578
579    /// RFC 8627 sections 1.1.3, 1.1.4 and 8: isolated losses, bursts, and both, read from the
580    /// runs of lost packets.
581    #[test]
582    fn isolated_losses_bursts_and_both_are_told_apart() {
583        let pattern = |runs: &[u16]| {
584            let mut rate = FecRate::new(12, 7, true);
585            let mut at = 1000u16;
586            for lost in runs {
587                rate.on_acknowledgements(None, &acks(&run(at, *lost)));
588                at = at.wrapping_add(lost + 1);
589            }
590            rate.loss_pattern()
591        };
592        assert_eq!(pattern(&[1, 1, 1]), None, "too few runs to tell");
593        assert_eq!(pattern(&[1; 8]), Some(LossPattern::Random));
594        assert_eq!(
595            pattern(&[1, 1, 1, 1, 1, 1, 1, 2]),
596            Some(LossPattern::Random)
597        );
598        assert_eq!(pattern(&[3; 8]), Some(LossPattern::Bursty));
599        assert_eq!(pattern(&[1, 4, 1, 4, 1, 4, 1, 4]), Some(LossPattern::Mixed));
600        // The window is the last 32 runs: bursts long ago are forgotten.
601        let mut runs = vec![3u16; 32];
602        runs.extend([1u16; 32]);
603        assert_eq!(pattern(&runs), Some(LossPattern::Random));
604    }
605
606    /// A packet reported twice (overlapping feedback) is read once, a run cut by packets no
607    /// report covered is not taken as going on, and the streams of RFC 8888 reports are runs
608    /// of their own.
609    #[test]
610    fn feedback_is_read_once_per_packet_and_per_sequence_space() {
611        let mut rate = FecRate::new(12, 7, true);
612        // Four bursts of two, each report repeating the packets of the one before.
613        let mut previous: Vec<(u16, bool)> = Vec::new();
614        for first in [10u16, 13, 16, 19] {
615            let mut report = previous.clone();
616            report.extend(run(first, 2));
617            rate.on_acknowledgements(None, &acks(&report));
618            previous = run(first, 2);
619        }
620        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
621        // Isolated losses on two streams, interleaved: neither joins the other's runs.
622        let mut rate = FecRate::new(12, 7, true);
623        for first in [100u16, 102, 104, 106] {
624            rate.on_acknowledgements(Some(1), &acks(&run(first, 1)));
625            rate.on_acknowledgements(Some(2), &acks(&run(first, 1)));
626        }
627        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
628        // Lost packets on either side of a stretch no report covered are two runs.
629        let mut rate = FecRate::new(12, 7, true);
630        for first in [200u16, 300, 400, 500] {
631            rate.on_acknowledgements(None, &acks(&[(first, false)]));
632            rate.on_acknowledgements(None, &acks(&[(first + 50, false), (first + 51, true)]));
633        }
634        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
635    }
636
637    /// Transport-wide feedback read through `on_read` feeds the pattern; an RFC 8888 report
638    /// only for a protected stream.
639    #[test]
640    fn per_packet_feedback_on_the_read_path_feeds_the_loss_pattern() {
641        use rtcp::transport_feedbacks::transport_layer_cc::{
642            PacketStatusChunk, RecvDelta, RunLengthChunk, SymbolTypeTcc, TransportLayerCc,
643        };
644        let chunk = |symbol, run_length| {
645            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
646                packet_status_symbol: symbol,
647                run_length,
648                ..Default::default()
649            })
650        };
651        let mut rate = FecRate::new(12, 7, true);
652        let mut base = 500u16;
653        for _ in 0..4 {
654            // Three lost, then two received.
655            let feedback = TransportLayerCc {
656                base_sequence_number: base,
657                packet_status_count: 5,
658                packet_chunks: vec![
659                    chunk(SymbolTypeTcc::PacketNotReceived, 3),
660                    chunk(SymbolTypeTcc::PacketReceivedSmallDelta, 2),
661                ],
662                recv_deltas: vec![
663                    RecvDelta {
664                        delta: 1000,
665                        ..Default::default()
666                    };
667                    2
668                ],
669                ..Default::default()
670            };
671            let mut msg = TaggedPacket {
672                now: Instant::now(),
673                transport: shared::TransportContext::default(),
674                message: crate::AttributedPacket::new(Packet::Rtcp(vec![Box::new(feedback)])),
675            };
676            rate.on_read(&mut msg, |_| true);
677            base = base.wrapping_add(5);
678        }
679        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
680    }
681
682    /// A fixed corpus of arbitrary report and send sequences: the repair per block stays
683    /// within zero and the bound, the media target never goes negative or above the target it
684    /// is cut from, and the FEC bit rate never goes negative.
685    #[test]
686    fn arbitrary_reports_keep_the_rate_within_its_bounds() {
687        let mut state = 0x0FEC_0001u32;
688        let mut next = move || {
689            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
690            state >> 8
691        };
692        for _ in 0..300 {
693            let media = 1 + next() % 48;
694            let configured = next() % 8;
695            let mut rate = FecRate::new(media, configured, next() % 4 != 0);
696            if next() % 3 == 0 {
697                rate = rate.with_max(next() % 30);
698            }
699            let mut at = Instant::now();
700            for _ in 0..300 {
701                at += Duration::from_millis(u64::from(next() % 200));
702                match next() % 3 {
703                    0 => rate.on_fraction_lost(next() as u8),
704                    1 => rate.on_repair_sent(at, (next() % 1500) as usize),
705                    _ => {
706                        let k = rate.fec_packets();
707                        assert!(k <= rate.max().max(configured), "{k} over the bound");
708                        let target = f64::from(next() % 5_000_000);
709                        let media_target = rate.media_target(at, target);
710                        assert!((0.0..=target).contains(&media_target));
711                        assert!(rate.fec_bitrate(at) >= 0.0);
712                    }
713                }
714            }
715        }
716    }
717}