use bytes::{BufMut, Bytes, BytesMut};
use std::collections::HashMap;
use std::time::{Duration, Instant};
pub(crate) const FMT_TMMBR: u8 = 3;
pub(crate) const FMT_TMMBN: u8 = 4;
const PT_RTPFB: u8 = 205;
pub const TMMBR_OWNER_TIMEOUT: Duration = Duration::from_secs(25);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TmmbEntry {
pub ssrc: u32,
pub bitrate: u64,
pub overhead: u16,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct TmmbPacket {
pub fmt: u8,
pub sender_ssrc: u32,
pub entries: Vec<TmmbEntry>,
}
pub(crate) fn parse(raw: &[u8]) -> Option<TmmbPacket> {
if raw.len() < 12 || raw[0] >> 6 != 2 || raw[1] != PT_RTPFB {
return None;
}
let fmt = raw[0] & 0x1F;
if fmt != FMT_TMMBR && fmt != FMT_TMMBN {
return None;
}
let length = (usize::from(u16::from_be_bytes([raw[2], raw[3]])) + 1) * 4;
if length < 12 || length > raw.len() || (length - 12) % 8 != 0 {
return None;
}
let sender_ssrc = u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]);
let entries = raw[12..length]
.as_chunks::<8>()
.0
.iter()
.map(|fci| {
let word = u32::from_be_bytes([fci[4], fci[5], fci[6], fci[7]]);
let exponent = word >> 26;
let mantissa = u64::from((word >> 9) & 0x1_FFFF);
TmmbEntry {
ssrc: u32::from_be_bytes([fci[0], fci[1], fci[2], fci[3]]),
bitrate: mantissa << exponent,
overhead: (word & 0x1FF) as u16,
}
})
.collect();
Some(TmmbPacket {
fmt,
sender_ssrc,
entries,
})
}
pub(crate) fn build_tmmbn(sender_ssrc: u32, entries: &[TmmbEntry]) -> Bytes {
let mut out = BytesMut::with_capacity(12 + 8 * entries.len());
out.put_u8(0x80 | FMT_TMMBN);
out.put_u8(PT_RTPFB);
out.put_u16(2 + 2 * entries.len() as u16);
out.put_u32(sender_ssrc);
out.put_u32(0);
for entry in entries {
let mut exponent = 0u32;
while entry.bitrate >> exponent > 0x1_FFFF && exponent < 63 {
exponent += 1;
}
let mantissa = ((entry.bitrate >> exponent) & 0x1_FFFF) as u32;
out.put_u32(entry.ssrc);
out.put_u32(exponent << 26 | mantissa << 9 | u32::from(entry.overhead.min(0x1FF)));
}
out.freeze()
}
pub(crate) fn bounding_set(tuples: &[TmmbEntry]) -> Vec<TmmbEntry> {
if tuples.len() <= 1 {
return tuples.to_vec();
}
let net = |tuple: &TmmbEntry, packet_rate: f64| {
tuple.bitrate as f64 - 8.0 * f64::from(tuple.overhead) * packet_rate
};
let mut switchovers = vec![0.0f64];
for (index, a) in tuples.iter().enumerate() {
for b in &tuples[index + 1..] {
if a.overhead != b.overhead {
let packet_rate = (a.bitrate as f64 - b.bitrate as f64)
/ (8.0 * (f64::from(a.overhead) - f64::from(b.overhead)));
if packet_rate > 0.0 && packet_rate.is_finite() {
switchovers.push(packet_rate);
}
}
}
}
switchovers.sort_by(f64::total_cmp);
let lowest_at = |packet_rate: f64| {
tuples.iter().min_by(|a, b| {
net(a, packet_rate)
.total_cmp(&net(b, packet_rate))
.then(a.bitrate.cmp(&b.bitrate))
.then(b.overhead.cmp(&a.overhead))
.then(a.ssrc.cmp(&b.ssrc))
})
};
let mut bounding: Vec<TmmbEntry> = Vec::new();
for (index, start) in switchovers.iter().enumerate() {
let probe = match switchovers.get(index + 1) {
Some(next) => (start + next) / 2.0,
None => start + 1.0,
};
let Some(lowest_here) = lowest_at(*start) else {
continue;
};
if net(lowest_here, *start) < 0.0 {
break;
}
if let Some(lowest) = lowest_at(probe)
&& !bounding.contains(lowest)
{
bounding.push(*lowest);
}
}
if bounding.is_empty()
&& let Some(lowest) = lowest_at(0.0)
{
bounding.push(*lowest);
}
bounding
}
pub(crate) fn net_media_bitrate(tuples: &[TmmbEntry], packet_rate: f64) -> Option<f64> {
tuples
.iter()
.map(|tuple| {
(tuple.bitrate as f64 - 8.0 * f64::from(tuple.overhead) * packet_rate).max(0.0)
})
.reduce(f64::min)
}
#[derive(Debug, Default)]
pub(crate) struct TmmbrState {
requests: HashMap<u32, (TmmbEntry, Instant)>,
bounding: Vec<TmmbEntry>,
in_force: Vec<TmmbEntry>,
pending: Option<(Instant, Vec<TmmbEntry>)>,
}
impl TmmbrState {
fn tuples(&self) -> Vec<TmmbEntry> {
let mut tuples: Vec<TmmbEntry> = self.requests.values().map(|(entry, _)| *entry).collect();
tuples.sort_unstable_by_key(|tuple| tuple.ssrc);
tuples
}
pub(crate) fn bounding(&self) -> &[TmmbEntry] {
&self.bounding
}
pub(crate) fn limit(&self, packet_rate: f64) -> Option<f64> {
net_media_bitrate(&self.in_force, packet_rate)
}
fn recompute(&mut self, now: Instant, packet_rate: f64, round_trip_time: Duration) {
self.bounding = bounding_set(&self.tuples());
let limit = net_media_bitrate(&self.bounding, packet_rate);
let tighter = match (limit, self.limit(packet_rate)) {
(Some(new), Some(old)) => new <= old,
(Some(_), None) => true,
(None, _) => false,
};
if tighter {
self.in_force.clone_from(&self.bounding);
self.pending = None;
} else {
self.pending = Some((now + round_trip_time * 2, self.bounding.clone()));
}
}
pub(crate) fn on_request(
&mut self,
now: Instant,
owner: u32,
entry: TmmbEntry,
packet_rate: f64,
round_trip_time: Duration,
) -> bool {
self.requests.insert(
owner,
(
TmmbEntry {
ssrc: owner,
..entry
},
now,
),
);
self.recompute(now, packet_rate, round_trip_time);
true
}
pub(crate) fn on_owner_seen(&mut self, now: Instant, owner: u32) {
if let Some((_, seen)) = self.requests.get_mut(&owner) {
*seen = now;
}
}
pub(crate) fn on_owner_left(
&mut self,
now: Instant,
owner: u32,
packet_rate: f64,
round_trip_time: Duration,
) -> bool {
if self.requests.remove(&owner).is_none() {
return false;
}
self.recompute(now, packet_rate, round_trip_time);
true
}
pub(crate) fn on_timeout(
&mut self,
now: Instant,
packet_rate: f64,
round_trip_time: Duration,
) -> bool {
let before = self.requests.len();
self.requests
.retain(|_, (_, seen)| now.saturating_duration_since(*seen) < TMMBR_OWNER_TIMEOUT);
let left = self.requests.len() != before;
if left {
self.recompute(now, packet_rate, round_trip_time);
}
if let Some((at, _)) = &self.pending
&& now >= *at
&& let Some((_, bounding)) = self.pending.take()
{
self.in_force = bounding;
}
left
}
pub(crate) fn poll_timeout(&self) -> Option<Instant> {
let owner = self
.requests
.values()
.map(|(_, seen)| *seen + TMMBR_OWNER_TIMEOUT)
.min();
let pending = self.pending.as_ref().map(|(at, _)| *at);
match (owner, pending) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn tuple(ssrc: u32, bitrate: u64, overhead: u16) -> TmmbEntry {
TmmbEntry {
ssrc,
bitrate,
overhead,
}
}
#[test]
fn a_tmmbr_fci_entry_is_read_as_the_rfc_lays_it_out() {
let word: u32 = 2 << 26 | 65_536 << 9 | 40;
let mut raw = vec![0x83, 205, 0, 4, 0x11, 0x22, 0x33, 0x44, 0, 0, 0, 0];
raw.extend_from_slice(&0xAABB_CCDDu32.to_be_bytes());
raw.extend_from_slice(&word.to_be_bytes());
let packet = parse(&raw).expect("a TMMBR");
assert_eq!(FMT_TMMBR, packet.fmt);
assert_eq!(0x1122_3344, packet.sender_ssrc);
assert_eq!(vec![tuple(0xAABB_CCDD, 262_144, 40)], packet.entries);
}
#[test]
fn a_truncated_or_foreign_packet_is_not_a_tmmbr() {
assert_eq!(
None,
parse(&[0x83, 205, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0]),
"length says 20"
);
assert_eq!(
None,
parse(&[0x81, 205, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]),
"a NACK"
);
assert_eq!(
None,
parse(&[0x83, 205, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
);
assert_eq!(None, parse(&[]));
}
#[test]
fn a_tmmbn_is_written_as_the_rfc_lays_it_out() {
let raw = build_tmmbn(7, &[tuple(9, 35_000, 40), tuple(10, 5_000_001, 60)]);
assert_eq!(&[0x84, 205, 0, 6, 0, 0, 0, 7, 0, 0, 0, 0], &raw[..12]);
let packet = parse(&raw).expect("a TMMBN");
assert_eq!(FMT_TMMBN, packet.fmt);
assert_eq!(
vec![tuple(9, 35_000, 40), tuple(10, 5_000_000, 60)],
packet.entries
);
let empty = build_tmmbn(7, &[]);
assert_eq!(&[0x84, 205, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0], &empty[..]);
}
#[test]
fn the_bounding_set_of_the_rfc_example() {
let a = tuple(1, 35_000, 40);
let b = tuple(2, 40_000, 60);
let c = tuple(3, 50_000, 40);
assert_eq!(
vec![a, b],
bounding_set(&[a, b, c]),
"C lies outside the polygon"
);
assert_eq!(Some(28_600.0), net_media_bitrate(&[a, b], 20.0));
assert_eq!(Some(30_400.0), net_media_bitrate(&[b], 20.0));
assert_eq!(Some(20_800.0), net_media_bitrate(&[a, b], 40.0));
}
#[test]
fn a_tuple_that_is_tighter_everywhere_is_the_whole_bounding_set() {
let tight = tuple(1, 20_000, 60);
let loose = tuple(2, 40_000, 40);
assert_eq!(vec![tight], bounding_set(&[loose, tight]));
}
#[test]
fn a_looser_limit_waits_two_round_trips() {
let now = Instant::now();
let rtt = Duration::from_millis(150);
let mut state = TmmbrState::default();
state.on_request(now, 9, tuple(1, 500_000, 0), 0.0, rtt);
assert_eq!(Some(500_000.0), state.limit(0.0), "at once");
state.on_request(
now + Duration::from_secs(1),
9,
tuple(1, 900_000, 0),
0.0,
rtt,
);
assert_eq!(Some(500_000.0), state.limit(0.0), "not yet");
assert_eq!(
Some(now + Duration::from_millis(1300)),
state.poll_timeout()
);
state.on_timeout(now + Duration::from_millis(1299), 0.0, rtt);
assert_eq!(Some(500_000.0), state.limit(0.0));
state.on_timeout(now + Duration::from_millis(1300), 0.0, rtt);
assert_eq!(Some(900_000.0), state.limit(0.0), "after 2 * RTT");
}
#[test]
fn the_limit_is_taken_at_the_packet_rate_in_use() {
let now = Instant::now();
let mut state = TmmbrState::default();
state.on_request(now, 9, tuple(1, 80_000, 60), 171.0, Duration::ZERO);
assert_eq!(Some(0.0), state.limit(171.0));
assert_eq!(Some(80_000.0 - 50.0 * 480.0), state.limit(50.0));
}
#[test]
fn an_owner_that_leaves_or_times_out_takes_its_tuple_with_it() {
let now = Instant::now();
let rtt = Duration::from_millis(100);
let mut state = TmmbrState::default();
state.on_request(now, 9, tuple(1, 500_000, 0), 0.0, rtt);
state.on_request(now, 10, tuple(1, 800_000, 0), 0.0, rtt);
assert_eq!(vec![tuple(9, 500_000, 0)], state.bounding());
assert!(state.on_owner_left(now, 9, 0.0, rtt), "a TMMBN is owed");
assert_eq!(vec![tuple(10, 800_000, 0)], state.bounding());
assert!(
!state.on_owner_left(now, 9, 0.0, rtt),
"it had no tuple any more"
);
assert!(!state.on_timeout(now + Duration::from_secs(24), 0.0, rtt));
assert!(state.on_timeout(now + TMMBR_OWNER_TIMEOUT, 0.0, rtt));
assert!(state.bounding().is_empty());
state.on_timeout(now + TMMBR_OWNER_TIMEOUT + rtt * 2, 0.0, rtt);
assert_eq!(
None,
state.limit(0.0),
"no tuple, no limit, after the hold-off"
);
}
}