Skip to main content

rtci_interceptor/cc/
tmmbr_request.rs

1//! The media receiver's side of TMMBR (RFC 5104 sections 3.5.4.1 and 4.2.1.2): asking a remote
2//! media sender to stay under a bit rate, for a stream that negotiated `ccm tmmbr`.
3//!
4//! The application sets a limit per remote media SSRC with [`TmmbrControl`], written into the
5//! chain; the congestion control interceptor ([`CongestionControlInterceptor`]
6//! (crate::CongestionControlInterceptor)), which already reads TMMBN, holds this state and
7//! sends the TMMBRs. What it does:
8//!
9//! * the overhead in each entry is the running average `avg_OH (new) = 15/16*avg_OH (old) +
10//!   1/16*pckt_OH` over the stream's packets (section 4.2.1.2), at the IP layer: IPv4 or IPv6
11//!   and UDP headers, and the RTP header with its CSRCs, extensions and padding;
12//! * the value never exceeds a negotiated maximum ([`TmmbrControl::NegotiatedMaximum`]),
13//!   "MUST NOT exceed the negotiated value";
14//! * the latest TMMBN from each media sender is saved ("SHALL save the contents of the latest
15//!   TMMBN"), and a TMMBR is sent in the three cases section 4.2.1.2 allows: before any TMMBN
16//!   came from that sender; as owner of a bounding tuple when the bit rate or the overhead
17//!   changed; as non-owner when the receiver's tuple would enter the bounding set
18//!   (section 3.5.4.2, the sender's own algorithm);
19//! * the first TMMBR goes at once (section 4.2.1.3: "MAY use early or immediate feedback"); while
20//!   no TMMBN has acknowledged it, it is repeated every [`TMMBR_REPEAT_INTERVAL`], a regular
21//!   reporting interval rather than early ("Any repetition [...] SHOULD use regular RTCP
22//!   mode"), with the overhead brought up to date ("SHALL be updated to the current value of
23//!   avg_OH each time the entry is sent");
24//! * lifting a limit is a TMMBR at the negotiated maximum, or with no maximum negotiated at the
25//!   highest value the entry can carry, so the sender's bounding set no longer holds the
26//!   receiver's tuple (section 3.5.4.1: an owner reports changed values).
27//!
28//! Section 4.2.1.2's SHOULD, to renegotiate the session parameters when a limit is expected to
29//! be permanent, is the application's: only it knows whether a limit is.
30
31use super::tmmbr::{TmmbEntry, bounding_set};
32use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
33use shared::TransportContext;
34use std::collections::HashMap;
35use std::sync::Arc;
36use std::time::{Duration, Instant};
37
38/// How long an unacknowledged TMMBR waits before it is sent again (RFC 5104 section 4.2.1.2):
39/// about a regular RTCP reporting interval of a WebRTC session.
40pub const TMMBR_REPEAT_INTERVAL: Duration = Duration::from_secs(1);
41
42/// IPv4 and UDP headers, in bytes.
43const IPV4_UDP: usize = 20 + 8;
44/// IPv6 and UDP headers, in bytes.
45const IPV6_UDP: usize = 40 + 8;
46/// The overhead change, in bytes, that makes an owner report its tuple again: the running
47/// average moves by fractions of a byte with every packet.
48const OVERHEAD_CHANGE: u16 = 4;
49/// The highest value a TMMBR entry can say (17 bits of mantissa, a 6-bit exponent), as far as
50/// a `u64` holds it: "no limit".
51const UNLIMITED: u64 = 0x1_FFFF << 46;
52
53/// What an application tells the TMMBR requester (the congestion control interceptor), written
54/// into the chain with [`into_packet`](Self::into_packet).
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum TmmbrControl {
58    /// Ask the remote sender of `media_ssrc` to stay under `bitrate` bits per second, total
59    /// media bit rate at the IP layer (RFC 5104 section 2.2: the RTP packets with their IP,
60    /// UDP and RTP headers). Only for a remote stream that negotiated `ccm tmmbr`.
61    Limit {
62        /// The remote media sender's SSRC.
63        media_ssrc: u32,
64        /// The maximum total media bit rate.
65        bitrate: u64,
66    },
67    /// Lift the limit set on `media_ssrc`.
68    Clear {
69        /// The remote media sender's SSRC.
70        media_ssrc: u32,
71    },
72    /// The maximum bit rate negotiated in signalling for what this endpoint receives (`b=TIAS`,
73    /// or `b=AS` times 1000), which no TMMBR value exceeds (RFC 5104 section 4.2.1.2). `None`:
74    /// none was negotiated.
75    NegotiatedMaximum(Option<u64>),
76}
77
78impl TmmbrControl {
79    /// The packet that carries this to the interceptor when written into the chain at `now`.
80    pub fn into_packet(self, now: Instant) -> TaggedPacket {
81        TaggedPacket {
82            now,
83            transport: TransportContext::default(),
84            message: AttributedPacket::new(Packet::Rtcp(vec![]))
85                .with(Attribute::Custom(Arc::new(self))),
86        }
87    }
88}
89
90/// One remote media sender.
91#[derive(Debug, Default)]
92struct Remote {
93    /// `a=rtcp-fb:<pt> ccm tmmbr` was negotiated for the stream (RFC 5104 section 7.2: no
94    /// CCM is used that was not).
95    negotiated: bool,
96    /// avg_OH, in bytes; `None` before the first packet.
97    avg_overhead: Option<f64>,
98    /// The limit the application wants; `None`: none.
99    wanted: Option<u64>,
100    /// The latest TMMBN from this sender: its bounding set (owners and tuples).
101    tmmbn: Option<Vec<TmmbEntry>>,
102    /// The tuple last sent, and when; cleared by a TMMBN.
103    unacknowledged: Option<(TmmbEntry, Instant)>,
104    /// A TMMBR is to be sent at the next opportunity.
105    owed: bool,
106}
107
108impl Remote {
109    fn overhead(&self, ipv6: bool) -> u16 {
110        let fallback = if ipv6 { IPV6_UDP } else { IPV4_UDP } + 12;
111        self.avg_overhead
112            .map_or(fallback as u16, |oh| oh.round().clamp(0.0, 511.0) as u16)
113    }
114}
115
116/// The receiver side of TMMBR for every remote stream. See the module documentation.
117#[derive(Debug, Default)]
118pub(crate) struct TmmbrRequester {
119    remotes: HashMap<u32, Remote>,
120    negotiated_maximum: Option<u64>,
121    /// Whether the transport runs over IPv6, from the last packet's address.
122    ipv6: bool,
123    /// Whether every entry [`poll_request`](Self::poll_request) last returned repeats an
124    /// unacknowledged one (section 4.2.1.3: regular RTCP timing for those).
125    repeats_only: bool,
126}
127
128impl TmmbrRequester {
129    pub(crate) fn bind(&mut self, media_ssrc: u32, negotiated: bool) {
130        self.remotes.entry(media_ssrc).or_default().negotiated = negotiated;
131    }
132
133    pub(crate) fn unbind(&mut self, media_ssrc: u32) {
134        self.remotes.remove(&media_ssrc);
135    }
136
137    /// An RTP packet of `media_ssrc` arrived: `rtp_overhead` bytes of RTP header and padding.
138    pub(crate) fn on_rtp(&mut self, media_ssrc: u32, rtp_overhead: usize, ipv6: bool) {
139        self.ipv6 = ipv6;
140        if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
141            let packet = (rtp_overhead + if ipv6 { IPV6_UDP } else { IPV4_UDP }) as f64;
142            remote.avg_overhead = Some(match remote.avg_overhead {
143                Some(average) => 15.0 / 16.0 * average + packet / 16.0,
144                None => packet,
145            });
146        }
147    }
148
149    pub(crate) fn on_control(&mut self, control: TmmbrControl, own_ssrc: u32) {
150        match control {
151            TmmbrControl::Limit {
152                media_ssrc,
153                bitrate,
154            } => {
155                if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
156                    remote.wanted = Some(bitrate);
157                }
158                self.evaluate(media_ssrc, own_ssrc);
159            }
160            TmmbrControl::Clear { media_ssrc } => {
161                if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
162                    remote.wanted = None;
163                }
164                self.evaluate(media_ssrc, own_ssrc);
165            }
166            TmmbrControl::NegotiatedMaximum(maximum) => {
167                self.negotiated_maximum = maximum;
168                let ssrcs: Vec<u32> = self.remotes.keys().copied().collect();
169                for ssrc in ssrcs {
170                    self.evaluate(ssrc, own_ssrc);
171                }
172            }
173        }
174    }
175
176    /// A TMMBN arrived from `media_sender`, with its bounding set.
177    pub(crate) fn on_tmmbn(&mut self, media_sender: u32, entries: Vec<TmmbEntry>, own_ssrc: u32) {
178        let Some(remote) = self.remotes.get_mut(&media_sender) else {
179            return;
180        };
181        remote.tmmbn = Some(entries);
182        remote.unacknowledged = None;
183        self.evaluate(media_sender, own_ssrc);
184    }
185
186    /// The tuple this receiver asks of `media_ssrc` now, if it asks anything: the wanted limit
187    /// under the negotiated maximum, or, with none wanted, the lifting value (only meaningful
188    /// once something was asked).
189    fn tuple(&self, media_ssrc: u32, own_ssrc: u32) -> Option<TmmbEntry> {
190        let remote = self.remotes.get(&media_ssrc)?;
191        let ceiling = self.negotiated_maximum.unwrap_or(UNLIMITED);
192        Some(TmmbEntry {
193            ssrc: own_ssrc,
194            bitrate: remote.wanted.map_or(ceiling, |wanted| wanted.min(ceiling)),
195            overhead: remote.overhead(self.ipv6),
196        })
197    }
198
199    /// Section 4.2.1.2's three cases.
200    fn evaluate(&mut self, media_ssrc: u32, own_ssrc: u32) {
201        let Some(ours) = self.tuple(media_ssrc, own_ssrc) else {
202            return;
203        };
204        let Some(remote) = self.remotes.get_mut(&media_ssrc) else {
205            return;
206        };
207        if !remote.negotiated {
208            return;
209        }
210        let owed = match &remote.tmmbn {
211            // Before any TMMBN: whenever there is a limit to ask for, or one to lift.
212            None => remote.wanted.is_some() || remote.unacknowledged.is_some(),
213            Some(bounding) => match bounding.iter().find(|tuple| tuple.ssrc == own_ssrc) {
214                // An owner reports a changed tuple.
215                Some(owned) => {
216                    owned.bitrate != ours.bitrate
217                        || owned.overhead.abs_diff(ours.overhead) >= OVERHEAD_CHANGE
218                }
219                // A non-owner asks when its tuple would bound the sender.
220                None => {
221                    remote.wanted.is_some() && {
222                        let mut tuples = bounding.clone();
223                        tuples.push(ours);
224                        bounding_set(&tuples).contains(&ours)
225                    }
226                }
227            },
228        };
229        remote.owed |= owed;
230    }
231
232    /// The TMMBR entries to send at `now`, owed ones and repetitions of unacknowledged ones,
233    /// each with the overhead as it is now.
234    pub(crate) fn poll_request(&mut self, now: Instant, own_ssrc: u32) -> Vec<TmmbEntry> {
235        let ssrcs: Vec<u32> = self.remotes.keys().copied().collect();
236        let mut entries = Vec::new();
237        let mut first_transmission = false;
238        for media_ssrc in ssrcs {
239            let Some(ours) = self.tuple(media_ssrc, own_ssrc) else {
240                continue;
241            };
242            let Some(remote) = self.remotes.get_mut(&media_ssrc) else {
243                continue;
244            };
245            if !remote.negotiated {
246                continue;
247            }
248            let repeat = remote
249                .unacknowledged
250                .is_some_and(|(_, at)| now.saturating_duration_since(at) >= TMMBR_REPEAT_INTERVAL);
251            if remote.owed || repeat {
252                first_transmission |= remote.owed;
253                remote.owed = false;
254                remote.unacknowledged = Some((ours, now));
255                // In a TMMBR an entry names the media sender asked.
256                entries.push(TmmbEntry {
257                    ssrc: media_ssrc,
258                    ..ours
259                });
260            }
261        }
262        entries.sort_by_key(|entry| entry.ssrc);
263        self.repeats_only = !entries.is_empty() && !first_transmission;
264        entries
265    }
266
267    /// Whether the entries [`poll_request`](Self::poll_request) last returned are all
268    /// repetitions, which RFC 5104 section 4.2.1.3 sends in regular RTCP mode.
269    pub(crate) fn repeats_only(&self) -> bool {
270        self.repeats_only
271    }
272
273    /// When the next repetition is due.
274    pub(crate) fn poll_timeout(&self) -> Option<Instant> {
275        self.remotes
276            .values()
277            .filter(|remote| remote.negotiated)
278            .filter_map(|remote| {
279                remote
280                    .unacknowledged
281                    .map(|(_, at)| at + TMMBR_REPEAT_INTERVAL)
282            })
283            .min()
284    }
285
286    /// The latest TMMBN from `media_sender`, as saved.
287    #[cfg(test)]
288    pub(crate) fn latest_tmmbn(&self, media_sender: u32) -> Option<&[TmmbEntry]> {
289        self.remotes.get(&media_sender)?.tmmbn.as_deref()
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    const SENDER: u32 = 0xA;
298    const OWN: u32 = 0xB;
299    const OTHER: u32 = 0xC;
300
301    fn requester() -> TmmbrRequester {
302        let mut r = TmmbrRequester::default();
303        r.bind(SENDER, true);
304        r
305    }
306
307    fn limit(r: &mut TmmbrRequester, bitrate: u64) {
308        r.on_control(
309            TmmbrControl::Limit {
310                media_ssrc: SENDER,
311                bitrate,
312            },
313            OWN,
314        );
315    }
316
317    #[test]
318    fn the_overhead_is_the_running_average_of_section_4_2_1_2() {
319        let mut r = requester();
320        r.on_rtp(SENDER, 12, false);
321        assert_eq!(r.remotes[&SENDER].avg_overhead, Some(40.0));
322        r.on_rtp(SENDER, 28, false);
323        // 15/16 * 40 + 1/16 * 56 = 41
324        assert_eq!(r.remotes[&SENDER].avg_overhead, Some(41.0));
325        r.on_rtp(SENDER, 12, true);
326        // IPv6: 15/16 * 41 + 1/16 * 60
327        let expected = 15.0 / 16.0 * 41.0 + 60.0 / 16.0;
328        assert!((r.remotes[&SENDER].avg_overhead.unwrap() - expected).abs() < 1e-9);
329    }
330
331    #[test]
332    fn a_first_limit_is_sent_at_once_and_repeated_until_a_tmmbn() {
333        let now = Instant::now();
334        let mut r = requester();
335        r.on_rtp(SENDER, 12, false);
336        limit(&mut r, 300_000);
337        let sent = r.poll_request(now, OWN);
338        assert_eq!(
339            sent,
340            vec![TmmbEntry {
341                ssrc: SENDER,
342                bitrate: 300_000,
343                overhead: 40
344            }]
345        );
346        assert!(!r.repeats_only(), "the first transmission");
347        assert!(
348            r.poll_request(now + Duration::from_millis(500), OWN)
349                .is_empty()
350        );
351        assert_eq!(r.poll_timeout(), Some(now + TMMBR_REPEAT_INTERVAL));
352        // The overhead moved meanwhile: the repetition carries the current value.
353        for _ in 0..32 {
354            r.on_rtp(SENDER, 32, false);
355        }
356        let again = r.poll_request(now + TMMBR_REPEAT_INTERVAL, OWN);
357        assert_eq!(again.len(), 1, "repeated without a TMMBN");
358        assert!(
359            r.repeats_only(),
360            "a repetition (section 4.2.1.3: regular RTCP mode)"
361        );
362        assert!(again[0].overhead > 40, "{again:?}");
363        r.on_tmmbn(
364            SENDER,
365            vec![TmmbEntry {
366                ssrc: OWN,
367                ..again[0]
368            }],
369            OWN,
370        );
371        assert!(r.latest_tmmbn(SENDER).is_some(), "the TMMBN is saved");
372        assert_eq!(r.poll_timeout(), None);
373        assert!(
374            r.poll_request(now + TMMBR_REPEAT_INTERVAL * 3, OWN)
375                .is_empty()
376        );
377    }
378
379    #[test]
380    fn an_owner_reports_a_changed_limit_and_lifts_it_at_the_negotiated_maximum() {
381        let now = Instant::now();
382        let mut r = requester();
383        r.on_control(TmmbrControl::NegotiatedMaximum(Some(2_000_000)), OWN);
384        limit(&mut r, 500_000);
385        let first = r.poll_request(now, OWN);
386        r.on_tmmbn(
387            SENDER,
388            vec![TmmbEntry {
389                ssrc: OWN,
390                ..first[0]
391            }],
392            OWN,
393        );
394        // Unchanged: nothing to say.
395        limit(&mut r, 500_000);
396        assert!(r.poll_request(now, OWN).is_empty());
397        limit(&mut r, 800_000);
398        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 800_000);
399        r.on_tmmbn(
400            SENDER,
401            vec![TmmbEntry {
402                ssrc: OWN,
403                bitrate: 800_000,
404                overhead: first[0].overhead,
405            }],
406            OWN,
407        );
408        r.on_control(TmmbrControl::Clear { media_ssrc: SENDER }, OWN);
409        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 2_000_000);
410    }
411
412    #[test]
413    fn a_limit_never_exceeds_the_negotiated_maximum() {
414        let mut r = requester();
415        r.on_control(TmmbrControl::NegotiatedMaximum(Some(1_000_000)), OWN);
416        limit(&mut r, 5_000_000);
417        assert_eq!(r.poll_request(Instant::now(), OWN)[0].bitrate, 1_000_000);
418    }
419
420    #[test]
421    fn a_non_owner_asks_only_when_its_tuple_would_bound_the_sender() {
422        let now = Instant::now();
423        let mut r = requester();
424        r.on_rtp(SENDER, 12, false);
425        let held = TmmbEntry {
426            ssrc: OTHER,
427            bitrate: 400_000,
428            overhead: 40,
429        };
430        r.on_tmmbn(SENDER, vec![held], OWN);
431        // Looser than another receiver's limit: it would not enter the bounding set.
432        limit(&mut r, 600_000);
433        assert!(r.poll_request(now, OWN).is_empty());
434        // Tighter: it would.
435        limit(&mut r, 300_000);
436        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 300_000);
437    }
438
439    #[test]
440    fn a_stream_without_ccm_tmmbr_is_never_asked() {
441        let mut r = TmmbrRequester::default();
442        r.bind(SENDER, false);
443        limit(&mut r, 100_000);
444        assert!(r.poll_request(Instant::now(), OWN).is_empty());
445        assert_eq!(r.poll_timeout(), None);
446    }
447}