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