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