Skip to main content

rtci_interceptor/cc/
tmmbr.rs

1//! Temporary Maximum Media Stream Bit Rate: what a media sender owes a TMMBR (RFC 5104
2//! sections 3.5.4 and 4.2).
3//!
4//! A receiver that cannot take more than some bit rate says so with a TMMBR; the media sender
5//! has to stay inside the limit and acknowledge it with a TMMBN naming the tuples that currently
6//! bound it. RFC 8834 section 5.1.6 makes honouring a TMMBR mandatory for an endpoint that sends
7//! media.
8//!
9//! The two packets are RTPFB feedback with FMT 3 and 4. `rtci-rtcp` has no codec for them yet and
10//! hands them over as [`rtcp::raw_packet::RawPacket`], so the eight-byte FCI entries are read and
11//! written here.
12
13use bytes::{BufMut, Bytes, BytesMut};
14use std::collections::HashMap;
15use std::time::{Duration, Instant};
16
17/// RTPFB feedback message type of a TMMBR.
18pub(crate) const FMT_TMMBR: u8 = 3;
19/// RTPFB feedback message type of a TMMBN.
20pub(crate) const FMT_TMMBN: u8 = 4;
21/// RTCP packet type of transport layer feedback.
22const PT_RTPFB: u8 = 205;
23
24/// How long the owner of a tuple may stay silent before it has left: five reporting intervals of
25/// five seconds, the RTP participant timeout (RFC 3550 section 6.3.5).
26pub const TMMBR_OWNER_TIMEOUT: Duration = Duration::from_secs(25);
27
28/// One FCI entry of a TMMBR or a TMMBN (RFC 5104 sections 4.2.1.1 and 4.2.2.1).
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct TmmbEntry {
31    /// In a TMMBR, the media sender the limit is for; in a TMMBN, the owner of the tuple.
32    pub ssrc: u32,
33    /// MxTBR: the maximum total media bit rate, in bits per second, IP and transport overhead
34    /// included.
35    pub bitrate: u64,
36    /// The per-packet overhead the requester measured, in bytes.
37    pub overhead: u16,
38}
39
40/// A TMMBR or TMMBN as it is on the wire.
41#[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
48/// Read a TMMBR or TMMBN from a raw RTCP packet. `None` for anything else, or a packet too
49/// short for what its header says.
50pub(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
85/// Write a TMMBN: "SSRC of media source" is 0, the length is 2 + 2 * N, and a bounding set with
86/// no tuple gives a TMMBN without FCI (RFC 5104 sections 4.2.2.1 and 4.2.2.2).
87pub(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        // The smallest exponent that lets the mantissa fit its 17 bits.
96        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
107/// The tuples that bound a sender: the lower envelope of the lines
108/// `net media bit rate = MxTBR - 8 * overhead * packet rate` over the packet rates at which the
109/// envelope is still above zero (RFC 5104 section 3.5.4.2).
110pub(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    // The packet rates at which the limiting tuple can change: where two lines cross.
118    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                // Equal lines: one of them bounds, and it is the same one every time.
137                .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        // The tuple that limits just after this switchover, while the envelope is feasible.
146        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
170/// The bit rate left for RTP packets (headers and payload) at `packet_rate` packets per second
171/// under `tuples`: the lowest of `MxTBR - 8 * overhead * packet rate` (equations (1) and (2) of
172/// section 3.5.4.2).
173pub(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/// What was asked of this media sender, and by whom.
183#[derive(Debug, Default)]
184pub(crate) struct TmmbrState {
185    /// The latest request of each owner (the SSRC that sent the TMMBR), with when it was last
186    /// heard from.
187    requests: HashMap<u32, (TmmbEntry, Instant)>,
188    /// The bounding set last computed.
189    bounding: Vec<TmmbEntry>,
190    /// The bounding set in force: the limit is its net media bit rate at the packet rate the
191    /// sender uses now ([`limit`](Self::limit)), not at the one it used when a request came.
192    in_force: Vec<TmmbEntry>,
193    /// A looser bounding set that may only be used from this instant on
194    /// (`2 * RTT + T_Dither_Max`, section 4.2.1.2).
195    pending: Option<(Instant, Vec<TmmbEntry>)>,
196}
197
198impl TmmbrState {
199    /// The owners' tuples, in a stable order.
200    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    /// The bounding set, as a TMMBN reports it: one tuple per owner.
207    pub(crate) fn bounding(&self) -> &[TmmbEntry] {
208        &self.bounding
209    }
210
211    /// The limit on this sender's RTP bit rate at `packet_rate` packets per second, the rate
212    /// it sends at now, if any tuple bounds it. Section 3.5.4.2: "the bit rate available for
213    /// RTP payloads is equal to the TMMBR reported bit rate minus the packet rate used,
214    /// multiplied by the TMMBR reported overhead converted to bits", and "which limitation
215    /// applies depends on the packet rate being considered": the limit follows the packet
216    /// rate, so a burst of packets around the request (a probe cluster) does not hold the
217    /// sender at what was left at that moment.
218    pub(crate) fn limit(&self, packet_rate: f64) -> Option<f64> {
219        net_media_bitrate(&self.in_force, packet_rate)
220    }
221
222    /// Recompute the bounding set and the limit after the requests changed.
223    ///
224    /// A tighter limit applies at once. A looser one (or none) applies only after
225    /// `2 * RTT + T_Dither_Max`, point-to-point included: other receivers may be about to say
226    /// that the old limit still holds for them. `T_Dither_Max` is 0 in a session of two.
227    /// Tighter and looser are judged at `packet_rate`, the rate the sender uses now.
228    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    /// A TMMBR from `owner` asking `ssrc`-addressed limits of this sender. Returns whether a
245    /// TMMBN is owed: it is, for every TMMBR, whether or not it changed anything
246    /// (section 4.2.2.2).
247    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    /// `owner` was heard from: it has not timed out.
270    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    /// `owner` left the session (BYE). Returns whether a TMMBN is owed: it is when the owner had
277    /// a tuple (section 4.2.2.2), and it carries no FCI when the set is now empty.
278    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    /// Time passing: owners that timed out are removed, and a looser limit whose hold-off has
293    /// passed takes effect. Returns whether a TMMBN is owed.
294    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    /// When this state next needs [`on_timeout`](Self::on_timeout).
317    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    /// RFC 5104 section 4.2.1.1: SSRC, MxTBR Exp (6 bits), MxTBR Mantissa (17 bits), Measured
344    /// Overhead (9 bits); MxTBR = mantissa * 2^exp.
345    #[test]
346    fn a_tmmbr_fci_entry_is_read_as_the_rfc_lays_it_out() {
347        // FMT 3, PT 205, length 4 (20 bytes); sender 0x11223344; media source 0.
348        // Entry: SSRC 0xAABBCCDD, exp 2, mantissa 65536, overhead 40.
349        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    /// RFC 5104 section 4.2.2.1: TMMBN is FMT 4 with length 2 + 2 * N and media source 0; an
380    /// empty bounding set gives a TMMBN without FCI.
381    #[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        // 5 000 001 needs an exponent of 6 for the mantissa to fit 17 bits: 78 125 * 64.
388        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    /// The example of RFC 5104 section 3.5.4.2: A (35 kbit/s, 40 bytes) limits below 31.25
398    /// packets per second, B (40 kbit/s, 60 bytes) above; at 20 packets per second the net media
399    /// bit rate is 28 600 bit/s.
400    #[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        // Past the switchover B is the limit: at 40 packets per second, 20 800 against 22 200.
414        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    /// RFC 5104 section 4.2.1.2: a tighter limit applies at once; before raising its rate after
425    /// a looser one the sender waits 2 * RTT + T_Dither_Max.
426    #[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    /// RFC 5104 section 3.5.4.2: the limit of a bounding set is its net media bit rate at the
454    /// packet rate it is asked for, not at the one of the request.
455    #[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    /// RFC 5104 section 4.2.2.2: when the owner of a tuple leaves or times out the tuple is
465    /// removed and a TMMBN is owed.
466    #[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        // The other owner goes silent.
483        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}