Skip to main content

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. It is not
20//! restarted automatically; the application restarts it through [`CircuitBreakerHandle`], and not
21//! before the interval that tripped it has passed again.
22
23use crate::Interceptor;
24use crate::never_sent::NeverSent;
25use crate::stream_info::StreamInfo;
26use crate::twcc::flow_ssrcs;
27use crate::{Packet, TaggedPacket};
28use sansio::Protocol;
29use shared::error::Error;
30use shared::marshal::MarshalSize;
31use std::collections::{HashMap, VecDeque};
32use std::sync::{Arc, Mutex, MutexGuard};
33use std::time::{Duration, Instant};
34
35/// The fixed minimum RTCP interval the RTCP timeout is computed with (Tmin, RFC 8083
36/// section 4.1).
37pub const DEFAULT_RTCP_INTERVAL: Duration = Duration::from_secs(5);
38
39/// The non-reporting threshold k: the RECOMMENDED value (RFC 8083 section 4.2).
40pub const DEFAULT_NON_REPORTING_THRESHOLD: u32 = 5;
41
42/// How many reporting intervals without RTCP trip the RTCP timeout breaker.
43const RTCP_TIMEOUT_INTERVALS: u32 = 3;
44
45/// How far back frame intervals are looked at for Tf ("the largest inter-frame interval used in
46/// the last 10 seconds", RFC 8083 section 3).
47const FRAME_INTERVAL_WINDOW: Duration = Duration::from_secs(10);
48
49/// How many sender reports are remembered to turn a report block's LSR into a send instant.
50const REMEMBERED_SENDER_REPORTS: usize = 16;
51
52/// Which breaker stopped a flow.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum CircuitBreakerReason {
56    /// No RTCP reported on the media being sent for three reporting intervals (section 4.1).
57    RtcpTimeout,
58    /// The receiver's reports showed the media not arriving (section 4.2).
59    MediaTimeout,
60    /// The flow sent more than ten times what TCP would have achieved (section 4.3).
61    Congestion,
62    /// Loss or delay stayed past the application's usability bound (section 4.4).
63    MediaUnusable,
64}
65
66/// What the circuit breaker is doing with one flow.
67#[derive(Debug, Clone, Copy, PartialEq)]
68#[non_exhaustive]
69pub enum CircuitBreakerState {
70    /// Sending normally.
71    Running,
72    /// The congestion breaker tripped once and the flow was given the chance to send at a tenth
73    /// of its rate (section 4.3). If the breaker trips again after the next `CB_INTERVAL`
74    /// reports, the flow ceases.
75    Reduced {
76        /// The rate the flow has to stay under, in bits per second.
77        limit_bits_per_second: f64,
78    },
79    /// Transmission has ceased (section 4.5): the flow's RTP is dropped.
80    Ceased {
81        /// The breaker that tripped.
82        reason: CircuitBreakerReason,
83        /// When it tripped.
84        at: Instant,
85        /// The earliest instant a restart is accepted.
86        restart_after: Instant,
87    },
88}
89
90/// How the congestion breaker takes s, the packet size of the TCP throughput equation (RFC
91/// 8083 section 4.3).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
93#[non_exhaustive]
94pub enum PacketSize {
95    /// The mean size of the RTP packets sent over the reporting intervals the sending rate is
96    /// measured over: s = (bytes sent) / (packets sent) over the last CB_INTERVAL intervals.
97    /// The default: s and the rate it is compared with describe the same packets.
98    #[default]
99    SendingWindow,
100    /// Section 3's definition as written: the mean size of the packets of the last 4 * G
101    /// frames. For speech with silence frames between talkspurts s is then the silence
102    /// frames' size (23 bytes) while the rate is that of the talkspurts, and a call over a
103    /// link with 1 to 5 % loss is ceased.
104    LastFrames,
105}
106
107/// The application's bound on what is still usable media (section 4.4). The RFC leaves the
108/// bound to the application on purpose.
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct MediaUsability {
111    /// Reported loss fraction (0.0 to 1.0) above which the media is unusable.
112    pub max_loss: f64,
113    /// Round trip time above which the media is unusable.
114    pub max_round_trip_time: Duration,
115    /// How long it has to stay unusable before transmission ceases.
116    pub period: Duration,
117}
118
119#[derive(Debug, Clone, Copy)]
120struct Config {
121    rtcp_interval: Duration,
122    t_rr_interval: Option<Duration>,
123    non_reporting_threshold: u32,
124    frame_group_size: u32,
125    full_tcp_equation: bool,
126    packet_size: PacketSize,
127    reduce_before_ceasing: bool,
128    group: bool,
129    usability: Option<MediaUsability>,
130}
131
132/// Builder for [`CircuitBreakerInterceptor`].
133///
134/// # Example
135///
136/// ```
137/// use rtci_interceptor::{CircuitBreakerBuilder, Registry, Slot};
138///
139/// let (breaker, handle) = CircuitBreakerBuilder::new().build();
140/// let chain = Registry::new().with(Slot::CircuitBreaker, breaker).build();
141/// assert!(handle.ceased().is_empty());
142/// # let _ = chain;
143/// ```
144pub struct CircuitBreakerBuilder {
145    config: Config,
146}
147
148impl Default for CircuitBreakerBuilder {
149    fn default() -> Self {
150        Self {
151            config: Config {
152                rtcp_interval: DEFAULT_RTCP_INTERVAL,
153                t_rr_interval: None,
154                non_reporting_threshold: DEFAULT_NON_REPORTING_THRESHOLD,
155                frame_group_size: 1,
156                full_tcp_equation: false,
157                packet_size: PacketSize::SendingWindow,
158                reduce_before_ceasing: false,
159                group: false,
160                usability: None,
161            },
162        }
163    }
164}
165
166impl CircuitBreakerBuilder {
167    /// A builder with the RFC's recommended values.
168    pub fn new() -> Self {
169        Self::default()
170    }
171
172    /// Td, this endpoint's deterministic RTCP reporting interval, computed with Tmin = 5 s
173    /// (section 4.1). The RTCP timeout breaker trips after three of them. Values above 5 s are
174    /// held to 5 s: the RFC says not to configure a longer one.
175    pub fn with_rtcp_interval(mut self, interval: Duration) -> Self {
176        self.config.rtcp_interval = interval.min(DEFAULT_RTCP_INTERVAL);
177        self
178    }
179
180    /// The AVPF `T_rr_interval` in use, which replaces Tdr in `CB_INTERVAL` when it is larger
181    /// (section 4.3). Held to 4 s (sections 4.1 and 4.3).
182    pub fn with_t_rr_interval(mut self, interval: Duration) -> Self {
183        self.config.t_rr_interval = Some(interval.min(Duration::from_secs(4)));
184        self
185    }
186
187    /// k, the number of reports without progress that gives assurance the forward path failed
188    /// (section 4.2). 5 is recommended.
189    pub fn with_non_reporting_threshold(mut self, k: u32) -> Self {
190        self.config.non_reporting_threshold = k.max(1);
191        self
192    }
193
194    /// G, the number of frames the codec needs before it can change rate (section 3). 1 for a
195    /// codec that can adapt on every frame.
196    pub fn with_frame_group_size(mut self, frames: u32) -> Self {
197        self.config.frame_group_size = frames.max(1);
198        self
199    }
200
201    /// Use the full TCP throughput equation instead of the simplified one (section 4.3: MAY; it
202    /// is more sensitive to loss and trips earlier).
203    pub fn with_full_tcp_equation(mut self, full: bool) -> Self {
204        self.config.full_tcp_equation = full;
205        self
206    }
207
208    /// How s, the packet size of the TCP throughput equation, is taken (section 4.3).
209    /// [`PacketSize::SendingWindow`] by default; [`PacketSize::LastFrames`] is section 3's
210    /// "last 4 * G frames".
211    pub fn with_packet_size(mut self, packet_size: PacketSize) -> Self {
212        self.config.packet_size = packet_size;
213        self
214    }
215
216    /// When the congestion breaker trips, first ask for a tenth of the rate
217    /// ([`CircuitBreakerState::Reduced`]) instead of ceasing at once (section 4.3: MAY). If it
218    /// trips again after the next `CB_INTERVAL` reports the flow ceases.
219    pub fn with_rate_reduction(mut self, reduce: bool) -> Self {
220        self.config.reduce_before_ceasing = reduce;
221        self
222    }
223
224    /// Treat every flow of the connection as one group: a breaker tripping for one flow applies
225    /// to all (section 8: MAY). By default each SSRC is judged on its own.
226    pub fn with_grouped_flows(mut self, group: bool) -> Self {
227        self.config.group = group;
228        self
229    }
230
231    /// The bound past which the media is unusable (section 4.4). Without one the media
232    /// usability breaker does not run: the RFC defines no bound.
233    pub fn with_media_usability(mut self, usability: MediaUsability) -> Self {
234        self.config.usability = Some(usability);
235        self
236    }
237
238    /// Build the interceptor and the handle the application watches it through.
239    pub fn build(self) -> (CircuitBreakerInterceptor, CircuitBreakerHandle) {
240        let handle = CircuitBreakerHandle::new();
241        (self.build_with_handle(&handle), handle)
242    }
243
244    /// Build the interceptor `handle` watches (made beforehand, for example to give it to the
245    /// congestion controller of the same transport). One interceptor per handle.
246    pub fn build_with_handle(self, handle: &CircuitBreakerHandle) -> CircuitBreakerInterceptor {
247        CircuitBreakerInterceptor {
248            config: self.config,
249            flows: HashMap::new(),
250            awaiting_rtcp_since: None,
251            shared: handle.shared.clone(),
252            read_queue: VecDeque::new(),
253            write_queue: VecDeque::new(),
254        }
255    }
256}
257
258#[derive(Default)]
259struct Shared {
260    states: HashMap<u32, CircuitBreakerState>,
261    restarts: Vec<u32>,
262    dropped: u64,
263    /// A round trip time measured elsewhere in the chain.
264    round_trip_time: Option<Duration>,
265}
266
267fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
268    shared
269        .lock()
270        .unwrap_or_else(|poisoned| poisoned.into_inner())
271}
272
273/// The application's view of the circuit breaker, and the only way a ceased flow restarts.
274#[derive(Clone)]
275pub struct CircuitBreakerHandle {
276    shared: Arc<Mutex<Shared>>,
277}
278
279impl Default for CircuitBreakerHandle {
280    fn default() -> Self {
281        Self::new()
282    }
283}
284
285impl CircuitBreakerHandle {
286    /// A handle with no interceptor yet: [`CircuitBreakerBuilder::build_with_handle`] builds
287    /// the one it watches.
288    pub fn new() -> Self {
289        Self {
290            shared: Arc::new(Mutex::new(Shared::default())),
291        }
292    }
293
294    /// What the breaker is doing with the flow sent on `ssrc`, if it is bound.
295    pub fn state(&self, ssrc: u32) -> Option<CircuitBreakerState> {
296        lock(&self.shared).states.get(&ssrc).copied()
297    }
298
299    /// The flows that have ceased transmission, with the breaker that stopped each.
300    pub fn ceased(&self) -> Vec<(u32, CircuitBreakerReason)> {
301        let mut ceased: Vec<_> = lock(&self.shared)
302            .states
303            .iter()
304            .filter_map(|(ssrc, state)| match state {
305                CircuitBreakerState::Ceased { reason, .. } => Some((*ssrc, *reason)),
306                _ => None,
307            })
308            .collect();
309        ceased.sort_unstable_by_key(|(ssrc, _)| *ssrc);
310        ceased
311    }
312
313    /// The lowest rate any flow has been asked to stay under after the congestion breaker
314    /// tripped, in bits per second. A congestion controller takes it as an upper bound.
315    pub fn rate_limit(&self) -> Option<f64> {
316        lock(&self.shared)
317            .states
318            .values()
319            .filter_map(|state| match state {
320                CircuitBreakerState::Reduced {
321                    limit_bits_per_second,
322                } => Some(*limit_bits_per_second),
323                _ => None,
324            })
325            .reduce(f64::min)
326    }
327
328    /// A round trip time measured from congestion-control feedback, for the breaker to use
329    /// when it cannot measure one itself.
330    ///
331    /// Tr is the RFC 3550 round trip time: a report block's LSR and DLSR against the instant
332    /// the named sender report left. The breaker only knows that instant for sender reports
333    /// that pass it on the way out; when the RTCP session sits wire-ward of it (as the standard
334    /// set places it) none does, and without Tr the congestion breaker could never compare the
335    /// flow with TCP. The congestion controller's feedback gives the same quantity many times
336    /// a second.
337    pub fn report_round_trip_time(&self, round_trip_time: Duration) {
338        lock(&self.shared).round_trip_time = Some(round_trip_time);
339    }
340
341    /// How many RTP packets of ceased flows were dropped.
342    pub fn dropped(&self) -> u64 {
343        lock(&self.shared).dropped
344    }
345
346    /// Restart a ceased flow. Returns whether it restarted.
347    ///
348    /// A flow is not restarted automatically (section 4.5): this is the application saying the
349    /// congestion can be expected to have gone. It is refused until the interval that tripped
350    /// the breaker has passed again, so the reaction to a tripped breaker lasts at least that
351    /// long however often a restart is attempted.
352    pub fn restart(&self, ssrc: u32, now: Instant) -> bool {
353        let mut shared = lock(&self.shared);
354        match shared.states.get(&ssrc) {
355            Some(CircuitBreakerState::Ceased { restart_after, .. }) if now >= *restart_after => {
356                shared.states.insert(ssrc, CircuitBreakerState::Running);
357                shared.restarts.push(ssrc);
358                true
359            }
360            _ => false,
361        }
362    }
363}
364
365/// One reporting interval as the congestion breaker records it.
366#[derive(Debug, Clone, Copy)]
367struct LossSample {
368    fraction_lost: f64,
369    duration: Duration,
370    bytes_sent: u64,
371    packets_sent: u64,
372    /// What the report's cumulative number lost and extended highest sequence number moved
373    /// by since the previous report (RFC 3550 6.4.1): the interval's net loss, in which a
374    /// packet that was only reordered counts in neither interval.
375    net_lost: i64,
376    net_expected: i64,
377}
378
379/// One frame's worth of packets, for the average packet size.
380#[derive(Debug, Clone, Copy, Default)]
381struct FrameSize {
382    bytes: u64,
383    packets: u64,
384}
385
386struct Flow {
387    state: CircuitBreakerState,
388    /// Packets and bytes sent since the last report block for this flow.
389    packets_since_report: u64,
390    bytes_since_report: u64,
391    /// The RTP timestamp of the frame being sent and when its first packet left.
392    current_frame: Option<(u32, Instant)>,
393    /// Inter-frame intervals of the last ten seconds, with the instant each ended.
394    frame_intervals: VecDeque<(Instant, Duration)>,
395    /// Sizes of the last `4 * G` frames, newest last.
396    frames: VecDeque<FrameSize>,
397    /// When the last report block for this flow arrived.
398    last_report_at: Option<Instant>,
399    /// When the flow's last packet left.
400    last_departure: Option<Instant>,
401    /// Smoothed interval between the receiver's reports: the estimate of Tdr.
402    receiver_interval: Option<Duration>,
403    /// The extended highest sequence number the receiver last reported.
404    highest_sequence: Option<u32>,
405    /// The previous report's cumulative number lost and extended highest sequence number,
406    /// as reported (for the net loss of the next interval).
407    previous_report: Option<(i32, u32)>,
408    /// The sequence numbers the flow jumped over on its way out: the packets the pacer
409    /// discarded, which the receiver counts as lost.
410    never_sent: NeverSent,
411    /// Consecutive reports that showed no progress while media was being sent.
412    stalled_reports: u32,
413    media_timeout: u32,
414    losses: VecDeque<LossSample>,
415    reports_received: u64,
416    /// Report blocks since the rate was reduced.
417    reports_since_reduction: u64,
418    /// Smoothed round trip time, Tr.
419    round_trip_time: Option<Duration>,
420    /// Sender reports sent for this flow: the middle 32 bits of the NTP timestamp, and when.
421    sender_reports: VecDeque<(u32, Instant)>,
422    unusable_since: Option<Instant>,
423}
424
425impl Flow {
426    fn new() -> Self {
427        Self {
428            state: CircuitBreakerState::Running,
429            packets_since_report: 0,
430            bytes_since_report: 0,
431            current_frame: None,
432            frame_intervals: VecDeque::new(),
433            frames: VecDeque::new(),
434            last_report_at: None,
435            last_departure: None,
436            receiver_interval: None,
437            highest_sequence: None,
438            previous_report: None,
439            never_sent: NeverSent::default(),
440            stalled_reports: 0,
441            media_timeout: 0,
442            losses: VecDeque::new(),
443            reports_received: 0,
444            reports_since_reduction: 0,
445            round_trip_time: None,
446            sender_reports: VecDeque::new(),
447            unusable_since: None,
448        }
449    }
450
451    fn is_ceased(&self) -> bool {
452        matches!(self.state, CircuitBreakerState::Ceased { .. })
453    }
454
455    /// Tf: the largest inter-frame interval of the last ten seconds.
456    fn frame_interval(&self) -> Duration {
457        self.frame_intervals
458            .iter()
459            .map(|(_, interval)| *interval)
460            .max()
461            .unwrap_or_default()
462    }
463
464    /// s: the average size of the packets of the last `4 * G` frames, in bytes.
465    fn packet_size(&self) -> Option<f64> {
466        let (bytes, packets) = self
467            .frames
468            .iter()
469            .fold((0u64, 0u64), |(bytes, packets), frame| {
470                (bytes + frame.bytes, packets + frame.packets)
471            });
472        (packets > 0).then(|| bytes as f64 / packets as f64)
473    }
474
475    fn on_departure(
476        &mut self,
477        now: Instant,
478        sequence_number: u16,
479        timestamp: u32,
480        size: usize,
481        frames_kept: usize,
482    ) {
483        self.last_departure = Some(now);
484        self.never_sent.on_sent(sequence_number);
485        self.packets_since_report += 1;
486        self.bytes_since_report += size as u64;
487
488        match self.current_frame {
489            Some((current, _)) if current == timestamp => {}
490            previous => {
491                if let Some((_, started)) = previous {
492                    self.frame_intervals
493                        .push_back((now, now.saturating_duration_since(started)));
494                }
495                self.current_frame = Some((timestamp, now));
496                self.frames.push_back(FrameSize::default());
497                while self.frames.len() > frames_kept {
498                    self.frames.pop_front();
499                }
500            }
501        }
502        while let Some((at, _)) = self.frame_intervals.front() {
503            if now.saturating_duration_since(*at) <= FRAME_INTERVAL_WINDOW {
504                break;
505            }
506            self.frame_intervals.pop_front();
507        }
508        if let Some(frame) = self.frames.back_mut() {
509            frame.bytes += size as u64;
510            frame.packets += 1;
511        }
512    }
513}
514
515/// The RTP circuit breaker of RFC 8083: stops a flow whose receiver has gone, whose media is
516/// not arriving, or that is persistently taking far more than its share.
517///
518/// # Where this belongs in the chain
519///
520/// [`Slot::CircuitBreaker`](crate::Slot::CircuitBreaker): below the pacer, so it sees every RTP
521/// packet when it is released, generated ones included; above the TWCC sender and the send
522/// history, so a packet it drops is never numbered or recorded as sent.
523pub struct CircuitBreakerInterceptor {
524    config: Config,
525    flows: HashMap<u32, Flow>,
526    /// When media was first sent since RTCP last reported on it: what the RTCP timeout runs
527    /// from. `None` while nothing sent is waiting to be reported on.
528    awaiting_rtcp_since: Option<Instant>,
529    shared: Arc<Mutex<Shared>>,
530    read_queue: VecDeque<TaggedPacket>,
531    write_queue: VecDeque<TaggedPacket>,
532}
533
534/// MEDIA_TIMEOUT = ceil(k * max(Tf, Tr, Tdr) / Tdr) (RFC 8083 section 4.2).
535fn media_timeout(k: u32, tf: Duration, tr: Duration, tdr: Duration) -> u32 {
536    let tdr = tdr.as_secs_f64().max(1e-3);
537    let longest = tf.as_secs_f64().max(tr.as_secs_f64()).max(tdr);
538    // The small allowance keeps a ratio that is a whole number in exact arithmetic from
539    // being rounded up by its floating-point error.
540    (f64::from(k) * longest / tdr - 1e-9).ceil().max(1.0) as u32
541}
542
543/// CB_INTERVAL = ceil(3 * min(max(10*G*Tf, 10*Tr, 3*Tdr), max(15, 3*Td)) / (3*Tdr))
544/// (RFC 8083 section 4.3).
545fn cb_interval(g: u32, tf: Duration, tr: Duration, tdr: Duration, td: Duration) -> u32 {
546    let tdr = tdr.as_secs_f64().max(1e-3);
547    let reaction = (10.0 * f64::from(g) * tf.as_secs_f64())
548        .max(10.0 * tr.as_secs_f64())
549        .max(3.0 * tdr);
550    let cap = 15f64.max(3.0 * td.as_secs_f64());
551    ((3.0 * reaction.min(cap)) / (3.0 * tdr) - 1e-9)
552        .ceil()
553        .max(1.0) as u32
554}
555
556/// s over the reporting intervals the sending rate is measured over: the bytes sent in them
557/// divided by the packets sent in them, `None` when none were sent.
558fn window_packet_size(samples: &VecDeque<LossSample>) -> Option<f64> {
559    let (bytes, packets) = samples
560        .iter()
561        .fold((0u64, 0u64), |(bytes, packets), sample| {
562            (bytes + sample.bytes_sent, packets + sample.packets_sent)
563        });
564    (packets > 0).then(|| bytes as f64 / packets as f64)
565}
566
567/// The share of the packets expected over `samples` that the cumulative count says were lost
568/// (RFC 3550 6.4.1: expected less received, late packets counted as received), `None` when
569/// the window expected none.
570///
571/// The fraction lost of each report cannot be negative (RFC 3550 A.3), so a packet that is
572/// only reordered across a report's boundary counts as lost in the interval that should have
573/// had it and is not given back in the next: on a path that reorders, the average of the
574/// fractions shows loss that never happened. RFC 8083 section 4.3 approximates the loss event
575/// rate by that average, a figure meant to err on the side of more loss; it cannot be more
576/// than the share actually lost, so the breaker takes the smaller of the two.
577///
578/// The newest report's own count is taken only where it gives packets back: a packet missing
579/// at that report may still be on its way (overtaken a moment before the report went), and
580/// the next report says whether it was lost. A packet really lost counts from then on, one
581/// reporting interval later.
582fn net_loss(samples: &VecDeque<LossSample>) -> Option<f64> {
583    let newest = samples.len().saturating_sub(1);
584    let (lost, expected) =
585        samples
586            .iter()
587            .enumerate()
588            .fold((0i64, 0i64), |(lost, expected), (index, sample)| {
589                let net_lost = if index == newest {
590                    sample.net_lost.min(0)
591                } else {
592                    sample.net_lost
593                };
594                (lost + net_lost, expected + sample.net_expected)
595            });
596    (expected > 0).then(|| lost.max(0) as f64 / expected as f64)
597}
598
599/// The throughput, in bytes per second, a TCP connection would achieve with packets of `s`
600/// bytes, round trip time `tr` and loss event rate `p` (RFC 8083 section 4.3), with b = 1 and
601/// t_RTO = 4 * Tr.
602fn tcp_throughput(s: f64, tr: Duration, p: f64, full: bool) -> f64 {
603    let tr = tr.as_secs_f64().max(1e-6);
604    let b = 1.0;
605    let simplified = tr * (2.0 * b * p / 3.0).sqrt();
606    let denominator = if full {
607        let t_rto = 4.0 * tr;
608        simplified + t_rto * (3.0 * (3.0 * b * p / 8.0).sqrt() * p * (1.0 + 32.0 * p * p))
609    } else {
610        simplified
611    };
612    s / denominator
613}
614
615impl CircuitBreakerInterceptor {
616    fn publish(&self, ssrc: u32) {
617        if let Some(flow) = self.flows.get(&ssrc) {
618            lock(&self.shared).states.insert(ssrc, flow.state);
619        }
620    }
621
622    /// Apply the restarts the application asked for through the handle.
623    fn apply_restarts(&mut self) {
624        let restarts = std::mem::take(&mut lock(&self.shared).restarts);
625        for ssrc in restarts {
626            if self.flows.contains_key(&ssrc) {
627                // A restarted flow starts from nothing: what was measured before describes
628                // the path that tripped the breaker.
629                self.flows.insert(ssrc, Flow::new());
630            }
631        }
632    }
633
634    /// Cease transmission of `ssrc`, or of every flow when flows are grouped.
635    fn cease(&mut self, ssrc: u32, reason: CircuitBreakerReason, now: Instant, hold: Duration) {
636        let ssrcs: Vec<u32> = if self.config.group {
637            self.flows.keys().copied().collect()
638        } else {
639            vec![ssrc]
640        };
641        for ssrc in ssrcs {
642            if let Some(flow) = self.flows.get_mut(&ssrc)
643                && !flow.is_ceased()
644            {
645                flow.state = CircuitBreakerState::Ceased {
646                    reason,
647                    at: now,
648                    restart_after: now + hold,
649                };
650                // Stopping a stream cancels its media timeout breaker (section 4.2).
651                flow.stalled_reports = 0;
652                log::warn!("RTP circuit breaker: SSRC {ssrc:#x} ceased transmission ({reason:?})");
653                self.publish(ssrc);
654            }
655        }
656    }
657
658    fn rtcp_timeout(&self) -> Duration {
659        self.config.rtcp_interval * RTCP_TIMEOUT_INTERVALS
660    }
661
662    /// One report block about a flow this endpoint sends.
663    fn on_report_block(&mut self, now: Instant, report: &rtcp::reception_report::ReceptionReport) {
664        let config = self.config;
665        let Some(flow) = self.flows.get_mut(&report.ssrc) else {
666            return;
667        };
668        if flow.is_ceased() {
669            return;
670        }
671
672        // Tr: RFC 3550 section 6.4.1, smoothed as RFC 8083 section 3 says.
673        if report.last_sender_report != 0
674            && let Some((_, sent)) = flow
675                .sender_reports
676                .iter()
677                .rev()
678                .find(|(lsr, _)| *lsr == report.last_sender_report)
679        {
680            let delay = Duration::from_secs_f64(f64::from(report.delay) / 65_536.0);
681            let sample = now.saturating_duration_since(*sent).saturating_sub(delay);
682            flow.round_trip_time = Some(match flow.round_trip_time {
683                Some(previous) => previous.mul_f64(0.8) + sample.mul_f64(0.2),
684                None => sample,
685            });
686        }
687
688        // No sender report of this flow was seen leaving (the report generator is wire-ward of
689        // here): Tr is the round trip time the congestion controller measured.
690        if flow.sender_reports.is_empty()
691            && let Some(reported) = lock(&self.shared).round_trip_time
692        {
693            flow.round_trip_time = Some(match flow.round_trip_time {
694                Some(previous) => previous.mul_f64(0.8) + reported.mul_f64(0.2),
695                None => reported,
696            });
697        }
698
699        // Tdr, from how often this receiver actually reports.
700        let since_last = flow
701            .last_report_at
702            .map(|last| now.saturating_duration_since(last));
703        if let Some(interval) = since_last {
704            flow.receiver_interval = Some(match flow.receiver_interval {
705                Some(previous) => previous.mul_f64(0.8) + interval.mul_f64(0.2),
706                None => interval,
707            });
708        }
709        flow.last_report_at = Some(now);
710        flow.reports_received += 1;
711
712        let tf = flow.frame_interval();
713        let tr = flow.round_trip_time.unwrap_or_default();
714        let tdr = flow.receiver_interval.unwrap_or(config.rtcp_interval);
715        let sent_packets = std::mem::take(&mut flow.packets_since_report);
716        let sent_bytes = std::mem::take(&mut flow.bytes_since_report);
717        log::debug!(
718            "circuit breaker: report on {:#x}: fraction lost {}/256, cumulative lost {}, \
719             extended highest {}, jitter {}, LSR {:#x}, DLSR {}; Tr {:?} (shared {:?}), Tdr {:?}, \
720             Tf {:?}, sent since last {} packets / {} bytes, report {}",
721            report.ssrc,
722            report.fraction_lost,
723            report.total_lost,
724            report.last_sequence_number,
725            report.jitter,
726            report.last_sender_report,
727            report.delay,
728            flow.round_trip_time,
729            lock(&self.shared).round_trip_time,
730            tdr,
731            tf,
732            sent_packets,
733            sent_bytes,
734            flow.reports_received,
735        );
736
737        // --- Media timeout (section 4.2) ---
738        let timeout = media_timeout(config.non_reporting_threshold, tf, tr, tdr);
739        let progressed = match flow.highest_sequence {
740            Some(previous) => report.last_sequence_number > previous,
741            None => true,
742        };
743        flow.highest_sequence = Some(
744            flow.highest_sequence
745                .map_or(report.last_sequence_number, |previous| {
746                    previous.max(report.last_sequence_number)
747                }),
748        );
749        let mut trip: Option<(CircuitBreakerReason, Duration)> = None;
750        if progressed {
751            // The media is arriving: the breaker is cancelled and set anew.
752            flow.stalled_reports = 0;
753            flow.media_timeout = timeout;
754        } else if sent_packets > 0 || flow.stalled_reports > 0 {
755            // Media was sent and the receiver did not see it. Reconsider: the timeout only
756            // ever extends.
757            flow.media_timeout = flow.media_timeout.max(timeout);
758            flow.stalled_reports += 1;
759            log::debug!(
760                "circuit breaker: {:#x}: no progress, {} of MEDIA_TIMEOUT {}",
761                report.ssrc,
762                flow.stalled_reports,
763                flow.media_timeout
764            );
765            if flow.stalled_reports >= flow.media_timeout {
766                trip = Some((CircuitBreakerReason::MediaTimeout, tdr * flow.media_timeout));
767            }
768        }
769
770        // The interval's net loss by the cumulative count (RFC 3550 6.4.1, A.3).
771        let cumulative = report.cumulative_lost();
772        // The receiver counts every sequence number it did not receive as lost, the ones the
773        // pacer discarded before they left included. Those are not the path's loss: over the
774        // interval the report covers they come out of the count, and out of the packets
775        // expected, and the fraction lost is that of the packets that left.
776        let interval = flow
777            .never_sent
778            .on_report(report.last_sequence_number, cumulative)
779            .filter(|interval| interval.never_sent() > 0);
780        let never_sent = interval.map_or(0, |interval| interval.never_sent());
781        let (net_lost, net_expected) = match flow
782            .previous_report
783            .replace((cumulative, report.last_sequence_number))
784        {
785            Some((previous_lost, previous_highest)) => (
786                i64::from(cumulative) - i64::from(previous_lost) - never_sent,
787                i64::from(report.last_sequence_number.wrapping_sub(previous_highest) as i32)
788                    - never_sent,
789            ),
790            None => (0, 0),
791        };
792        let fraction_lost = interval.map_or(f64::from(report.fraction_lost) / 256.0, |interval| {
793            interval.fraction_lost()
794        });
795
796        // --- Congestion (section 4.3) ---
797        let cb_tdr = config.t_rr_interval.map_or(tdr, |t_rr| t_rr.max(tdr));
798        let interval = cb_interval(
799            config.frame_group_size,
800            tf,
801            tr,
802            cb_tdr,
803            config.rtcp_interval,
804        );
805        if let Some(duration) = since_last {
806            // Only while at least one packet is sent every max(Tdr, Tr): with fewer, the
807            // fraction lost is a measurement artefact. That is the sender's rate, not every
808            // report's: reports closer together than max(Tdr, Tr) (AVPF with early feedback
809            // compounds: every 10 ms on a video flow) often see no packet of a flow that sends
810            // a frame every 20 ms, and clearing the samples on each such report kept the
811            // breaker from ever judging the flow. Over an interval shorter than the period, a
812            // packet sent within the last period is enough.
813            let period = tdr.max(tr).as_secs_f64().max(1e-3);
814            let enough = if duration.as_secs_f64() >= period {
815                sent_packets as f64 >= (duration.as_secs_f64() / period).floor()
816            } else {
817                flow.last_departure
818                    .is_some_and(|sent| now.saturating_duration_since(sent).as_secs_f64() <= period)
819            };
820            if enough {
821                flow.losses.push_back(LossSample {
822                    fraction_lost,
823                    duration,
824                    bytes_sent: sent_bytes,
825                    packets_sent: sent_packets,
826                    net_lost,
827                    net_expected,
828                });
829            } else {
830                flow.losses.clear();
831            }
832            while flow.losses.len() > interval as usize {
833                flow.losses.pop_front();
834            }
835        }
836        if matches!(flow.state, CircuitBreakerState::Reduced { .. }) {
837            flow.reports_since_reduction += 1;
838        }
839        let window: Duration = flow.losses.iter().map(|sample| sample.duration).sum();
840        if trip.is_none()
841            && flow.reports_received > u64::from(interval)
842            && flow.losses.len() >= interval as usize
843            && !window.is_zero()
844            && let Some(tr) = flow.round_trip_time
845            && let Some(packet_size) = match config.packet_size {
846                PacketSize::SendingWindow => window_packet_size(&flow.losses),
847                PacketSize::LastFrames => flow.packet_size(),
848            }
849        {
850            let average = flow
851                .losses
852                .iter()
853                .map(|sample| sample.fraction_lost * sample.duration.as_secs_f64())
854                .sum::<f64>()
855                / window.as_secs_f64();
856            let loss = average.min(net_loss(&flow.losses).unwrap_or(average));
857            let bytes: u64 = flow.losses.iter().map(|sample| sample.bytes_sent).sum();
858            let sending_rate = bytes as f64 / window.as_secs_f64();
859            log::debug!(
860                "circuit breaker: {:#x}: CB_INTERVAL {interval}, loss {loss:.4} over {window:?}, \
861                 sending {sending_rate:.0} B/s, s {packet_size:.0} B, Tr {tr:?}, TCP {:.0} B/s",
862                report.ssrc,
863                tcp_throughput(packet_size, tr, loss, config.full_tcp_equation),
864            );
865            if loss > 0.0
866                && sending_rate
867                    > 10.0 * tcp_throughput(packet_size, tr, loss, config.full_tcp_equation)
868            {
869                match flow.state {
870                    CircuitBreakerState::Running if config.reduce_before_ceasing => {
871                        flow.state = CircuitBreakerState::Reduced {
872                            limit_bits_per_second: sending_rate * 8.0 / 10.0,
873                        };
874                        flow.reports_since_reduction = 0;
875                        // The next verdict is on what is sent from here on.
876                        flow.losses.clear();
877                        flow.reports_received = 0;
878                    }
879                    _ => trip = Some((CircuitBreakerReason::Congestion, window)),
880                }
881            } else if matches!(flow.state, CircuitBreakerState::Reduced { .. })
882                && flow.reports_since_reduction >= u64::from(interval)
883            {
884                // The reduction resolved it.
885                flow.state = CircuitBreakerState::Running;
886            }
887        }
888
889        // --- Media usability (section 4.4) ---
890        if let Some(usability) = config.usability {
891            let unusable = fraction_lost > usability.max_loss
892                || flow
893                    .round_trip_time
894                    .is_some_and(|rtt| rtt > usability.max_round_trip_time);
895            if unusable {
896                let since = *flow.unusable_since.get_or_insert(now);
897                if trip.is_none() && now.saturating_duration_since(since) >= usability.period {
898                    trip = Some((CircuitBreakerReason::MediaUnusable, usability.period));
899                }
900            } else {
901                flow.unusable_since = None;
902            }
903        }
904
905        let ssrc = report.ssrc;
906        match trip {
907            Some((reason, hold)) => self.cease(ssrc, reason, now, hold),
908            None => self.publish(ssrc),
909        }
910    }
911
912    /// Inbound RTCP: the report blocks feed the breakers, and anything at all shows the
913    /// receiver and the return path are alive.
914    fn on_rtcp(&mut self, now: Instant, packets: &[Box<dyn rtcp::Packet>]) {
915        let mut reports = Vec::new();
916        let mut has_report_packet = false;
917        for packet in packets {
918            let any = packet.as_any();
919            if let Some(sr) = any.downcast_ref::<rtcp::sender_report::SenderReport>() {
920                has_report_packet = true;
921                reports.extend(sr.reports.iter().cloned());
922            } else if let Some(rr) = any.downcast_ref::<rtcp::receiver_report::ReceiverReport>() {
923                has_report_packet = true;
924                reports.extend(rr.reports.iter().cloned());
925            }
926        }
927
928        // RTCP timeout (section 4.1): a report on any SSRC this endpoint sends shows the
929        // receiver and the return path work. A reduced-size packet without SR or RR counts as
930        // received for this breaker too (section 5), and for this breaker only.
931        let reports_on_us = reports
932            .iter()
933            .any(|report| self.flows.contains_key(&report.ssrc));
934        if !packets.is_empty() && (!has_report_packet || reports_on_us) {
935            self.awaiting_rtcp_since = None;
936        }
937
938        for report in &reports {
939            self.on_report_block(now, report);
940        }
941    }
942}
943
944impl Protocol<TaggedPacket, TaggedPacket, ()> for CircuitBreakerInterceptor {
945    type Rout = TaggedPacket;
946    type Wout = TaggedPacket;
947    type Eout = ();
948    type Error = Error;
949    type Time = Instant;
950
951    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
952        self.apply_restarts();
953        if let Packet::Rtcp(packets) = &msg.message.packet {
954            let packets: Vec<_> = packets.to_vec();
955            self.on_rtcp(msg.now, &packets);
956        }
957        self.read_queue.push_back(msg);
958        Ok(())
959    }
960
961    fn poll_read(&mut self) -> Option<Self::Rout> {
962        self.read_queue.pop_front()
963    }
964
965    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
966        self.apply_restarts();
967        match &msg.message.packet {
968            Packet::Rtp(rtp_packet) => {
969                let frames_kept = 4 * self.config.frame_group_size as usize;
970                if let Some(flow) = self.flows.get_mut(&rtp_packet.header.ssrc) {
971                    if flow.is_ceased() {
972                        // Transmission has ceased (section 4.5): the packet does not leave.
973                        lock(&self.shared).dropped += 1;
974                        return Ok(());
975                    }
976                    flow.on_departure(
977                        msg.now,
978                        rtp_packet.header.sequence_number,
979                        rtp_packet.header.timestamp,
980                        rtp_packet.marshal_size(),
981                        frames_kept,
982                    );
983                    self.awaiting_rtcp_since.get_or_insert(msg.now);
984                }
985            }
986            Packet::Rtcp(packets) => {
987                // The sender reports this endpoint sends: a report block's LSR names one.
988                for packet in packets {
989                    if let Some(sr) = packet
990                        .as_any()
991                        .downcast_ref::<rtcp::sender_report::SenderReport>()
992                        && let Some(flow) = self.flows.get_mut(&sr.ssrc)
993                    {
994                        flow.sender_reports
995                            .push_back(((sr.ntp_time >> 16) as u32, msg.now));
996                        while flow.sender_reports.len() > REMEMBERED_SENDER_REPORTS {
997                            flow.sender_reports.pop_front();
998                        }
999                    }
1000                }
1001            }
1002        }
1003        self.write_queue.push_back(msg);
1004        Ok(())
1005    }
1006
1007    fn poll_write(&mut self) -> Option<Self::Wout> {
1008        self.write_queue.pop_front()
1009    }
1010
1011    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
1012        self.apply_restarts();
1013        if let Some(since) = self.awaiting_rtcp_since
1014            && now.saturating_duration_since(since) >= self.rtcp_timeout()
1015        {
1016            // Media has been sent for three reporting intervals and nothing reported on it:
1017            // there is no way to know whether it is causing congestion (section 4.1).
1018            self.awaiting_rtcp_since = None;
1019            let hold = self.rtcp_timeout();
1020            let ssrcs: Vec<u32> = self
1021                .flows
1022                .iter()
1023                .filter(|(_, flow)| !flow.is_ceased() && flow.current_frame.is_some())
1024                .map(|(ssrc, _)| *ssrc)
1025                .collect();
1026            for ssrc in ssrcs {
1027                self.cease(ssrc, CircuitBreakerReason::RtcpTimeout, now, hold);
1028            }
1029        }
1030        Ok(())
1031    }
1032
1033    /// The RTCP timeout's deadline while sent media is waiting to be reported on, `None`
1034    /// otherwise.
1035    fn poll_timeout(&mut self) -> Option<Self::Time> {
1036        self.awaiting_rtcp_since
1037            .map(|since| since + self.rtcp_timeout())
1038    }
1039}
1040
1041impl Interceptor for CircuitBreakerInterceptor {
1042    /// The media SSRC and its repair flows are each a flow on the transport.
1043    fn bind_local_stream(&mut self, info: &StreamInfo) {
1044        for ssrc in flow_ssrcs(info) {
1045            self.flows.entry(ssrc).or_insert_with(Flow::new);
1046            self.publish(ssrc);
1047        }
1048    }
1049
1050    /// Stopping a stream cancels its breakers (section 4.2).
1051    fn unbind_local_stream(&mut self, info: &StreamInfo) {
1052        for ssrc in flow_ssrcs(info) {
1053            self.flows.remove(&ssrc);
1054            lock(&self.shared).states.remove(&ssrc);
1055        }
1056        if self.flows.values().all(|flow| flow.current_frame.is_none()) {
1057            self.awaiting_rtcp_since = None;
1058        }
1059    }
1060
1061    fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1062    fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067    use super::*;
1068
1069    fn secs(seconds: f64) -> Duration {
1070        Duration::from_secs_f64(seconds)
1071    }
1072
1073    /// RFC 8083 section 4.2: MEDIA_TIMEOUT = ceil(k * max(Tf, Tr, Tdr) / Tdr).
1074    #[test]
1075    fn media_timeout_is_k_reports_scaled_by_the_slowest_interval() {
1076        // Tdr dominates: k reports.
1077        assert_eq!(5, media_timeout(5, secs(0.033), secs(0.1), secs(1.0)));
1078        // A frame every 3 s against reports every second: 15 reports.
1079        assert_eq!(15, media_timeout(5, secs(3.0), secs(0.1), secs(1.0)));
1080        // A round trip of 1.5 reporting intervals: ceil(7.5).
1081        assert_eq!(8, media_timeout(5, secs(0.02), secs(1.5), secs(1.0)));
1082    }
1083
1084    /// RFC 8083 section 4.3:
1085    /// CB_INTERVAL = ceil(3 * min(max(10*G*Tf, 10*Tr, 3*Tdr), max(15, 3*Td)) / (3*Tdr)).
1086    #[test]
1087    fn cb_interval_gives_the_congestion_controller_time_to_react() {
1088        // 30 fps, 100 ms round trip, reports every second: max(0.33, 1, 3) = 3 s, 3 reports.
1089        assert_eq!(
1090            3,
1091            cb_interval(1, secs(1.0 / 30.0), secs(0.1), secs(1.0), secs(5.0))
1092        );
1093        // A 600 ms round trip: 10 * Tr = 6 s, 6 reports.
1094        assert_eq!(
1095            6,
1096            cb_interval(1, secs(0.033), secs(0.6), secs(1.0), secs(5.0))
1097        );
1098        // A long GOP (G = 300 at 30 fps is 100 s) is capped at max(15, 3 * Td) = 15 s.
1099        assert_eq!(
1100            15,
1101            cb_interval(300, secs(1.0 / 30.0), secs(0.1), secs(1.0), secs(5.0))
1102        );
1103        // Reports every 5 s: 3 * Tdr = 15 s, 3 reports.
1104        assert_eq!(
1105            3,
1106            cb_interval(1, secs(0.033), secs(0.1), secs(5.0), secs(5.0))
1107        );
1108    }
1109
1110    /// RFC 8083 section 4.3: X = s / (Tr * sqrt(2*b*p/3)), b = 1.
1111    #[test]
1112    fn the_simplified_tcp_equation_matches_the_rfc() {
1113        // s = 1200 bytes, Tr = 100 ms, p = 0.06: sqrt(0.04) = 0.2, so 1200 / 0.02.
1114        let x = tcp_throughput(1200.0, secs(0.1), 0.06, false);
1115        assert!((x - 60_000.0).abs() < 1e-6, "{x}");
1116    }
1117
1118    /// RFC 8083 section 4.3 with t_RTO = 4 * Tr (section 3): the full equation is the more
1119    /// sensitive one, so it gives the lower throughput.
1120    #[test]
1121    fn the_full_tcp_equation_matches_the_rfc() {
1122        let p: f64 = 0.06;
1123        let tr: f64 = 0.1;
1124        let expected = 1200.0
1125            / (tr * (2.0 * p / 3.0).sqrt()
1126                + 4.0 * tr * (3.0 * (3.0 * p / 8.0).sqrt() * p * (1.0 + 32.0 * p * p)));
1127        let x = tcp_throughput(1200.0, secs(tr), p, true);
1128        assert!((x - expected).abs() < 1e-6, "{x} against {expected}");
1129        assert!(x < tcp_throughput(1200.0, secs(tr), p, false));
1130    }
1131}