rtci_interceptor/circuit_breaker/mod.rs
1//! The RTP circuit breaker (RFC 8083).
2//!
3//! A congestion controller keeps a flow at the rate the path carries. A circuit breaker is what
4//! stops the flow when that has failed: the receiver has gone, the path delivers nothing, or the
5//! flow has been taking ten times what a TCP connection would get for long enough that it is no
6//! longer a transient. RFC 8834 section 7.1 requires both.
7//!
8//! It works from the plain RTCP every RTP endpoint sends: the report blocks of SR and RR packets.
9//! Nothing here depends on a congestion-control feedback format being negotiated.
10//!
11//! | Breaker | Trips when (RFC 8083) |
12//! |---|---|
13//! | RTCP timeout (4.1) | media is sent and no RTCP reports on it for three reporting intervals |
14//! | Media timeout (4.2) | `MEDIA_TIMEOUT` consecutive reports show the extended highest sequence number not moving |
15//! | Congestion (4.3) | the sending rate is more than ten times the TCP throughput for the reported loss and round trip time, averaged over `CB_INTERVAL` reports |
16//! | Media usability (4.4) | reported loss or delay stayed past the application's bound for the application's period |
17//!
18//! A tripped flow ceases transmission (4.5): its RTP is dropped here, above the TWCC sender and the
19//! send history, so a packet that does not leave is neither numbered nor counted. The
20//! application is told ([`CircuitBreakerNotice`]) and can restart it through
21//! [`CircuitBreakerHandle`], not before the interval that tripped it has passed again. The
22//! breaker restarts it itself only on what section 4.5 allows an automatic restart on,
23//! "information that the congestion has dissipated": the receiver's own reports on another
24//! flow of the same transport (see [`CircuitBreakerBuilder::with_automatic_restart`]).
25//!
26//! # The intervals
27//!
28//! Every count above is in reporting intervals of the receiver, Tdr: "the sender's estimate of
29//! the deterministic RTCP reporting interval, Td, calculated by a receiver of the data it is
30//! sending", which "can be estimated by executing the algorithm in Section 6.2 of \[RFC3550\]"
31//! (section 3). The RTCP session of the chain runs that algorithm and says what it gives
32//! ([`RtcpReportingInterval`](crate::RtcpReportingInterval), on every RTCP packet it hands
33//! application-ward); the breaker takes it as the least Tdr can be, and a receiver whose
34//! reports come further apart than that (a minimum interval of its own: RTP/AVP's five
35//! seconds, a `T_rr_interval`, a browser's fixed second) has the interval its reports show
36//! (section 4.3: "If the incoming RTCP SR or RR packets are using a reduced minimum RTCP
37//! reporting interval ... then that reduced RTCP reporting interval is used"). Reports that
38//! come closer together than the calculated interval (early feedback packets that carry a
39//! report) are each counted and do not shorten Tdr (section 5: they are "counted towards the
40//! circuit breaker conditions", which "will potentially make the RTP circuit breaker trigger
41//! earlier"). Without an RTCP session in the chain Tdr is the spacing of the reports.
42//!
43//! With RTP/AVPF and no `T_rr_interval` the calculated interval of a call that carries video
44//! is some tens of milliseconds, so k = 5 reports without progress are a quarter of a second
45//! or less: the breaker's timescale is the receiver's reporting timescale, as the RFC has it.
46
47use crate::Interceptor;
48use crate::never_sent::NeverSent;
49use crate::stream_info::StreamInfo;
50use crate::twcc::flow_ssrcs;
51use crate::{Packet, TaggedPacket};
52use sansio::Protocol;
53use shared::error::Error;
54use shared::marshal::MarshalSize;
55use std::collections::{HashMap, VecDeque};
56use std::sync::{Arc, Mutex, MutexGuard};
57use std::time::{Duration, Instant};
58
59/// The fixed minimum RTCP interval the RTCP timeout is computed with (Tmin, RFC 8083
60/// section 4.1).
61pub const DEFAULT_RTCP_INTERVAL: Duration = Duration::from_secs(5);
62
63/// The non-reporting threshold k: the RECOMMENDED value (RFC 8083 section 4.2).
64pub const DEFAULT_NON_REPORTING_THRESHOLD: u32 = 5;
65
66/// How many reporting intervals without RTCP trip the RTCP timeout breaker.
67const RTCP_TIMEOUT_INTERVALS: u32 = 3;
68
69/// How far back frame intervals are looked at for Tf ("the largest inter-frame interval used in
70/// the last 10 seconds", RFC 8083 section 3).
71const FRAME_INTERVAL_WINDOW: Duration = Duration::from_secs(10);
72
73/// How many sender reports are remembered to turn a report block's LSR into a send instant.
74const REMEMBERED_SENDER_REPORTS: usize = 16;
75
76/// How many departures of a flow are remembered until a report covers them.
77const REMEMBERED_DEPARTURES: usize = 4096;
78
79/// How many times the hold of a flow that trips again soon after a restart is doubled.
80const MAX_HOLD_DOUBLINGS: u32 = 6;
81
82/// A restarted flow that has run this many times its last hold without tripping starts over
83/// with the triggering interval alone as its hold.
84const CLEAN_RUN_HOLDS: u32 = 10;
85
86/// Which breaker stopped a flow.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88#[non_exhaustive]
89pub enum CircuitBreakerReason {
90 /// No RTCP reported on the media being sent for three reporting intervals (section 4.1).
91 RtcpTimeout,
92 /// The receiver's reports showed the media not arriving (section 4.2).
93 MediaTimeout,
94 /// The flow sent more than ten times what TCP would have achieved (section 4.3).
95 Congestion,
96 /// Loss or delay stayed past the application's usability bound (section 4.4).
97 MediaUnusable,
98}
99
100/// The circuit breaker ceased or restarted a flow (RFC 8083 section 4.5).
101///
102/// The breaker sends it application-ward, on an empty RTCP carrier on its read leg, at the
103/// instant a flow ceases and when a restart takes effect: one the application asked for
104/// ([`CircuitBreakerHandle::restart`]) or one the breaker made on the receiver's reports
105/// ([`CircuitBreakerBuilder::with_automatic_restart`]). A ceased flow's RTP is dropped at the
106/// breaker until it is restarted. Section 4.5: "RTP flows halted by the circuit breaker
107/// SHOULD NOT be restarted automatically unless the sender has received information that the
108/// congestion has dissipated or can reasonably be expected to have dissipated"; where no such
109/// information can reach the breaker (every flow of the transport has ceased) only the
110/// application can restart the flow, so it has to hear of it: the peer connection hands this
111/// to the application as `RTCPeerConnectionEvent::OnCircuitBreaker`. The pacer reads it on
112/// its way past and stops charging the flow's packets to its budget (they do not leave).
113/// Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
114#[derive(Debug, Clone, Copy, PartialEq)]
115pub struct CircuitBreakerNotice {
116 /// The flow (a media, RTX or FEC SSRC this endpoint sends).
117 pub ssrc: u32,
118 /// The breaker that tripped, `None` for a flow that was restarted.
119 pub ceased: Option<CircuitBreakerReason>,
120 /// For a ceased flow: how long from now until a restart is accepted (section 4.5: "the
121 /// reaction to a triggered circuit breaker lasts for at least the triggering interval").
122 /// The triggering interval, doubled for each time the flow tripped again soon after a
123 /// restart.
124 pub restart_after: Duration,
125}
126
127/// What the circuit breaker is doing with one flow.
128#[derive(Debug, Clone, Copy, PartialEq)]
129#[non_exhaustive]
130pub enum CircuitBreakerState {
131 /// Sending normally.
132 Running,
133 /// The congestion breaker tripped once and the flow was given the chance to send at a tenth
134 /// of its rate (section 4.3). If the breaker trips again after the next `CB_INTERVAL`
135 /// reports, the flow ceases.
136 Reduced {
137 /// The rate the flow has to stay under, in bits per second.
138 limit_bits_per_second: f64,
139 },
140 /// Transmission has ceased (section 4.5): the flow's RTP is dropped.
141 Ceased {
142 /// The breaker that tripped.
143 reason: CircuitBreakerReason,
144 /// When it tripped.
145 at: Instant,
146 /// The earliest instant a restart is accepted.
147 restart_after: Instant,
148 },
149}
150
151/// How the congestion breaker takes s, the packet size of the TCP throughput equation (RFC
152/// 8083 section 4.3).
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154#[non_exhaustive]
155pub enum PacketSize {
156 /// The mean size of the RTP packets sent over the reporting intervals the sending rate is
157 /// measured over: s = (bytes sent) / (packets sent) over the last CB_INTERVAL intervals.
158 /// The default: s and the rate it is compared with describe the same packets.
159 #[default]
160 SendingWindow,
161 /// Section 3's definition as written: the mean size of the packets of the last 4 * G
162 /// frames. For speech with silence frames between talkspurts s is then the silence
163 /// frames' size (23 bytes) while the rate is that of the talkspurts, and a call over a
164 /// link with 1 to 5 % loss is ceased.
165 LastFrames,
166}
167
168/// The application's bound on what is still usable media (section 4.4). The RFC leaves the
169/// bound to the application on purpose.
170#[derive(Debug, Clone, Copy, PartialEq)]
171pub struct MediaUsability {
172 /// Reported loss fraction (0.0 to 1.0) above which the media is unusable.
173 pub max_loss: f64,
174 /// Round trip time above which the media is unusable.
175 pub max_round_trip_time: Duration,
176 /// How long it has to stay unusable before transmission ceases.
177 pub period: Duration,
178}
179
180#[derive(Debug, Clone, Copy)]
181struct Config {
182 rtcp_interval: Duration,
183 t_rr_interval: Option<Duration>,
184 non_reporting_threshold: u32,
185 frame_group_size: u32,
186 full_tcp_equation: bool,
187 packet_size: PacketSize,
188 reduce_before_ceasing: bool,
189 group: bool,
190 usability: Option<MediaUsability>,
191 automatic_restart: bool,
192}
193
194/// Builder for [`CircuitBreakerInterceptor`].
195///
196/// # Example
197///
198/// ```
199/// use rtci_interceptor::{CircuitBreakerBuilder, Registry, Slot};
200///
201/// let (breaker, handle) = CircuitBreakerBuilder::new().build();
202/// let chain = Registry::new().with(Slot::CircuitBreaker, breaker).build();
203/// assert!(handle.ceased().is_empty());
204/// # let _ = chain;
205/// ```
206pub struct CircuitBreakerBuilder {
207 config: Config,
208}
209
210impl Default for CircuitBreakerBuilder {
211 fn default() -> Self {
212 Self {
213 config: Config {
214 rtcp_interval: DEFAULT_RTCP_INTERVAL,
215 t_rr_interval: None,
216 non_reporting_threshold: DEFAULT_NON_REPORTING_THRESHOLD,
217 frame_group_size: 1,
218 full_tcp_equation: false,
219 packet_size: PacketSize::SendingWindow,
220 reduce_before_ceasing: false,
221 group: false,
222 usability: None,
223 automatic_restart: true,
224 },
225 }
226 }
227}
228
229impl CircuitBreakerBuilder {
230 /// A builder with the RFC's recommended values.
231 pub fn new() -> Self {
232 Self::default()
233 }
234
235 /// Td, this endpoint's deterministic RTCP reporting interval, computed with Tmin = 5 s
236 /// (section 4.1). The RTCP timeout breaker trips after three of them. Values above 5 s are
237 /// held to 5 s: the RFC says not to configure a longer one.
238 pub fn with_rtcp_interval(mut self, interval: Duration) -> Self {
239 self.config.rtcp_interval = interval.min(DEFAULT_RTCP_INTERVAL);
240 self
241 }
242
243 /// The AVPF `T_rr_interval` in use, which replaces Tdr in `CB_INTERVAL` when it is larger
244 /// (section 4.3). Held to 4 s (sections 4.1 and 4.3).
245 pub fn with_t_rr_interval(mut self, interval: Duration) -> Self {
246 self.config.t_rr_interval = Some(interval.min(Duration::from_secs(4)));
247 self
248 }
249
250 /// k, the number of reports without progress that gives assurance the forward path failed
251 /// (section 4.2). 5 is recommended.
252 pub fn with_non_reporting_threshold(mut self, k: u32) -> Self {
253 self.config.non_reporting_threshold = k.max(1);
254 self
255 }
256
257 /// G, the number of frames the codec needs before it can change rate (section 3). 1 for a
258 /// codec that can adapt on every frame.
259 pub fn with_frame_group_size(mut self, frames: u32) -> Self {
260 self.config.frame_group_size = frames.max(1);
261 self
262 }
263
264 /// Use the full TCP throughput equation instead of the simplified one (section 4.3: MAY; it
265 /// is more sensitive to loss and trips earlier).
266 pub fn with_full_tcp_equation(mut self, full: bool) -> Self {
267 self.config.full_tcp_equation = full;
268 self
269 }
270
271 /// How s, the packet size of the TCP throughput equation, is taken (section 4.3).
272 /// [`PacketSize::SendingWindow`] by default; [`PacketSize::LastFrames`] is section 3's
273 /// "last 4 * G frames".
274 pub fn with_packet_size(mut self, packet_size: PacketSize) -> Self {
275 self.config.packet_size = packet_size;
276 self
277 }
278
279 /// When the congestion breaker trips, first ask for a tenth of the rate
280 /// ([`CircuitBreakerState::Reduced`]) instead of ceasing at once (section 4.3: MAY). If it
281 /// trips again after the next `CB_INTERVAL` reports the flow ceases.
282 pub fn with_rate_reduction(mut self, reduce: bool) -> Self {
283 self.config.reduce_before_ceasing = reduce;
284 self
285 }
286
287 /// Treat every flow of the connection as one group: a breaker tripping for one flow applies
288 /// to all (section 8: MAY). By default each SSRC is judged on its own.
289 pub fn with_grouped_flows(mut self, group: bool) -> Self {
290 self.config.group = group;
291 self
292 }
293
294 /// The bound past which the media is unusable (section 4.4). Without one the media
295 /// usability breaker does not run: the RFC defines no bound.
296 pub fn with_media_usability(mut self, usability: MediaUsability) -> Self {
297 self.config.usability = Some(usability);
298 self
299 }
300
301 /// Whether the breaker restarts a ceased flow itself when the receiver's reports show what
302 /// stopped it has gone (`true`, the default), or leaves every restart to the application
303 /// (`false`).
304 ///
305 /// Section 4.5: "RTP flows halted by the circuit breaker SHOULD NOT be restarted
306 /// automatically unless the sender has received information that the congestion has
307 /// dissipated or can reasonably be expected to have dissipated." The information the
308 /// breaker takes is the receiver's reports on another flow this endpoint sends on the same
309 /// transport, received after the flow ceased:
310 ///
311 /// - a flow stopped by the media timeout (4.2, "most likely due to a path failure")
312 /// restarts when such a report shows the other flow's packets arriving: the path
313 /// delivers;
314 /// - a flow stopped by the congestion breaker (4.3) restarts when those reports, over a
315 /// whole hold, show a loss at which the rate that tripped it is within ten times the
316 /// TCP throughput again (or no loss at all);
317 /// - a flow stopped for unusable media (4.4) restarts when they show loss and round trip
318 /// time back inside the application's bound over a whole hold;
319 /// - a flow stopped by the RTCP timeout (4.1) restarts when a report on an SSRC this
320 /// endpoint sends arrives again: "the receiver and return path are working".
321 ///
322 /// Never before the hold has passed ("the reaction to a triggered circuit breaker lasts
323 /// for at least the triggering interval"), and a flow that trips again soon after a
324 /// restart is held twice as long each time (up to 64 times the triggering interval), so a
325 /// path that keeps failing is tried ever more rarely. When every flow of the transport has
326 /// ceased nothing is sent that a report could speak of: the application restarts
327 /// ([`CircuitBreakerHandle::restart`]) or nobody does.
328 pub fn with_automatic_restart(mut self, automatic: bool) -> Self {
329 self.config.automatic_restart = automatic;
330 self
331 }
332
333 /// Build the interceptor and the handle the application watches it through.
334 pub fn build(self) -> (CircuitBreakerInterceptor, CircuitBreakerHandle) {
335 let handle = CircuitBreakerHandle::new();
336 (self.build_with_handle(&handle), handle)
337 }
338
339 /// Build the interceptor `handle` watches (made beforehand, for example to give it to the
340 /// congestion controller of the same transport). One interceptor per handle.
341 pub fn build_with_handle(self, handle: &CircuitBreakerHandle) -> CircuitBreakerInterceptor {
342 CircuitBreakerInterceptor {
343 config: self.config,
344 flows: HashMap::new(),
345 awaiting_rtcp_since: None,
346 calculated_interval: None,
347 shared: handle.shared.clone(),
348 read_queue: VecDeque::new(),
349 write_queue: VecDeque::new(),
350 }
351 }
352}
353
354#[derive(Default)]
355struct Shared {
356 states: HashMap<u32, CircuitBreakerState>,
357 restarts: Vec<u32>,
358 dropped: u64,
359 /// The round trip time measured elsewhere in the chain, smoothed as section 3 says.
360 round_trip_time: Option<Duration>,
361}
362
363fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
364 shared
365 .lock()
366 .unwrap_or_else(|poisoned| poisoned.into_inner())
367}
368
369/// The application's view of the circuit breaker, and its way to restart a ceased flow.
370#[derive(Clone)]
371pub struct CircuitBreakerHandle {
372 shared: Arc<Mutex<Shared>>,
373}
374
375impl Default for CircuitBreakerHandle {
376 fn default() -> Self {
377 Self::new()
378 }
379}
380
381impl CircuitBreakerHandle {
382 /// A handle with no interceptor yet: [`CircuitBreakerBuilder::build_with_handle`] builds
383 /// the one it watches.
384 pub fn new() -> Self {
385 Self {
386 shared: Arc::new(Mutex::new(Shared::default())),
387 }
388 }
389
390 /// What the breaker is doing with the flow sent on `ssrc`, if it is bound.
391 pub fn state(&self, ssrc: u32) -> Option<CircuitBreakerState> {
392 lock(&self.shared).states.get(&ssrc).copied()
393 }
394
395 /// The flows that have ceased transmission, with the breaker that stopped each.
396 pub fn ceased(&self) -> Vec<(u32, CircuitBreakerReason)> {
397 let mut ceased: Vec<_> = lock(&self.shared)
398 .states
399 .iter()
400 .filter_map(|(ssrc, state)| match state {
401 CircuitBreakerState::Ceased { reason, .. } => Some((*ssrc, *reason)),
402 _ => None,
403 })
404 .collect();
405 ceased.sort_unstable_by_key(|(ssrc, _)| *ssrc);
406 ceased
407 }
408
409 /// The lowest rate any flow has been asked to stay under after the congestion breaker
410 /// tripped, in bits per second. A congestion controller takes it as an upper bound.
411 pub fn rate_limit(&self) -> Option<f64> {
412 lock(&self.shared)
413 .states
414 .values()
415 .filter_map(|state| match state {
416 CircuitBreakerState::Reduced {
417 limit_bits_per_second,
418 } => Some(*limit_bits_per_second),
419 _ => None,
420 })
421 .reduce(f64::min)
422 }
423
424 /// One round trip time measurement from congestion-control feedback, for the breaker to
425 /// use when it cannot measure one itself.
426 ///
427 /// Tr is the RFC 3550 round trip time: a report block's LSR and DLSR against the instant
428 /// the named sender report left. The breaker only knows that instant for sender reports
429 /// that pass it on the way out; when the RTCP session sits wire-ward of it (as the standard
430 /// set places it) none does, and without Tr the congestion breaker could never compare the
431 /// flow with TCP. The congestion controller's feedback gives the same quantity many times
432 /// a second.
433 ///
434 /// Give each measurement as it is made: this smooths them as section 3 says ("Tr = (0.8 *
435 /// Tr) + (0.2 * Tr_new) where Tr_new is the latest RTT estimate"), once. A value that is
436 /// already an average makes Tr trail the path by that average's memory on top of its own.
437 pub fn report_round_trip_time(&self, round_trip_time: Duration) {
438 let mut shared = lock(&self.shared);
439 shared.round_trip_time = Some(match shared.round_trip_time {
440 Some(previous) => previous.mul_f64(0.8) + round_trip_time.mul_f64(0.2),
441 None => round_trip_time,
442 });
443 }
444
445 /// How many RTP packets of ceased flows were dropped.
446 pub fn dropped(&self) -> u64 {
447 lock(&self.shared).dropped
448 }
449
450 /// Restart a ceased flow. Returns whether it restarted.
451 ///
452 /// This is the application saying the congestion can be expected to have gone (section
453 /// 4.5), for a flow the breaker has no information to restart on by itself
454 /// ([`CircuitBreakerBuilder::with_automatic_restart`]). It is refused until the hold has
455 /// passed (the interval that tripped the breaker, doubled for each trip that followed a
456 /// restart closely), so the reaction to a tripped breaker lasts at least the triggering
457 /// interval however often a restart is attempted.
458 pub fn restart(&self, ssrc: u32, now: Instant) -> bool {
459 let mut shared = lock(&self.shared);
460 match shared.states.get(&ssrc) {
461 Some(CircuitBreakerState::Ceased { restart_after, .. }) if now >= *restart_after => {
462 shared.states.insert(ssrc, CircuitBreakerState::Running);
463 shared.restarts.push(ssrc);
464 true
465 }
466 _ => false,
467 }
468 }
469}
470
471/// One reporting interval as the congestion breaker records it.
472#[derive(Debug, Clone, Copy)]
473struct LossSample {
474 fraction_lost: f64,
475 duration: Duration,
476 bytes_sent: u64,
477 packets_sent: u64,
478 /// What the report's cumulative number lost and extended highest sequence number moved
479 /// by since the previous report (RFC 3550 6.4.1): the interval's net loss, in which a
480 /// packet that was only reordered counts in neither interval.
481 net_lost: i64,
482 net_expected: i64,
483}
484
485/// One frame's worth of packets, for the average packet size.
486#[derive(Debug, Clone, Copy, Default)]
487struct FrameSize {
488 bytes: u64,
489 packets: u64,
490}
491
492struct Flow {
493 state: CircuitBreakerState,
494 /// Packets and bytes sent since the last report block for this flow.
495 packets_since_report: u64,
496 bytes_since_report: u64,
497 /// The RTP timestamp of the frame being sent and when its first packet left.
498 current_frame: Option<(u32, Instant)>,
499 /// Inter-frame intervals of the last ten seconds, with the instant each ended.
500 frame_intervals: VecDeque<(Instant, Duration)>,
501 /// Sizes of the last `4 * G` frames, newest last.
502 frames: VecDeque<FrameSize>,
503 /// When the last report block for this flow arrived.
504 last_report_at: Option<Instant>,
505 /// When the flow's last packet left.
506 last_departure: Option<Instant>,
507 /// Smoothed interval between the receiver's reports: the estimate of Tdr.
508 receiver_interval: Option<Duration>,
509 /// The reporting SSRC whose blocks the flow follows, and when it last reported.
510 reporter: Option<(u32, Instant)>,
511 /// The extended highest sequence number the receiver last reported.
512 highest_sequence: Option<u32>,
513 /// The previous report's cumulative number lost and extended highest sequence number,
514 /// as reported (for the net loss of the next interval).
515 previous_report: Option<(i32, u32)>,
516 /// The sequence numbers the flow jumped over on its way out: the packets the pacer
517 /// discarded, which the receiver counts as lost.
518 never_sent: NeverSent,
519 /// Consecutive reports that showed no progress while media was being sent.
520 stalled_reports: u32,
521 media_timeout: u32,
522 losses: VecDeque<LossSample>,
523 reports_received: u64,
524 /// Report blocks since the rate was reduced.
525 reports_since_reduction: u64,
526 /// Smoothed round trip time, Tr.
527 round_trip_time: Option<Duration>,
528 /// Sender reports sent for this flow: the middle 32 bits of the NTP timestamp, and when.
529 sender_reports: VecDeque<(u32, Instant)>,
530 unusable_since: Option<Instant>,
531 /// The packets no report has covered yet: sequence number and when each left, oldest
532 /// first. What a report that shows no progress is held against (section 4.2).
533 unreported: VecDeque<(u16, Instant)>,
534 /// The newest sequence number that left.
535 newest_sent: Option<u16>,
536 /// What stopped the flow and what a restart waits for, while it is ceased.
537 halt: Option<Halt>,
538 /// How many times in a row the flow tripped soon after a restart (1 for a first trip).
539 trips: u32,
540 /// The hold of the last trip.
541 last_hold: Duration,
542 /// When the flow was last restarted.
543 restarted_at: Option<Instant>,
544}
545
546/// A ceased flow: what stopped it, and what the receiver's reports on the transport's other
547/// flows have shown since (the information section 4.5 lets a restart rest on).
548#[derive(Debug, Clone, Copy)]
549struct Halt {
550 reason: CircuitBreakerReason,
551 /// How long the reaction lasts at least.
552 hold: Duration,
553 restart_after: Instant,
554 /// The rate, in bytes per second, and the packet size the congestion breaker tripped at.
555 rate: f64,
556 packet_size: f64,
557 /// The start of the stretch of reports being weighed.
558 since: Instant,
559 /// Over that stretch, from reports that showed another flow's packets arriving: the time
560 /// they cover, in seconds, and the fraction lost weighted by it.
561 covered: f64,
562 lost: f64,
563}
564
565/// A breaker that tripped: which, the interval that triggered it, and for the congestion
566/// breaker the rate (bytes per second) and packet size it was judged at.
567#[derive(Debug, Clone, Copy)]
568struct Trip {
569 reason: CircuitBreakerReason,
570 interval: Duration,
571 rate: f64,
572 packet_size: f64,
573}
574
575impl Trip {
576 fn new(reason: CircuitBreakerReason, interval: Duration) -> Self {
577 Self {
578 reason,
579 interval,
580 rate: 0.0,
581 packet_size: 0.0,
582 }
583 }
584}
585
586/// What a report block said about a running flow, for the ceased flows of the same transport.
587#[derive(Debug, Clone, Copy)]
588struct Witness {
589 ssrc: u32,
590 /// Whether the report showed packets of the flow arriving since the one before.
591 progressed: bool,
592 fraction_lost: f64,
593 /// The time since the flow's previous report.
594 duration: Duration,
595 round_trip_time: Option<Duration>,
596}
597
598impl Flow {
599 fn new() -> Self {
600 Self {
601 state: CircuitBreakerState::Running,
602 packets_since_report: 0,
603 bytes_since_report: 0,
604 current_frame: None,
605 frame_intervals: VecDeque::new(),
606 frames: VecDeque::new(),
607 last_report_at: None,
608 last_departure: None,
609 receiver_interval: None,
610 reporter: None,
611 highest_sequence: None,
612 previous_report: None,
613 never_sent: NeverSent::default(),
614 stalled_reports: 0,
615 media_timeout: 0,
616 losses: VecDeque::new(),
617 reports_received: 0,
618 reports_since_reduction: 0,
619 round_trip_time: None,
620 sender_reports: VecDeque::new(),
621 unusable_since: None,
622 unreported: VecDeque::new(),
623 newest_sent: None,
624 halt: None,
625 trips: 0,
626 last_hold: Duration::ZERO,
627 restarted_at: None,
628 }
629 }
630
631 fn is_ceased(&self) -> bool {
632 matches!(self.state, CircuitBreakerState::Ceased { .. })
633 }
634
635 /// Tf: the largest inter-frame interval of the last ten seconds.
636 fn frame_interval(&self) -> Duration {
637 self.frame_intervals
638 .iter()
639 .map(|(_, interval)| *interval)
640 .max()
641 .unwrap_or_default()
642 }
643
644 /// s: the average size of the packets of the last `4 * G` frames, in bytes.
645 fn packet_size(&self) -> Option<f64> {
646 let (bytes, packets) = self
647 .frames
648 .iter()
649 .fold((0u64, 0u64), |(bytes, packets), frame| {
650 (bytes + frame.bytes, packets + frame.packets)
651 });
652 (packets > 0).then(|| bytes as f64 / packets as f64)
653 }
654
655 fn on_departure(
656 &mut self,
657 now: Instant,
658 sequence_number: u16,
659 timestamp: u32,
660 size: usize,
661 frames_kept: usize,
662 ) {
663 self.last_departure = Some(now);
664 self.never_sent.on_sent(sequence_number);
665 self.packets_since_report += 1;
666 self.bytes_since_report += size as u64;
667 // A sequence number behind the newest is a retransmission: the report that covers the
668 // newest covers it.
669 if self
670 .newest_sent
671 .is_none_or(|newest| is_newer(sequence_number, newest))
672 {
673 self.newest_sent = Some(sequence_number);
674 self.unreported.push_back((sequence_number, now));
675 while self.unreported.len() > REMEMBERED_DEPARTURES {
676 self.unreported.pop_front();
677 }
678 }
679
680 match self.current_frame {
681 Some((current, _)) if current == timestamp => {}
682 previous => {
683 if let Some((_, started)) = previous {
684 self.frame_intervals
685 .push_back((now, now.saturating_duration_since(started)));
686 }
687 self.current_frame = Some((timestamp, now));
688 self.frames.push_back(FrameSize::default());
689 while self.frames.len() > frames_kept {
690 self.frames.pop_front();
691 }
692 }
693 }
694 while let Some((at, _)) = self.frame_intervals.front() {
695 if now.saturating_duration_since(*at) <= FRAME_INTERVAL_WINDOW {
696 break;
697 }
698 self.frame_intervals.pop_front();
699 }
700 if let Some(frame) = self.frames.back_mut() {
701 frame.bytes += size as u64;
702 frame.packets += 1;
703 }
704 }
705
706 /// The receiver reported `highest` as the extended highest sequence number received: the
707 /// departures up to it are covered.
708 fn on_reported(&mut self, highest: u32) {
709 let highest = highest as u16;
710 while let Some((sequence_number, _)) = self.unreported.front() {
711 if is_newer(*sequence_number, highest) {
712 break;
713 }
714 self.unreported.pop_front();
715 }
716 }
717
718 /// When the oldest packet no report has covered left.
719 fn oldest_unreported(&self) -> Option<Instant> {
720 self.unreported.front().map(|(_, sent)| *sent)
721 }
722}
723
724/// Whether sequence number `a` is ahead of `b` (RFC 3550 A.1: within half the number space).
725fn is_newer(a: u16, b: u16) -> bool {
726 a != b && a.wrapping_sub(b) < 0x8000
727}
728
729/// The RTP circuit breaker of RFC 8083: stops a flow whose receiver has gone, whose media is
730/// not arriving, or that is persistently taking far more than its share.
731///
732/// # Where this belongs in the chain
733///
734/// [`Slot::CircuitBreaker`](crate::Slot::CircuitBreaker): below the pacer, so it sees every RTP
735/// packet when it is released, generated ones included; above the TWCC sender and the send
736/// history, so a packet it drops is never numbered or recorded as sent.
737pub struct CircuitBreakerInterceptor {
738 config: Config,
739 flows: HashMap<u32, Flow>,
740 /// When media was first sent since RTCP last reported on it: what the RTCP timeout runs
741 /// from. `None` while nothing sent is waiting to be reported on.
742 awaiting_rtcp_since: Option<Instant>,
743 /// What the chain's RTCP session last calculated as the deterministic reporting interval
744 /// (RFC 3550 section 6.3.1), `None` when no RTCP session says.
745 calculated_interval: Option<crate::RtcpReportingInterval>,
746 shared: Arc<Mutex<Shared>>,
747 read_queue: VecDeque<TaggedPacket>,
748 write_queue: VecDeque<TaggedPacket>,
749}
750
751/// MEDIA_TIMEOUT = ceil(k * max(Tf, Tr, Tdr) / Tdr) (RFC 8083 section 4.2).
752fn media_timeout(k: u32, tf: Duration, tr: Duration, tdr: Duration) -> u32 {
753 let tdr = tdr.as_secs_f64().max(1e-3);
754 let longest = tf.as_secs_f64().max(tr.as_secs_f64()).max(tdr);
755 // The small allowance keeps a ratio that is a whole number in exact arithmetic from
756 // being rounded up by its floating-point error.
757 (f64::from(k) * longest / tdr - 1e-9).ceil().max(1.0) as u32
758}
759
760/// CB_INTERVAL = ceil(3 * min(max(10*G*Tf, 10*Tr, 3*Tdr), max(15, 3*Td)) / (3*Tdr))
761/// (RFC 8083 section 4.3).
762fn cb_interval(g: u32, tf: Duration, tr: Duration, tdr: Duration, td: Duration) -> u32 {
763 let tdr = tdr.as_secs_f64().max(1e-3);
764 let reaction = (10.0 * f64::from(g) * tf.as_secs_f64())
765 .max(10.0 * tr.as_secs_f64())
766 .max(3.0 * tdr);
767 let cap = 15f64.max(3.0 * td.as_secs_f64());
768 ((3.0 * reaction.min(cap)) / (3.0 * tdr) - 1e-9)
769 .ceil()
770 .max(1.0) as u32
771}
772
773/// The sending rate, in bytes per second, over the newest of `samples` that together cover at
774/// least `span` (one reporting interval at least); 0 without samples.
775///
776/// RFC 8083 section 4.3 compares X "with the actual sending rate of the RTP stream", and the
777/// RFC 3551 text it quotes gives the timescale: "The timescale on which TCP throughput is
778/// measured is the round-trip time of the connection."
779fn recent_rate(samples: &VecDeque<LossSample>, span: Duration) -> f64 {
780 let mut covered = Duration::ZERO;
781 let mut bytes = 0u64;
782 for sample in samples.iter().rev() {
783 covered += sample.duration;
784 bytes += sample.bytes_sent;
785 if covered >= span {
786 break;
787 }
788 }
789 if covered.is_zero() {
790 0.0
791 } else {
792 bytes as f64 / covered.as_secs_f64()
793 }
794}
795
796/// s over the reporting intervals the sending rate is measured over: the bytes sent in them
797/// divided by the packets sent in them, `None` when none were sent.
798fn window_packet_size(samples: &VecDeque<LossSample>) -> Option<f64> {
799 let (bytes, packets) = samples
800 .iter()
801 .fold((0u64, 0u64), |(bytes, packets), sample| {
802 (bytes + sample.bytes_sent, packets + sample.packets_sent)
803 });
804 (packets > 0).then(|| bytes as f64 / packets as f64)
805}
806
807/// The share of the packets expected over `samples` that the cumulative count says were lost
808/// (RFC 3550 6.4.1: expected less received, late packets counted as received), `None` when
809/// the window expected none.
810///
811/// The fraction lost of each report cannot be negative (RFC 3550 A.3), so a packet that is
812/// only reordered across a report's boundary counts as lost in the interval that should have
813/// had it and is not given back in the next: on a path that reorders, the average of the
814/// fractions shows loss that never happened. RFC 8083 section 4.3 approximates the loss event
815/// rate by that average, a figure meant to err on the side of more loss; it cannot be more
816/// than the share actually lost, so the breaker takes the smaller of the two.
817///
818/// The newest report's own count is taken only where it gives packets back: a packet missing
819/// at that report may still be on its way (overtaken a moment before the report went), and
820/// the next report says whether it was lost. A packet really lost counts from then on, one
821/// reporting interval later.
822fn net_loss(samples: &VecDeque<LossSample>) -> Option<f64> {
823 let newest = samples.len().saturating_sub(1);
824 let (lost, expected) =
825 samples
826 .iter()
827 .enumerate()
828 .fold((0i64, 0i64), |(lost, expected), (index, sample)| {
829 let net_lost = if index == newest {
830 sample.net_lost.min(0)
831 } else {
832 sample.net_lost
833 };
834 (lost + net_lost, expected + sample.net_expected)
835 });
836 (expected > 0).then(|| lost.max(0) as f64 / expected as f64)
837}
838
839/// The throughput, in bytes per second, a TCP connection would achieve with packets of `s`
840/// bytes, round trip time `tr` and loss event rate `p` (RFC 8083 section 4.3), with b = 1 and
841/// t_RTO = 4 * Tr.
842fn tcp_throughput(s: f64, tr: Duration, p: f64, full: bool) -> f64 {
843 let tr = tr.as_secs_f64().max(1e-6);
844 let b = 1.0;
845 let simplified = tr * (2.0 * b * p / 3.0).sqrt();
846 let denominator = if full {
847 let t_rto = 4.0 * tr;
848 simplified + t_rto * (3.0 * (3.0 * b * p / 8.0).sqrt() * p * (1.0 + 32.0 * p * p))
849 } else {
850 simplified
851 };
852 s / denominator
853}
854
855impl CircuitBreakerInterceptor {
856 fn publish(&self, ssrc: u32) {
857 if let Some(flow) = self.flows.get(&ssrc) {
858 lock(&self.shared).states.insert(ssrc, flow.state);
859 }
860 }
861
862 /// Apply the restarts the application asked for through the handle.
863 fn apply_restarts(&mut self, now: Instant) {
864 let restarts = std::mem::take(&mut lock(&self.shared).restarts);
865 for ssrc in restarts {
866 self.restart(now, ssrc);
867 }
868 }
869
870 /// The flow sends again, and the chain application-ward is told.
871 fn restart(&mut self, now: Instant, ssrc: u32) {
872 let Some(flow) = self.flows.get_mut(&ssrc) else {
873 return;
874 };
875 // A restarted flow starts from nothing: what was measured before describes the path
876 // that tripped the breaker. What it keeps is how often it tripped, which the next
877 // hold is measured by.
878 let (trips, last_hold) = (flow.trips, flow.last_hold);
879 *flow = Flow::new();
880 flow.trips = trips;
881 flow.last_hold = last_hold;
882 flow.restarted_at = Some(now);
883 self.publish(ssrc);
884 self.notify(now, ssrc, None, Duration::ZERO);
885 }
886
887 /// Tells the chain application-ward, and through it the application, that a flow ceased
888 /// or was restarted ([`CircuitBreakerNotice`]).
889 fn notify(
890 &mut self,
891 now: Instant,
892 ssrc: u32,
893 ceased: Option<CircuitBreakerReason>,
894 restart_after: Duration,
895 ) {
896 self.read_queue.push_back(TaggedPacket {
897 now,
898 transport: shared::TransportContext::default(),
899 message: crate::AttributedPacket::new(Packet::Rtcp(vec![])).with(
900 crate::Attribute::Custom(Arc::new(CircuitBreakerNotice {
901 ssrc,
902 ceased,
903 restart_after,
904 })),
905 ),
906 });
907 }
908
909 /// Cease transmission of `ssrc`, or of every flow when flows are grouped.
910 fn cease(&mut self, ssrc: u32, trip: Trip, now: Instant) {
911 let ssrcs: Vec<u32> = if self.config.group {
912 self.flows.keys().copied().collect()
913 } else {
914 vec![ssrc]
915 };
916 for ssrc in ssrcs {
917 if let Some(flow) = self.flows.get_mut(&ssrc)
918 && !flow.is_ceased()
919 {
920 // Section 4.5: "the reaction to a triggered circuit breaker lasts for at least
921 // the triggering interval". A flow that trips again soon after a restart is
922 // held twice as long each time: a restart that keeps failing is the "automatic
923 // redial" the section warns of, and has to become rare.
924 let soon = flow.restarted_at.is_some_and(|at| {
925 now.saturating_duration_since(at)
926 < flow.last_hold.saturating_mul(CLEAN_RUN_HOLDS)
927 });
928 flow.trips = if soon {
929 (flow.trips + 1).min(MAX_HOLD_DOUBLINGS + 1)
930 } else {
931 1
932 };
933 let hold = trip.interval.saturating_mul(1 << (flow.trips - 1));
934 flow.last_hold = hold;
935 let restart_after = now + hold;
936 flow.state = CircuitBreakerState::Ceased {
937 reason: trip.reason,
938 at: now,
939 restart_after,
940 };
941 flow.halt = Some(Halt {
942 reason: trip.reason,
943 hold,
944 restart_after,
945 rate: trip.rate,
946 packet_size: trip.packet_size,
947 since: now,
948 covered: 0.0,
949 lost: 0.0,
950 });
951 // Stopping a stream cancels its media timeout breaker (section 4.2).
952 flow.stalled_reports = 0;
953 log::warn!(
954 "RTP circuit breaker: SSRC {ssrc:#x} ceased transmission ({:?}), held {hold:?}",
955 trip.reason
956 );
957 self.publish(ssrc);
958 self.notify(now, ssrc, Some(trip.reason), hold);
959 }
960 }
961 }
962
963 fn rtcp_timeout(&self) -> Duration {
964 self.config.rtcp_interval * RTCP_TIMEOUT_INTERVALS
965 }
966
967 /// A report on a running flow, held against the ceased flows of the same transport:
968 /// section 4.5's "information that the congestion has dissipated".
969 fn on_witness(&mut self, now: Instant, witness: Witness) {
970 if !self.config.automatic_restart {
971 return;
972 }
973 let config = self.config;
974 let mut restarts = Vec::new();
975 for (ssrc, flow) in self.flows.iter_mut() {
976 if *ssrc == witness.ssrc {
977 continue;
978 }
979 let Some(halt) = flow.halt.as_mut() else {
980 continue;
981 };
982 match halt.reason {
983 // "Most likely due to a path failure" (section 4): packets of another flow
984 // arriving over the same 5-tuple show the path delivers.
985 CircuitBreakerReason::MediaTimeout => {
986 if witness.progressed && now >= halt.restart_after {
987 restarts.push(*ssrc);
988 }
989 }
990 // A report on an SSRC this endpoint sends, see `on_rtcp`.
991 CircuitBreakerReason::RtcpTimeout => {}
992 CircuitBreakerReason::Congestion | CircuitBreakerReason::MediaUnusable => {
993 if witness.progressed {
994 let duration = witness.duration.as_secs_f64();
995 halt.covered += duration;
996 halt.lost += witness.fraction_lost * duration;
997 }
998 if now.saturating_duration_since(halt.since) < halt.hold {
999 continue;
1000 }
1001 // A whole hold of reports: what do they say of the path now?
1002 let informed = halt.covered >= halt.hold.as_secs_f64() / 2.0;
1003 let loss = if halt.covered > 0.0 {
1004 halt.lost / halt.covered
1005 } else {
1006 0.0
1007 };
1008 let dissipated = informed
1009 && match halt.reason {
1010 CircuitBreakerReason::Congestion => {
1011 loss <= 0.0
1012 || witness.round_trip_time.is_some_and(|tr| {
1013 halt.rate
1014 <= 10.0
1015 * tcp_throughput(
1016 halt.packet_size,
1017 tr,
1018 loss,
1019 config.full_tcp_equation,
1020 )
1021 })
1022 }
1023 _ => config.usability.is_none_or(|usability| {
1024 loss <= usability.max_loss
1025 && witness
1026 .round_trip_time
1027 .is_none_or(|tr| tr <= usability.max_round_trip_time)
1028 }),
1029 };
1030 if dissipated {
1031 restarts.push(*ssrc);
1032 } else {
1033 // Not yet: the next verdict is on another whole hold of reports.
1034 halt.since = now;
1035 halt.covered = 0.0;
1036 halt.lost = 0.0;
1037 }
1038 }
1039 }
1040 }
1041 for ssrc in restarts {
1042 log::info!("RTP circuit breaker: SSRC {ssrc:#x} restarted on the receiver's reports");
1043 self.restart(now, ssrc);
1044 }
1045 }
1046
1047 /// One report block about a flow this endpoint sends, from the SSRC `reporter`, in a
1048 /// sender report or a receiver report.
1049 ///
1050 /// The breaker is RFC 8083's for a unicast session: one receiver. That receiver reports on
1051 /// the flow from each of its SSRCs (RFC 8108 section 5.1: "each SSRC will send RTCP reports
1052 /// for all other SSRCs"), the same reception each time: the flow follows one reporting
1053 /// SSRC, and takes another only once the one it follows has been silent for the RTCP
1054 /// timeout (it left, or changed SSRC). Counting every copy would count each report several
1055 /// times (MEDIA_TIMEOUT reached in a fraction of the reports, each loss interval's packets
1056 /// taken by the first copy) and see a zero spacing between the copies (Tdr).
1057 fn on_report_block(
1058 &mut self,
1059 now: Instant,
1060 reporter: u32,
1061 report: &rtcp::reception_report::ReceptionReport,
1062 in_sender_report: bool,
1063 ) {
1064 let config = self.config;
1065 let rtcp_timeout = self.rtcp_timeout();
1066 // What the RTCP session calculates for a member in the receiver's place (RFC 8083
1067 // section 3: "whether the receiver is sending SR or RR packets"). Tdr above five
1068 // seconds is not to be configured (section 4.3), so the calculation claims no more.
1069 let calculated = self.calculated_interval.map(|interval| {
1070 if in_sender_report {
1071 interval.sender
1072 } else {
1073 interval.receiver
1074 }
1075 .min(DEFAULT_RTCP_INTERVAL)
1076 });
1077 let Some(flow) = self.flows.get_mut(&report.ssrc) else {
1078 return;
1079 };
1080 if flow.is_ceased() {
1081 return;
1082 }
1083 if let Some((followed, at)) = flow.reporter
1084 && followed != reporter
1085 && now.saturating_duration_since(at) < rtcp_timeout
1086 {
1087 return;
1088 }
1089 flow.reporter = Some((reporter, now));
1090
1091 // Tr: RFC 3550 section 6.4.1, smoothed as RFC 8083 section 3 says.
1092 if report.last_sender_report != 0
1093 && let Some((_, sent)) = flow
1094 .sender_reports
1095 .iter()
1096 .rev()
1097 .find(|(lsr, _)| *lsr == report.last_sender_report)
1098 {
1099 let delay = Duration::from_secs_f64(f64::from(report.delay) / 65_536.0);
1100 let sample = now.saturating_duration_since(*sent).saturating_sub(delay);
1101 flow.round_trip_time = Some(match flow.round_trip_time {
1102 Some(previous) => previous.mul_f64(0.8) + sample.mul_f64(0.2),
1103 None => sample,
1104 });
1105 }
1106
1107 // No sender report of this flow was seen leaving (the report generator is wire-ward of
1108 // here): Tr is the round trip time the congestion controller measured, smoothed where
1109 // its measurements are handed in (`CircuitBreakerHandle::report_round_trip_time`).
1110 if flow.sender_reports.is_empty()
1111 && let Some(reported) = lock(&self.shared).round_trip_time
1112 {
1113 flow.round_trip_time = Some(reported);
1114 }
1115
1116 // How often this receiver actually reports.
1117 let since_last = flow
1118 .last_report_at
1119 .map(|last| now.saturating_duration_since(last));
1120 if let Some(interval) = since_last {
1121 flow.receiver_interval = Some(match flow.receiver_interval {
1122 Some(previous) => previous.mul_f64(0.8) + interval.mul_f64(0.2),
1123 None => interval,
1124 });
1125 }
1126 flow.last_report_at = Some(now);
1127 flow.reports_received += 1;
1128
1129 // Tdr: the calculated deterministic interval, or the spacing of the reports where that
1130 // is longer (the receiver uses a minimum interval the calculation cannot know of).
1131 // Without an RTCP session to calculate it, the spacing; Td until there is one.
1132 let tdr = match (calculated, flow.receiver_interval) {
1133 (Some(calculated), Some(observed)) => calculated.max(observed),
1134 (Some(calculated), None) => calculated,
1135 (None, Some(observed)) => observed,
1136 (None, None) => config.rtcp_interval,
1137 };
1138 let tf = flow.frame_interval();
1139 let tr = flow.round_trip_time.unwrap_or_default();
1140 let sent_packets = std::mem::take(&mut flow.packets_since_report);
1141 let sent_bytes = std::mem::take(&mut flow.bytes_since_report);
1142 log::debug!(
1143 "circuit breaker: report on {:#x}: fraction lost {}/256, cumulative lost {}, \
1144 extended highest {}, jitter {}, LSR {:#x}, DLSR {}; Tr {:?} (shared {:?}), Tdr {:?} \
1145 (calculated {:?}, observed {:?}), Tf {:?}, sent since last {} packets / {} bytes, \
1146 report {}",
1147 report.ssrc,
1148 report.fraction_lost,
1149 report.total_lost,
1150 report.last_sequence_number,
1151 report.jitter,
1152 report.last_sender_report,
1153 report.delay,
1154 flow.round_trip_time,
1155 lock(&self.shared).round_trip_time,
1156 tdr,
1157 calculated,
1158 flow.receiver_interval,
1159 tf,
1160 sent_packets,
1161 sent_bytes,
1162 flow.reports_received,
1163 );
1164
1165 // --- Media timeout (section 4.2) ---
1166 let timeout = media_timeout(config.non_reporting_threshold, tf, tr, tdr);
1167 let progressed = match flow.highest_sequence {
1168 Some(previous) => report.last_sequence_number > previous,
1169 None => true,
1170 };
1171 let highest = flow
1172 .highest_sequence
1173 .map_or(report.last_sequence_number, |previous| {
1174 previous.max(report.last_sequence_number)
1175 });
1176 flow.highest_sequence = Some(highest);
1177 flow.on_reported(highest);
1178 // "If RTP data packets are being sent": a flow that has sent nothing for twice the
1179 // longest of its intervals has stopped (a paused pacer, a muted source), and
1180 // "When stopping sending an RTP stream, a sender MUST cancel the corresponding media
1181 // timeout circuit breaker."
1182 let slowest = tf.max(tr).max(tdr);
1183 let sending = flow
1184 .last_departure
1185 .is_some_and(|sent| now.saturating_duration_since(sent) <= slowest * 2);
1186 // "An RTCP packet indicating that its media was not received": a packet the report
1187 // does not cover left long enough ago to have arrived and been reported, a round trip
1188 // at least. A report that comes sooner than that after the packet says nothing of it.
1189 let missed = flow
1190 .oldest_unreported()
1191 .is_some_and(|sent| now.saturating_duration_since(sent) >= tr);
1192 let mut trip: Option<Trip> = None;
1193 if progressed {
1194 // The media is arriving: the breaker is cancelled and set anew.
1195 flow.stalled_reports = 0;
1196 flow.media_timeout = timeout;
1197 } else if !sending {
1198 flow.stalled_reports = 0;
1199 flow.media_timeout = timeout;
1200 } else if missed {
1201 // Media was sent and the receiver did not see it. Reconsider: the timeout only
1202 // ever extends.
1203 flow.media_timeout = flow.media_timeout.max(timeout);
1204 flow.stalled_reports += 1;
1205 log::debug!(
1206 "circuit breaker: {:#x}: no progress, {} of MEDIA_TIMEOUT {}",
1207 report.ssrc,
1208 flow.stalled_reports,
1209 flow.media_timeout
1210 );
1211 if flow.stalled_reports >= flow.media_timeout {
1212 trip = Some(Trip::new(
1213 CircuitBreakerReason::MediaTimeout,
1214 tdr * flow.media_timeout,
1215 ));
1216 }
1217 }
1218
1219 // The interval's net loss by the cumulative count (RFC 3550 6.4.1, A.3).
1220 let cumulative = report.cumulative_lost();
1221 // The receiver counts every sequence number it did not receive as lost, the ones the
1222 // pacer discarded before they left included. Those are not the path's loss: over the
1223 // interval the report covers they come out of the count, and out of the packets
1224 // expected, and the fraction lost is that of the packets that left.
1225 let interval = flow
1226 .never_sent
1227 .on_report(report.last_sequence_number, cumulative)
1228 .filter(|interval| interval.never_sent() > 0);
1229 let never_sent = interval.map_or(0, |interval| interval.never_sent());
1230 let (net_lost, net_expected) = match flow
1231 .previous_report
1232 .replace((cumulative, report.last_sequence_number))
1233 {
1234 Some((previous_lost, previous_highest)) => (
1235 i64::from(cumulative) - i64::from(previous_lost) - never_sent,
1236 i64::from(report.last_sequence_number.wrapping_sub(previous_highest) as i32)
1237 - never_sent,
1238 ),
1239 None => (0, 0),
1240 };
1241 let fraction_lost = interval.map_or(f64::from(report.fraction_lost) / 256.0, |interval| {
1242 interval.fraction_lost()
1243 });
1244
1245 // --- Congestion (section 4.3) ---
1246 let cb_tdr = config.t_rr_interval.map_or(tdr, |t_rr| t_rr.max(tdr));
1247 let interval = cb_interval(
1248 config.frame_group_size,
1249 tf,
1250 tr,
1251 cb_tdr,
1252 config.rtcp_interval,
1253 );
1254 if let Some(duration) = since_last {
1255 // Only while at least one packet is sent every max(Tdr, Tr): with fewer, the
1256 // fraction lost is a measurement artefact. That is the sender's rate, not every
1257 // report's: reports closer together than max(Tdr, Tr) (AVPF with early feedback
1258 // compounds: every 10 ms on a video flow) often see no packet of a flow that sends
1259 // a frame every 20 ms, and clearing the samples on each such report kept the
1260 // breaker from ever judging the flow. Over an interval shorter than the period, a
1261 // packet sent within the last period is enough.
1262 let period = tdr.max(tr).as_secs_f64().max(1e-3);
1263 let enough = if duration.as_secs_f64() >= period {
1264 sent_packets as f64 >= (duration.as_secs_f64() / period).floor()
1265 } else {
1266 flow.last_departure
1267 .is_some_and(|sent| now.saturating_duration_since(sent).as_secs_f64() <= period)
1268 };
1269 if enough {
1270 flow.losses.push_back(LossSample {
1271 fraction_lost,
1272 duration,
1273 bytes_sent: sent_bytes,
1274 packets_sent: sent_packets,
1275 net_lost,
1276 net_expected,
1277 });
1278 } else {
1279 flow.losses.clear();
1280 }
1281 while flow.losses.len() > interval as usize {
1282 flow.losses.pop_front();
1283 }
1284 }
1285 if matches!(flow.state, CircuitBreakerState::Reduced { .. }) {
1286 flow.reports_since_reduction += 1;
1287 }
1288 let window: Duration = flow.losses.iter().map(|sample| sample.duration).sum();
1289 if trip.is_none()
1290 && flow.reports_received > u64::from(interval)
1291 && flow.losses.len() >= interval as usize
1292 && !window.is_zero()
1293 && let Some(tr) = flow.round_trip_time
1294 && let Some(packet_size) = match config.packet_size {
1295 PacketSize::SendingWindow => window_packet_size(&flow.losses),
1296 PacketSize::LastFrames => flow.packet_size(),
1297 }
1298 {
1299 let average = flow
1300 .losses
1301 .iter()
1302 .map(|sample| sample.fraction_lost * sample.duration.as_secs_f64())
1303 .sum::<f64>()
1304 / window.as_secs_f64();
1305 let loss = average.min(net_loss(&flow.losses).unwrap_or(average));
1306 let bytes: u64 = flow.losses.iter().map(|sample| sample.bytes_sent).sum();
1307 let sending_rate = bytes as f64 / window.as_secs_f64();
1308 // "The actual sending rate of the RTP stream": what it sends now, over a round
1309 // trip (and a group of frames at least). CB_INTERVAL is there "to give the
1310 // congestion control algorithm time to react", so a flow whose rate came down
1311 // inside it is judged at the rate it came down to. The breaker trips on a flow
1312 // that was above ten times X over the intervals the loss is averaged over and
1313 // still is.
1314 let actual_rate = recent_rate(&flow.losses, tr.max(tf * config.frame_group_size));
1315 let bound = 10.0 * tcp_throughput(packet_size, tr, loss, config.full_tcp_equation);
1316 log::debug!(
1317 "circuit breaker: {:#x}: CB_INTERVAL {interval}, loss {loss:.4} over {window:?}, \
1318 sending {sending_rate:.0} B/s (now {actual_rate:.0} B/s), s {packet_size:.0} B, \
1319 Tr {tr:?}, 10 x TCP {bound:.0} B/s",
1320 report.ssrc,
1321 );
1322 if loss > 0.0 && sending_rate > bound && actual_rate > bound {
1323 match flow.state {
1324 CircuitBreakerState::Running if config.reduce_before_ceasing => {
1325 flow.state = CircuitBreakerState::Reduced {
1326 limit_bits_per_second: sending_rate * 8.0 / 10.0,
1327 };
1328 flow.reports_since_reduction = 0;
1329 // The next verdict is on what is sent from here on.
1330 flow.losses.clear();
1331 flow.reports_received = 0;
1332 }
1333 _ => {
1334 trip = Some(Trip {
1335 reason: CircuitBreakerReason::Congestion,
1336 interval: window,
1337 rate: sending_rate,
1338 packet_size,
1339 })
1340 }
1341 }
1342 } else if matches!(flow.state, CircuitBreakerState::Reduced { .. })
1343 && flow.reports_since_reduction >= u64::from(interval)
1344 {
1345 // The reduction resolved it.
1346 flow.state = CircuitBreakerState::Running;
1347 }
1348 }
1349
1350 // --- Media usability (section 4.4) ---
1351 if let Some(usability) = config.usability {
1352 let unusable = fraction_lost > usability.max_loss
1353 || flow
1354 .round_trip_time
1355 .is_some_and(|rtt| rtt > usability.max_round_trip_time);
1356 if unusable {
1357 let since = *flow.unusable_since.get_or_insert(now);
1358 if trip.is_none() && now.saturating_duration_since(since) >= usability.period {
1359 trip = Some(Trip::new(
1360 CircuitBreakerReason::MediaUnusable,
1361 usability.period,
1362 ));
1363 }
1364 } else {
1365 flow.unusable_since = None;
1366 }
1367 }
1368
1369 let witness = Witness {
1370 ssrc: report.ssrc,
1371 progressed,
1372 fraction_lost,
1373 duration: since_last.unwrap_or_default(),
1374 round_trip_time: flow.round_trip_time,
1375 };
1376 match trip {
1377 Some(trip) => self.cease(witness.ssrc, trip, now),
1378 None => {
1379 self.publish(witness.ssrc);
1380 self.on_witness(now, witness);
1381 }
1382 }
1383 }
1384
1385 /// Inbound RTCP: the report blocks feed the breakers, and anything at all shows the
1386 /// receiver and the return path are alive.
1387 fn on_rtcp(&mut self, now: Instant, packets: &[Box<dyn rtcp::Packet>]) {
1388 let mut reports = Vec::new();
1389 let mut has_report_packet = false;
1390 for packet in packets {
1391 let any = packet.as_any();
1392 if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
1393 has_report_packet = true;
1394 reports.extend(
1395 sr.reports
1396 .iter()
1397 .cloned()
1398 .map(|report| (sr.ssrc, report, true)),
1399 );
1400 } else if let Some(rr) = any.downcast_ref::<rtcp::receiver_report::ReceiverReport>() {
1401 has_report_packet = true;
1402 reports.extend(
1403 rr.reports
1404 .iter()
1405 .cloned()
1406 .map(|report| (rr.ssrc, report, false)),
1407 );
1408 }
1409 }
1410
1411 // RTCP timeout (section 4.1): a report on any SSRC this endpoint sends shows the
1412 // receiver and the return path work. A reduced-size packet without SR or RR counts as
1413 // received for this breaker too (section 5), and for this breaker only.
1414 let reports_on_us = reports
1415 .iter()
1416 .any(|(_, report, _)| self.flows.contains_key(&report.ssrc));
1417 if !packets.is_empty() && (!has_report_packet || reports_on_us) {
1418 self.awaiting_rtcp_since = None;
1419 }
1420
1421 // A flow the RTCP timeout stopped had "no way of knowing if it is causing congestion"
1422 // (section 4.1). A report on an SSRC this endpoint sends is that way back: once the
1423 // hold has passed the flow sends again.
1424 if self.config.automatic_restart && reports_on_us {
1425 let due: Vec<u32> = self
1426 .flows
1427 .iter()
1428 .filter(|(_, flow)| {
1429 flow.halt.is_some_and(|halt| {
1430 halt.reason == CircuitBreakerReason::RtcpTimeout
1431 && now >= halt.restart_after
1432 })
1433 })
1434 .map(|(ssrc, _)| *ssrc)
1435 .collect();
1436 for ssrc in due {
1437 log::info!("RTP circuit breaker: SSRC {ssrc:#x} restarted: RTCP reports again");
1438 self.restart(now, ssrc);
1439 }
1440 }
1441
1442 for (reporter, report, in_sender_report) in &reports {
1443 self.on_report_block(now, *reporter, report, *in_sender_report);
1444 }
1445 }
1446}
1447
1448impl Protocol<TaggedPacket, TaggedPacket, ()> for CircuitBreakerInterceptor {
1449 type Rout = TaggedPacket;
1450 type Wout = TaggedPacket;
1451 type Eout = ();
1452 type Error = Error;
1453 type Time = Instant;
1454
1455 fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1456 self.apply_restarts(msg.now);
1457 if let Some(interval) = msg.message.custom::<crate::RtcpReportingInterval>() {
1458 self.calculated_interval = Some(*interval);
1459 }
1460 if let Packet::Rtcp(packets) = &msg.message.packet {
1461 let packets: Vec<_> = packets.to_vec();
1462 self.on_rtcp(msg.now, &packets);
1463 }
1464 self.read_queue.push_back(msg);
1465 Ok(())
1466 }
1467
1468 fn poll_read(&mut self) -> Option<Self::Rout> {
1469 self.read_queue.pop_front()
1470 }
1471
1472 fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1473 self.apply_restarts(msg.now);
1474 match &msg.message.packet {
1475 Packet::Rtp(rtp_packet) => {
1476 let frames_kept = 4 * self.config.frame_group_size as usize;
1477 if let Some(flow) = self.flows.get_mut(&rtp_packet.header.ssrc) {
1478 if flow.is_ceased() {
1479 // Transmission has ceased (section 4.5): the packet does not leave.
1480 lock(&self.shared).dropped += 1;
1481 return Ok(());
1482 }
1483 flow.on_departure(
1484 msg.now,
1485 rtp_packet.header.sequence_number,
1486 rtp_packet.header.timestamp,
1487 rtp_packet.marshal_size(),
1488 frames_kept,
1489 );
1490 self.awaiting_rtcp_since.get_or_insert(msg.now);
1491 }
1492 }
1493 Packet::Rtcp(packets) => {
1494 // The sender reports this endpoint sends: a report block's LSR names one.
1495 for packet in packets {
1496 if let Some(sr) = packet
1497 .as_any()
1498 .downcast_ref::<rtcp::sender_report::SenderReport>()
1499 && let Some(flow) = self.flows.get_mut(&sr.ssrc)
1500 {
1501 flow.sender_reports
1502 .push_back(((sr.ntp_time >> 16) as u32, msg.now));
1503 while flow.sender_reports.len() > REMEMBERED_SENDER_REPORTS {
1504 flow.sender_reports.pop_front();
1505 }
1506 }
1507 }
1508 }
1509 }
1510 self.write_queue.push_back(msg);
1511 Ok(())
1512 }
1513
1514 fn poll_write(&mut self) -> Option<Self::Wout> {
1515 self.write_queue.pop_front()
1516 }
1517
1518 fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
1519 self.apply_restarts(now);
1520 if let Some(since) = self.awaiting_rtcp_since
1521 && now.saturating_duration_since(since) >= self.rtcp_timeout()
1522 {
1523 // Media has been sent for three reporting intervals and nothing reported on it:
1524 // there is no way to know whether it is causing congestion (section 4.1).
1525 self.awaiting_rtcp_since = None;
1526 let hold = self.rtcp_timeout();
1527 let ssrcs: Vec<u32> = self
1528 .flows
1529 .iter()
1530 .filter(|(_, flow)| !flow.is_ceased() && flow.current_frame.is_some())
1531 .map(|(ssrc, _)| *ssrc)
1532 .collect();
1533 for ssrc in ssrcs {
1534 self.cease(
1535 ssrc,
1536 Trip::new(CircuitBreakerReason::RtcpTimeout, hold),
1537 now,
1538 );
1539 }
1540 }
1541 Ok(())
1542 }
1543
1544 /// The RTCP timeout's deadline while sent media is waiting to be reported on, `None`
1545 /// otherwise.
1546 fn poll_timeout(&mut self) -> Option<Self::Time> {
1547 self.awaiting_rtcp_since
1548 .map(|since| since + self.rtcp_timeout())
1549 }
1550}
1551
1552impl Interceptor for CircuitBreakerInterceptor {
1553 /// The media SSRC and its repair flows are each a flow on the transport.
1554 fn bind_local_stream(&mut self, info: &StreamInfo) {
1555 for ssrc in flow_ssrcs(info) {
1556 self.flows.entry(ssrc).or_insert_with(Flow::new);
1557 self.publish(ssrc);
1558 }
1559 }
1560
1561 /// Stopping a stream cancels its breakers (section 4.2).
1562 fn unbind_local_stream(&mut self, info: &StreamInfo) {
1563 for ssrc in flow_ssrcs(info) {
1564 self.flows.remove(&ssrc);
1565 lock(&self.shared).states.remove(&ssrc);
1566 }
1567 if self.flows.values().all(|flow| flow.current_frame.is_none()) {
1568 self.awaiting_rtcp_since = None;
1569 }
1570 }
1571
1572 fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1573 fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1574}
1575
1576#[cfg(test)]
1577mod tests {
1578 use super::*;
1579
1580 fn secs(seconds: f64) -> Duration {
1581 Duration::from_secs_f64(seconds)
1582 }
1583
1584 /// RFC 8083 section 4.2: MEDIA_TIMEOUT = ceil(k * max(Tf, Tr, Tdr) / Tdr).
1585 #[test]
1586 fn media_timeout_is_k_reports_scaled_by_the_slowest_interval() {
1587 // Tdr dominates: k reports.
1588 assert_eq!(5, media_timeout(5, secs(0.033), secs(0.1), secs(1.0)));
1589 // A frame every 3 s against reports every second: 15 reports.
1590 assert_eq!(15, media_timeout(5, secs(3.0), secs(0.1), secs(1.0)));
1591 // A round trip of 1.5 reporting intervals: ceil(7.5).
1592 assert_eq!(8, media_timeout(5, secs(0.02), secs(1.5), secs(1.0)));
1593 }
1594
1595 /// RFC 8083 section 4.3:
1596 /// CB_INTERVAL = ceil(3 * min(max(10*G*Tf, 10*Tr, 3*Tdr), max(15, 3*Td)) / (3*Tdr)).
1597 #[test]
1598 fn cb_interval_gives_the_congestion_controller_time_to_react() {
1599 // 30 fps, 100 ms round trip, reports every second: max(0.33, 1, 3) = 3 s, 3 reports.
1600 assert_eq!(
1601 3,
1602 cb_interval(1, secs(1.0 / 30.0), secs(0.1), secs(1.0), secs(5.0))
1603 );
1604 // A 600 ms round trip: 10 * Tr = 6 s, 6 reports.
1605 assert_eq!(
1606 6,
1607 cb_interval(1, secs(0.033), secs(0.6), secs(1.0), secs(5.0))
1608 );
1609 // A long GOP (G = 300 at 30 fps is 100 s) is capped at max(15, 3 * Td) = 15 s.
1610 assert_eq!(
1611 15,
1612 cb_interval(300, secs(1.0 / 30.0), secs(0.1), secs(1.0), secs(5.0))
1613 );
1614 // Reports every 5 s: 3 * Tdr = 15 s, 3 reports.
1615 assert_eq!(
1616 3,
1617 cb_interval(1, secs(0.033), secs(0.1), secs(5.0), secs(5.0))
1618 );
1619 }
1620
1621 /// The boundary values of MEDIA_TIMEOUT = ceil(k * max(Tf, Tr, Tdr) / Tdr): a ratio that is
1622 /// a whole number is that number, the least bit more is one more report; each of the
1623 /// three intervals takes over at the instant it becomes the longest.
1624 #[test]
1625 fn media_timeout_at_its_boundaries() {
1626 // Tr exactly Tdr: k. A millisecond longer: ceil(5 * 0.026 / 0.025) = 6.
1627 assert_eq!(5, media_timeout(5, secs(0.02), secs(0.025), secs(0.025)));
1628 assert_eq!(6, media_timeout(5, secs(0.02), secs(0.026), secs(0.025)));
1629 // Tf exactly twice Tdr: 10. Tf just past it: 11.
1630 assert_eq!(10, media_timeout(5, secs(0.05), secs(0.0), secs(0.025)));
1631 assert_eq!(11, media_timeout(5, secs(0.0501), secs(0.0), secs(0.025)));
1632 // A queue that makes the round trip 300 ms against reports every 25 ms: 60 reports.
1633 assert_eq!(60, media_timeout(5, secs(0.02), secs(0.3), secs(0.025)));
1634 // k = 1 with everything shorter than Tdr: one report.
1635 assert_eq!(1, media_timeout(1, secs(0.0), secs(0.0), secs(5.0)));
1636 }
1637
1638 /// The boundary values of CB_INTERVAL: where each term of the inner max takes over, and
1639 /// the cap max(15, 3 * Td).
1640 #[test]
1641 fn cb_interval_at_its_boundaries() {
1642 // 10 * Tr exactly 3 * Tdr (0.3 s, 1 s): 3 reports. Tr a little longer: 4.
1643 assert_eq!(
1644 3,
1645 cb_interval(1, secs(0.02), secs(0.3), secs(1.0), secs(5.0))
1646 );
1647 assert_eq!(
1648 4,
1649 cb_interval(1, secs(0.02), secs(0.31), secs(1.0), secs(5.0))
1650 );
1651 // 10 * G * Tf takes over from 10 * Tr: G = 30 frames of 33 ms is 10 s, 10 reports.
1652 assert_eq!(
1653 10,
1654 cb_interval(30, secs(1.0 / 30.0), secs(0.1), secs(1.0), secs(5.0))
1655 );
1656 // The cap: 10 * Tr = 20 s is held to max(15, 3 * 5) = 15 s; with Td = 6 s to 18 s.
1657 assert_eq!(
1658 15,
1659 cb_interval(1, secs(0.02), secs(2.0), secs(1.0), secs(5.0))
1660 );
1661 assert_eq!(
1662 18,
1663 cb_interval(1, secs(0.02), secs(2.0), secs(1.0), secs(6.0))
1664 );
1665 // Reports every 25 ms and a 142 ms round trip: ceil(1.42 / 0.025) = 57 reports.
1666 assert_eq!(
1667 57,
1668 cb_interval(1, secs(0.02), secs(0.142), secs(0.025), secs(5.0))
1669 );
1670 }
1671
1672 /// The sending rate "now": over the newest samples that cover the span, one at least.
1673 #[test]
1674 fn the_recent_rate_is_that_of_the_newest_samples_covering_the_span() {
1675 let sample = |milliseconds: u64, bytes: u64| LossSample {
1676 fraction_lost: 0.0,
1677 duration: Duration::from_millis(milliseconds),
1678 bytes_sent: bytes,
1679 packets_sent: 1,
1680 net_lost: 0,
1681 net_expected: 1,
1682 };
1683 let samples: VecDeque<LossSample> =
1684 [sample(100, 50_000), sample(100, 10_000), sample(100, 2_000)].into();
1685 // A span shorter than the newest sample: that sample, 2000 bytes in 0.1 s.
1686 assert!((recent_rate(&samples, secs(0.05)) - 20_000.0).abs() < 1e-6);
1687 // Exactly one sample long: still that one. A little more: two (12000 in 0.2 s).
1688 assert!((recent_rate(&samples, secs(0.1)) - 20_000.0).abs() < 1e-6);
1689 assert!((recent_rate(&samples, secs(0.101)) - 60_000.0).abs() < 1e-6);
1690 // Longer than everything held: all of it.
1691 assert!((recent_rate(&samples, secs(5.0)) - 62_000.0 / 0.3).abs() < 1e-6);
1692 assert_eq!(0.0, recent_rate(&VecDeque::new(), secs(1.0)));
1693 }
1694
1695 /// RFC 3550 A.1 sequence number order, across the wrap.
1696 #[test]
1697 fn sequence_numbers_are_ordered_across_the_wrap() {
1698 assert!(is_newer(2, 1));
1699 assert!(!is_newer(1, 2));
1700 assert!(!is_newer(7, 7));
1701 assert!(is_newer(3, 65_530));
1702 assert!(!is_newer(65_530, 3));
1703 }
1704
1705 /// RFC 8083 section 4.3: X = s / (Tr * sqrt(2*b*p/3)), b = 1.
1706 #[test]
1707 fn the_simplified_tcp_equation_matches_the_rfc() {
1708 // s = 1200 bytes, Tr = 100 ms, p = 0.06: sqrt(0.04) = 0.2, so 1200 / 0.02.
1709 let x = tcp_throughput(1200.0, secs(0.1), 0.06, false);
1710 assert!((x - 60_000.0).abs() < 1e-6, "{x}");
1711 }
1712
1713 /// RFC 8083 section 4.3 with t_RTO = 4 * Tr (section 3): the full equation is the more
1714 /// sensitive one, so it gives the lower throughput.
1715 #[test]
1716 fn the_full_tcp_equation_matches_the_rfc() {
1717 let p: f64 = 0.06;
1718 let tr: f64 = 0.1;
1719 let expected = 1200.0
1720 / (tr * (2.0 * p / 3.0).sqrt()
1721 + 4.0 * tr * (3.0 * (3.0 * p / 8.0).sqrt() * p * (1.0 + 32.0 * p * p)));
1722 let x = tcp_throughput(1200.0, secs(tr), p, true);
1723 assert!((x - expected).abs() < 1e-6, "{x} against {expected}");
1724 assert!(x < tcp_throughput(1200.0, secs(tr), p, false));
1725 }
1726}