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