1use bytes::{BufMut, Bytes, BytesMut};
14use std::collections::HashMap;
15use std::time::{Duration, Instant};
16
17pub(crate) const FMT_TMMBR: u8 = 3;
19pub(crate) const FMT_TMMBN: u8 = 4;
21const PT_RTPFB: u8 = 205;
23
24pub const TMMBR_OWNER_TIMEOUT: Duration = Duration::from_secs(25);
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct TmmbEntry {
31 pub ssrc: u32,
33 pub bitrate: u64,
36 pub overhead: u16,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
42pub(crate) struct TmmbPacket {
43 pub fmt: u8,
44 pub sender_ssrc: u32,
45 pub entries: Vec<TmmbEntry>,
46}
47
48pub(crate) fn parse(raw: &[u8]) -> Option<TmmbPacket> {
51 if raw.len() < 12 || raw[0] >> 6 != 2 || raw[1] != PT_RTPFB {
52 return None;
53 }
54 let fmt = raw[0] & 0x1F;
55 if fmt != FMT_TMMBR && fmt != FMT_TMMBN {
56 return None;
57 }
58 let length = (usize::from(u16::from_be_bytes([raw[2], raw[3]])) + 1) * 4;
59 if length < 12 || length > raw.len() || (length - 12) % 8 != 0 {
60 return None;
61 }
62 let sender_ssrc = u32::from_be_bytes([raw[4], raw[5], raw[6], raw[7]]);
63 let entries = raw[12..length]
64 .as_chunks::<8>()
65 .0
66 .iter()
67 .map(|fci| {
68 let word = u32::from_be_bytes([fci[4], fci[5], fci[6], fci[7]]);
69 let exponent = word >> 26;
70 let mantissa = u64::from((word >> 9) & 0x1_FFFF);
71 TmmbEntry {
72 ssrc: u32::from_be_bytes([fci[0], fci[1], fci[2], fci[3]]),
73 bitrate: mantissa << exponent,
74 overhead: (word & 0x1FF) as u16,
75 }
76 })
77 .collect();
78 Some(TmmbPacket {
79 fmt,
80 sender_ssrc,
81 entries,
82 })
83}
84
85pub(crate) fn build_tmmbn(sender_ssrc: u32, entries: &[TmmbEntry]) -> Bytes {
88 let mut out = BytesMut::with_capacity(12 + 8 * entries.len());
89 out.put_u8(0x80 | FMT_TMMBN);
90 out.put_u8(PT_RTPFB);
91 out.put_u16(2 + 2 * entries.len() as u16);
92 out.put_u32(sender_ssrc);
93 out.put_u32(0);
94 for entry in entries {
95 let mut exponent = 0u32;
97 while entry.bitrate >> exponent > 0x1_FFFF && exponent < 63 {
98 exponent += 1;
99 }
100 let mantissa = ((entry.bitrate >> exponent) & 0x1_FFFF) as u32;
101 out.put_u32(entry.ssrc);
102 out.put_u32(exponent << 26 | mantissa << 9 | u32::from(entry.overhead.min(0x1FF)));
103 }
104 out.freeze()
105}
106
107pub(crate) fn bounding_set(tuples: &[TmmbEntry]) -> Vec<TmmbEntry> {
111 if tuples.len() <= 1 {
112 return tuples.to_vec();
113 }
114 let net = |tuple: &TmmbEntry, packet_rate: f64| {
115 tuple.bitrate as f64 - 8.0 * f64::from(tuple.overhead) * packet_rate
116 };
117 let mut switchovers = vec![0.0f64];
119 for (index, a) in tuples.iter().enumerate() {
120 for b in &tuples[index + 1..] {
121 if a.overhead != b.overhead {
122 let packet_rate = (a.bitrate as f64 - b.bitrate as f64)
123 / (8.0 * (f64::from(a.overhead) - f64::from(b.overhead)));
124 if packet_rate > 0.0 && packet_rate.is_finite() {
125 switchovers.push(packet_rate);
126 }
127 }
128 }
129 }
130 switchovers.sort_by(f64::total_cmp);
131
132 let lowest_at = |packet_rate: f64| {
133 tuples.iter().min_by(|a, b| {
134 net(a, packet_rate)
135 .total_cmp(&net(b, packet_rate))
136 .then(a.bitrate.cmp(&b.bitrate))
138 .then(b.overhead.cmp(&a.overhead))
139 .then(a.ssrc.cmp(&b.ssrc))
140 })
141 };
142
143 let mut bounding: Vec<TmmbEntry> = Vec::new();
144 for (index, start) in switchovers.iter().enumerate() {
145 let probe = match switchovers.get(index + 1) {
147 Some(next) => (start + next) / 2.0,
148 None => start + 1.0,
149 };
150 let Some(lowest_here) = lowest_at(*start) else {
151 continue;
152 };
153 if net(lowest_here, *start) < 0.0 {
154 break;
155 }
156 if let Some(lowest) = lowest_at(probe)
157 && !bounding.contains(lowest)
158 {
159 bounding.push(*lowest);
160 }
161 }
162 if bounding.is_empty()
163 && let Some(lowest) = lowest_at(0.0)
164 {
165 bounding.push(*lowest);
166 }
167 bounding
168}
169
170pub(crate) fn net_media_bitrate(tuples: &[TmmbEntry], packet_rate: f64) -> Option<f64> {
174 tuples
175 .iter()
176 .map(|tuple| {
177 (tuple.bitrate as f64 - 8.0 * f64::from(tuple.overhead) * packet_rate).max(0.0)
178 })
179 .reduce(f64::min)
180}
181
182#[derive(Debug, Default)]
184pub(crate) struct TmmbrState {
185 requests: HashMap<u32, (TmmbEntry, Instant)>,
188 bounding: Vec<TmmbEntry>,
190 in_force: Vec<TmmbEntry>,
193 pending: Option<(Instant, Vec<TmmbEntry>)>,
196}
197
198impl TmmbrState {
199 fn tuples(&self) -> Vec<TmmbEntry> {
201 let mut tuples: Vec<TmmbEntry> = self.requests.values().map(|(entry, _)| *entry).collect();
202 tuples.sort_unstable_by_key(|tuple| tuple.ssrc);
203 tuples
204 }
205
206 pub(crate) fn bounding(&self) -> &[TmmbEntry] {
208 &self.bounding
209 }
210
211 pub(crate) fn limit(&self, packet_rate: f64) -> Option<f64> {
219 net_media_bitrate(&self.in_force, packet_rate)
220 }
221
222 fn recompute(&mut self, now: Instant, packet_rate: f64, round_trip_time: Duration) {
229 self.bounding = bounding_set(&self.tuples());
230 let limit = net_media_bitrate(&self.bounding, packet_rate);
231 let tighter = match (limit, self.limit(packet_rate)) {
232 (Some(new), Some(old)) => new <= old,
233 (Some(_), None) => true,
234 (None, _) => false,
235 };
236 if tighter {
237 self.in_force.clone_from(&self.bounding);
238 self.pending = None;
239 } else {
240 self.pending = Some((now + round_trip_time * 2, self.bounding.clone()));
241 }
242 }
243
244 pub(crate) fn on_request(
248 &mut self,
249 now: Instant,
250 owner: u32,
251 entry: TmmbEntry,
252 packet_rate: f64,
253 round_trip_time: Duration,
254 ) -> bool {
255 self.requests.insert(
256 owner,
257 (
258 TmmbEntry {
259 ssrc: owner,
260 ..entry
261 },
262 now,
263 ),
264 );
265 self.recompute(now, packet_rate, round_trip_time);
266 true
267 }
268
269 pub(crate) fn on_owner_seen(&mut self, now: Instant, owner: u32) {
271 if let Some((_, seen)) = self.requests.get_mut(&owner) {
272 *seen = now;
273 }
274 }
275
276 pub(crate) fn on_owner_left(
279 &mut self,
280 now: Instant,
281 owner: u32,
282 packet_rate: f64,
283 round_trip_time: Duration,
284 ) -> bool {
285 if self.requests.remove(&owner).is_none() {
286 return false;
287 }
288 self.recompute(now, packet_rate, round_trip_time);
289 true
290 }
291
292 pub(crate) fn on_timeout(
295 &mut self,
296 now: Instant,
297 packet_rate: f64,
298 round_trip_time: Duration,
299 ) -> bool {
300 let before = self.requests.len();
301 self.requests
302 .retain(|_, (_, seen)| now.saturating_duration_since(*seen) < TMMBR_OWNER_TIMEOUT);
303 let left = self.requests.len() != before;
304 if left {
305 self.recompute(now, packet_rate, round_trip_time);
306 }
307 if let Some((at, _)) = &self.pending
308 && now >= *at
309 && let Some((_, bounding)) = self.pending.take()
310 {
311 self.in_force = bounding;
312 }
313 left
314 }
315
316 pub(crate) fn poll_timeout(&self) -> Option<Instant> {
318 let owner = self
319 .requests
320 .values()
321 .map(|(_, seen)| *seen + TMMBR_OWNER_TIMEOUT)
322 .min();
323 let pending = self.pending.as_ref().map(|(at, _)| *at);
324 match (owner, pending) {
325 (Some(a), Some(b)) => Some(a.min(b)),
326 (a, b) => a.or(b),
327 }
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 fn tuple(ssrc: u32, bitrate: u64, overhead: u16) -> TmmbEntry {
336 TmmbEntry {
337 ssrc,
338 bitrate,
339 overhead,
340 }
341 }
342
343 #[test]
346 fn a_tmmbr_fci_entry_is_read_as_the_rfc_lays_it_out() {
347 let word: u32 = 2 << 26 | 65_536 << 9 | 40;
350 let mut raw = vec![0x83, 205, 0, 4, 0x11, 0x22, 0x33, 0x44, 0, 0, 0, 0];
351 raw.extend_from_slice(&0xAABB_CCDDu32.to_be_bytes());
352 raw.extend_from_slice(&word.to_be_bytes());
353
354 let packet = parse(&raw).expect("a TMMBR");
355 assert_eq!(FMT_TMMBR, packet.fmt);
356 assert_eq!(0x1122_3344, packet.sender_ssrc);
357 assert_eq!(vec![tuple(0xAABB_CCDD, 262_144, 40)], packet.entries);
358 }
359
360 #[test]
361 fn a_truncated_or_foreign_packet_is_not_a_tmmbr() {
362 assert_eq!(
363 None,
364 parse(&[0x83, 205, 0, 4, 0, 0, 0, 1, 0, 0, 0, 0]),
365 "length says 20"
366 );
367 assert_eq!(
368 None,
369 parse(&[0x81, 205, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0]),
370 "a NACK"
371 );
372 assert_eq!(
373 None,
374 parse(&[0x83, 205, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
375 );
376 assert_eq!(None, parse(&[]));
377 }
378
379 #[test]
382 fn a_tmmbn_is_written_as_the_rfc_lays_it_out() {
383 let raw = build_tmmbn(7, &[tuple(9, 35_000, 40), tuple(10, 5_000_001, 60)]);
384 assert_eq!(&[0x84, 205, 0, 6, 0, 0, 0, 7, 0, 0, 0, 0], &raw[..12]);
385 let packet = parse(&raw).expect("a TMMBN");
386 assert_eq!(FMT_TMMBN, packet.fmt);
387 assert_eq!(
389 vec![tuple(9, 35_000, 40), tuple(10, 5_000_000, 60)],
390 packet.entries
391 );
392
393 let empty = build_tmmbn(7, &[]);
394 assert_eq!(&[0x84, 205, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0], &empty[..]);
395 }
396
397 #[test]
401 fn the_bounding_set_of_the_rfc_example() {
402 let a = tuple(1, 35_000, 40);
403 let b = tuple(2, 40_000, 60);
404 let c = tuple(3, 50_000, 40);
405
406 assert_eq!(
407 vec![a, b],
408 bounding_set(&[a, b, c]),
409 "C lies outside the polygon"
410 );
411 assert_eq!(Some(28_600.0), net_media_bitrate(&[a, b], 20.0));
412 assert_eq!(Some(30_400.0), net_media_bitrate(&[b], 20.0));
413 assert_eq!(Some(20_800.0), net_media_bitrate(&[a, b], 40.0));
415 }
416
417 #[test]
418 fn a_tuple_that_is_tighter_everywhere_is_the_whole_bounding_set() {
419 let tight = tuple(1, 20_000, 60);
420 let loose = tuple(2, 40_000, 40);
421 assert_eq!(vec![tight], bounding_set(&[loose, tight]));
422 }
423
424 #[test]
427 fn a_looser_limit_waits_two_round_trips() {
428 let now = Instant::now();
429 let rtt = Duration::from_millis(150);
430 let mut state = TmmbrState::default();
431
432 state.on_request(now, 9, tuple(1, 500_000, 0), 0.0, rtt);
433 assert_eq!(Some(500_000.0), state.limit(0.0), "at once");
434
435 state.on_request(
436 now + Duration::from_secs(1),
437 9,
438 tuple(1, 900_000, 0),
439 0.0,
440 rtt,
441 );
442 assert_eq!(Some(500_000.0), state.limit(0.0), "not yet");
443 assert_eq!(
444 Some(now + Duration::from_millis(1300)),
445 state.poll_timeout()
446 );
447 state.on_timeout(now + Duration::from_millis(1299), 0.0, rtt);
448 assert_eq!(Some(500_000.0), state.limit(0.0));
449 state.on_timeout(now + Duration::from_millis(1300), 0.0, rtt);
450 assert_eq!(Some(900_000.0), state.limit(0.0), "after 2 * RTT");
451 }
452
453 #[test]
456 fn the_limit_is_taken_at_the_packet_rate_in_use() {
457 let now = Instant::now();
458 let mut state = TmmbrState::default();
459 state.on_request(now, 9, tuple(1, 80_000, 60), 171.0, Duration::ZERO);
460 assert_eq!(Some(0.0), state.limit(171.0));
461 assert_eq!(Some(80_000.0 - 50.0 * 480.0), state.limit(50.0));
462 }
463
464 #[test]
467 fn an_owner_that_leaves_or_times_out_takes_its_tuple_with_it() {
468 let now = Instant::now();
469 let rtt = Duration::from_millis(100);
470 let mut state = TmmbrState::default();
471 state.on_request(now, 9, tuple(1, 500_000, 0), 0.0, rtt);
472 state.on_request(now, 10, tuple(1, 800_000, 0), 0.0, rtt);
473 assert_eq!(vec![tuple(9, 500_000, 0)], state.bounding());
474
475 assert!(state.on_owner_left(now, 9, 0.0, rtt), "a TMMBN is owed");
476 assert_eq!(vec![tuple(10, 800_000, 0)], state.bounding());
477 assert!(
478 !state.on_owner_left(now, 9, 0.0, rtt),
479 "it had no tuple any more"
480 );
481
482 assert!(!state.on_timeout(now + Duration::from_secs(24), 0.0, rtt));
484 assert!(state.on_timeout(now + TMMBR_OWNER_TIMEOUT, 0.0, rtt));
485 assert!(state.bounding().is_empty());
486 state.on_timeout(now + TMMBR_OWNER_TIMEOUT + rtt * 2, 0.0, rtt);
487 assert_eq!(
488 None,
489 state.limit(0.0),
490 "no tuple, no limit, after the hold-off"
491 );
492 }
493}