Skip to main content

rtci_interceptor/rfc8888/
sender.rs

1//! Emits RFC 8888 congestion control feedback for the streams being received.
2
3use super::recorder::CcFeedbackRecorder;
4use crate::Interceptor;
5use crate::cc::feedback_cadence::{CongestionFeedbackCadence, FeedbackCadence};
6use crate::stream_info::StreamInfo;
7use crate::twcc::flow_ssrcs;
8use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
9use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
10use sansio::Protocol;
11use shared::error::Error;
12use shared::marshal::MarshalSize;
13use shared::time::SystemInstant;
14use shared::{EcnCodepoint, TransportContext};
15use std::collections::HashSet;
16use std::collections::VecDeque;
17use std::time::{Duration, Instant};
18
19/// How often feedback is sent when no interval is configured.
20pub const DEFAULT_INTERVAL: Duration = Duration::from_millis(100);
21
22/// Byte budget for one report, chosen to sit inside a conservative path MTU.
23pub const DEFAULT_MAX_REPORT_SIZE: usize = 1200;
24
25/// The RFC 8888 marking for the codepoint a datagram arrived with (`None` is Not-ECT).
26fn ecn_of(codepoint: Option<EcnCodepoint>) -> Ecn {
27    match codepoint {
28        None => Ecn::NotEct,
29        Some(EcnCodepoint::Ect0) => Ecn::Ect0,
30        Some(EcnCodepoint::Ect1) => Ecn::Ect1,
31        Some(EcnCodepoint::Ce) => Ecn::Ce,
32    }
33}
34
35/// Builder for [`Rfc8888Interceptor`].
36///
37/// # Example
38///
39/// ```
40/// use rtci_interceptor::{Slot, Registry, Rfc8888Builder};
41/// use std::time::Duration;
42///
43/// let chain = Registry::new()
44///     .with(Slot::Rfc8888, Rfc8888Builder::new().with_interval(Duration::from_millis(50)).build())
45///     .build();
46/// ```
47pub struct Rfc8888Builder {
48    interval: Duration,
49    adaptive_interval: bool,
50    cadence: CongestionFeedbackCadence,
51    feedback_share: f64,
52    max_adaptive_interval: Duration,
53    max_report_size: usize,
54    sender_ssrc: Option<u32>,
55    /// The wall-clock anchor report timestamps derive from (`None`: the process-wide one).
56    wall_clock: Option<SystemInstant>,
57}
58
59impl Default for Rfc8888Builder {
60    fn default() -> Self {
61        Self {
62            interval: DEFAULT_INTERVAL,
63            adaptive_interval: true,
64            cadence: CongestionFeedbackCadence::default(),
65            feedback_share: crate::cc::feedback_cadence::FEEDBACK_SHARE,
66            max_adaptive_interval: crate::cc::feedback_cadence::MAX_ADAPTIVE_INTERVAL,
67            max_report_size: DEFAULT_MAX_REPORT_SIZE,
68            sender_ssrc: None,
69            wall_clock: None,
70        }
71    }
72}
73
74/// Whether a stream negotiated RFC 8888 feedback: `a=rtcp-fb:<pt> ack ccfb` (RFC 8888
75/// section 6).
76pub(crate) fn stream_supports_ccfb(info: &StreamInfo) -> bool {
77    info.rtcp_feedback
78        .iter()
79        .any(|feedback| feedback.typ == "ack" && feedback.parameter == "ccfb")
80}
81
82/// An SSRC for a participant that sends no media: random, and never 0 (RFC 3550 section 8).
83pub(crate) fn random_ssrc() -> u32 {
84    loop {
85        let ssrc: u32 = rand::random();
86        if ssrc != 0 {
87            return ssrc;
88        }
89    }
90}
91
92impl Rfc8888Builder {
93    /// Create a builder with the default interval and report size.
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// How often feedback is sent.
99    ///
100    /// Congestion control wants this often — the estimate is only as fresh as the feedback
101    /// driving it — traded against the RTCP bandwidth it costs.
102    pub fn with_interval(mut self, interval: Duration) -> Self {
103        self.interval = interval;
104        self
105    }
106
107    /// Whether the interval follows the cadence ([`Self::with_cadence`]) or stays fixed at
108    /// [`Self::with_interval`] (`false`). On by default.
109    pub fn with_adaptive_interval(mut self, adaptive_interval: bool) -> Self {
110        self.adaptive_interval = adaptive_interval;
111        self
112    }
113
114    /// When a report is built while the interval is not fixed: see
115    /// [`CongestionFeedbackCadence`]. Default [`CongestionFeedbackCadence::ReceivedMedia`],
116    /// the engine's own form, which no specification has (RFC 8888 section 4 leaves the
117    /// interval to the application: "Applications need to negotiate an appropriate congestion
118    /// control feedback interval"). [`CongestionFeedbackCadence::PerFrame`] is the form of
119    /// the texts (RFC 8888 section 4, "sending feedback once per frame is an upper bound
120    /// before the reporting overhead becomes excessive", and "Specifications for RTP
121    /// congestion control algorithms can also provide guidance": draft-ietf-rmcat-gcc-02
122    /// section 3, "once per received video frame or at least once every 30 ms if audio-only
123    /// or multi-stream", up to 100 ms where the overhead needs to be limited): measured
124    /// worse as the default, it is the `StrictRfc` behaviour profile's.
125    pub fn with_cadence(mut self, cadence: CongestionFeedbackCadence) -> Self {
126        self.cadence = cadence;
127        self
128    }
129
130    /// The share of the rate it is sized to that the feedback may take with
131    /// [`CongestionFeedbackCadence::SendEstimate`] and
132    /// [`CongestionFeedbackCadence::ReceivedMedia`]. Default 0.05; the `Performance`
133    /// behaviour profile takes 0.025. [`CongestionFeedbackCadence::PerFrame`] does not use it.
134    pub fn with_feedback_share(mut self, share: f64) -> Self {
135        self.feedback_share = share;
136        self
137    }
138
139    /// The longest interval of [`CongestionFeedbackCadence::SendEstimate`] and
140    /// [`CongestionFeedbackCadence::ReceivedMedia`] while media flows. Default 250 ms; the
141    /// `Performance` behaviour profile takes 500 ms.
142    pub fn with_max_adaptive_interval(mut self, max_interval: Duration) -> Self {
143        self.max_adaptive_interval = max_interval;
144        self
145    }
146
147    /// Byte budget for one report.
148    ///
149    /// A report larger than the path MTU is fragmented or dropped, and feedback that does not
150    /// arrive is worth nothing, so feedback that exceeds the budget is split into several
151    /// reports (RFC 8888 section 3.1).
152    pub fn with_max_report_size(mut self, max_report_size: usize) -> Self {
153        self.max_report_size = max_report_size;
154        self
155    }
156
157    /// The SSRC these reports are sent from.
158    ///
159    /// Left unset, the interceptor uses the SSRC of the first local stream bound to it (the
160    /// RTCP packet sender is then the endpoint's own media source), and while there is none, a
161    /// random non-zero SSRC chosen when it is built, as a receive-only RTP participant has
162    /// (RFC 3550 section 8). It is never 0.
163    pub fn with_sender_ssrc(mut self, sender_ssrc: u32) -> Self {
164        self.sender_ssrc = Some(sender_ssrc);
165        self
166    }
167
168    /// The wall-clock anchor the reports' timestamps derive from (RFC 8888 section 3.1: the
169    /// clock of the RTCP sender reports' NTP timestamps, so give the RTCP session the same).
170    /// Default: the process-wide [`SystemInstant::shared`]. Give one per peer connection for
171    /// reproducible virtual-time runs: two runs in one process otherwise map the same instants
172    /// to NTP times as far apart as the real time between them.
173    pub fn with_wall_clock(mut self, anchor: SystemInstant) -> Self {
174        self.wall_clock = Some(anchor);
175        self
176    }
177
178    /// Build the interceptor.
179    pub fn build(self) -> Rfc8888Interceptor {
180        let mut interceptor = Rfc8888Interceptor::new(
181            self.interval,
182            self.adaptive_interval,
183            self.max_report_size,
184            self.sender_ssrc,
185        );
186        interceptor.cadence = FeedbackCadence::new(self.interval, self.adaptive_interval)
187            .with_form(self.cadence)
188            .with_limits(self.feedback_share, self.max_adaptive_interval);
189        interceptor.epoch = self.wall_clock;
190        interceptor
191    }
192}
193
194/// Reports when each packet of each bound remote stream arrived ([RFC 8888]).
195///
196/// # Differences from upstream
197///
198/// `pion/interceptor` injects a `SenderTicker` and a `SenderNow` so its tests can control time.
199/// Sans-I/O needs neither: every instant arrives as a parameter, so the tests drive the clock by
200/// passing one. Both are dropped.
201///
202/// Upstream's `Recorder` also never sets its sender SSRC, so every report it builds claims to come
203/// from SSRC 0. Here it is configured.
204///
205/// [RFC 8888]: https://www.rfc-editor.org/rfc/rfc8888
206pub struct Rfc8888Interceptor {
207    /// When a report is built ([`Rfc8888Builder::with_cadence`]).
208    cadence: FeedbackCadence,
209    max_report_size: usize,
210    /// The SSRC set on the builder, if one was.
211    configured_ssrc: Option<u32>,
212    /// The SSRC reports are sent from when none was configured and no local stream is bound.
213    receiver_ssrc: u32,
214    /// Local streams in the order they were bound: the first is the RTCP packet sender.
215    local_ssrcs: Vec<u32>,
216    recorder: CcFeedbackRecorder,
217    /// Remote streams being reported on.
218    streams: HashSet<u32>,
219    next_timeout: Option<Instant>,
220    /// Wall-clock reference, captured from the first instant handed over, so a monotonic `Instant`
221    /// can be turned into the NTP timestamp a report carries.
222    epoch: Option<SystemInstant>,
223    write_queue: VecDeque<TaggedPacket>,
224    /// Inbound packets ready for the next interceptor.
225    read_queue: VecDeque<TaggedPacket>,
226}
227
228impl Rfc8888Interceptor {
229    fn new(
230        interval: Duration,
231        adaptive_interval: bool,
232        max_report_size: usize,
233        sender_ssrc: Option<u32>,
234    ) -> Self {
235        Self {
236            read_queue: VecDeque::new(),
237            cadence: FeedbackCadence::new(interval, adaptive_interval),
238            max_report_size,
239            configured_ssrc: sender_ssrc,
240            receiver_ssrc: random_ssrc(),
241            local_ssrcs: Vec::new(),
242            recorder: CcFeedbackRecorder::new(),
243            streams: HashSet::new(),
244            next_timeout: None,
245            epoch: None,
246            write_queue: VecDeque::new(),
247        }
248    }
249
250    /// The SSRC the next report is sent from (RFC 8888 section 3.1: the SSRC of the RTCP packet
251    /// sender).
252    pub fn sender_ssrc(&self) -> u32 {
253        self.configured_ssrc
254            .or_else(|| self.local_ssrcs.first().copied())
255            .unwrap_or(self.receiver_ssrc)
256    }
257
258    /// The middle 32 bits of the NTP timestamp for `now`, which is what a report carries.
259    fn report_timestamp(&mut self, now: Instant) -> u32 {
260        let epoch = self.epoch.get_or_insert_with(|| SystemInstant::shared(now));
261        (epoch.ntp(now) >> 16) as u32
262    }
263
264    /// Builds the reports on what arrived since the last ones.
265    fn build_reports(&mut self, now: Instant) {
266        self.cadence.reported(now);
267        if self.recorder.is_empty() {
268            return;
269        }
270        let report_timestamp = self.report_timestamp(now);
271        let sender_ssrc = self.sender_ssrc();
272        for report in
273            self.recorder
274                .build_reports(now, sender_ssrc, report_timestamp, self.max_report_size)
275        {
276            if report.report_blocks.is_empty() {
277                continue;
278            }
279            self.cadence.on_feedback(report.marshal_size());
280            self.write_queue.push_back(TaggedPacket {
281                now,
282                transport: TransportContext::default(),
283                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(report)])),
284            });
285        }
286    }
287
288    /// Arm the interval from the first instant this interceptor is given.
289    fn arm(&mut self, now: Instant) {
290        if self.next_timeout.is_none() && !self.streams.is_empty() && !self.cadence.is_off() {
291            self.next_timeout = Some(now + self.cadence.interval(now));
292        }
293    }
294}
295
296impl Protocol<TaggedPacket, TaggedPacket, ()> for Rfc8888Interceptor {
297    type Rout = TaggedPacket;
298    type Wout = TaggedPacket;
299    type Eout = ();
300    type Error = Error;
301    type Time = Instant;
302
303    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
304        // Whether this packet ends a frame the cadence reports at once (per-frame feedback).
305        let frame_ended = self.cadence.on_packet(&msg);
306        if let Packet::Rtp(rtp_packet) = &msg.message.packet {
307            // An RTX packet reaches the chain rewritten into the original it carries; what
308            // arrived on the wire was a packet of the retransmission stream, and that is what
309            // the report describes (RFC 8888 section 3.1: a block "for each RTP stream", and
310            // section 6: feedback for every payload type in use, retransmission included). Its
311            // SSRC and sequence number are the ones the sender's history knows the RTX packet
312            // by; reporting it as the original would tell the sender a lost packet arrived.
313            let (ssrc, sequence_number) = msg
314                .message
315                .attributes
316                .iter()
317                .find_map(|attribute| match attribute {
318                    Attribute::Retransmitted {
319                        ssrc,
320                        sequence_number,
321                    } => Some((*ssrc, *sequence_number)),
322                    _ => None,
323                })
324                .unwrap_or((rtp_packet.header.ssrc, rtp_packet.header.sequence_number));
325            if self.streams.contains(&ssrc) {
326                // ECN lives in the IP header, which a sans-I/O interceptor never sees: the
327                // application's socket layer reads it and hands it over in the transport
328                // context. A datagram without one is reported Not-ECT, which is what an
329                // endpoint without ECN support reports anyway.
330                self.recorder
331                    .add_packet(msg.now, ssrc, sequence_number, ecn_of(msg.transport.ecn));
332                self.arm(msg.now);
333                if frame_ended {
334                    self.next_timeout = Some(msg.now + self.cadence.interval(msg.now));
335                    self.build_reports(msg.now);
336                }
337            }
338        }
339        self.read_queue.push_back(msg);
340        Ok(())
341    }
342
343    fn poll_read(&mut self) -> Option<Self::Rout> {
344        self.read_queue.pop_front()
345    }
346
347    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
348        // The media this endpoint sends is part of the session bandwidth, and what the RTCP
349        // session is told about its bandwidth passes here on its way to it.
350        self.cadence.on_write(&msg);
351        self.write_queue.push_back(msg);
352        Ok(())
353    }
354
355    fn poll_write(&mut self) -> Option<TaggedPacket> {
356        // Rejoins the belt and passes every interceptor between here and the wire, so a pacer
357        // meters it and a send history counts its bytes like any other outgoing packet.
358        self.write_queue.pop_front()
359    }
360
361    fn handle_timeout(&mut self, now: Instant) -> Result<(), Error> {
362        self.arm(now);
363
364        if let Some(next_timeout) = self.next_timeout
365            && now >= next_timeout
366        {
367            self.next_timeout = Some(now + self.cadence.interval(now));
368            self.build_reports(now);
369        }
370        Ok(())
371    }
372
373    fn poll_timeout(&mut self) -> Option<Instant> {
374        self.next_timeout
375    }
376}
377
378impl Interceptor for Rfc8888Interceptor {
379    /// Only a stream that negotiated `ack ccfb` is reported on: RTCP feedback is sent for the
380    /// payload types whose `a=rtcp-fb` line names it and for no other (RFC 4585 section 4.2,
381    /// RFC 8888 section 6). A peer that declined `ack ccfb` gets no report.
382    ///
383    /// The stream's retransmission and FEC SSRCs are reported with it: the feedback covers
384    /// every packet of the session's negotiated payload types, repair included (section 6).
385    fn bind_remote_stream(&mut self, info: &StreamInfo) {
386        if stream_supports_ccfb(info) {
387            self.streams.extend(flow_ssrcs(info));
388            self.cadence.bind_remote(info);
389        }
390    }
391
392    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
393        for ssrc in flow_ssrcs(info) {
394            self.streams.remove(&ssrc);
395            self.recorder.remove_stream(ssrc);
396        }
397        self.cadence.unbind_remote(info);
398        if self.streams.is_empty() {
399            self.next_timeout = None;
400        }
401    }
402
403    fn bind_local_stream(&mut self, info: &StreamInfo) {
404        if !self.local_ssrcs.contains(&info.ssrc) {
405            self.local_ssrcs.push(info.ssrc);
406        }
407    }
408
409    fn unbind_local_stream(&mut self, info: &StreamInfo) {
410        self.local_ssrcs.retain(|ssrc| *ssrc != info.ssrc);
411    }
412}
413
414#[cfg(test)]
415mod report_timestamp_test {
416    use super::*;
417    use crate::report::sender_stream::SenderStream;
418    use std::time::Duration;
419
420    /// RFC 8888 section 3.1: the report timestamp is "the middle 32 bits of an NTP format
421    /// timestamp ... derived from the same clock used to generate the NTP timestamp field in
422    /// RTCP SR packets". A stream that started sending well before the first feedback report
423    /// (thirty seconds of a clock the caller drives) and the report agree on the time.
424    #[test]
425    fn the_report_timestamp_is_on_the_clock_of_the_sender_reports() {
426        let start = Instant::now();
427        let mut stream = SenderStream::new(0x1234, 90_000, false);
428        stream.process_rtp(
429            start,
430            &rtp::packet::Packet {
431                header: rtp::header::Header {
432                    ssrc: 0x1234,
433                    timestamp: 1,
434                    ..Default::default()
435                },
436                payload: bytes::Bytes::from_static(b"media"),
437            },
438        );
439
440        let later = start + Duration::from_secs(30);
441        let mut feedback = Rfc8888Builder::new().build();
442        let rts = feedback.report_timestamp(later);
443        let sr = stream.generate_report(later).expect("a sender report");
444        assert_eq!((sr.ntp_time >> 16) as u32, rts);
445    }
446}