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//! * RFC 8627 section 8: "the applications MUST NOT arbitrarily increase the amount of FEC
40//!   protection since doing so may lead to a congestion collapse. If desired, stronger FEC
41//!   protection MAY be applied only after the source rate has been reduced." Once a congestion
42//!   controller's target has gone by ([`Attribute::TargetBitrateChanged`]), more FEC than is
43//!   sent now waits until the source's rate leaves room for it under that target: the source
44//!   packets handed to the sender in the last second ([`FecRate::on_media_sent`]) plus the FEC
45//!   the stronger amount would add (its share of the protected packets) within the target (5%
46//!   tolerance for an encoder's aim). Meanwhile the target on its way to the application is
47//!   lowered by the FEC asked for, not only by the FEC sent, so the application makes the room;
48//!   when it passes no target, the lowered one rides up on the next inbound packet. Less FEC is
49//!   never held. Without a target (no congestion controller in the chain) the amount follows
50//!   the loss as before; [`FecRate::with_source_rate_first`] `false` turns the rule off.
51
52use crate::rtpfb::acknowledgement::Acknowledgement;
53use crate::{Attribute, Packet, TaggedPacket};
54use std::collections::{HashMap, VecDeque};
55use std::time::{Duration, Instant};
56
57/// Smoothed loss under which no repair packet is sent: it would not help recover anything.
58pub const MIN_LOSS: f64 = 0.005;
59/// Weight of a new report in the smoothed loss.
60const LOSS_WEIGHT: f64 = 0.3;
61/// The window the FEC bit rate is measured over.
62const RATE_WINDOW: Duration = Duration::from_secs(1);
63
64/// The latency budget a FEC sender assumes when its builder names none: the round trip within
65/// which a retransmission is preferred to FEC (RFC 8854 section 8). ITU-T G.114 (05/2003)
66/// takes a one-way delay of up to 150 ms as acceptable to most interactive applications; a
67/// retransmission delays the packet it repairs by about one round trip.
68pub const FEC_DEFAULT_LATENCY_BUDGET: Duration = Duration::from_millis(150);
69
70/// How far above the congestion controller's target the source and the stronger FEC may be
71/// measured and still count as within it (RFC 8627 section 8; an encoder aims at its target and
72/// lands about it).
73const SOURCE_RATE_TOLERANCE: f64 = 0.05;
74/// How far (of the target) the target for the application must fall before it is told again
75/// while stronger FEC waits.
76const ANNOUNCE_STEP: f64 = 0.01;
77
78/// How many of the most recent runs of lost packets [`FecRate::loss_pattern`] reads.
79const LOSS_RUN_WINDOW: usize = 32;
80/// Runs of lost packets needed before a pattern is named.
81const MIN_LOSS_RUNS: usize = 4;
82
83/// What the recent losses of the path looked like (RFC 8627 sections 1.1.3, 1.1.4 and 8).
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85#[non_exhaustive]
86pub enum LossPattern {
87    /// Isolated losses (fewer than a quarter of the runs of lost packets are longer than one):
88    /// row (non-interleaved) protection recovers them.
89    Random,
90    /// Losses in bursts (more than three quarters of the runs are longer than one): column
91    /// (interleaved) protection recovers a burst no longer than a row.
92    Bursty,
93    /// Both: rows and columns.
94    Mixed,
95}
96
97/// Runs of consecutive lost packets, read from per-packet feedback, each sequence number space
98/// (transport-wide, or one stream's RTP sequence numbers) on its own.
99#[derive(Debug, Clone, Default)]
100struct LossRuns {
101    /// By space (`None`: transport-wide): the newest sequence number read and the length of the
102    /// run of lost packets it ends, if it was lost.
103    spaces: HashMap<Option<u32>, (u16, u32)>,
104    /// The lengths of the most recent runs that ended, oldest first.
105    runs: VecDeque<u32>,
106}
107
108impl LossRuns {
109    fn close(&mut self, run: u32) {
110        if run == 0 {
111            return;
112        }
113        if self.runs.len() == LOSS_RUN_WINDOW {
114            self.runs.pop_front();
115        }
116        self.runs.push_back(run);
117    }
118
119    fn on_acknowledgements(&mut self, space: Option<u32>, acknowledgements: &[Acknowledgement]) {
120        for acknowledgement in acknowledgements {
121            let sequence_number = acknowledgement.sequence_number;
122            let open = match self.spaces.get(&space).copied() {
123                Some((newest, open)) => {
124                    let step = sequence_number.wrapping_sub(newest);
125                    // Reported before (feedback ranges may overlap), or older.
126                    if step == 0 || step >= 0x8000 {
127                        continue;
128                    }
129                    // Packets no feedback reported: the run cannot be known to go on.
130                    if step > 1 {
131                        self.close(open);
132                        0
133                    } else {
134                        open
135                    }
136                }
137                None => 0,
138            };
139            let open = if acknowledgement.arrived {
140                self.close(open);
141                0
142            } else {
143                open + 1
144            };
145            self.spaces.insert(space, (sequence_number, open));
146        }
147    }
148
149    fn pattern(&self) -> Option<LossPattern> {
150        if self.runs.len() < MIN_LOSS_RUNS {
151            return None;
152        }
153        let bursts = self.runs.iter().filter(|run| **run > 1).count();
154        Some(if bursts * 4 < self.runs.len() {
155            LossPattern::Random
156        } else if bursts * 4 > self.runs.len() * 3 {
157            LossPattern::Bursty
158        } else {
159            LossPattern::Mixed
160        })
161    }
162}
163
164/// The loss-driven amount of FEC for one sender. See the module documentation.
165#[derive(Debug, Clone)]
166pub struct FecRate {
167    media_packets: u32,
168    configured: u32,
169    max: u32,
170    adaptive: bool,
171    loss: Option<f64>,
172    /// Repair packets sent in the last [`RATE_WINDOW`]: when and how many octets.
173    sent: VecDeque<(Instant, usize)>,
174    /// The round trip within which retransmission is preferred to FEC; `None`: FEC whatever
175    /// the round trip.
176    latency_budget: Option<Duration>,
177    /// The newest round trip measured to the receiver of a protected stream.
178    round_trip_time: Option<Duration>,
179    /// The runs of lost packets the feedback reported.
180    loss_runs: LossRuns,
181    /// Stronger FEC only after the source rate has been reduced (RFC 8627 section 8).
182    source_rate_first: bool,
183    /// The protection is a fixed shape (RFC 8627 rows / columns), sent whole or not at all: its
184    /// cost is the configured amount whenever any is sent.
185    fixed_shape: bool,
186    /// Source packets handed to the sender in the last [`RATE_WINDOW`]: when, how many octets,
187    /// and whether their stream is protected.
188    media: VecDeque<(Instant, usize, bool)>,
189    /// The octets of `media`, all and protected.
190    media_octets: usize,
191    protected_octets: usize,
192    /// The newest congestion controller's target that went by, before the FEC was taken out.
193    target: Option<f64>,
194    /// The FEC (repair packets per source packet) in force since the rule applies: more waits
195    /// for room under `target`. `None` until a target went by.
196    granted: Option<f64>,
197    /// The target the application was last told on this sender's way.
198    announced: Option<f64>,
199    /// Every protected stream can be repaired by retransmission (RTX, or FlexFEC's own: the
200    /// encoder says so, [`FecRate::set_retransmission_repairable`]): while
201    /// [`retransmission_preferred`](Self::retransmission_preferred) no FEC will be sent, so
202    /// none is asked for, held or reserved.
203    retransmission_repairable: bool,
204}
205
206impl FecRate {
207    /// `fec_packets` repair packets per `media_packets` source packets until the loss is known;
208    /// `adaptive` false keeps that amount whatever the loss.
209    pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
210        let media_packets = media_packets.max(1);
211        Self {
212            media_packets,
213            configured: fec_packets,
214            max: media_packets.div_ceil(2).max(fec_packets),
215            adaptive,
216            loss: None,
217            sent: VecDeque::new(),
218            latency_budget: Some(FEC_DEFAULT_LATENCY_BUDGET),
219            round_trip_time: None,
220            loss_runs: LossRuns::default(),
221            source_rate_first: true,
222            fixed_shape: false,
223            media: VecDeque::new(),
224            media_octets: 0,
225            protected_octets: 0,
226            target: None,
227            granted: None,
228            announced: None,
229            retransmission_repairable: false,
230        }
231    }
232
233    /// The encoder's word that every stream it protects can be repaired by retransmission (RTX,
234    /// or FlexFEC retransmissions where RFC 8627 section 1.1.7 left FlexFEC alone), or not.
235    /// While it does and [`retransmission_preferred`](Self::retransmission_preferred) holds, the
236    /// encoder sends no FEC (RFC 8854 section 8), so nothing is asked for, held or taken out of
237    /// the target for FEC that will not be sent.
238    pub(crate) fn set_retransmission_repairable(&mut self, repairable: bool) {
239        self.retransmission_repairable = repairable;
240    }
241
242    /// Whether FEC can be sent now: not while every protected stream is left to retransmission
243    /// within the latency budget.
244    fn fec_expected(&self) -> bool {
245        !(self.retransmission_repairable && self.left_to_retransmission())
246    }
247
248    /// Whether a stream that can be repaired by retransmission gets no FEC now: while
249    /// [`retransmission_preferred`](Self::retransmission_preferred), and, when the amount follows
250    /// the loss within a latency budget, before any receiver report told the loss (RFC 8854
251    /// section 8: retransmission is preferred within the budget, "and otherwise ... only the
252    /// amount of FEC needed to protect against the observed packet loss": none is observed yet,
253    /// and nothing says the round trip is beyond the budget). A stream without retransmission
254    /// has nothing else, and keeps the configured amount until the loss is known.
255    fn left_to_retransmission(&self) -> bool {
256        self.retransmission_preferred()
257            || (self.adaptive && self.latency_budget.is_some() && self.loss.is_none())
258    }
259
260    /// Whether stronger FEC waits until the source rate has been reduced (RFC 8627 section 8;
261    /// the default): once a congestion controller's target went by, the amount of FEC rises
262    /// only when the source sent in the last second plus the FEC the higher amount adds fit
263    /// within that target, and the target for the application is lowered by the FEC asked for
264    /// so the source makes the room. `false`: the amount follows the loss at once, and only
265    /// the FEC sent is taken out of the target.
266    pub fn with_source_rate_first(mut self, source_rate_first: bool) -> Self {
267        self.source_rate_first = source_rate_first;
268        self
269    }
270
271    /// Whether stronger FEC waits until the source rate has been reduced.
272    pub fn source_rate_first(&self) -> bool {
273        self.source_rate_first
274    }
275
276    /// The protection is a fixed shape (sent whole or not at all), whose cost is the configured
277    /// amount whenever any is sent.
278    pub(crate) fn with_fixed_shape(mut self, fixed_shape: bool) -> Self {
279        self.fixed_shape = fixed_shape;
280        self
281    }
282
283    /// A source packet of `size` octets was handed to the sender at `now`; `protected`: its
284    /// stream is one this sender protects. Retransmissions and repair packets are not source
285    /// packets.
286    pub fn on_media_sent(&mut self, now: Instant, size: usize, protected: bool) {
287        self.media.push_back((now, size, protected));
288        self.media_octets += size;
289        if protected {
290            self.protected_octets += size;
291        }
292        self.admit(now);
293    }
294
295    /// Reads what an outbound packet tells the rate: an RTP packet that is no retransmission is
296    /// a source packet ([`on_media_sent`](Self::on_media_sent)).
297    pub(crate) fn on_write(&mut self, msg: &TaggedPacket, protected: impl Fn(u32) -> bool) {
298        if let Packet::Rtp(rtp_packet) = &msg.message.packet
299            && !msg.message.has(&Attribute::Retransmission)
300        {
301            let size = shared::marshal::MarshalSize::marshal_size(rtp_packet);
302            self.on_media_sent(msg.now, size, protected(rtp_packet.header.ssrc));
303        }
304    }
305
306    fn expire_media(&mut self, now: Instant) {
307        while let Some(&(at, size, protected)) = self.media.front() {
308            if now.saturating_duration_since(at) <= RATE_WINDOW {
309                break;
310            }
311            self.media.pop_front();
312            self.media_octets -= size;
313            if protected {
314                self.protected_octets -= size;
315            }
316        }
317    }
318
319    /// The bit rate of the source packets handed to the sender in the last second at `now`.
320    pub fn media_bitrate(&mut self, now: Instant) -> f64 {
321        self.expire_media(now);
322        self.media_octets as f64 * 8.0 / RATE_WINDOW.as_secs_f64()
323    }
324
325    /// [`media_bitrate`](Self::media_bitrate) of the protected streams.
326    fn protected_bitrate(&mut self, now: Instant) -> f64 {
327        self.expire_media(now);
328        self.protected_octets as f64 * 8.0 / RATE_WINDOW.as_secs_f64()
329    }
330
331    /// Whether the rule of RFC 8627 section 8 applies now: the amount follows the loss, the rule
332    /// is on, and a congestion controller's target went by.
333    fn gated(&self) -> bool {
334        self.adaptive && self.source_rate_first && self.target.is_some() && self.fec_expected()
335    }
336
337    /// Repair packets per source packet the loss asks for (the configured shape's whole amount
338    /// for a fixed shape).
339    fn wanted_overhead(&self) -> f64 {
340        let wanted = self.wanted_packets();
341        if wanted == 0 {
342            0.0
343        } else if self.fixed_shape {
344            f64::from(self.configured) / f64::from(self.media_packets)
345        } else {
346            f64::from(wanted) / f64::from(self.media_packets)
347        }
348    }
349
350    /// Raises the FEC in force towards what the loss asks for as far as the source leaves room
351    /// under the target, or lowers it to that at once.
352    fn admit(&mut self, now: Instant) {
353        if !self.gated() {
354            return;
355        }
356        let wanted = self.wanted_overhead();
357        let granted = *self.granted.get_or_insert(wanted);
358        if wanted <= granted {
359            self.granted = Some(wanted);
360            return;
361        }
362        let Some(target) = self.target else {
363            return;
364        };
365        let media = self.media_bitrate(now);
366        let protected = self.protected_bitrate(now);
367        let room = target * (1.0 + SOURCE_RATE_TOLERANCE) - media;
368        let fits = if protected > 0.0 {
369            room / protected
370        } else if room >= 0.0 {
371            wanted
372        } else {
373            0.0
374        };
375        let admitted = if self.fixed_shape {
376            if fits >= wanted { wanted } else { granted }
377        } else {
378            // Whole repair packets per block.
379            let block = f64::from(self.media_packets);
380            (fits.min(wanted) * block + 1e-9).floor() / block
381        };
382        if admitted > granted {
383            self.granted = Some(admitted);
384        }
385    }
386
387    /// `wanted` repair packets for a block of `media_packets`, held to the FEC in force while
388    /// the rule applies.
389    fn held(&self, wanted: u32, media_packets: u32) -> u32 {
390        let Some(granted) = self.granted.filter(|_| self.gated()) else {
391            return wanted;
392        };
393        if self.fixed_shape {
394            let whole = f64::from(self.configured) / f64::from(self.media_packets);
395            return if granted + 1e-9 >= whole { wanted } else { 0 };
396        }
397        wanted.min((granted * f64::from(media_packets) - 1e-9).ceil().max(0.0) as u32)
398    }
399
400    /// The FEC to take out of the target on its way to the application at `now`: the FEC sent
401    /// in the last second, or, while the rule is on, the FEC the loss asks for if that is more.
402    ///
403    /// The FEC asked for is that of a protected source at most the target: after a collapse of
404    /// the target the source rate of the last second is no measure of the FEC to come, and the
405    /// application must not be told to stop for it. None is asked for FEC that will not be sent
406    /// ([`FecRate::set_retransmission_repairable`]).
407    fn reserve(&mut self, now: Instant) -> f64 {
408        let sent = self.fec_bitrate(now);
409        if !(self.adaptive && self.source_rate_first) || !self.fec_expected() {
410            return sent;
411        }
412        let protected = self.protected_bitrate(now);
413        let source = self
414            .target
415            .map_or(protected, |target| protected.min(target));
416        let asked = self.wanted_overhead() * source;
417        sent.max(asked)
418    }
419
420    /// The round trip within which a stream that can be repaired by retransmission gets no FEC
421    /// (RFC 8854 section 8); [`FEC_DEFAULT_LATENCY_BUDGET`] by default. `None` is the
422    /// application paying for proactive FEC: the amount follows the loss whatever the round
423    /// trip.
424    pub fn with_latency_budget(mut self, latency_budget: Option<Duration>) -> Self {
425        self.latency_budget = latency_budget;
426        self
427    }
428
429    /// The latency budget in force.
430    pub fn latency_budget(&self) -> Option<Duration> {
431        self.latency_budget
432    }
433
434    /// The newest round trip measured to the receiver of a protected stream.
435    pub fn round_trip_time(&self) -> Option<Duration> {
436        self.round_trip_time
437    }
438
439    /// A round trip measured to the receiver of a protected stream.
440    pub fn on_round_trip_time(&mut self, round_trip_time: Duration) {
441        self.round_trip_time = Some(round_trip_time);
442    }
443
444    /// Whether retransmission is to repair a stream that can be retransmitted, rather than FEC:
445    /// the amount follows the loss, a latency budget is set, and the round trip measured is
446    /// within it.
447    pub fn retransmission_preferred(&self) -> bool {
448        self.adaptive
449            && matches!(
450                (self.round_trip_time, self.latency_budget),
451                (Some(round_trip_time), Some(budget)) if round_trip_time <= budget
452            )
453    }
454
455    /// Repair packets for the next block of a stream; `retransmission`: whether the stream can
456    /// be repaired by retransmission. None while [`retransmission_preferred`](Self::retransmission_preferred)
457    /// or, for an amount that follows the loss within a latency budget, before any report told
458    /// the loss; otherwise [`fec_packets`](Self::fec_packets).
459    pub fn fec_packets_with(&self, retransmission: bool) -> u32 {
460        if retransmission && self.left_to_retransmission() {
461            0
462        } else {
463            self.fec_packets()
464        }
465    }
466
467    /// Repair packets for a block of `media_packets` source packets that closed short (or is
468    /// shorter than the configured block), as [`fec_packets_with`](Self::fec_packets_with)
469    /// decides for a full one, and never more than the block has packets.
470    pub fn fec_packets_for(&self, media_packets: u32, retransmission: bool) -> u32 {
471        let media_packets = media_packets.max(1);
472        if retransmission && self.left_to_retransmission() {
473            return 0;
474        }
475        let wanted = match self.loss {
476            Some(loss) if self.adaptive => {
477                if loss < MIN_LOSS {
478                    0
479                } else {
480                    ((2.0 * loss * f64::from(media_packets)).ceil() as u32)
481                        .max(1)
482                        .min(self.max)
483                        .min(media_packets)
484                }
485            }
486            _ => self.configured.min(media_packets),
487        };
488        self.held(wanted, media_packets)
489    }
490
491    /// Per-packet feedback for one sequence number space: `ssrc` names the stream an RFC 8888
492    /// report is about, `None` is transport-wide feedback. Feeds [`loss_pattern`](Self::loss_pattern).
493    pub fn on_acknowledgements(&mut self, ssrc: Option<u32>, acknowledgements: &[Acknowledgement]) {
494        self.loss_runs.on_acknowledgements(ssrc, acknowledgements);
495    }
496
497    /// Whether the recent losses were isolated, in bursts, or both (the last 32 runs of lost
498    /// packets; `None` before four runs were seen).
499    pub fn loss_pattern(&self) -> Option<LossPattern> {
500        self.loss_runs.pattern()
501    }
502
503    /// The most repair packets per block, whatever the loss.
504    pub fn with_max(mut self, max: u32) -> Self {
505        self.max = max;
506        self
507    }
508
509    /// The most repair packets per block.
510    pub fn max(&self) -> u32 {
511        self.max
512    }
513
514    /// Whether the amount follows the loss (`false`: the configured amount whatever happens).
515    pub fn adaptive(&self) -> bool {
516        self.adaptive
517    }
518
519    /// The smoothed loss fraction, once a report gave one.
520    pub fn loss(&self) -> Option<f64> {
521        self.loss
522    }
523
524    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for a protected stream.
525    pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
526        let sample = f64::from(fraction_lost) / 256.0;
527        self.loss = Some(match self.loss {
528            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
529            None => sample,
530        });
531    }
532
533    /// Repair packets for the next block: what the loss asks for, held, while the rule of RFC
534    /// 8627 section 8 applies, to the amount in force until the source leaves room for more.
535    pub fn fec_packets(&self) -> u32 {
536        self.held(self.wanted_packets(), self.media_packets)
537    }
538
539    /// Repair packets per block the loss asks for.
540    fn wanted_packets(&self) -> u32 {
541        match self.loss {
542            Some(loss) if self.adaptive => {
543                if loss < MIN_LOSS {
544                    0
545                } else {
546                    // At least one, unless the bound allows none (`clamp` would panic on it).
547                    ((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
548                        .max(1)
549                        .min(self.max)
550                }
551            }
552            _ => self.configured,
553        }
554    }
555
556    /// Whether any repair is to be sent now (for protection shapes whose amount is fixed:
557    /// sent or not).
558    pub fn protects(&self) -> bool {
559        self.fec_packets() > 0
560    }
561
562    /// A repair packet of `size` octets left at `now`.
563    pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
564        self.sent.push_back((now, size));
565        self.expire(now);
566    }
567
568    fn expire(&mut self, now: Instant) {
569        while self
570            .sent
571            .front()
572            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
573        {
574            self.sent.pop_front();
575        }
576    }
577
578    /// The bit rate of the repair packets of the last second at `now`.
579    pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
580        self.expire(now);
581        self.sent
582            .iter()
583            .map(|(_, size)| *size as f64 * 8.0)
584            .sum::<f64>()
585            / RATE_WINDOW.as_secs_f64()
586    }
587
588    /// The target the application encodes at, out of the congestion controller's `target`:
589    /// what is left after the FEC (the FEC sent in the last second, or, while stronger FEC
590    /// waits for the source to give up rate, the FEC asked for if that is more).
591    pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
592        (target - self.reserve(now)).max(0.0)
593    }
594
595    /// Reads what an inbound packet tells the FEC rate, and takes the FEC out of a target it
596    /// carries: the receiver reports of `protected` streams feed the loss, the round trip the
597    /// RTCP session measured to one of them the latency rule, per-packet feedback (transport-wide,
598    /// and RFC 8888 reports on `protected` streams) the loss pattern, and an
599    /// [`Attribute::TargetBitrateChanged`] on the packet is lowered by the FEC bit rate.
600    pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
601        if let Some(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }) =
602            msg.message.custom::<crate::RtcpSessionEvent>()
603            && protected(*ssrc)
604        {
605            self.round_trip_time = Some(*rtt);
606        }
607        if let Packet::Rtcp(packets) = &msg.message.packet {
608            for packet in packets {
609                let any = packet.as_any();
610                if let Some(feedback) = any
611                    .downcast_ref::<rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc>(
612                ) {
613                    let acknowledgements = crate::rtpfb::convert::convert_twcc(feedback);
614                    self.loss_runs.on_acknowledgements(None, &acknowledgements);
615                    continue;
616                }
617                if let Some(feedback) = any
618                    .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>(
619                ) {
620                    let (_, per_stream) = crate::rtpfb::convert::convert_ccfb(feedback);
621                    for (ssrc, acknowledgements) in per_stream {
622                        if protected(ssrc) {
623                            self.loss_runs
624                                .on_acknowledgements(Some(ssrc), &acknowledgements);
625                        }
626                    }
627                    continue;
628                }
629                let reports = if let Some(rr) =
630                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
631                {
632                    &rr.reports
633                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
634                    &sr.reports
635                } else {
636                    continue;
637                };
638                for report in reports {
639                    if protected(report.ssrc) {
640                        self.on_fraction_lost(report.fraction_lost);
641                    }
642                }
643            }
644        }
645        let now = msg.now;
646        // The congestion controller's target, before the FEC is taken out of it.
647        for attribute in &msg.message.attributes {
648            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute
649                && bits_per_second.is_finite()
650                && *bits_per_second >= 0.0
651            {
652                self.target = Some(*bits_per_second);
653            }
654        }
655        self.admit(now);
656        let reserve = self.reserve(now);
657        let mut carried = false;
658        for attribute in &mut msg.message.attributes {
659            if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
660                carried = true;
661                if reserve > 0.0 {
662                    *bits_per_second = (*bits_per_second - reserve).max(0.0);
663                }
664                self.announced = Some(*bits_per_second);
665            }
666        }
667        // RFC 8627 section 8: while stronger FEC waits for the source to give up rate, the
668        // application is asked for the room even when no new target goes by.
669        if !carried
670            && self.gated()
671            && let Some(target) = self.target.filter(|target| *target > 0.0)
672            && self.wanted_overhead() > self.granted.unwrap_or(0.0) + 1e-9
673        {
674            let lowered = (target - reserve).max(0.0);
675            if self
676                .announced
677                .is_none_or(|announced| lowered < announced - ANNOUNCE_STEP * target)
678            {
679                msg.message.add(Attribute::TargetBitrateChanged {
680                    bits_per_second: lowered,
681                });
682                self.announced = Some(lowered);
683            }
684        } else if !carried && let (Some(target), Some(announced)) = (self.target, self.announced) {
685            // A reservation that went (the loss fell, the FEC stopped, retransmission took
686            // over) gives the room back: the controller's target need not move for the
687            // application to hear of it, so the raised target rides up the same way.
688            // A reservation gone to nothing gives the whole target back however small it was:
689            // the step that keeps small moves quiet must not keep the application under the
690            // controller's target for good while that target stands still.
691            let raised = (target - reserve).max(0.0);
692            if raised > announced + ANNOUNCE_STEP * target || (reserve == 0.0 && raised > announced)
693            {
694                msg.message.add(Attribute::TargetBitrateChanged {
695                    bits_per_second: raised,
696                });
697                self.announced = Some(raised);
698            }
699        }
700    }
701}
702
703#[cfg(test)]
704mod tests {
705    use super::*;
706
707    #[test]
708    fn before_any_report_the_configured_amount_is_sent() {
709        assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
710        assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
711    }
712
713    #[test]
714    fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
715        let mut rate = FecRate::new(10, 1, true);
716        rate.on_fraction_lost(0);
717        assert_eq!(
718            rate.fec_packets(),
719            0,
720            "repair that helps nothing is not sent"
721        );
722        let mut rate = FecRate::new(10, 1, true);
723        rate.on_fraction_lost(5); // 2%
724        assert_eq!(rate.fec_packets(), 1);
725        let mut rate = FecRate::new(10, 1, true);
726        rate.on_fraction_lost(13); // 5%
727        assert_eq!(rate.fec_packets(), 2);
728        let mut rate = FecRate::new(10, 1, true);
729        rate.on_fraction_lost(51); // 20%
730        assert_eq!(rate.fec_packets(), 4);
731        let mut rate = FecRate::new(10, 1, true);
732        rate.on_fraction_lost(200); // 78%
733        assert_eq!(rate.fec_packets(), 5, "at most half the block");
734    }
735
736    #[test]
737    fn the_loss_is_smoothed_over_reports() {
738        let mut rate = FecRate::new(10, 1, true);
739        rate.on_fraction_lost(51);
740        rate.on_fraction_lost(0);
741        let loss = rate.loss().unwrap();
742        assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
743        assert_eq!(rate.fec_packets(), 3);
744    }
745
746    #[test]
747    fn a_fixed_rate_ignores_the_loss() {
748        let mut rate = FecRate::new(10, 1, false);
749        rate.on_fraction_lost(0);
750        assert_eq!(rate.fec_packets(), 1);
751        rate.on_fraction_lost(128);
752        assert_eq!(rate.fec_packets(), 1);
753    }
754
755    fn carrier(now: Instant, target: Option<f64>, fraction_lost: Option<u8>) -> TaggedPacket {
756        let mut packets: Vec<Box<dyn rtcp::Packet>> = Vec::new();
757        if let Some(fraction_lost) = fraction_lost {
758            packets.push(Box::new(rtcp::receiver_report::ReceiverReport {
759                ssrc: 0x7777,
760                reports: vec![rtcp::reception_report::ReceptionReport {
761                    ssrc: 1000,
762                    fraction_lost,
763                    ..Default::default()
764                }],
765                ..Default::default()
766            }));
767        }
768        let mut message = crate::AttributedPacket::new(Packet::Rtcp(packets));
769        if let Some(bits_per_second) = target {
770            message.add(Attribute::TargetBitrateChanged { bits_per_second });
771        }
772        TaggedPacket {
773            now,
774            transport: shared::TransportContext::default(),
775            message,
776        }
777    }
778
779    fn target_of(msg: &TaggedPacket) -> Option<f64> {
780        msg.message
781            .attributes
782            .iter()
783            .find_map(|attribute| match attribute {
784                Attribute::TargetBitrateChanged { bits_per_second } => Some(*bits_per_second),
785                _ => None,
786            })
787    }
788
789    /// `count` source packets of 1000 octets of the protected stream, `interval_ms` apart from
790    /// `from`; returns the instant of the last.
791    fn source(rate: &mut FecRate, from: Instant, count: u64, interval_ms: u64) -> Instant {
792        let mut at = from;
793        for n in 0..count {
794            at = from + Duration::from_millis(n * interval_ms);
795            rate.on_media_sent(at, 1000, true);
796        }
797        at
798    }
799
800    /// RFC 8627 section 8: "stronger FEC protection MAY be applied only after the source rate
801    /// has been reduced". A source at the 800 kbit/s target: the 20% loss asks for four repair
802    /// packets per ten and gets the one in force; the application is told the target less the
803    /// FEC asked for; once the source sent half as much for a second, the four go. Less FEC is
804    /// never held.
805    #[test]
806    fn stronger_fec_waits_for_room_under_the_target_and_less_is_never_held() {
807        let t0 = Instant::now();
808        let mut rate = FecRate::new(10, 1, true);
809        let mut msg = carrier(t0, Some(800_000.0), None);
810        rate.on_read(&mut msg, |_| true);
811        assert_eq!(target_of(&msg), Some(800_000.0));
812        let at = source(&mut rate, t0, 100, 10);
813        assert!((rate.media_bitrate(at) - 800_000.0).abs() < 1e-6);
814        rate.on_fraction_lost(51);
815        assert_eq!(rate.loss_pattern(), None);
816        assert_eq!(
817            rate.fec_packets(),
818            1,
819            "the amount in force, not the four the loss asks for"
820        );
821        let at = source(&mut rate, at + Duration::from_millis(10), 1, 10);
822        assert_eq!(rate.fec_packets(), 1, "the source has not slowed");
823        let told = rate.media_target(at, 800_000.0);
824        assert!(
825            (told - 480_000.0).abs() < 10_000.0,
826            "the application is asked for the room: {told}"
827        );
828        // A second at half the rate.
829        let at = source(&mut rate, at + Duration::from_millis(20), 50, 20);
830        assert!(rate.media_bitrate(at) <= 410_000.0);
831        assert_eq!(rate.fec_packets(), 4, "the source gave the rate up");
832        rate.on_fraction_lost(0);
833        assert_eq!(rate.fec_packets(), 3, "less FEC at once");
834    }
835
836    /// Rows and columns are sent whole or not at all: they start only when the source leaves
837    /// room for the whole shape (seven repair packets per twelve).
838    #[test]
839    fn a_fixed_shape_waits_for_room_for_the_whole_shape() {
840        let t0 = Instant::now();
841        let mut rate = FecRate::new(12, 7, true).with_fixed_shape(true);
842        rate.on_read(&mut carrier(t0, Some(800_000.0), Some(0)), |_| true);
843        let at = source(&mut rate, t0, 100, 10);
844        assert_eq!(rate.fec_packets(), 0, "no loss, no repair");
845        rate.on_fraction_lost(51);
846        assert_eq!(rate.fec_packets(), 0, "no room for 7/12 more");
847        // A second at about 570 kbit/s: room for the two repair packets the loss asks for,
848        // not for the seven of the shape.
849        let at = source(&mut rate, at + Duration::from_millis(14), 72, 14);
850        let media = rate.media_bitrate(at);
851        assert!(media > 560_000.0 && media < 580_000.0, "{media}");
852        assert_eq!(rate.fec_packets(), 0, "no room for the whole shape");
853        let at = source(&mut rate, at + Duration::from_millis(20), 50, 20);
854        assert!(rate.media_bitrate(at) <= 410_000.0);
855        assert!(rate.fec_packets() > 0, "room for the shape");
856    }
857
858    /// While stronger FEC waits and no target goes by, the lowered target rides up on an inbound
859    /// packet, once until it falls further.
860    #[test]
861    fn a_held_increase_asks_the_application_for_room() {
862        let t0 = Instant::now();
863        let mut rate = FecRate::new(10, 1, true);
864        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
865        let at = source(&mut rate, t0, 100, 10);
866        let mut report = carrier(at, None, Some(51));
867        rate.on_read(&mut report, |_| true);
868        assert_eq!(rate.fec_packets(), 1, "held at the amount in force");
869        let told = target_of(&report).expect("the room is asked for");
870        assert!((told - 480_000.0).abs() < 10_000.0, "{told}");
871        let mut again = carrier(at + Duration::from_millis(5), None, None);
872        rate.on_read(&mut again, |_| true);
873        assert_eq!(target_of(&again), None, "told once");
874    }
875
876    /// RFC 8854 section 8: a stream that retransmission repairs gets no FEC within the latency
877    /// budget, so none is reserved either. Every protected stream repairable by retransmission,
878    /// a 20 ms round trip, 20 % loss: the 800 kbit/s target reaches the application whole and
879    /// no FEC is asked for (the same loss without the encoder's word reserves 320 kbit/s).
880    #[test]
881    fn no_fec_is_reserved_while_retransmission_repairs_every_protected_stream() {
882        let t0 = Instant::now();
883        for repairable in [true, false] {
884            let mut rate = FecRate::new(10, 1, true);
885            rate.set_retransmission_repairable(repairable);
886            rate.on_round_trip_time(Duration::from_millis(20));
887            rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
888            let at = source(&mut rate, t0, 100, 10);
889            rate.on_fraction_lost(51);
890            let told = rate.media_target(at, 800_000.0);
891            if repairable {
892                assert_eq!(told, 800_000.0, "nothing reserved");
893                assert_eq!(rate.fec_packets_with(true), 0, "no FEC sent");
894            } else {
895                assert!((told - 480_000.0).abs() < 10_000.0, "reserved: {told}");
896            }
897        }
898    }
899
900    /// After a collapse of the target, the FEC asked for is that of a source at the target, not
901    /// at the rate of the second before: a source at 2.4 Mbit/s whose target falls to 300 kbit/s
902    /// at 20 % loss is told 300 kbit/s less four tenths of it (180 kbit/s), not to stop.
903    #[test]
904    fn the_fec_asked_for_is_that_of_a_source_at_the_target() {
905        let t0 = Instant::now();
906        let mut rate = FecRate::new(10, 1, true);
907        rate.on_read(&mut carrier(t0, Some(2_400_000.0), None), |_| true);
908        // 2.4 Mbit/s: 300 packets of 1000 octets in a second.
909        let mut at = t0;
910        for n in 0..300u64 {
911            at = t0 + Duration::from_micros(n * 3_333);
912            rate.on_media_sent(at, 1000, true);
913        }
914        rate.on_fraction_lost(51);
915        let mut collapse = carrier(at, Some(300_000.0), None);
916        rate.on_read(&mut collapse, |_| true);
917        let told = target_of(&collapse).expect("the target");
918        assert!((told - 180_000.0).abs() < 5_000.0, "{told}");
919    }
920
921    /// A reservation that goes gives its room back without waiting for the controller's target
922    /// to move: once retransmission takes the stream over (a round trip within the budget) the
923    /// next inbound packet carries the whole target again.
924    #[test]
925    fn a_released_reservation_gives_the_room_back() {
926        let t0 = Instant::now();
927        let mut rate = FecRate::new(10, 1, true);
928        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
929        let at = source(&mut rate, t0, 100, 10);
930        let mut report = carrier(at, None, Some(51));
931        rate.on_read(&mut report, |_| true);
932        let lowered = target_of(&report).expect("the room is asked for");
933        assert!(lowered < 600_000.0, "{lowered}");
934        rate.set_retransmission_repairable(true);
935        rate.on_round_trip_time(Duration::from_millis(20));
936        let mut later = carrier(at + Duration::from_millis(5), None, None);
937        rate.on_read(&mut later, |_| true);
938        assert_eq!(target_of(&later), Some(800_000.0), "the room given back");
939    }
940
941    /// RFC 8854 section 8 before the first receiver report: nothing is observed, so a stream
942    /// that retransmission can repair gets no FEC and none is reserved (the default chain's
943    /// open link sent two repair packets before the first report, and the application's target
944    /// was the start rate less them); a stream without retransmission, or an application that
945    /// named no latency budget, keeps the configured amount; once the loss is reported it
946    /// decides, the round trip still unknown.
947    #[test]
948    fn before_any_report_a_stream_retransmission_repairs_gets_no_fec() {
949        let t0 = Instant::now();
950        let mut rate = FecRate::new(5, 2, true);
951        rate.set_retransmission_repairable(true);
952        assert_eq!(rate.fec_packets_with(true), 0);
953        assert_eq!(rate.fec_packets_for(3, true), 0);
954        assert_eq!(rate.fec_packets_with(false), 2, "no retransmission: FEC");
955        let mut start = carrier(t0, Some(300_000.0), None);
956        rate.on_read(&mut start, |_| true);
957        let at = source(&mut rate, t0, 50, 10);
958        assert_eq!(
959            rate.media_target(at, 300_000.0),
960            300_000.0,
961            "nothing reserved"
962        );
963        rate.on_fraction_lost(51);
964        assert_eq!(rate.fec_packets_with(true), 2, "the loss reported decides");
965        let proactive = FecRate::new(5, 2, true).with_latency_budget(None);
966        assert_eq!(
967            proactive.fec_packets_with(true),
968            2,
969            "no budget: proactive FEC"
970        );
971    }
972
973    /// A reservation that fell to nothing gives the whole target back however small it was: a
974    /// repair packet of 2472 octets took 19.8 kbit/s off a 2.5 Mbit/s target that then stood
975    /// still (the open link's maximum), under the step a re-announcement waits for (1 % of the
976    /// target), and the application stayed under the maximum for the rest of the call.
977    #[test]
978    fn a_reservation_gone_to_nothing_gives_the_whole_target_back() {
979        let t0 = Instant::now();
980        let mut rate = FecRate::new(5, 2, true);
981        rate.on_repair_sent(t0, 2472);
982        let mut at_max = carrier(t0, Some(2_500_000.0), None);
983        rate.on_read(&mut at_max, |_| true);
984        assert_eq!(target_of(&at_max), Some(2_500_000.0 - 19_776.0));
985        let mut later = carrier(t0 + Duration::from_millis(1_500), None, None);
986        rate.on_read(&mut later, |_| true);
987        assert_eq!(
988            target_of(&later),
989            Some(2_500_000.0),
990            "the whole target again"
991        );
992    }
993
994    /// Without a congestion controller's target, or with the rule off, the amount follows the
995    /// loss at once (and only the FEC sent comes out of the target).
996    #[test]
997    fn without_a_target_or_with_the_rule_off_the_amount_follows_the_loss_at_once() {
998        let t0 = Instant::now();
999        let mut rate = FecRate::new(10, 1, true);
1000        let at = source(&mut rate, t0, 100, 10);
1001        rate.on_fraction_lost(51);
1002        assert_eq!(rate.fec_packets(), 4);
1003        let mut rate = FecRate::new(10, 1, true).with_source_rate_first(false);
1004        assert!(!rate.source_rate_first());
1005        rate.on_read(&mut carrier(t0, Some(800_000.0), None), |_| true);
1006        source(&mut rate, t0, 100, 10);
1007        rate.on_fraction_lost(51);
1008        assert_eq!(rate.fec_packets(), 4);
1009        assert_eq!(rate.media_target(at, 800_000.0), 800_000.0);
1010    }
1011
1012    #[test]
1013    fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
1014        let mut rate = FecRate::new(10, 1, true);
1015        let now = Instant::now();
1016        for n in 0..10u64 {
1017            rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
1018        }
1019        let at = now + Duration::from_millis(950);
1020        assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
1021        assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
1022        // A second later the repair has aged out.
1023        assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
1024    }
1025
1026    /// RFC 8854 section 8: retransmission is preferred to FEC while the round trip is within
1027    /// the latency budget, for a stream that can be retransmitted; otherwise the amount
1028    /// follows the loss.
1029    #[test]
1030    fn within_the_latency_budget_a_stream_with_rtx_gets_no_fec() {
1031        let mut rate = FecRate::new(10, 1, true);
1032        assert_eq!(rate.latency_budget(), Some(FEC_DEFAULT_LATENCY_BUDGET));
1033        rate.on_fraction_lost(51); // 20%
1034        assert_eq!(rate.fec_packets(), 4, "precondition: the loss asks for FEC");
1035        assert_eq!(rate.fec_packets_with(true), 4, "no round trip measured yet");
1036        rate.on_round_trip_time(Duration::from_millis(80));
1037        assert!(rate.retransmission_preferred());
1038        assert_eq!(
1039            rate.fec_packets_with(true),
1040            0,
1041            "RTX repairs within the budget"
1042        );
1043        assert_eq!(rate.fec_packets_for(3, true), 0);
1044        assert_eq!(
1045            rate.fec_packets_with(false),
1046            4,
1047            "a stream without RTX keeps its FEC"
1048        );
1049        rate.on_round_trip_time(FEC_DEFAULT_LATENCY_BUDGET + Duration::from_millis(1));
1050        assert_eq!(
1051            rate.fec_packets_with(true),
1052            4,
1053            "beyond the budget FEC follows the loss"
1054        );
1055        // No budget: the application pays for proactive FEC.
1056        let mut rate = FecRate::new(10, 1, true).with_latency_budget(None);
1057        rate.on_fraction_lost(51);
1058        rate.on_round_trip_time(Duration::from_millis(1));
1059        assert_eq!(rate.fec_packets_with(true), 4);
1060        // A fixed amount was asked for explicitly.
1061        let mut rate = FecRate::new(10, 2, false);
1062        rate.on_round_trip_time(Duration::from_millis(1));
1063        assert_eq!(rate.fec_packets_with(true), 2);
1064    }
1065
1066    /// A block that closed short gets its share of the repair, never more packets than it has.
1067    #[test]
1068    fn a_short_block_gets_its_share_of_the_repair() {
1069        let mut rate = FecRate::new(10, 1, true);
1070        rate.on_fraction_lost(51); // 20%: 4 for 10 packets
1071        assert_eq!(rate.fec_packets_for(10, false), 4);
1072        assert_eq!(rate.fec_packets_for(3, false), 2);
1073        assert_eq!(rate.fec_packets_for(1, false), 1);
1074        let rate = FecRate::new(10, 3, false);
1075        assert_eq!(rate.fec_packets_for(2, false), 2);
1076    }
1077
1078    fn session_round_trip(ssrc: u32, rtt: Duration) -> TaggedPacket {
1079        TaggedPacket {
1080            now: Instant::now(),
1081            transport: shared::TransportContext::default(),
1082            message: crate::AttributedPacket::new(Packet::Rtcp(vec![])).with(Attribute::Custom(
1083                std::sync::Arc::new(crate::RtcpSessionEvent::RoundTripTime { ssrc, rtt }),
1084            )),
1085        }
1086    }
1087
1088    /// The round trip the RTCP session measured to the receiver of a protected stream is the
1089    /// one the latency rule reads; another stream's is not.
1090    #[test]
1091    fn the_round_trip_the_rtcp_session_measured_to_a_protected_stream_is_read() {
1092        let mut rate = FecRate::new(10, 1, true);
1093        rate.on_read(
1094            &mut session_round_trip(7, Duration::from_millis(40)),
1095            |ssrc| ssrc == 9,
1096        );
1097        assert_eq!(rate.round_trip_time(), None, "not a protected stream");
1098        rate.on_read(
1099            &mut session_round_trip(9, Duration::from_millis(40)),
1100            |ssrc| ssrc == 9,
1101        );
1102        assert_eq!(rate.round_trip_time(), Some(Duration::from_millis(40)));
1103    }
1104
1105    fn acks(statuses: &[(u16, bool)]) -> Vec<Acknowledgement> {
1106        statuses
1107            .iter()
1108            .map(|&(sequence_number, arrived)| {
1109                if arrived {
1110                    Acknowledgement::received(
1111                        sequence_number,
1112                        None,
1113                        rtcp::transport_feedbacks::cc_feedback_report::Ecn::NotEct,
1114                    )
1115                } else {
1116                    Acknowledgement::lost(sequence_number)
1117                }
1118            })
1119            .collect()
1120    }
1121
1122    /// A run of `lost` packets lost then one received, from `first`.
1123    fn run(first: u16, lost: u16) -> Vec<(u16, bool)> {
1124        (0..lost)
1125            .map(|offset| (first.wrapping_add(offset), false))
1126            .chain(std::iter::once((first.wrapping_add(lost), true)))
1127            .collect()
1128    }
1129
1130    /// RFC 8627 sections 1.1.3, 1.1.4 and 8: isolated losses, bursts, and both, read from the
1131    /// runs of lost packets.
1132    #[test]
1133    fn isolated_losses_bursts_and_both_are_told_apart() {
1134        let pattern = |runs: &[u16]| {
1135            let mut rate = FecRate::new(12, 7, true);
1136            let mut at = 1000u16;
1137            for lost in runs {
1138                rate.on_acknowledgements(None, &acks(&run(at, *lost)));
1139                at = at.wrapping_add(lost + 1);
1140            }
1141            rate.loss_pattern()
1142        };
1143        assert_eq!(pattern(&[1, 1, 1]), None, "too few runs to tell");
1144        assert_eq!(pattern(&[1; 8]), Some(LossPattern::Random));
1145        assert_eq!(
1146            pattern(&[1, 1, 1, 1, 1, 1, 1, 2]),
1147            Some(LossPattern::Random)
1148        );
1149        assert_eq!(pattern(&[3; 8]), Some(LossPattern::Bursty));
1150        assert_eq!(pattern(&[1, 4, 1, 4, 1, 4, 1, 4]), Some(LossPattern::Mixed));
1151        // The window is the last 32 runs: bursts long ago are forgotten.
1152        let mut runs = vec![3u16; 32];
1153        runs.extend([1u16; 32]);
1154        assert_eq!(pattern(&runs), Some(LossPattern::Random));
1155    }
1156
1157    /// A packet reported twice (overlapping feedback) is read once, a run cut by packets no
1158    /// report covered is not taken as going on, and the streams of RFC 8888 reports are runs
1159    /// of their own.
1160    #[test]
1161    fn feedback_is_read_once_per_packet_and_per_sequence_space() {
1162        let mut rate = FecRate::new(12, 7, true);
1163        // Four bursts of two, each report repeating the packets of the one before.
1164        let mut previous: Vec<(u16, bool)> = Vec::new();
1165        for first in [10u16, 13, 16, 19] {
1166            let mut report = previous.clone();
1167            report.extend(run(first, 2));
1168            rate.on_acknowledgements(None, &acks(&report));
1169            previous = run(first, 2);
1170        }
1171        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
1172        // Isolated losses on two streams, interleaved: neither joins the other's runs.
1173        let mut rate = FecRate::new(12, 7, true);
1174        for first in [100u16, 102, 104, 106] {
1175            rate.on_acknowledgements(Some(1), &acks(&run(first, 1)));
1176            rate.on_acknowledgements(Some(2), &acks(&run(first, 1)));
1177        }
1178        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
1179        // Lost packets on either side of a stretch no report covered are two runs.
1180        let mut rate = FecRate::new(12, 7, true);
1181        for first in [200u16, 300, 400, 500] {
1182            rate.on_acknowledgements(None, &acks(&[(first, false)]));
1183            rate.on_acknowledgements(None, &acks(&[(first + 50, false), (first + 51, true)]));
1184        }
1185        assert_eq!(rate.loss_pattern(), Some(LossPattern::Random));
1186    }
1187
1188    /// Transport-wide feedback read through `on_read` feeds the pattern; an RFC 8888 report
1189    /// only for a protected stream.
1190    #[test]
1191    fn per_packet_feedback_on_the_read_path_feeds_the_loss_pattern() {
1192        use rtcp::transport_feedbacks::transport_layer_cc::{
1193            PacketStatusChunk, RecvDelta, RunLengthChunk, SymbolTypeTcc, TransportLayerCc,
1194        };
1195        let chunk = |symbol, run_length| {
1196            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
1197                packet_status_symbol: symbol,
1198                run_length,
1199                ..Default::default()
1200            })
1201        };
1202        let mut rate = FecRate::new(12, 7, true);
1203        let mut base = 500u16;
1204        for _ in 0..4 {
1205            // Three lost, then two received.
1206            let feedback = TransportLayerCc {
1207                base_sequence_number: base,
1208                packet_status_count: 5,
1209                packet_chunks: vec![
1210                    chunk(SymbolTypeTcc::PacketNotReceived, 3),
1211                    chunk(SymbolTypeTcc::PacketReceivedSmallDelta, 2),
1212                ],
1213                recv_deltas: vec![
1214                    RecvDelta {
1215                        delta: 1000,
1216                        ..Default::default()
1217                    };
1218                    2
1219                ],
1220                ..Default::default()
1221            };
1222            let mut msg = TaggedPacket {
1223                now: Instant::now(),
1224                transport: shared::TransportContext::default(),
1225                message: crate::AttributedPacket::new(Packet::Rtcp(vec![Box::new(feedback)])),
1226            };
1227            rate.on_read(&mut msg, |_| true);
1228            base = base.wrapping_add(5);
1229        }
1230        assert_eq!(rate.loss_pattern(), Some(LossPattern::Bursty));
1231    }
1232
1233    /// A fixed corpus of arbitrary report and send sequences: the repair per block stays
1234    /// within zero and the bound, the media target never goes negative or above the target it
1235    /// is cut from, and the FEC bit rate never goes negative.
1236    #[test]
1237    fn arbitrary_reports_keep_the_rate_within_its_bounds() {
1238        let mut state = 0x0FEC_0001u32;
1239        let mut next = move || {
1240            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
1241            state >> 8
1242        };
1243        for _ in 0..300 {
1244            let media = 1 + next() % 48;
1245            let configured = next() % 8;
1246            let mut rate = FecRate::new(media, configured, next() % 4 != 0);
1247            if next() % 3 == 0 {
1248                rate = rate.with_max(next() % 30);
1249            }
1250            let mut at = Instant::now();
1251            for _ in 0..300 {
1252                at += Duration::from_millis(u64::from(next() % 200));
1253                match next() % 3 {
1254                    0 => rate.on_fraction_lost(next() as u8),
1255                    1 => rate.on_repair_sent(at, (next() % 1500) as usize),
1256                    _ => {
1257                        let k = rate.fec_packets();
1258                        assert!(k <= rate.max().max(configured), "{k} over the bound");
1259                        let target = f64::from(next() % 5_000_000);
1260                        let media_target = rate.media_target(at, target);
1261                        assert!((0.0..=target).contains(&media_target));
1262                        assert!(rate.fec_bitrate(at) >= 0.0);
1263                    }
1264                }
1265            }
1266        }
1267    }
1268}