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
21use crate::{Attribute, Packet, TaggedPacket};
22use std::collections::VecDeque;
23use std::time::{Duration, Instant};
24
25/// Smoothed loss under which no repair packet is sent: it would not help recover anything.
26pub const MIN_LOSS: f64 = 0.005;
27/// Weight of a new report in the smoothed loss.
28const LOSS_WEIGHT: f64 = 0.3;
29/// The window the FEC bit rate is measured over.
30const RATE_WINDOW: Duration = Duration::from_secs(1);
31
32/// The loss-driven amount of FEC for one sender. See the module documentation.
33#[derive(Debug, Clone)]
34pub struct FecRate {
35    media_packets: u32,
36    configured: u32,
37    max: u32,
38    adaptive: bool,
39    loss: Option<f64>,
40    /// Repair packets sent in the last [`RATE_WINDOW`]: when and how many octets.
41    sent: VecDeque<(Instant, usize)>,
42}
43
44impl FecRate {
45    /// `fec_packets` repair packets per `media_packets` source packets until the loss is known;
46    /// `adaptive` false keeps that amount whatever the loss.
47    pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
48        let media_packets = media_packets.max(1);
49        Self {
50            media_packets,
51            configured: fec_packets,
52            max: media_packets.div_ceil(2).max(fec_packets),
53            adaptive,
54            loss: None,
55            sent: VecDeque::new(),
56        }
57    }
58
59    /// The most repair packets per block, whatever the loss.
60    pub fn with_max(mut self, max: u32) -> Self {
61        self.max = max;
62        self
63    }
64
65    /// The most repair packets per block.
66    pub fn max(&self) -> u32 {
67        self.max
68    }
69
70    /// The smoothed loss fraction, once a report gave one.
71    pub fn loss(&self) -> Option<f64> {
72        self.loss
73    }
74
75    /// A receiver report's fraction lost (RFC 3550 6.4.1, in 1/256) for a protected stream.
76    pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
77        let sample = f64::from(fraction_lost) / 256.0;
78        self.loss = Some(match self.loss {
79            Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
80            None => sample,
81        });
82    }
83
84    /// Repair packets for the next block.
85    pub fn fec_packets(&self) -> u32 {
86        match self.loss {
87            Some(loss) if self.adaptive => {
88                if loss < MIN_LOSS {
89                    0
90                } else {
91                    // At least one, unless the bound allows none (`clamp` would panic on it).
92                    ((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
93                        .max(1)
94                        .min(self.max)
95                }
96            }
97            _ => self.configured,
98        }
99    }
100
101    /// Whether any repair is to be sent now (for protection shapes whose amount is fixed:
102    /// sent or not).
103    pub fn protects(&self) -> bool {
104        self.fec_packets() > 0
105    }
106
107    /// A repair packet of `size` octets left at `now`.
108    pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
109        self.sent.push_back((now, size));
110        self.expire(now);
111    }
112
113    fn expire(&mut self, now: Instant) {
114        while self
115            .sent
116            .front()
117            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
118        {
119            self.sent.pop_front();
120        }
121    }
122
123    /// The bit rate of the repair packets of the last second at `now`.
124    pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
125        self.expire(now);
126        self.sent
127            .iter()
128            .map(|(_, size)| *size as f64 * 8.0)
129            .sum::<f64>()
130            / RATE_WINDOW.as_secs_f64()
131    }
132
133    /// The target the application encodes at, out of the congestion controller's `target`:
134    /// what is left after the FEC.
135    pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
136        (target - self.fec_bitrate(now)).max(0.0)
137    }
138
139    /// Reads what an inbound packet tells the FEC rate, and takes the FEC out of a target it
140    /// carries: the receiver reports of `protected` streams feed the loss, and an
141    /// [`Attribute::TargetBitrateChanged`] on the packet is lowered by the FEC bit rate.
142    pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
143        if let Packet::Rtcp(packets) = &msg.message.packet {
144            for packet in packets {
145                let any = packet.as_any();
146                let reports = if let Some(rr) =
147                    any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
148                {
149                    &rr.reports
150                } else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
151                    &sr.reports
152                } else {
153                    continue;
154                };
155                for report in reports {
156                    if protected(report.ssrc) {
157                        self.on_fraction_lost(report.fraction_lost);
158                    }
159                }
160            }
161        }
162        let now = msg.now;
163        let fec = self.fec_bitrate(now);
164        if fec > 0.0 {
165            for attribute in &mut msg.message.attributes {
166                if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
167                    *bits_per_second = (*bits_per_second - fec).max(0.0);
168                }
169            }
170        }
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    #[test]
179    fn before_any_report_the_configured_amount_is_sent() {
180        assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
181        assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
182    }
183
184    #[test]
185    fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
186        let mut rate = FecRate::new(10, 1, true);
187        rate.on_fraction_lost(0);
188        assert_eq!(
189            rate.fec_packets(),
190            0,
191            "repair that helps nothing is not sent"
192        );
193        let mut rate = FecRate::new(10, 1, true);
194        rate.on_fraction_lost(5); // 2%
195        assert_eq!(rate.fec_packets(), 1);
196        let mut rate = FecRate::new(10, 1, true);
197        rate.on_fraction_lost(13); // 5%
198        assert_eq!(rate.fec_packets(), 2);
199        let mut rate = FecRate::new(10, 1, true);
200        rate.on_fraction_lost(51); // 20%
201        assert_eq!(rate.fec_packets(), 4);
202        let mut rate = FecRate::new(10, 1, true);
203        rate.on_fraction_lost(200); // 78%
204        assert_eq!(rate.fec_packets(), 5, "at most half the block");
205    }
206
207    #[test]
208    fn the_loss_is_smoothed_over_reports() {
209        let mut rate = FecRate::new(10, 1, true);
210        rate.on_fraction_lost(51);
211        rate.on_fraction_lost(0);
212        let loss = rate.loss().unwrap();
213        assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
214        assert_eq!(rate.fec_packets(), 3);
215    }
216
217    #[test]
218    fn a_fixed_rate_ignores_the_loss() {
219        let mut rate = FecRate::new(10, 1, false);
220        rate.on_fraction_lost(0);
221        assert_eq!(rate.fec_packets(), 1);
222        rate.on_fraction_lost(128);
223        assert_eq!(rate.fec_packets(), 1);
224    }
225
226    #[test]
227    fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
228        let mut rate = FecRate::new(10, 1, true);
229        let now = Instant::now();
230        for n in 0..10u64 {
231            rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
232        }
233        let at = now + Duration::from_millis(950);
234        assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
235        assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
236        // A second later the repair has aged out.
237        assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
238    }
239
240    /// A fixed corpus of arbitrary report and send sequences: the repair per block stays
241    /// within zero and the bound, the media target never goes negative or above the target it
242    /// is cut from, and the FEC bit rate never goes negative.
243    #[test]
244    fn arbitrary_reports_keep_the_rate_within_its_bounds() {
245        let mut state = 0x0FEC_0001u32;
246        let mut next = move || {
247            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
248            state >> 8
249        };
250        for _ in 0..300 {
251            let media = 1 + next() % 48;
252            let configured = next() % 8;
253            let mut rate = FecRate::new(media, configured, next() % 4 != 0);
254            if next() % 3 == 0 {
255                rate = rate.with_max(next() % 30);
256            }
257            let mut at = Instant::now();
258            for _ in 0..300 {
259                at += Duration::from_millis(u64::from(next() % 200));
260                match next() % 3 {
261                    0 => rate.on_fraction_lost(next() as u8),
262                    1 => rate.on_repair_sent(at, (next() % 1500) as usize),
263                    _ => {
264                        let k = rate.fec_packets();
265                        assert!(k <= rate.max().max(configured), "{k} over the bound");
266                        let target = f64::from(next() % 5_000_000);
267                        let media_target = rate.media_target(at, target);
268                        assert!((0.0..=target).contains(&media_target));
269                        assert!(rate.fec_bitrate(at) >= 0.0);
270                    }
271                }
272            }
273        }
274    }
275}