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}
124
125impl TmmbrRequester {
126    pub(crate) fn bind(&mut self, media_ssrc: u32, negotiated: bool) {
127        self.remotes.entry(media_ssrc).or_default().negotiated = negotiated;
128    }
129
130    pub(crate) fn unbind(&mut self, media_ssrc: u32) {
131        self.remotes.remove(&media_ssrc);
132    }
133
134    /// An RTP packet of `media_ssrc` arrived: `rtp_overhead` bytes of RTP header and padding.
135    pub(crate) fn on_rtp(&mut self, media_ssrc: u32, rtp_overhead: usize, ipv6: bool) {
136        self.ipv6 = ipv6;
137        if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
138            let packet = (rtp_overhead + if ipv6 { IPV6_UDP } else { IPV4_UDP }) as f64;
139            remote.avg_overhead = Some(match remote.avg_overhead {
140                Some(average) => 15.0 / 16.0 * average + packet / 16.0,
141                None => packet,
142            });
143        }
144    }
145
146    pub(crate) fn on_control(&mut self, control: TmmbrControl, own_ssrc: u32) {
147        match control {
148            TmmbrControl::Limit {
149                media_ssrc,
150                bitrate,
151            } => {
152                if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
153                    remote.wanted = Some(bitrate);
154                }
155                self.evaluate(media_ssrc, own_ssrc);
156            }
157            TmmbrControl::Clear { media_ssrc } => {
158                if let Some(remote) = self.remotes.get_mut(&media_ssrc) {
159                    remote.wanted = None;
160                }
161                self.evaluate(media_ssrc, own_ssrc);
162            }
163            TmmbrControl::NegotiatedMaximum(maximum) => {
164                self.negotiated_maximum = maximum;
165                let ssrcs: Vec<u32> = self.remotes.keys().copied().collect();
166                for ssrc in ssrcs {
167                    self.evaluate(ssrc, own_ssrc);
168                }
169            }
170        }
171    }
172
173    /// A TMMBN arrived from `media_sender`, with its bounding set.
174    pub(crate) fn on_tmmbn(&mut self, media_sender: u32, entries: Vec<TmmbEntry>, own_ssrc: u32) {
175        let Some(remote) = self.remotes.get_mut(&media_sender) else {
176            return;
177        };
178        remote.tmmbn = Some(entries);
179        remote.unacknowledged = None;
180        self.evaluate(media_sender, own_ssrc);
181    }
182
183    /// The tuple this receiver asks of `media_ssrc` now, if it asks anything: the wanted limit
184    /// under the negotiated maximum, or, with none wanted, the lifting value (only meaningful
185    /// once something was asked).
186    fn tuple(&self, media_ssrc: u32, own_ssrc: u32) -> Option<TmmbEntry> {
187        let remote = self.remotes.get(&media_ssrc)?;
188        let ceiling = self.negotiated_maximum.unwrap_or(UNLIMITED);
189        Some(TmmbEntry {
190            ssrc: own_ssrc,
191            bitrate: remote.wanted.map_or(ceiling, |wanted| wanted.min(ceiling)),
192            overhead: remote.overhead(self.ipv6),
193        })
194    }
195
196    /// Section 4.2.1.2's three cases.
197    fn evaluate(&mut self, media_ssrc: u32, own_ssrc: u32) {
198        let Some(ours) = self.tuple(media_ssrc, own_ssrc) else {
199            return;
200        };
201        let Some(remote) = self.remotes.get_mut(&media_ssrc) else {
202            return;
203        };
204        if !remote.negotiated {
205            return;
206        }
207        let owed = match &remote.tmmbn {
208            // Before any TMMBN: whenever there is a limit to ask for, or one to lift.
209            None => remote.wanted.is_some() || remote.unacknowledged.is_some(),
210            Some(bounding) => match bounding.iter().find(|tuple| tuple.ssrc == own_ssrc) {
211                // An owner reports a changed tuple.
212                Some(owned) => {
213                    owned.bitrate != ours.bitrate
214                        || owned.overhead.abs_diff(ours.overhead) >= OVERHEAD_CHANGE
215                }
216                // A non-owner asks when its tuple would bound the sender.
217                None => {
218                    remote.wanted.is_some() && {
219                        let mut tuples = bounding.clone();
220                        tuples.push(ours);
221                        bounding_set(&tuples).contains(&ours)
222                    }
223                }
224            },
225        };
226        remote.owed |= owed;
227    }
228
229    /// The TMMBR entries to send at `now`, owed ones and repetitions of unacknowledged ones,
230    /// each with the overhead as it is now.
231    pub(crate) fn poll_request(&mut self, now: Instant, own_ssrc: u32) -> Vec<TmmbEntry> {
232        let ssrcs: Vec<u32> = self.remotes.keys().copied().collect();
233        let mut entries = Vec::new();
234        for media_ssrc in ssrcs {
235            let Some(ours) = self.tuple(media_ssrc, own_ssrc) else {
236                continue;
237            };
238            let Some(remote) = self.remotes.get_mut(&media_ssrc) else {
239                continue;
240            };
241            if !remote.negotiated {
242                continue;
243            }
244            let repeat = remote
245                .unacknowledged
246                .is_some_and(|(_, at)| now.saturating_duration_since(at) >= TMMBR_REPEAT_INTERVAL);
247            if remote.owed || repeat {
248                remote.owed = false;
249                remote.unacknowledged = Some((ours, now));
250                // In a TMMBR an entry names the media sender asked.
251                entries.push(TmmbEntry {
252                    ssrc: media_ssrc,
253                    ..ours
254                });
255            }
256        }
257        entries.sort_by_key(|entry| entry.ssrc);
258        entries
259    }
260
261    /// When the next repetition is due.
262    pub(crate) fn poll_timeout(&self) -> Option<Instant> {
263        self.remotes
264            .values()
265            .filter(|remote| remote.negotiated)
266            .filter_map(|remote| {
267                remote
268                    .unacknowledged
269                    .map(|(_, at)| at + TMMBR_REPEAT_INTERVAL)
270            })
271            .min()
272    }
273
274    /// The latest TMMBN from `media_sender`, as saved.
275    #[cfg(test)]
276    pub(crate) fn latest_tmmbn(&self, media_sender: u32) -> Option<&[TmmbEntry]> {
277        self.remotes.get(&media_sender)?.tmmbn.as_deref()
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    const SENDER: u32 = 0xA;
286    const OWN: u32 = 0xB;
287    const OTHER: u32 = 0xC;
288
289    fn requester() -> TmmbrRequester {
290        let mut r = TmmbrRequester::default();
291        r.bind(SENDER, true);
292        r
293    }
294
295    fn limit(r: &mut TmmbrRequester, bitrate: u64) {
296        r.on_control(
297            TmmbrControl::Limit {
298                media_ssrc: SENDER,
299                bitrate,
300            },
301            OWN,
302        );
303    }
304
305    #[test]
306    fn the_overhead_is_the_running_average_of_section_4_2_1_2() {
307        let mut r = requester();
308        r.on_rtp(SENDER, 12, false);
309        assert_eq!(r.remotes[&SENDER].avg_overhead, Some(40.0));
310        r.on_rtp(SENDER, 28, false);
311        // 15/16 * 40 + 1/16 * 56 = 41
312        assert_eq!(r.remotes[&SENDER].avg_overhead, Some(41.0));
313        r.on_rtp(SENDER, 12, true);
314        // IPv6: 15/16 * 41 + 1/16 * 60
315        let expected = 15.0 / 16.0 * 41.0 + 60.0 / 16.0;
316        assert!((r.remotes[&SENDER].avg_overhead.unwrap() - expected).abs() < 1e-9);
317    }
318
319    #[test]
320    fn a_first_limit_is_sent_at_once_and_repeated_until_a_tmmbn() {
321        let now = Instant::now();
322        let mut r = requester();
323        r.on_rtp(SENDER, 12, false);
324        limit(&mut r, 300_000);
325        let sent = r.poll_request(now, OWN);
326        assert_eq!(
327            sent,
328            vec![TmmbEntry {
329                ssrc: SENDER,
330                bitrate: 300_000,
331                overhead: 40
332            }]
333        );
334        assert!(
335            r.poll_request(now + Duration::from_millis(500), OWN)
336                .is_empty()
337        );
338        assert_eq!(r.poll_timeout(), Some(now + TMMBR_REPEAT_INTERVAL));
339        // The overhead moved meanwhile: the repetition carries the current value.
340        for _ in 0..32 {
341            r.on_rtp(SENDER, 32, false);
342        }
343        let again = r.poll_request(now + TMMBR_REPEAT_INTERVAL, OWN);
344        assert_eq!(again.len(), 1, "repeated without a TMMBN");
345        assert!(again[0].overhead > 40, "{again:?}");
346        r.on_tmmbn(
347            SENDER,
348            vec![TmmbEntry {
349                ssrc: OWN,
350                ..again[0]
351            }],
352            OWN,
353        );
354        assert!(r.latest_tmmbn(SENDER).is_some(), "the TMMBN is saved");
355        assert_eq!(r.poll_timeout(), None);
356        assert!(
357            r.poll_request(now + TMMBR_REPEAT_INTERVAL * 3, OWN)
358                .is_empty()
359        );
360    }
361
362    #[test]
363    fn an_owner_reports_a_changed_limit_and_lifts_it_at_the_negotiated_maximum() {
364        let now = Instant::now();
365        let mut r = requester();
366        r.on_control(TmmbrControl::NegotiatedMaximum(Some(2_000_000)), OWN);
367        limit(&mut r, 500_000);
368        let first = r.poll_request(now, OWN);
369        r.on_tmmbn(
370            SENDER,
371            vec![TmmbEntry {
372                ssrc: OWN,
373                ..first[0]
374            }],
375            OWN,
376        );
377        // Unchanged: nothing to say.
378        limit(&mut r, 500_000);
379        assert!(r.poll_request(now, OWN).is_empty());
380        limit(&mut r, 800_000);
381        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 800_000);
382        r.on_tmmbn(
383            SENDER,
384            vec![TmmbEntry {
385                ssrc: OWN,
386                bitrate: 800_000,
387                overhead: first[0].overhead,
388            }],
389            OWN,
390        );
391        r.on_control(TmmbrControl::Clear { media_ssrc: SENDER }, OWN);
392        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 2_000_000);
393    }
394
395    #[test]
396    fn a_limit_never_exceeds_the_negotiated_maximum() {
397        let mut r = requester();
398        r.on_control(TmmbrControl::NegotiatedMaximum(Some(1_000_000)), OWN);
399        limit(&mut r, 5_000_000);
400        assert_eq!(r.poll_request(Instant::now(), OWN)[0].bitrate, 1_000_000);
401    }
402
403    #[test]
404    fn a_non_owner_asks_only_when_its_tuple_would_bound_the_sender() {
405        let now = Instant::now();
406        let mut r = requester();
407        r.on_rtp(SENDER, 12, false);
408        let held = TmmbEntry {
409            ssrc: OTHER,
410            bitrate: 400_000,
411            overhead: 40,
412        };
413        r.on_tmmbn(SENDER, vec![held], OWN);
414        // Looser than another receiver's limit: it would not enter the bounding set.
415        limit(&mut r, 600_000);
416        assert!(r.poll_request(now, OWN).is_empty());
417        // Tighter: it would.
418        limit(&mut r, 300_000);
419        assert_eq!(r.poll_request(now, OWN)[0].bitrate, 300_000);
420    }
421
422    #[test]
423    fn a_stream_without_ccm_tmmbr_is_never_asked() {
424        let mut r = TmmbrRequester::default();
425        r.bind(SENDER, false);
426        limit(&mut r, 100_000);
427        assert!(r.poll_request(Instant::now(), OWN).is_empty());
428        assert_eq!(r.poll_timeout(), None);
429    }
430}