use crate::{Attribute, Packet, TaggedPacket};
use std::collections::VecDeque;
use std::time::{Duration, Instant};
pub const MIN_LOSS: f64 = 0.005;
const LOSS_WEIGHT: f64 = 0.3;
const RATE_WINDOW: Duration = Duration::from_secs(1);
#[derive(Debug, Clone)]
pub struct FecRate {
media_packets: u32,
configured: u32,
max: u32,
adaptive: bool,
loss: Option<f64>,
sent: VecDeque<(Instant, usize)>,
}
impl FecRate {
pub fn new(media_packets: u32, fec_packets: u32, adaptive: bool) -> Self {
let media_packets = media_packets.max(1);
Self {
media_packets,
configured: fec_packets,
max: media_packets.div_ceil(2).max(fec_packets),
adaptive,
loss: None,
sent: VecDeque::new(),
}
}
pub fn with_max(mut self, max: u32) -> Self {
self.max = max;
self
}
pub fn max(&self) -> u32 {
self.max
}
pub fn loss(&self) -> Option<f64> {
self.loss
}
pub fn on_fraction_lost(&mut self, fraction_lost: u8) {
let sample = f64::from(fraction_lost) / 256.0;
self.loss = Some(match self.loss {
Some(loss) => (1.0 - LOSS_WEIGHT) * loss + LOSS_WEIGHT * sample,
None => sample,
});
}
pub fn fec_packets(&self) -> u32 {
match self.loss {
Some(loss) if self.adaptive => {
if loss < MIN_LOSS {
0
} else {
((2.0 * loss * f64::from(self.media_packets)).ceil() as u32)
.max(1)
.min(self.max)
}
}
_ => self.configured,
}
}
pub fn protects(&self) -> bool {
self.fec_packets() > 0
}
pub fn on_repair_sent(&mut self, now: Instant, size: usize) {
self.sent.push_back((now, size));
self.expire(now);
}
fn expire(&mut self, now: Instant) {
while self
.sent
.front()
.is_some_and(|(at, _)| now.saturating_duration_since(*at) > RATE_WINDOW)
{
self.sent.pop_front();
}
}
pub fn fec_bitrate(&mut self, now: Instant) -> f64 {
self.expire(now);
self.sent
.iter()
.map(|(_, size)| *size as f64 * 8.0)
.sum::<f64>()
/ RATE_WINDOW.as_secs_f64()
}
pub fn media_target(&mut self, now: Instant, target: f64) -> f64 {
(target - self.fec_bitrate(now)).max(0.0)
}
pub fn on_read(&mut self, msg: &mut TaggedPacket, protected: impl Fn(u32) -> bool) {
if let Packet::Rtcp(packets) = &msg.message.packet {
for packet in packets {
let any = packet.as_any();
let reports = if let Some(rr) =
any.downcast_ref::<rtcp::receiver_report::ReceiverReport>()
{
&rr.reports
} else if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
&sr.reports
} else {
continue;
};
for report in reports {
if protected(report.ssrc) {
self.on_fraction_lost(report.fraction_lost);
}
}
}
}
let now = msg.now;
let fec = self.fec_bitrate(now);
if fec > 0.0 {
for attribute in &mut msg.message.attributes {
if let Attribute::TargetBitrateChanged { bits_per_second } = attribute {
*bits_per_second = (*bits_per_second - fec).max(0.0);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn before_any_report_the_configured_amount_is_sent() {
assert_eq!(FecRate::new(10, 1, true).fec_packets(), 1);
assert_eq!(FecRate::new(5, 2, true).fec_packets(), 2);
}
#[test]
fn no_loss_means_no_repair_and_more_loss_more_repair_up_to_the_bound() {
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(0);
assert_eq!(
rate.fec_packets(),
0,
"repair that helps nothing is not sent"
);
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(5); assert_eq!(rate.fec_packets(), 1);
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(13); assert_eq!(rate.fec_packets(), 2);
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(51); assert_eq!(rate.fec_packets(), 4);
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(200); assert_eq!(rate.fec_packets(), 5, "at most half the block");
}
#[test]
fn the_loss_is_smoothed_over_reports() {
let mut rate = FecRate::new(10, 1, true);
rate.on_fraction_lost(51);
rate.on_fraction_lost(0);
let loss = rate.loss().unwrap();
assert!((loss - 0.7 * 51.0 / 256.0).abs() < 1e-9);
assert_eq!(rate.fec_packets(), 3);
}
#[test]
fn a_fixed_rate_ignores_the_loss() {
let mut rate = FecRate::new(10, 1, false);
rate.on_fraction_lost(0);
assert_eq!(rate.fec_packets(), 1);
rate.on_fraction_lost(128);
assert_eq!(rate.fec_packets(), 1);
}
#[test]
fn the_fec_of_the_last_second_comes_out_of_the_media_target() {
let mut rate = FecRate::new(10, 1, true);
let now = Instant::now();
for n in 0..10u64 {
rate.on_repair_sent(now + Duration::from_millis(n * 100), 1250);
}
let at = now + Duration::from_millis(950);
assert!((rate.fec_bitrate(at) - 100_000.0).abs() < 1e-6);
assert!((rate.media_target(at, 1_000_000.0) - 900_000.0).abs() < 1e-6);
assert_eq!(rate.media_target(at + Duration::from_secs(2), 1e6), 1e6);
}
#[test]
fn arbitrary_reports_keep_the_rate_within_its_bounds() {
let mut state = 0x0FEC_0001u32;
let mut next = move || {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
state >> 8
};
for _ in 0..300 {
let media = 1 + next() % 48;
let configured = next() % 8;
let mut rate = FecRate::new(media, configured, next() % 4 != 0);
if next() % 3 == 0 {
rate = rate.with_max(next() % 30);
}
let mut at = Instant::now();
for _ in 0..300 {
at += Duration::from_millis(u64::from(next() % 200));
match next() % 3 {
0 => rate.on_fraction_lost(next() as u8),
1 => rate.on_repair_sent(at, (next() % 1500) as usize),
_ => {
let k = rate.fec_packets();
assert!(k <= rate.max().max(configured), "{k} over the bound");
let target = f64::from(next() % 5_000_000);
let media_target = rate.media_target(at, target);
assert!((0.0..=target).contains(&media_target));
assert!(rate.fec_bitrate(at) >= 0.0);
}
}
}
}
}
}