Skip to main content

rtci_interceptor/gcc/
remb.rs

1//! The receive-side variant of draft-ietf-rmcat-gcc-02 (section 3): the delay-based controller
2//! runs where the media arrives, and its estimate goes back to the sender in a REMB
3//! (draft-alvestrand-rmcat-remb).
4//!
5//! Two interceptors:
6//!
7//! - [`RembGeneratorInterceptor`] (receiver): for every remote stream that negotiated
8//!   `goog-remb` and neither transport-wide congestion control nor RFC 8888 (with either of
9//!   those the sender runs the controller itself), it times the arrivals against the send
10//!   times, runs the delay-based controller of [`Gcc`] on them, and sends a REMB "as soon as
11//!   congestion is detected, otherwise at least once per second" (section 3).
12//! - [`AbsSendTimeInterceptor`] (sender): stamps the abs-send-time header extension on every
13//!   packet of a local stream that negotiated it, as the packet leaves the pacer (section 3:
14//!   "the sender SHOULD use the abs-send-time RTP header extension" with this variant).
15//!
16//! The send time of a packet is its abs-send-time when the stream carries one (one clock for
17//! every stream of the sender, so one estimator for all of them), else its RTP timestamp over
18//! the clock rate (one estimator per stream, as libwebrtc's single-stream estimator: RTP
19//! timestamps of different streams do not share an origin). The REMB carries the sum of the
20//! estimates and names every stream it covers. Retransmissions are left out: a repair leaves
21//! long after its timestamp says, and would read as a queue.
22
23use super::estimator::Gcc;
24use super::rate_calc::RateCalculator;
25use crate::cc::estimator::BandwidthEstimator;
26use crate::cc::feedback::negotiated_congestion_feedback;
27use crate::rtpfb::acknowledgement::PacketReport;
28use crate::stream_info::StreamInfo;
29use crate::twcc::flow_ssrcs;
30use crate::{Attribute, AttributedPacket, Interceptor, Packet, TaggedPacket};
31use rtcp::payload_feedbacks::receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate;
32use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
33use sansio::Protocol;
34use shared::TransportContext;
35use shared::error::Error;
36use shared::marshal::{MarshalSize, Unmarshal};
37use std::collections::{BTreeMap, HashMap, VecDeque};
38use std::time::{Duration, Instant};
39
40/// The abs-send-time header extension's URI.
41pub const ABS_SEND_TIME_URI: &str = "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time";
42
43/// Where the default interceptor set puts the [`RembGeneratorInterceptor`]
44/// (`Slot::Custom(REMB_GENERATOR_SLOT)`): with the other arrival recorders, after the RFC 8888
45/// one (9_000) and before the receiver report (10_000).
46pub const REMB_GENERATOR_SLOT: usize = 9_500;
47
48/// Where the default interceptor set puts the [`AbsSendTimeInterceptor`]
49/// (`Slot::Custom(ABS_SEND_TIME_SLOT)`): wire-ward of the pacer (3_000), so the stamp is the
50/// instant a packet leaves it, and of the TWCC sender (2_000); application-ward of the FEC
51/// wire-image tap (1_500), so FEC protects the stamped packet.
52pub const ABS_SEND_TIME_SLOT: usize = 1_900;
53
54/// The RTCP feedback type that negotiates REMB (`a=rtcp-fb:<pt> goog-remb`).
55pub const GOOG_REMB: &str = "goog-remb";
56
57/// How often the arrivals are given to the estimator.
58pub const REMB_UPDATE_INTERVAL: Duration = Duration::from_millis(100);
59
60/// The longest a REMB waits when nothing has changed (section 3: "at least once per second").
61pub const REMB_MAX_INTERVAL: Duration = Duration::from_secs(1);
62
63/// An estimate below this share of the last one sent is news (congestion) and goes out at
64/// once, as libwebrtc's `kSendThresholdPercent` has it.
65pub const REMB_DECREASE_TRIGGER: f64 = 0.97;
66
67/// How long arrivals are watched before the first estimate is made from what they carry.
68///
69/// A sender is still finding its rate in its first seconds; an estimate started from the
70/// controller's default and sent at once would cap it there. As libwebrtc's
71/// `AimdRateControl` does, the first estimate is the incoming rate after this long.
72pub const REMB_INITIALIZATION_TIME: Duration = Duration::from_secs(5);
73
74/// The lowest estimate a REMB carries.
75const REMB_MIN_BITRATE: f64 = 10_000.0;
76/// The highest.
77const REMB_MAX_BITRATE: f64 = 1_000_000_000.0;
78
79/// Abs-send-time: 6.18 fixed-point seconds in 24 bits.
80const ABS_SEND_TIME_HZ: f64 = (1u64 << 18) as f64;
81const ABS_SEND_TIME_MODULUS: u64 = 1 << 24;
82const RTP_TIMESTAMP_MODULUS: u64 = 1 << 32;
83
84/// A wrapping send clock, unwrapped: ticks since its first reading.
85#[derive(Debug, Clone, Copy)]
86struct SendClock {
87    hz: f64,
88    modulus: u64,
89    last: Option<u64>,
90    /// Ticks since the first reading (negative for a packet sent before it, reordered).
91    unwrapped: i64,
92}
93
94impl SendClock {
95    fn new(hz: f64, modulus: u64) -> Self {
96        Self {
97            hz,
98            modulus,
99            last: None,
100            unwrapped: 0,
101        }
102    }
103
104    /// Seconds since the first reading, for a raw reading.
105    fn seconds(&mut self, raw: u64) -> f64 {
106        let raw = raw % self.modulus;
107        if let Some(last) = self.last {
108            // The shorter way round the circle: forward up to half of it, back otherwise.
109            let forward = (raw + self.modulus - last) % self.modulus;
110            let delta = if forward <= self.modulus / 2 {
111                forward as i64
112            } else {
113                forward as i64 - self.modulus as i64
114            };
115            self.unwrapped += delta;
116        }
117        self.last = Some(raw);
118        self.unwrapped as f64 / self.hz
119    }
120}
121
122/// One delay-based estimate and what feeds it.
123struct Estimate {
124    clock: SendClock,
125    /// The arrival instant the first packet's send time is placed at.
126    anchor: Instant,
127    /// The send time of the packet placed at `anchor`, in seconds of `clock`.
128    anchor_seconds: f64,
129    /// Arrivals not yet given to the estimator.
130    reports: Vec<PacketReport>,
131    /// What arrived, for the first estimate.
132    incoming: RateCalculator,
133    first_arrival: Instant,
134    gcc: Option<Gcc>,
135    next_id: u64,
136}
137
138impl Estimate {
139    fn new(clock: SendClock, now: Instant) -> Self {
140        Self {
141            clock,
142            anchor: now,
143            anchor_seconds: f64::NAN,
144            reports: Vec::new(),
145            incoming: RateCalculator::new(Duration::from_secs(1)),
146            first_arrival: now,
147            gcc: None,
148            next_id: 0,
149        }
150    }
151
152    fn record(&mut self, now: Instant, epoch: Instant, ssrc: u32, raw_send_time: u64, size: usize) {
153        let seconds = self.clock.seconds(raw_send_time);
154        if self.anchor_seconds.is_nan() {
155            self.anchor_seconds = seconds;
156        }
157        let offset = seconds - self.anchor_seconds;
158        let departure = if offset >= 0.0 {
159            self.anchor + Duration::from_secs_f64(offset)
160        } else {
161            self.anchor
162                .checked_sub(Duration::from_secs_f64(-offset))
163                .unwrap_or(self.anchor)
164        };
165        self.incoming.add(now, size);
166        let id = self.next_id;
167        self.next_id += 1;
168        self.reports.push(PacketReport {
169            ssrc,
170            id,
171            rtp_sequence_number: 0,
172            is_twcc: false,
173            twcc_sequence_number: 0,
174            size,
175            arrived: true,
176            departure,
177            arrival: Some(now.saturating_duration_since(epoch)),
178            ecn: Ecn::default(),
179        });
180    }
181
182    /// Gives the estimator what arrived; the estimate, once there is one.
183    fn update(&mut self, now: Instant) -> Option<f64> {
184        if self.gcc.is_none() {
185            if now.saturating_duration_since(self.first_arrival) < REMB_INITIALIZATION_TIME {
186                self.reports.clear();
187                return None;
188            }
189            let incoming = self.incoming.rate_bits_per_second(now)?;
190            self.gcc = Some(Gcc::new(incoming, REMB_MIN_BITRATE, REMB_MAX_BITRATE));
191        }
192        let gcc = self.gcc.as_mut()?;
193        let reports = std::mem::take(&mut self.reports);
194        gcc.on_reports(now, &reports);
195        Some(gcc.target_bitrate())
196    }
197}
198
199/// A remote stream REMB is generated for.
200#[derive(Debug, Clone, Copy)]
201struct RembStream {
202    clock_rate: u32,
203    abs_send_time_id: Option<u8>,
204}
205
206/// Which estimate a stream's packets feed: the shared one of the abs-send-time clock, or the
207/// stream's own.
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
209enum EstimateKey {
210    AbsSendTime,
211    Stream(u32),
212}
213
214/// Builds a [`RembGeneratorInterceptor`].
215#[derive(Debug, Clone)]
216pub struct RembGeneratorBuilder {
217    interval: Duration,
218    sender_ssrc: Option<u32>,
219}
220
221impl Default for RembGeneratorBuilder {
222    fn default() -> Self {
223        Self {
224            interval: REMB_UPDATE_INTERVAL,
225            sender_ssrc: None,
226        }
227    }
228}
229
230impl RembGeneratorBuilder {
231    /// A builder with the defaults: arrivals read every 100 ms.
232    pub fn new() -> Self {
233        Self::default()
234    }
235
236    /// How often the arrivals are given to the estimator.
237    pub fn with_interval(mut self, interval: Duration) -> Self {
238        self.interval = interval;
239        self
240    }
241
242    /// The SSRC the REMB is sent from (random by default, as the other feedback
243    /// generators' are).
244    pub fn with_sender_ssrc(mut self, sender_ssrc: u32) -> Self {
245        self.sender_ssrc = Some(sender_ssrc);
246        self
247    }
248
249    /// Build the interceptor.
250    pub fn build(self) -> RembGeneratorInterceptor {
251        RembGeneratorInterceptor {
252            interval: self.interval,
253            sender_ssrc: self
254                .sender_ssrc
255                .unwrap_or_else(|| rand::random::<u32>().max(1)),
256            streams: HashMap::new(),
257            estimates: BTreeMap::new(),
258            epoch: None,
259            next_update: None,
260            last_sent: None,
261            read_queue: VecDeque::new(),
262            write_queue: VecDeque::new(),
263        }
264    }
265}
266
267/// Generates REMB for the remote streams that negotiated `goog-remb` and no per-packet
268/// congestion feedback (see the `gcc::remb` module's source documentation).
269pub struct RembGeneratorInterceptor {
270    interval: Duration,
271    sender_ssrc: u32,
272    streams: HashMap<u32, RembStream>,
273    estimates: BTreeMap<EstimateKey, Estimate>,
274    /// The first arrival: what arrival times are measured from.
275    epoch: Option<Instant>,
276    next_update: Option<Instant>,
277    /// The last REMB: its bit rate and when it was sent.
278    last_sent: Option<(f64, Instant)>,
279    read_queue: VecDeque<TaggedPacket>,
280    write_queue: VecDeque<TaggedPacket>,
281}
282
283impl RembGeneratorInterceptor {
284    fn record(&mut self, msg: &TaggedPacket) {
285        let Packet::Rtp(packet) = &msg.message.packet else {
286            return;
287        };
288        let Some(stream) = self.streams.get(&packet.header.ssrc).copied() else {
289            return;
290        };
291        if msg
292            .message
293            .attributes
294            .iter()
295            .any(|attribute| matches!(attribute, Attribute::Retransmitted { .. }))
296        {
297            return;
298        }
299        let abs_send_time = stream.abs_send_time_id.and_then(|id| {
300            let mut data = packet.header.get_extension(id)?;
301            rtp::extension::abs_send_time_extension::AbsSendTimeExtension::unmarshal(&mut data).ok()
302        });
303        let (key, raw, clock) = match abs_send_time {
304            Some(extension) => (
305                EstimateKey::AbsSendTime,
306                extension.timestamp,
307                SendClock::new(ABS_SEND_TIME_HZ, ABS_SEND_TIME_MODULUS),
308            ),
309            None if stream.clock_rate > 0 => (
310                EstimateKey::Stream(packet.header.ssrc),
311                u64::from(packet.header.timestamp),
312                SendClock::new(f64::from(stream.clock_rate), RTP_TIMESTAMP_MODULUS),
313            ),
314            None => return,
315        };
316        let now = msg.now;
317        let epoch = *self.epoch.get_or_insert(now);
318        self.next_update.get_or_insert(now + self.interval);
319        self.estimates
320            .entry(key)
321            .or_insert_with(|| Estimate::new(clock, now))
322            .record(now, epoch, packet.header.ssrc, raw, packet.marshal_size());
323    }
324
325    fn update(&mut self, now: Instant) {
326        let mut total = 0.0;
327        let mut any = false;
328        for estimate in self.estimates.values_mut() {
329            if let Some(bitrate) = estimate.update(now) {
330                total += bitrate;
331                any = true;
332            }
333        }
334        if !any {
335            return;
336        }
337        let due = match self.last_sent {
338            None => true,
339            Some((last, at)) => {
340                total < REMB_DECREASE_TRIGGER * last
341                    || now.saturating_duration_since(at) >= REMB_MAX_INTERVAL
342            }
343        };
344        if !due {
345            return;
346        }
347        let mut ssrcs: Vec<u32> = self.streams.keys().copied().collect();
348        ssrcs.sort_unstable();
349        self.last_sent = Some((total, now));
350        self.write_queue.push_back(TaggedPacket {
351            now,
352            transport: TransportContext::default(),
353            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
354                ReceiverEstimatedMaximumBitrate {
355                    sender_ssrc: self.sender_ssrc,
356                    bitrate: total as f32,
357                    ssrcs,
358                },
359            )])),
360        });
361    }
362}
363
364impl Protocol<TaggedPacket, TaggedPacket, ()> for RembGeneratorInterceptor {
365    type Rout = TaggedPacket;
366    type Wout = TaggedPacket;
367    type Eout = ();
368    type Error = Error;
369    type Time = Instant;
370
371    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
372        self.record(&msg);
373        self.read_queue.push_back(msg);
374        Ok(())
375    }
376
377    fn poll_read(&mut self) -> Option<Self::Rout> {
378        self.read_queue.pop_front()
379    }
380
381    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
382        self.write_queue.push_back(msg);
383        Ok(())
384    }
385
386    fn poll_write(&mut self) -> Option<Self::Wout> {
387        self.write_queue.pop_front()
388    }
389
390    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
391        if let Some(at) = self.next_update
392            && now >= at
393        {
394            self.update(now);
395            self.next_update = (!self.streams.is_empty()).then(|| now + self.interval);
396        }
397        Ok(())
398    }
399
400    fn poll_timeout(&mut self) -> Option<Self::Time> {
401        self.next_update
402    }
403}
404
405/// Whether REMB is generated for a remote stream: it negotiated `goog-remb`, and no
406/// per-packet feedback that would let the sender estimate for itself.
407fn wants_remb(info: &StreamInfo) -> bool {
408    info.rtcp_feedback.iter().any(|fb| fb.typ == GOOG_REMB)
409        && negotiated_congestion_feedback(info).is_none()
410}
411
412fn abs_send_time_id(info: &StreamInfo) -> Option<u8> {
413    info.rtp_header_extensions
414        .iter()
415        .find(|ext| ext.uri == ABS_SEND_TIME_URI)
416        .and_then(|ext| u8::try_from(ext.id).ok())
417        .filter(|id| *id != 0)
418}
419
420impl Interceptor for RembGeneratorInterceptor {
421    fn bind_remote_stream(&mut self, info: &StreamInfo) {
422        if !wants_remb(info) {
423            self.streams.remove(&info.ssrc);
424            return;
425        }
426        self.streams.insert(
427            info.ssrc,
428            RembStream {
429                clock_rate: info.clock_rate,
430                abs_send_time_id: abs_send_time_id(info),
431            },
432        );
433    }
434
435    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
436        self.streams.remove(&info.ssrc);
437        self.estimates.remove(&EstimateKey::Stream(info.ssrc));
438        if !self
439            .streams
440            .values()
441            .any(|stream| stream.abs_send_time_id.is_some())
442        {
443            self.estimates.remove(&EstimateKey::AbsSendTime);
444        }
445        if self.streams.is_empty() {
446            self.next_update = None;
447        }
448    }
449
450    fn bind_local_stream(&mut self, _info: &StreamInfo) {}
451
452    fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
453}
454
455/// Stamps the abs-send-time header extension on every packet of a local stream that
456/// negotiated it (see the `gcc::remb` module's source documentation): 6.18 fixed-point seconds of the
457/// instant the packet passes, which is as it leaves the pacer when the interceptor sits below
458/// it (the default set puts it at `Slot::Custom(1_900)`).
459#[derive(Default)]
460pub struct AbsSendTimeInterceptor {
461    /// The extension id, by SSRC (media, RTX and FEC of each stream).
462    ids: HashMap<u32, u8>,
463    epoch: Option<Instant>,
464    read_queue: VecDeque<TaggedPacket>,
465    write_queue: VecDeque<TaggedPacket>,
466}
467
468impl AbsSendTimeInterceptor {
469    /// An interceptor with no stream bound yet.
470    pub fn new() -> Self {
471        Self::default()
472    }
473
474    /// The extension's value at `now`: seconds since the first packet stamped, 6.18
475    /// fixed-point, modulo 64 s.
476    fn stamp(&mut self, now: Instant) -> [u8; 3] {
477        let epoch = *self.epoch.get_or_insert(now);
478        let seconds = now.saturating_duration_since(epoch).as_secs_f64();
479        let ticks = ((seconds * ABS_SEND_TIME_HZ) as u64) % ABS_SEND_TIME_MODULUS;
480        [(ticks >> 16) as u8, (ticks >> 8) as u8, ticks as u8]
481    }
482}
483
484impl Protocol<TaggedPacket, TaggedPacket, ()> for AbsSendTimeInterceptor {
485    type Rout = TaggedPacket;
486    type Wout = TaggedPacket;
487    type Eout = ();
488    type Error = Error;
489    type Time = Instant;
490
491    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
492        self.read_queue.push_back(msg);
493        Ok(())
494    }
495
496    fn poll_read(&mut self) -> Option<Self::Rout> {
497        self.read_queue.pop_front()
498    }
499
500    fn handle_write(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
501        if let Packet::Rtp(packet) = &mut msg.message.packet
502            && let Some(id) = self.ids.get(&packet.header.ssrc).copied()
503        {
504            let stamp = self.stamp(msg.now);
505            let _ = packet
506                .header
507                .set_extension_upgrading(id, bytes::Bytes::copy_from_slice(&stamp));
508        }
509        self.write_queue.push_back(msg);
510        Ok(())
511    }
512
513    fn poll_write(&mut self) -> Option<Self::Wout> {
514        self.write_queue.pop_front()
515    }
516
517    fn handle_timeout(&mut self, _now: Instant) -> Result<(), Self::Error> {
518        Ok(())
519    }
520
521    fn poll_timeout(&mut self) -> Option<Self::Time> {
522        None
523    }
524}
525
526impl Interceptor for AbsSendTimeInterceptor {
527    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
528
529    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
530
531    fn bind_local_stream(&mut self, info: &StreamInfo) {
532        if let Some(id) = abs_send_time_id(info) {
533            for ssrc in flow_ssrcs(info) {
534                self.ids.insert(ssrc, id);
535            }
536        }
537    }
538
539    fn unbind_local_stream(&mut self, info: &StreamInfo) {
540        for ssrc in flow_ssrcs(info) {
541            self.ids.remove(&ssrc);
542        }
543    }
544}
545
546#[cfg(test)]
547#[path = "remb_test.rs"]
548mod remb_test;