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