Skip to main content

rtci_interceptor/cc/
interceptor.rs

1//! Records what left, ingests what the remote said about it, and drives an estimator.
2
3use super::estimator::{BandwidthEstimator, EstimatorStats};
4use super::feedback::{CongestionFeedbackFormat, negotiated_congestion_feedback};
5use super::probe::{
6    AfterDropProbe, PROBE_RESULT_TIMEOUT, ProbeController, ProbePacket, ProbeUnsent,
7    burst_estimate, probe_estimate,
8};
9use super::tmmbr::{self, TmmbrState};
10use super::tmmbr_request::{TmmbrControl, TmmbrRequester};
11use crate::Interceptor;
12use crate::circuit_breaker::CircuitBreakerHandle;
13use crate::never_sent::NeverSent;
14use crate::rtpfb::acknowledgement::PacketReport;
15use crate::rtpfb::convert::FeedbackTimeline;
16use crate::rtpfb::history::History;
17use crate::stream_info::StreamInfo;
18use crate::twcc::{flow_ssrcs, stream_supports_twcc};
19use crate::{Attribute, AttributedPacket, Packet, TaggedPacket};
20use rtcp::transport_feedbacks::tmmb::{
21    TemporaryMaximumBitrateNotification, TemporaryMaximumBitrateRequest,
22};
23use sansio::Protocol;
24use shared::error::Error;
25use shared::marshal::{MarshalSize, Unmarshal};
26use std::collections::{HashMap, VecDeque};
27use std::sync::{Arc, Mutex, MutexGuard};
28use std::time::{Duration, Instant};
29
30/// How long an unacknowledged packet is kept before it is written off.
31///
32/// Bounds the send history on a path that has stopped reporting. Too short and late feedback names
33/// packets there is no record of; too long and memory grows on a dead path. Two seconds is several
34/// round trips on any path worth estimating for, and one report interval is measured in tens of
35/// milliseconds.
36pub const DEFAULT_PRUNE_HORIZON: Duration = Duration::from_secs(2);
37
38/// How long a REMB keeps bounding the target after it was received.
39///
40/// A receiver that uses REMB sends one at least once per second
41/// (draft-ietf-rmcat-gcc-02 section 3). Three of those intervals without one and the bound is
42/// taken to be gone, as a receiver that stopped estimating has no other way to lift it.
43pub const REMB_TIMEOUT: Duration = Duration::from_secs(3);
44
45/// Rides with [`Attribute::TargetBitrateChanged`] application-ward: the congestion
46/// controller's estimate of what this endpoint may send, as the estimator has it. The target
47/// beside it is lowered on its way up (the NACK responder takes its retransmission reserve
48/// off, the pacer writes zero for a pause); this is not. The congestion control feedback
49/// generators size [`CongestionFeedbackCadence::SendEstimate`](crate::CongestionFeedbackCadence)
50/// by it. Read with [`AttributedPacket::custom`](crate::AttributedPacket::custom).
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct SendEstimate {
53    /// The estimate, bits per second.
54    pub bits_per_second: f64,
55}
56
57/// The addresses and protocol a packet arrived between.
58type PathKey = (
59    std::net::SocketAddr,
60    std::net::SocketAddr,
61    shared::TransportProtocol,
62);
63
64/// How many packets in a row arrive between new addresses before the path counts as changed:
65/// one straggler on the old pair, or one early packet on a new one, is not a change.
66const PATH_CHANGE_PACKETS: u8 = 3;
67
68/// How long after its last packet left a probe cluster counts as sent in full: the pacer
69/// spaces a cluster's packets by less than this.
70const PROBE_CLOSED_AFTER: Duration = Duration::from_millis(50);
71
72/// How long a probe cluster's packets are remembered without their reports.
73const PROBE_FORGET: Duration = Duration::from_secs(2);
74
75/// How long after its last packet left a probe cluster waits for the reports still missing
76/// before it is measured on those it has: the reports of packets sent since have come by then
77/// (feedback every 50 to 250 ms and a round trip), so what is still missing was in a feedback
78/// packet that was lost. Short of [`PROBE_RESULT_TIMEOUT`](super::probe::PROBE_RESULT_TIMEOUT)
79/// from when the cluster was asked for, less the quarter second it may take to leave, so the
80/// result still finds its cluster awaited.
81const PROBE_REPORTS_WAIT: Duration = Duration::from_millis(500);
82
83/// A probe cluster on the path.
84struct ProbeCluster {
85    /// How many of its packets left.
86    sent: usize,
87    last_sent: Instant,
88    /// The reports on them so far.
89    reports: Vec<PacketReport>,
90}
91
92impl ProbeCluster {
93    fn new(now: Instant) -> Self {
94        Self {
95            sent: 0,
96            last_sent: now,
97            reports: Vec::new(),
98        }
99    }
100
101    /// Whether the pacer has finished sending it.
102    fn closed(&self, now: Instant) -> bool {
103        now.saturating_duration_since(self.last_sent) >= PROBE_CLOSED_AFTER
104    }
105}
106
107/// Per-stream state: the header-extension id the transport-wide sequence number is written under.
108struct LocalStream {
109    hdr_ext_id: u8,
110    /// The one feedback format this stream is reported in; reports in the other are not read.
111    feedback: Option<CongestionFeedbackFormat>,
112    /// Whether `a=rtcp-fb:<pt> ccm tmmbr` was negotiated for the stream (RFC 5104 section 7.1).
113    tmmbr: bool,
114}
115
116/// Whether a stream negotiated TMMBR: `ccm tmmbr`, with or without `smaxpr=` (RFC 5104
117/// section 7.1).
118fn stream_negotiated_tmmbr(info: &StreamInfo) -> bool {
119    info.rtcp_feedback.iter().any(|feedback| {
120        feedback.typ == "ccm" && feedback.parameter.split_whitespace().next() == Some("tmmbr")
121    })
122}
123
124/// Builder for [`CongestionControlInterceptor`].
125///
126/// # Example
127///
128/// ```
129/// use rtci_interceptor::{Slot, CongestionControlBuilder, ConstantBitrate, Registry};
130///
131/// let chain = Registry::new()
132///     .with(Slot::CongestionControl, CongestionControlBuilder::new(ConstantBitrate::new(1_000_000.0)).build())
133///     .build();
134/// # let _ = chain;
135/// ```
136pub struct CongestionControlBuilder<E: BandwidthEstimator> {
137    estimator: E,
138    prune_horizon: Duration,
139    circuit_breaker: Option<CircuitBreakerHandle>,
140    unnegotiated_tmmbr: bool,
141    bandwidth_probing: bool,
142    after_drop_probe: AfterDropProbe,
143    recovery_probing: bool,
144    send_rate_told_to_rtcp: bool,
145}
146
147impl<E: BandwidthEstimator> CongestionControlBuilder<E> {
148    /// A builder driving `estimator`.
149    pub fn new(estimator: E) -> Self {
150        Self {
151            estimator,
152            prune_horizon: DEFAULT_PRUNE_HORIZON,
153            circuit_breaker: None,
154            unnegotiated_tmmbr: false,
155            bandwidth_probing: false,
156            after_drop_probe: AfterDropProbe::default(),
157            recovery_probing: false,
158            send_rate_told_to_rtcp: false,
159        }
160    }
161
162    /// Whether the estimate is told to the RTCP session of the same chain
163    /// ([`RtcpSessionControl::SendRate`](crate::RtcpSessionControl::SendRate), written
164    /// wire-ward whenever the estimate has moved by a twentieth), for
165    /// [`RtcpSessionBuilder::with_share_following_send_rate`](crate::RtcpSessionBuilder::with_share_following_send_rate).
166    /// Off by default; it needs an RTCP session wire-ward of this interceptor, which takes
167    /// the control out of the chain.
168    pub fn with_send_rate_told_to_rtcp(mut self, told: bool) -> Self {
169        self.send_rate_told_to_rtcp = told;
170        self
171    }
172
173    /// How long an unacknowledged packet is kept before it is written off.
174    pub fn with_prune_horizon(mut self, prune_horizon: Duration) -> Self {
175        self.prune_horizon = prune_horizon;
176        self
177    }
178
179    /// The circuit breaker of the same chain. When its congestion breaker asks for a tenth of
180    /// the rate (RFC 8083 section 4.3) the limit becomes an upper bound of the estimator.
181    pub fn with_circuit_breaker(mut self, handle: CircuitBreakerHandle) -> Self {
182        self.circuit_breaker = Some(handle);
183        self
184    }
185
186    /// Whether a TMMBR is honoured for a stream that did not negotiate `ccm tmmbr`.
187    ///
188    /// Off by default: RFC 5104 section 7.1 has a codec control message used only when the
189    /// session description names it (`a=rtcp-fb:<pt> ccm tmmbr`), and section 7.2 has the
190    /// answerer remove what it does not support, so a TMMBR for a stream without it is a
191    /// message the session never agreed to and is ignored, unanswered. `true` is the lenient
192    /// behaviour: every TMMBR that names one of this endpoint's streams limits it and is
193    /// answered with a TMMBN.
194    pub fn with_unnegotiated_tmmbr(mut self, honoured: bool) -> Self {
195        self.unnegotiated_tmmbr = honoured;
196        self
197    }
198
199    /// Whether the path is probed for capacity above the target: short clusters of packets
200    /// at a multiple of the target, whose arrival shows at once whether the path carries
201    /// that rate. Off for a builder (it needs the pacer and the NACK responder of the same
202    /// chain); on in the peer connection's default interceptor set
203    /// (`DefaultInterceptorOptions::bandwidth_probing`).
204    ///
205    /// Without it the estimate climbs as fast as the delay-based controller raises it, 8% a
206    /// second in [`Gcc`](crate::Gcc): from 300 kbit/s to 2.5 Mbit/s takes most of half a
207    /// minute. With it, two clusters at the start (three and six times the starting rate),
208    /// further ones at twice the result while the path keeps carrying what is asked, and one
209    /// every five seconds while the application sends less than the target allows; a path
210    /// with 2.5 Mbit/s is found in well under a second.
211    ///
212    /// RFC 8836 section 2 (requirement 4, a SHOULD) asks for quick adaptation to the initial
213    /// conditions and names "probing during setup" as one way; draft-ietf-rmcat-gcc-02 has
214    /// none. It is libwebrtc's behaviour, in outline, and adds traffic the application did
215    /// not write: padding-only packets on the RTX stream fill a cluster the application's own
216    /// media does not (they carry no media, and receivers drop them), so it needs RTX
217    /// negotiated to probe a sender with little to send. After a large drop of the target
218    /// (a third or more), the rate before it is probed for a few seconds
219    /// ([`ProbeController::with_probe_after_drop`](crate::ProbeController::with_probe_after_drop)).
220    /// What it costs: an application sending a fifth of what the path carries spends about
221    /// 4% of its octets on probes, one cluster every five seconds. The pacer
222    /// ([`PacerInterceptor`](crate::PacerInterceptor)) and the NACK responder
223    /// ([`NackResponderInterceptor`](crate::NackResponderInterceptor)) of the same chain do
224    /// the sending; the estimator hears the result through
225    /// [`BandwidthEstimator::on_probe_result`].
226    pub fn with_bandwidth_probing(mut self, bandwidth_probing: bool) -> Self {
227        self.bandwidth_probing = bandwidth_probing;
228        self
229    }
230
231    /// With bandwidth probing on, what is probed for after a large drop of the target:
232    /// [`AfterDropProbe`] (the engine's repeated probe by default, libwebrtc's single one, or
233    /// none).
234    pub fn with_after_drop_probe(mut self, after_drop_probe: AfterDropProbe) -> Self {
235        self.after_drop_probe = after_drop_probe;
236        self
237    }
238
239    /// Whether, with bandwidth probing on, the path is probed back towards the rate it
240    /// carried before a large drop of the target for as long as that rate is remembered (a
241    /// minute): a cluster at twice the target every five seconds while the target is below
242    /// 85% of it and the estimator does not read the path as over-used
243    /// ([`BandwidthEstimator::usage`]), with further clusters while the path carries what is
244    /// asked. Off by default, in every behaviour profile
245    /// (`DefaultInterceptorOptions::recovery_probing`): it is tuning, with no specification
246    /// behind it, and Chrome does not do it.
247    ///
248    /// Without it a sender that keeps up with its target climbs back from a limit that has
249    /// gone at the delay-based controller's 8% a second (about 17 s from 250 kbit/s to
250    /// 1 Mbit/s); with it the next cluster finds the path, within five seconds. Measured
251    /// (capacity instrument, 200 calls a cell, a 20 s limit of 300 kbit/s on a 2.5 Mbit/s
252    /// path): 1 Mbit/s 4.9 s after the limit went against 17.3 s, and the full rate from
253    /// then on; it costs 3% of the target under the limit (238 against 246 kbit/s) and,
254    /// behind a 100 ms queue, 11 more audio packets lost a call (52 against 41); it gains
255    /// nothing after a limit longer than the minute the rate is remembered. All the
256    /// figures, why no specification asks for it and what libwebrtc does instead:
257    /// [`ProbeController::with_recovery_probing`](crate::ProbeController::with_recovery_probing).
258    /// It needs the pacer of the same chain: a chain whose clusters leave as bursts is not
259    /// probed this way.
260    pub fn with_recovery_probing(mut self, recovery_probing: bool) -> Self {
261        self.recovery_probing = recovery_probing;
262        self
263    }
264
265    /// Build the interceptor.
266    pub fn build(self) -> CongestionControlInterceptor<E> {
267        self.build_with_handle().0
268    }
269
270    /// Build the interceptor and the handle the application reads the estimate from and gives
271    /// the negotiated limits to.
272    pub fn build_with_handle(self) -> (CongestionControlInterceptor<E>, CongestionControlHandle) {
273        let shared = Arc::new(Mutex::new(Shared {
274            target: self.estimator.target_bitrate(),
275            stats: self.estimator.stats(),
276            ..Shared::default()
277        }));
278        let probing = self.bandwidth_probing.then(|| {
279            ProbeController::new(self.estimator.target_bitrate(), f64::INFINITY)
280                .with_after_drop_probe(self.after_drop_probe)
281                .with_recovery_probing(self.recovery_probing)
282        });
283        (
284            CongestionControlInterceptor {
285                tmmbn_owed: false,
286                ecn_counters: HashMap::new(),
287                tmmbr_requests: TmmbrRequester::default(),
288                receiver_ssrc: crate::rfc8888::sender::random_ssrc(),
289                path: None,
290                path_candidate: None,
291                probing,
292                probe_packets: HashMap::new(),
293                probe_clusters: HashMap::new(),
294                probe_asked: None,
295                probe_marked: None,
296                probe_unanswered: false,
297                probe_chain_changed: false,
298                probe_senders: std::collections::HashSet::new(),
299                sent: VecDeque::new(),
300                last_target: None,
301                send_rate_told_to_rtcp: self.send_rate_told_to_rtcp,
302                told_rate: None,
303                estimator: self.estimator,
304                prune_horizon: self.prune_horizon,
305                history: History::new(),
306                timeline: FeedbackTimeline::new(),
307                streams: HashMap::new(),
308                local_ssrcs: Vec::new(),
309                tmmbr: TmmbrState::default(),
310                remb: None,
311                round_trip_time: None,
312                departures: VecDeque::new(),
313                never_sent: HashMap::new(),
314                per_packet_feedback: false,
315                applied_max: None,
316                unnegotiated_tmmbr: self.unnegotiated_tmmbr,
317                circuit_breaker: self.circuit_breaker,
318                shared: shared.clone(),
319                read_queue: VecDeque::new(),
320                write_queue: VecDeque::new(),
321            },
322            CongestionControlHandle { shared },
323        )
324    }
325}
326
327#[derive(Default)]
328struct Shared {
329    target: f64,
330    stats: EstimatorStats,
331    session_max: Option<f64>,
332    min: Option<f64>,
333    remb: Option<f64>,
334    tmmbr: Option<f64>,
335    path_changed: bool,
336    inputs_changed: bool,
337}
338
339fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
340    shared
341        .lock()
342        .unwrap_or_else(|poisoned| poisoned.into_inner())
343}
344
345/// The application's end of the congestion controller: the estimate, pulled when the encoder
346/// wants it, and the limits only the application knows.
347///
348/// # Inputs from signalling
349///
350/// The engine's SDP layer does not feed these yet; an application that negotiates them passes
351/// them on:
352///
353/// - `b=AS:<kbit/s>` and `b=TIAS:<bit/s>` of the remote description (RFC 8866 section 5.8,
354///   RFC 3890): [`set_session_bitrate_limit`](Self::set_session_bitrate_limit). `b=AS` counts
355///   IP and UDP headers, `b=TIAS` does not; the caller converts.
356/// - a selected candidate pair change: [`notify_path_change`](Self::notify_path_change).
357///   The engine's peer connection tells the interceptor of its own pair changes
358///   ([`PathChanged`](crate::PathChanged)); this is for a change it cannot see.
359///
360/// TMMBR and REMB arrive as RTCP and are read by the interceptor itself.
361#[derive(Clone)]
362pub struct CongestionControlHandle {
363    shared: Arc<Mutex<Shared>>,
364}
365
366impl CongestionControlHandle {
367    /// The current target, in bits per second.
368    pub fn target_bitrate(&self) -> f64 {
369        lock(&self.shared).target
370    }
371
372    /// What the estimator says about itself.
373    pub fn stats(&self) -> EstimatorStats {
374        lock(&self.shared).stats
375    }
376
377    /// The bit rate the remote description allows this endpoint to send (`b=AS`, `b=TIAS`), in
378    /// bits per second of RTP; `None` when it names none.
379    pub fn set_session_bitrate_limit(&self, bits_per_second: Option<f64>) {
380        let mut shared = lock(&self.shared);
381        shared.session_max = bits_per_second;
382        shared.inputs_changed = true;
383    }
384
385    /// A floor for the target, in bits per second; `None` leaves the estimator's own.
386    pub fn set_min_bitrate(&self, bits_per_second: Option<f64>) {
387        let mut shared = lock(&self.shared);
388        shared.min = bits_per_second;
389        shared.inputs_changed = true;
390    }
391
392    /// The network path changed: the estimator starts over from its current target.
393    pub fn notify_path_change(&self) {
394        lock(&self.shared).path_changed = true;
395    }
396
397    /// The limit the receiver's last REMB set, while it is in force.
398    pub fn remb_limit(&self) -> Option<f64> {
399        lock(&self.shared).remb
400    }
401
402    /// The limit the TMMBR bounding set puts on this sender, while there is one.
403    pub fn tmmbr_limit(&self) -> Option<f64> {
404        lock(&self.shared).tmmbr
405    }
406}
407
408/// Records every departing packet, resolves the remote's feedback against it, and drives a
409/// [`BandwidthEstimator`].
410///
411/// # Where this belongs in the chain
412///
413/// **Wire-most.** It is the only position that sees every byte that leaves: nothing exits the chain
414/// except through the interceptors ahead of it in the walk, so a retransmission emitted by the NACK
415/// responder and a repair packet emitted by the FEC encoder both arrive here, already paced and
416/// already numbered. An estimator reading a history that omits them sees fewer bytes than are on
417/// the wire, infers headroom, and raises the target during loss — a positive feedback loop that is
418/// hard to spot, because the estimator's own accounting stays internally consistent throughout.
419///
420/// It also has to be **below the pacer**, so `packet.now` is the instant the packet was *released*
421/// rather than the instant the application enqueued it. A pacer can hold a packet for tens of
422/// milliseconds; counting that as network delay is exactly the error that makes a delay-based
423/// estimate collapse.
424///
425/// # How the estimate gets out
426///
427/// On the read leg, as [`Attribute::TargetBitrateChanged`]: attached to the feedback packet that
428/// produced it, or, when the estimate moved on a timer with no packet to ride on, on an empty
429/// RTCP packet, the chain's attribute carrier. The pacer sits application-ward of this
430/// interceptor and reads the attribute on its way past. An application pulls the same number
431/// from [`CongestionControlHandle`].
432///
433/// # Limits from outside the algorithm
434///
435/// The estimator's target is held under the tightest of: the negotiated session bit rate
436/// ([`CongestionControlHandle::set_session_bitrate_limit`]), the receiver's REMB, the TMMBR
437/// bounding set (RFC 5104; every TMMBR is answered with a TMMBN), and the circuit breaker's
438/// reduced rate.
439pub struct CongestionControlInterceptor<E: BandwidthEstimator> {
440    estimator: E,
441    history: History,
442    /// The receiver's clock, followed across feedback reports.
443    timeline: FeedbackTimeline,
444    streams: HashMap<u32, LocalStream>,
445    /// Media SSRCs in the order they were bound: the first sends this endpoint's TMMBN.
446    local_ssrcs: Vec<u32>,
447    tmmbr: TmmbrState,
448    /// The last REMB: its bit rate and when it was read.
449    remb: Option<(f64, Instant)>,
450    /// Smoothed round trip time from feedback.
451    round_trip_time: Option<Duration>,
452    /// Departure instants of the last second, for the packet rate a TMMBR limit depends on.
453    departures: VecDeque<Instant>,
454    /// The sequence numbers each local SSRC jumped over on its way out, while receiver reports
455    /// are the loss-based controller's input: the packets the pacer discarded, which the
456    /// receiver counts as lost.
457    never_sent: HashMap<u32, NeverSent>,
458    /// Whether TWCC or RFC 8888 feedback has ever been read.
459    per_packet_feedback: bool,
460    /// The external maximum last handed to the estimator.
461    applied_max: Option<Option<f64>>,
462    /// Whether a TMMBR limits a stream that did not negotiate `ccm tmmbr`.
463    unnegotiated_tmmbr: bool,
464    /// Whether the compound packet being read asks for a TMMBN.
465    tmmbn_owed: bool,
466    /// The last RFC 6679 ECN counters read about each local stream: (CE, packets received),
467    /// each kept in the width of its field.
468    ecn_counters: HashMap<u32, rtcp::transport_feedbacks::ecn_feedback::EcnCounters>,
469    /// The receiver side of TMMBR: the limits this endpoint asks of remote senders.
470    tmmbr_requests: TmmbrRequester,
471    /// The SSRC a receive-only endpoint sends its TMMBRs from (RFC 3550 section 8: random,
472    /// never 0); a sending endpoint uses its first media SSRC.
473    receiver_ssrc: u32,
474    /// The addresses inbound packets arrive between: the path, as far as this interceptor
475    /// can see it.
476    path: Option<PathKey>,
477    /// A different pair of addresses, and how many packets in a row arrived on it.
478    path_candidate: Option<(PathKey, u8)>,
479    /// Bandwidth probing, when it is on.
480    probing: Option<ProbeController>,
481    /// The packets that left as part of a probe cluster and await their report: SSRC and RTP
482    /// sequence number to cluster.
483    probe_packets: HashMap<(u32, u16), u32>,
484    /// What is known of each cluster in flight.
485    probe_clusters: HashMap<u32, ProbeCluster>,
486    /// The cluster last asked for, and when.
487    probe_asked: Option<(u32, Instant)>,
488    /// The newest cluster a packet left for that feedback will report.
489    probe_marked: Option<u32>,
490    /// Whether the last cluster asked for went unanswered: no packet left with its mark, so
491    /// nothing in this chain sends clusters as it is (no pacer, and no RTX stream for the
492    /// NACK responder to pad on). No cluster is asked for while this is so; it ends when
493    /// another stream is bound or starts to send.
494    probe_unanswered: bool,
495    /// Whether a stream was bound or sent its first packet since the last cluster was asked
496    /// for. A cluster asked for before then was asked of a chain that may not have been able
497    /// to send it (the first audio packet asks before the video, whose RTX stream carries the
498    /// padding, has sent): its going unanswered says nothing of the chain as it is now.
499    probe_chain_changed: bool,
500    /// The SSRCs that have sent since probing began.
501    probe_senders: std::collections::HashSet<u32>,
502    /// Departures of the last second with their sizes, for the rate being sent.
503    sent: VecDeque<(Instant, usize)>,
504    circuit_breaker: Option<CircuitBreakerHandle>,
505    shared: Arc<Mutex<Shared>>,
506    prune_horizon: Duration,
507    /// The last target handed onward, so an unchanged estimate does not re-announce itself.
508    /// `None` until the first one has been announced: the pacer has to learn the estimator's
509    /// starting rate too, not only its changes.
510    last_target: Option<f64>,
511    /// [`CongestionControlBuilder::with_send_rate_told_to_rtcp`], and the rate last told.
512    send_rate_told_to_rtcp: bool,
513    told_rate: Option<f64>,
514    read_queue: VecDeque<TaggedPacket>,
515    write_queue: VecDeque<TaggedPacket>,
516}
517
518impl<E: BandwidthEstimator> CongestionControlInterceptor<E> {
519    /// RFC 6679 sections 5 and 7.3.3: the CE marks an RTCP ECN Feedback packet or an XR ECN
520    /// Summary Report counts for a local stream since the last such report reach the
521    /// estimator as congestion, as losses would. A stream reported in RFC 8888, whose
522    /// per-packet reports carry each mark already, is left out, so no mark counts twice.
523    fn observe_congestion_marks(&mut self, now: Instant, packets: &[Box<dyn rtcp::Packet>]) {
524        use rtcp::extended_report::{EcnSummaryReportBlock, ExtendedReport};
525        use rtcp::transport_feedbacks::ecn_feedback::{EcnCounters, EcnFeedback};
526        let mut seen: Vec<(u32, EcnCounters)> = vec![];
527        for packet in packets {
528            let any = packet.as_any();
529            if let Some(feedback) = any.downcast_ref::<EcnFeedback>() {
530                seen.push((feedback.media_ssrc, feedback.counters));
531            } else if let Some(xr) = any.downcast_ref::<ExtendedReport>() {
532                for block in &xr.reports {
533                    if let Some(summary) = block.as_any().downcast_ref::<EcnSummaryReportBlock>() {
534                        seen.extend(summary.reports.iter().map(|r| (r.ssrc, r.counters)));
535                    }
536                }
537            }
538        }
539        let (mut marked, mut total) = (0u64, 0u64);
540        for (ssrc, counters) in seen {
541            let Some(stream) = self.streams.get(&ssrc) else {
542                continue;
543            };
544            if stream.feedback == Some(CongestionFeedbackFormat::Rfc8888) {
545                continue;
546            }
547            // "The counters SHALL be initiated to 0 for each new SSRC": the first report
548            // counts from zero. Each counter wraps in its own width.
549            let last = self.ecn_counters.insert(ssrc, counters).unwrap_or_default();
550            let ce = u64::from(counters.ce.wrapping_sub(last.ce));
551            let received = u64::from(counters.ect0.wrapping_sub(last.ect0))
552                + u64::from(counters.ect1.wrapping_sub(last.ect1))
553                + ce
554                + u64::from(counters.not_ect.wrapping_sub(last.not_ect));
555            marked += ce;
556            total += received;
557        }
558        if total > 0 {
559            self.estimator.on_congestion_marks(now, marked, total);
560        }
561    }
562
563    /// The estimator, for reading its stats.
564    pub fn estimator(&self) -> &E {
565        &self.estimator
566    }
567
568    /// How many TWCC feedback packets the receiver sent that never arrived here, by the gaps
569    /// in the feedback packet count.
570    pub fn lost_feedback(&self) -> u64 {
571        self.history.lost_feedback()
572    }
573
574    /// How many sent packets are still awaiting a verdict.
575    pub fn outstanding(&self) -> usize {
576        self.history.len()
577    }
578
579    /// The transport-wide sequence number the TWCC sender wrote, if this stream carries one.
580    ///
581    /// The sender sits between the pacer and here, so by the time a packet arrives the number is
582    /// already in its header — which is the whole reason this interceptor is wire-most rather than
583    /// the sender being.
584    fn twcc_sequence_number(&self, rtp_packet: &rtp::Packet) -> Option<u16> {
585        let stream = self.streams.get(&rtp_packet.header.ssrc)?;
586        let mut extension = rtp_packet.header.get_extension(stream.hdr_ext_id)?;
587        rtp::extension::transport_cc_extension::TransportCcExtension::unmarshal(&mut extension)
588            .ok()
589            .map(|extension| extension.transport_sequence)
590    }
591
592    /// RTP packets per second over the last second.
593    fn packet_rate(&mut self, now: Instant) -> f64 {
594        while let Some(at) = self.departures.front() {
595            if now.saturating_duration_since(*at) <= Duration::from_secs(1) {
596                break;
597            }
598            self.departures.pop_front();
599        }
600        self.departures.len() as f64
601    }
602
603    fn note_round_trip_time(&mut self, now: Instant, sample: Duration) {
604        let smoothed = match self.round_trip_time {
605            Some(previous) => previous.mul_f64(0.8) + sample.mul_f64(0.2),
606            None => sample,
607        };
608        self.round_trip_time = Some(smoothed);
609        self.estimator.on_round_trip_time(now, smoothed);
610        if let Some(breaker) = &self.circuit_breaker {
611            // Each measurement as it is: the breaker smooths Tr itself (RFC 8083 section 3).
612            breaker.report_round_trip_time(sample);
613        }
614    }
615
616    /// Queue a TMMBN with the current bounding set (RFC 5104 section 4.2.2.2).
617    fn send_tmmbn(&mut self, now: Instant) {
618        let Some(sender_ssrc) = self.local_ssrcs.first().copied() else {
619            return;
620        };
621        let notification = TemporaryMaximumBitrateNotification {
622            sender_ssrc,
623            entries: self
624                .tmmbr
625                .bounding()
626                .iter()
627                .map(|tuple| {
628                    rtcp::transport_feedbacks::tmmb::TmmbEntry::new(
629                        tuple.ssrc,
630                        tuple.bitrate,
631                        tuple.overhead,
632                    )
633                })
634                .collect(),
635        };
636        self.write_queue.push_back(TaggedPacket {
637            now,
638            transport: shared::TransportContext::default(),
639            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(notification)])),
640        });
641    }
642
643    /// The SSRC this endpoint's TMMBRs come from, which a TMMBN names as owner.
644    fn own_ssrc(&self) -> u32 {
645        self.local_ssrcs
646            .first()
647            .copied()
648            .unwrap_or(self.receiver_ssrc)
649    }
650
651    /// Queue the TMMBR the receiver side owes now, if any: one packet with an entry per media
652    /// sender asked (RFC 5104 section 4.2.1.1).
653    fn send_tmmbr(&mut self, now: Instant) {
654        let own_ssrc = self.own_ssrc();
655        let entries = self.tmmbr_requests.poll_request(now, own_ssrc);
656        if entries.is_empty() {
657            return;
658        }
659        let request = TemporaryMaximumBitrateRequest {
660            sender_ssrc: own_ssrc,
661            entries: entries
662                .iter()
663                .map(|entry| {
664                    rtcp::transport_feedbacks::tmmb::TmmbEntry::new(
665                        entry.ssrc,
666                        entry.bitrate,
667                        entry.overhead,
668                    )
669                })
670                .collect(),
671        };
672        self.write_queue.push_back(TaggedPacket {
673            now,
674            transport: shared::TransportContext::default(),
675            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(request)])),
676        });
677    }
678
679    /// Feed one inbound RTCP packet to the history and the limits. Returns whether it was
680    /// per-packet feedback.
681    #[allow(clippy::borrowed_box)]
682    fn ingest(&mut self, now: Instant, rtcp_packet: &Box<dyn rtcp::Packet>) -> bool {
683        let payload = rtcp_packet.as_any();
684
685        if let Some(feedback) = payload
686            .downcast_ref::<rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc>(
687        ) {
688            self.history.on_twcc_feedback_count(feedback.fb_pkt_count);
689            let mut round_trip: Option<Duration> = None;
690            for acknowledgement in self.timeline.convert_twcc(feedback) {
691                if let Some(rtt) = self.history.on_twcc_feedback(now, acknowledgement)
692                    && acknowledgement.arrived
693                {
694                    round_trip = Some(round_trip.map_or(rtt, |best| best.min(rtt)));
695                }
696            }
697            if let Some(rtt) = round_trip {
698                self.note_round_trip_time(now, rtt);
699            }
700            self.tmmbr.on_owner_seen(now, feedback.sender_ssrc);
701            return true;
702        }
703
704        if let Some(feedback) = payload
705            .downcast_ref::<rtcp::transport_feedbacks::cc_feedback_report::CcFeedbackReport>(
706        ) {
707            let (report_delay, per_stream) = self.timeline.convert_ccfb(feedback);
708            let mut round_trip: Option<Duration> = None;
709            for (ssrc, acknowledgements) in per_stream {
710                // A stream that runs on transport-wide feedback is not also read from RFC 8888
711                // reports: the estimator would count each of its packets twice.
712                if self.streams.get(&ssrc).is_some_and(|stream| {
713                    stream.feedback == Some(CongestionFeedbackFormat::TransportCc)
714                }) {
715                    continue;
716                }
717                for acknowledgement in acknowledgements {
718                    if let Some(rtt) = self.history.on_ccfb_feedback(now, ssrc, acknowledgement)
719                        && acknowledgement.arrived
720                    {
721                        round_trip = Some(round_trip.map_or(rtt, |best| best.min(rtt)));
722                    }
723                }
724            }
725            if let Some(rtt) = round_trip {
726                // The receiver held the report for `report_delay` after the newest arrival.
727                self.note_round_trip_time(now, rtt.saturating_sub(report_delay));
728            }
729            self.tmmbr.on_owner_seen(now, feedback.sender_ssrc);
730            return true;
731        }
732
733        // REMB: the receiver's own estimate bounds the sender's (draft-ietf-rmcat-gcc-02
734        // sections 3 and 6).
735        if let Some(remb) = payload.downcast_ref::<rtcp::payload_feedbacks::receiver_estimated_maximum_bitrate::ReceiverEstimatedMaximumBitrate>() {
736            let ours = remb.ssrcs.is_empty()
737                || remb.ssrcs.iter().any(|ssrc| self.streams.contains_key(ssrc));
738            if ours && remb.bitrate.is_finite() && remb.bitrate >= 0.0 {
739                self.remb = Some((f64::from(remb.bitrate), now));
740            }
741            self.tmmbr.on_owner_seen(now, remb.sender_ssrc);
742            return false;
743        }
744
745        // TMMBR (RFC 5104 section 4.2.1): the typed packet, or the same bytes handed over raw.
746        let request =
747            if let Some(request) = payload.downcast_ref::<TemporaryMaximumBitrateRequest>() {
748                Some(tmmbr::TmmbPacket {
749                    fmt: tmmbr::FMT_TMMBR,
750                    sender_ssrc: request.sender_ssrc,
751                    entries: request
752                        .entries
753                        .iter()
754                        .map(|entry| tmmbr::TmmbEntry {
755                            ssrc: entry.ssrc,
756                            bitrate: entry.bitrate(),
757                            overhead: entry.measured_overhead,
758                        })
759                        .collect(),
760                })
761            } else {
762                payload
763                    .downcast_ref::<rtcp::raw_packet::RawPacket>()
764                    .and_then(|raw| tmmbr::parse(&raw.0))
765                    .filter(|packet| packet.fmt == tmmbr::FMT_TMMBR)
766            };
767        if let Some(packet) = request {
768            let packet_rate = self.packet_rate(now);
769            let round_trip_time = self.round_trip_time.unwrap_or_default();
770            let mut owed = false;
771            for entry in packet.entries {
772                // An entry is for the media sender its SSRC names, and binds it only when the
773                // session negotiated the message for that stream (RFC 5104 section 7.1).
774                if self
775                    .streams
776                    .get(&entry.ssrc)
777                    .is_some_and(|stream| stream.tmmbr || self.unnegotiated_tmmbr)
778                {
779                    owed |= self.tmmbr.on_request(
780                        now,
781                        packet.sender_ssrc,
782                        entry,
783                        packet_rate,
784                        round_trip_time,
785                    );
786                }
787            }
788            // One TMMBN for the compound packet, however many TMMBRs and entries it had, and
789            // whether or not the bounding set changed (RFC 5104 section 4.2.2.2: "only a
790            // single TMMBN SHALL be sent, even if more than one TMMBR is received").
791            self.tmmbn_owed |= owed;
792            return false;
793        }
794
795        if let Some(bye) = payload.downcast_ref::<rtcp::goodbye::Goodbye>() {
796            let packet_rate = self.packet_rate(now);
797            let round_trip_time = self.round_trip_time.unwrap_or_default();
798            let mut owed = false;
799            for source in &bye.sources {
800                owed |= self
801                    .tmmbr
802                    .on_owner_left(now, *source, packet_rate, round_trip_time);
803            }
804            self.tmmbn_owed |= owed;
805            return false;
806        }
807
808        // TMMBN (RFC 5104 section 4.2.2): a media sender's bounding set, which the receiver
809        // side saves and decides its next TMMBR by (section 4.2.1.2).
810        let notification = if let Some(notification) =
811            payload.downcast_ref::<TemporaryMaximumBitrateNotification>()
812        {
813            Some((
814                notification.sender_ssrc,
815                notification
816                    .entries
817                    .iter()
818                    .map(|entry| tmmbr::TmmbEntry {
819                        ssrc: entry.ssrc,
820                        bitrate: entry.bitrate(),
821                        overhead: entry.measured_overhead,
822                    })
823                    .collect::<Vec<_>>(),
824            ))
825        } else {
826            payload
827                .downcast_ref::<rtcp::raw_packet::RawPacket>()
828                .and_then(|raw| tmmbr::parse(&raw.0))
829                .filter(|packet| packet.fmt == tmmbr::FMT_TMMBN)
830                .map(|packet| (packet.sender_ssrc, packet.entries))
831        };
832        if let Some((media_sender, entries)) = notification {
833            let own_ssrc = self.own_ssrc();
834            self.tmmbr_requests
835                .on_tmmbn(media_sender, entries, own_ssrc);
836            return false;
837        }
838
839        // Receiver reports: the loss-based controller's input while the receiver sends no
840        // per-packet feedback (draft-ietf-rmcat-gcc-02 section 7).
841        let reports =
842            if let Some(rr) = payload.downcast_ref::<rtcp::receiver_report::ReceiverReport>() {
843                self.tmmbr.on_owner_seen(now, rr.ssrc);
844                Some(&rr.reports)
845            } else if let Some(sr) = payload.downcast_ref::<rtcp::sender_report::SenderReport>() {
846                self.tmmbr.on_owner_seen(now, sr.ssrc);
847                Some(&sr.reports)
848            } else {
849                None
850            };
851        if let Some(reports) = reports
852            && !self.per_packet_feedback
853        {
854            for report in reports {
855                if self.streams.contains_key(&report.ssrc) {
856                    // The receiver counts every sequence number it did not receive as lost
857                    // (RFC 3550 section 6.4.1), the ones the pacer discarded before they left
858                    // included. Those are not the path's loss: over the interval the report
859                    // covers they are taken out of the count and the fraction is that of the
860                    // packets that left.
861                    let mut fraction_lost = f64::from(report.fraction_lost) / 256.0;
862                    if let Some(interval) =
863                        self.never_sent
864                            .get_mut(&report.ssrc)
865                            .and_then(|never_sent| {
866                                never_sent.on_report(
867                                    report.last_sequence_number,
868                                    report.cumulative_lost(),
869                                )
870                            })
871                        && interval.never_sent() > 0
872                    {
873                        fraction_lost = interval.fraction_lost();
874                    }
875                    self.estimator.on_receiver_report(now, fraction_lost);
876                }
877            }
878        }
879
880        false
881    }
882
883    /// Hand the estimator the tightest of the outside limits, when it changed.
884    fn apply_bounds(&mut self, now: Instant) {
885        if let Some((_, at)) = self.remb
886            && now.saturating_duration_since(at) >= REMB_TIMEOUT
887        {
888            self.remb = None;
889        }
890        let remb = self.remb.map(|(bitrate, _)| bitrate);
891        let packet_rate = self.packet_rate(now);
892        let tmmbr = self.tmmbr.limit(packet_rate);
893        let breaker = self
894            .circuit_breaker
895            .as_ref()
896            .and_then(CircuitBreakerHandle::rate_limit);
897
898        let (session, min, inputs_changed, path_changed) = {
899            let mut shared = lock(&self.shared);
900            shared.remb = remb;
901            shared.tmmbr = tmmbr;
902            (
903                shared.session_max,
904                shared.min,
905                std::mem::take(&mut shared.inputs_changed),
906                std::mem::take(&mut shared.path_changed),
907            )
908        };
909        if path_changed {
910            self.estimator.on_path_change(now);
911            self.restart_probing(now);
912        }
913
914        let max = [session, remb, tmmbr, breaker]
915            .into_iter()
916            .flatten()
917            .reduce(f64::min);
918        if inputs_changed || self.applied_max != Some(max) {
919            self.applied_max = Some(max);
920            self.estimator.set_external_bounds(min, max);
921        }
922    }
923
924    /// Follows the addresses inbound packets arrive between, and tells the estimator when
925    /// they change (RFC 8836 section 2, requirement 1: a congestion controller reacts to a
926    /// change of the path, and "the application may be able to notify it").
927    ///
928    /// The peer connection moves to another candidate pair without this interceptor being
929    /// told, but every inbound packet carries the pair it arrived on. A new local or remote
930    /// address is a new path in at least one direction, and what was measured on the old one
931    /// (its delay gradient, where its capacity was) describes nothing any more.
932    fn observe_path(&mut self, now: Instant, transport: &shared::TransportContext) {
933        let key = (
934            transport.local_addr,
935            transport.peer_addr,
936            transport.transport_protocol,
937        );
938        let Some(current) = self.path else {
939            self.path = Some(key);
940            return;
941        };
942        if key == current {
943            self.path_candidate = None;
944            return;
945        }
946        let seen = match self.path_candidate {
947            Some((candidate, seen)) if candidate == key => seen + 1,
948            _ => 1,
949        };
950        if seen >= PATH_CHANGE_PACKETS {
951            self.path = Some(key);
952            self.path_candidate = None;
953            self.on_new_path(now);
954        } else {
955            self.path_candidate = Some((key, seen));
956        }
957    }
958
959    /// The path changed: seen in the addresses inbound packets arrive between
960    /// ([`observe_path`](Self::observe_path)), or said by the peer connection
961    /// ([`PathChanged`](crate::PathChanged)), which covers a change that keeps the addresses.
962    ///
963    /// The estimator starts over ([`BandwidthEstimator::on_path_change`]), and the packets sent
964    /// before the change are forgotten: they went into the path that was left, and the
965    /// feedback that reports them missing after a break (every packet sent while the old path
966    /// was already dead) would read as the new path's loss. libwebrtc's feedback adapter
967    /// likewise "only reports packets sent on the new route"
968    /// (`RtpTransportControllerSend::OnNetworkRouteChanged`,
969    /// `TransportFeedbackAdapter::SetNetworkRoute`). The probe clusters in flight go with
970    /// them: their packets are among those forgotten. And probing starts over
971    /// ([`restart_probing`](Self::restart_probing)).
972    ///
973    /// What is sent on the new path before it carries anything to the other end (the two ends
974    /// do not change at the same instant) is in the same case, and a report of it as not
975    /// received is no loss of the new path's either
976    /// ([`History::before_the_path_carried`](crate::rtpfb::history::History::before_the_path_carried)).
977    fn on_new_path(&mut self, now: Instant) {
978        self.estimator.on_path_change(now);
979        self.history.forget_sent();
980        self.probe_packets.clear();
981        self.probe_clusters.clear();
982        self.probe_asked = None;
983        self.restart_probing(now);
984    }
985
986    /// After the estimator started over on a new path: the probe controller starts over from
987    /// the estimator's rate now ([`ProbeController::on_path_change`]). The estimator's fall
988    /// to its starting rate is not a capacity drop to probe after, and the new path's rate is
989    /// looked for as the first path's was.
990    fn restart_probing(&mut self, now: Instant) {
991        let start = self.estimator.target_bitrate();
992        if let Some(probing) = self.probing.as_mut() {
993            probing.on_path_change(now, start);
994        }
995    }
996
997    /// Bits per second sent over the last second.
998    fn sending_rate(&mut self, now: Instant) -> f64 {
999        while let Some((at, _)) = self.sent.front() {
1000            if now.saturating_duration_since(*at) <= Duration::from_secs(1) {
1001                break;
1002            }
1003            self.sent.pop_front();
1004        }
1005        self.sent.iter().map(|(_, size)| *size as f64 * 8.0).sum()
1006    }
1007
1008    /// Sorts the reports of probe packets into their clusters, and gives the estimator the
1009    /// result of every cluster that has been reported in full.
1010    fn collect_probe_reports(&mut self, now: Instant, reports: &[PacketReport]) {
1011        if self.probing.is_none() {
1012            return;
1013        }
1014        for report in reports {
1015            if let Some(cluster) = self
1016                .probe_packets
1017                .remove(&(report.ssrc, report.rtp_sequence_number))
1018                && let Some(state) = self.probe_clusters.get_mut(&cluster)
1019            {
1020                state.reports.push(report.clone());
1021            }
1022        }
1023        // Reported in full, or as far as it will be: a cluster one of whose reports never
1024        // comes (a lost feedback packet) is measured on the others, which `probe_estimate`
1025        // takes when four of them arrived, instead of being given up as a whole.
1026        let complete: Vec<u32> = self
1027            .probe_clusters
1028            .iter()
1029            .filter(|(_, state)| {
1030                state.closed(now)
1031                    && (state.reports.len() >= state.sent
1032                        || now.saturating_duration_since(state.last_sent) >= PROBE_REPORTS_WAIT)
1033            })
1034            .map(|(cluster, _)| *cluster)
1035            .collect();
1036        for cluster in complete {
1037            let Some(state) = self.probe_clusters.remove(&cluster) else {
1038                continue;
1039            };
1040            // A cluster whose packets all left in one instant was not paced (no pacer in
1041            // the chain: the NACK responder's padding): it is measured by how the path
1042            // spread it, up to the rate it was asked for at.
1043            let burst = state
1044                .reports
1045                .first()
1046                .is_some_and(|first| state.reports.iter().all(|r| r.departure == first.departure));
1047            if !state.reports.is_empty()
1048                && let Some(probing) = self.probing.as_mut()
1049            {
1050                probing.set_unpaced(burst);
1051            }
1052            let estimate = if burst {
1053                self.probing
1054                    .as_ref()
1055                    .and_then(|probing| probing.asked_rate(cluster))
1056                    .and_then(|asked| burst_estimate(&state.reports, asked))
1057            } else {
1058                probe_estimate(&state.reports)
1059            };
1060            if let Some(estimate) = estimate
1061                && let Some(probing) = self.probing.as_mut()
1062                && let Some(estimate) = probing.on_result(cluster, estimate)
1063            {
1064                self.estimator.on_probe_result(now, estimate);
1065            }
1066        }
1067        // A cluster whose packets were never all reported is forgotten with its packets.
1068        self.probe_clusters
1069            .retain(|_, state| now.saturating_duration_since(state.last_sent) < PROBE_FORGET);
1070        if self.probe_clusters.is_empty() {
1071            self.probe_packets.clear();
1072        }
1073    }
1074
1075    /// Asks for the next probe cluster when one is due: the request leaves on the read leg,
1076    /// towards the pacer and the NACK responder.
1077    fn poll_probe(&mut self, now: Instant) {
1078        if self.probing.is_none() {
1079            return;
1080        }
1081        // A cluster that no packet left for by the time its result is given up: nothing in
1082        // this chain sends clusters. Asking again would be asking for a result that cannot
1083        // come.
1084        if let Some((cluster, asked)) = self.probe_asked
1085            && now.saturating_duration_since(asked) >= PROBE_RESULT_TIMEOUT
1086        {
1087            self.probe_asked = None;
1088            // Only when the chain is as it was when the cluster was asked for: a stream that
1089            // was bound or started to send since then may carry the next one.
1090            if self.probe_marked != Some(cluster) && !self.probe_chain_changed {
1091                self.probe_unanswered = true;
1092            }
1093        }
1094        if self.probe_unanswered {
1095            return;
1096        }
1097        let target = self.estimator.target_bitrate();
1098        let sending = self.sending_rate(now);
1099        let media_flowing = !self.sent.is_empty();
1100        let usage = self.estimator.usage();
1101        let max = [self.applied_max.flatten(), self.estimator.max_bitrate()]
1102            .into_iter()
1103            .flatten()
1104            .reduce(f64::min)
1105            .unwrap_or(f64::INFINITY);
1106        let Some(probing) = self.probing.as_mut() else {
1107            return;
1108        };
1109        probing.set_max_bitrate(max);
1110        probing.set_usage(usage);
1111        if let Some(request) = probing.poll(now, target, sending, media_flowing) {
1112            self.probe_asked = Some((request.cluster, now));
1113            self.probe_chain_changed = false;
1114            self.read_queue.push_back(request.into_packet(now));
1115        }
1116    }
1117
1118    /// `cluster` left no packet ([`ProbeUnsent`]): it is counted as never asked for, and no
1119    /// cluster is asked for until a stream is bound or sends its first packet (one that can
1120    /// carry it may then be there). A chain that never has one (video without an RTX stream,
1121    /// no pacer) asks once and no more, as it does when a result times out.
1122    fn on_probe_unsent(&mut self, cluster: u32) {
1123        let Some(probing) = self.probing.as_mut() else {
1124            return;
1125        };
1126        if probing.on_unsent(cluster) {
1127            self.probe_asked = None;
1128            self.probe_unanswered = true;
1129        }
1130    }
1131
1132    /// The estimator's floor, to ride with an announced target ([`crate::MinimumTarget`]).
1133    fn minimum_attribute(&self) -> Option<Attribute> {
1134        self.estimator.min_bitrate().map(|bits_per_second| {
1135            Attribute::Custom(std::sync::Arc::new(crate::MinimumTarget {
1136                bits_per_second,
1137            }))
1138        })
1139    }
1140
1141    /// Tells the RTCP session wire-ward the estimate, when it has moved by a twentieth since
1142    /// it was last told ([`CongestionControlBuilder::with_send_rate_told_to_rtcp`]).
1143    fn tell_rtcp(&mut self, now: Instant) {
1144        if !self.send_rate_told_to_rtcp {
1145            return;
1146        }
1147        let target = self.estimator.target_bitrate();
1148        if self
1149            .told_rate
1150            .is_some_and(|told| (target - told).abs() < told * 0.05)
1151        {
1152            return;
1153        }
1154        self.told_rate = Some(target);
1155        self.write_queue.push_back(
1156            crate::RtcpSessionControl::SendRate(target.max(0.0) as u64).into_packet(now),
1157        );
1158    }
1159
1160    /// The estimate as it is, for what application-ward needs the congestion controller's
1161    /// own value: the target that rides beside it is lowered on its way (the retransmission
1162    /// reserve, a pause).
1163    fn estimate_attribute(&self) -> Attribute {
1164        Attribute::Custom(std::sync::Arc::new(SendEstimate {
1165            bits_per_second: self.estimator.target_bitrate(),
1166        }))
1167    }
1168
1169    /// Publish the estimate, and return the attribute to announce when it moved.
1170    fn publish(&mut self) -> Option<Attribute> {
1171        let target = self.estimator.target_bitrate();
1172        {
1173            let mut shared = lock(&self.shared);
1174            shared.target = target;
1175            shared.stats = self.estimator.stats();
1176        }
1177        if self.last_target == Some(target) {
1178            return None;
1179        }
1180        self.last_target = Some(target);
1181        Some(Attribute::TargetBitrateChanged {
1182            bits_per_second: target,
1183        })
1184    }
1185}
1186
1187impl<E: BandwidthEstimator> Protocol<TaggedPacket, TaggedPacket, ()>
1188    for CongestionControlInterceptor<E>
1189{
1190    type Rout = TaggedPacket;
1191    type Wout = TaggedPacket;
1192    type Eout = ();
1193    type Error = Error;
1194    type Time = Instant;
1195
1196    fn handle_read(&mut self, mut msg: TaggedPacket) -> Result<(), Self::Error> {
1197        if msg.message.custom::<crate::PathChanged>().is_some() {
1198            // The peer connection selected another candidate pair. The next inbound packet's
1199            // addresses are the new path's, whatever they are: the address-based detection
1200            // starts from them and does not count the same change a second time.
1201            self.path = None;
1202            self.path_candidate = None;
1203            self.on_new_path(msg.now);
1204        } else if !matches!(&msg.message.packet, Packet::Rtcp(packets) if packets.is_empty()) {
1205            // A packet from the wire, not one of the chain's attribute carriers (an empty
1206            // RTCP packet, which never had an address).
1207            self.observe_path(msg.now, &msg.transport);
1208        }
1209        if let Packet::Rtp(ref rtp_packet) = msg.message.packet {
1210            self.tmmbr_requests.on_rtp(
1211                rtp_packet.header.ssrc,
1212                rtp_packet
1213                    .marshal_size()
1214                    .saturating_sub(rtp_packet.payload.len()),
1215                msg.transport.peer_addr.is_ipv6(),
1216            );
1217        }
1218        let mut reported = false;
1219        if let Packet::Rtcp(ref rtcp_packets) = msg.message.packet {
1220            // `for` over a borrow of `msg` while `self` is borrowed mutably: collect first.
1221            let feedback: Vec<_> = rtcp_packets.to_vec();
1222            for rtcp_packet in &feedback {
1223                reported |= self.ingest(msg.now, rtcp_packet);
1224            }
1225            self.observe_congestion_marks(msg.now, &feedback);
1226        }
1227        if std::mem::take(&mut self.tmmbn_owed) {
1228            self.send_tmmbn(msg.now);
1229        }
1230        self.send_tmmbr(msg.now);
1231
1232        if reported {
1233            self.per_packet_feedback = true;
1234            let reports = self.history.take_reports();
1235            self.estimator.on_reports(msg.now, &reports);
1236            self.collect_probe_reports(msg.now, &reports);
1237        }
1238        self.apply_bounds(msg.now);
1239
1240        // Announced on a change, and once at the start on whatever inbound packet comes first:
1241        // a pacer that only ever heard about changes would run at its own default until the
1242        // estimate first moved, which with no feedback yet is exactly when the estimator's
1243        // cautious starting rate matters.
1244        //
1245        // Onto *this* packet: the pacer is application-ward of here, so it sees this packet
1246        // after this interceptor does and reads the attribute on its way past.
1247        self.tell_rtcp(msg.now);
1248        if let Some(attribute) = self.publish() {
1249            msg.message.add(attribute);
1250            msg.message.add(self.estimate_attribute());
1251            if let Some(minimum) = self.minimum_attribute() {
1252                msg.message.add(minimum);
1253            }
1254        }
1255
1256        self.read_queue.push_back(msg);
1257        Ok(())
1258    }
1259
1260    fn poll_read(&mut self) -> Option<Self::Rout> {
1261        self.read_queue.pop_front()
1262    }
1263
1264    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1265        // The NACK responder had nothing to pad a cluster with, and no pacer sent it: the
1266        // cluster was never sent. Taken out of the chain here, where it was asked for.
1267        if let Some(unsent) = msg.message.custom::<ProbeUnsent>().copied() {
1268            self.on_probe_unsent(unsent.cluster);
1269            return Ok(());
1270        }
1271        if let Some(control) = msg.message.custom::<TmmbrControl>().copied() {
1272            let own_ssrc = self.own_ssrc();
1273            self.tmmbr_requests.on_control(control, own_ssrc);
1274            // The first TMMBR goes at once (RFC 5104 section 4.2.1.3).
1275            self.send_tmmbr(msg.now);
1276        }
1277        if let Packet::Rtp(ref rtp_packet) = msg.message.packet {
1278            let twcc_sequence_number = self.twcc_sequence_number(rtp_packet);
1279            // Only a stream this endpoint is sending is tracked; anything else has no sequence
1280            // space the remote will report against.
1281            if self.streams.contains_key(&rtp_packet.header.ssrc) {
1282                let size = rtp_packet.marshal_size();
1283                self.history.add_outgoing(
1284                    rtp_packet.header.ssrc,
1285                    rtp_packet.header.sequence_number,
1286                    twcc_sequence_number.is_some(),
1287                    twcc_sequence_number.unwrap_or_default(),
1288                    size,
1289                    // The release instant. The pacer has already run on this leg — recording the
1290                    // enqueue instant instead would charge its queueing delay to the network.
1291                    msg.now,
1292                );
1293                if !self.per_packet_feedback {
1294                    self.never_sent
1295                        .entry(rtp_packet.header.ssrc)
1296                        .or_default()
1297                        .on_sent(rtp_packet.header.sequence_number);
1298                }
1299                self.departures.push_back(msg.now);
1300                if self.departures.len() > 4096 {
1301                    self.departures.pop_front();
1302                }
1303                // Only a packet that per-packet feedback will report starts the estimator's
1304                // wait for feedback: audio without transport-wide sequence numbers, sent
1305                // while the video that has them is off, is not "sent and nothing came back".
1306                if self
1307                    .streams
1308                    .get(&rtp_packet.header.ssrc)
1309                    .is_some_and(|stream| stream.feedback.is_some())
1310                {
1311                    self.estimator.on_packet_sent(msg.now, size);
1312                } else {
1313                    self.estimator.on_unreported_packet_sent(msg.now, size);
1314                }
1315
1316                if self.probing.is_some() {
1317                    // Another stream has started to send: a cluster may be answered now
1318                    // where none was (video with its RTX stream after audio alone).
1319                    if self.probe_senders.insert(rtp_packet.header.ssrc) {
1320                        self.probe_unanswered = false;
1321                        self.probe_chain_changed = true;
1322                        // A media stream's first packet is the start of its flow (not one of
1323                        // a repair stream: RTX, FEC).
1324                        if self.local_ssrcs.contains(&rtp_packet.header.ssrc) {
1325                            let target = self.estimator.target_bitrate();
1326                            if let Some(probing) = self.probing.as_mut() {
1327                                probing.on_new_flow(target);
1328                            }
1329                        }
1330                    }
1331                    self.sent.push_back((msg.now, size));
1332                    if self.sent.len() > 4096 {
1333                        self.sent.pop_front();
1334                    }
1335                    // The pacer marked it as part of a cluster: its report is the cluster's.
1336                    // Only a packet per-packet feedback will report is counted: one of a
1337                    // stream without it (audio that negotiated none, leaving while the
1338                    // cluster does) would be waited for and never come.
1339                    if let Some(probe) = msg.message.custom::<ProbePacket>()
1340                        && self
1341                            .streams
1342                            .get(&rtp_packet.header.ssrc)
1343                            .is_some_and(|stream| stream.feedback.is_some())
1344                    {
1345                        self.probe_packets.insert(
1346                            (rtp_packet.header.ssrc, rtp_packet.header.sequence_number),
1347                            probe.cluster,
1348                        );
1349                        let state = self
1350                            .probe_clusters
1351                            .entry(probe.cluster)
1352                            .or_insert_with(|| ProbeCluster::new(msg.now));
1353                        state.sent += 1;
1354                        state.last_sent = msg.now;
1355                        self.probe_marked = Some(probe.cluster);
1356                    }
1357                }
1358            }
1359        }
1360        if matches!(msg.message.packet, Packet::Rtp(_)) {
1361            self.poll_probe(msg.now);
1362        }
1363
1364        self.write_queue.push_back(msg);
1365        Ok(())
1366    }
1367
1368    fn poll_write(&mut self) -> Option<Self::Wout> {
1369        self.write_queue.pop_front()
1370    }
1371
1372    fn handle_timeout(&mut self, now: Instant) -> Result<(), Self::Error> {
1373        self.history
1374            .prune_before(now.checked_sub(self.prune_horizon).unwrap_or(now));
1375
1376        let packet_rate = self.packet_rate(now);
1377        let round_trip_time = self.round_trip_time.unwrap_or_default();
1378        if self.tmmbr.on_timeout(now, packet_rate, round_trip_time) {
1379            // An owner timed out: the bounding set changed and the session is told.
1380            self.send_tmmbn(now);
1381        }
1382
1383        self.send_tmmbr(now);
1384        self.estimator.handle_timeout(now);
1385        self.apply_bounds(now);
1386        self.poll_probe(now);
1387
1388        // No packet to ride on: the estimate leaves on the chain's attribute carrier.
1389        self.tell_rtcp(now);
1390        if let Some(attribute) = self.publish() {
1391            let mut message = AttributedPacket::new(Packet::Rtcp(Vec::new())).with(attribute);
1392            message.add(self.estimate_attribute());
1393            if let Some(minimum) = self.minimum_attribute() {
1394                message.add(minimum);
1395            }
1396            self.read_queue.push_back(TaggedPacket {
1397                now,
1398                transport: shared::TransportContext::default(),
1399                message,
1400            });
1401        }
1402        Ok(())
1403    }
1404
1405    /// Whatever the estimator and the outside limits want, and `None` when they want nothing.
1406    ///
1407    /// This interceptor has no timer of its own: pruning is bounded work that can ride any wake-up,
1408    /// and asking for one on its own account would wake the whole chain on an idle connection.
1409    fn poll_timeout(&mut self) -> Option<Self::Time> {
1410        [
1411            self.estimator.poll_timeout(),
1412            self.tmmbr.poll_timeout(),
1413            self.tmmbr_requests.poll_timeout(),
1414            self.remb.map(|(_, at)| at + REMB_TIMEOUT),
1415            self.probing
1416                .as_ref()
1417                .filter(|_| !self.probe_unanswered)
1418                .and_then(ProbeController::poll_timeout),
1419        ]
1420        .into_iter()
1421        .flatten()
1422        .min()
1423    }
1424}
1425
1426impl<E: BandwidthEstimator> Interceptor for CongestionControlInterceptor<E> {
1427    fn bind_local_stream(&mut self, info: &StreamInfo) {
1428        // Tracked whether or not it negotiated transport-wide CC: RFC 8888 reports against the RTP
1429        // sequence number and needs no extension, so a stream without one is still worth recording.
1430        // The retransmission and FEC SSRCs are recorded with the media SSRC: their packets are
1431        // bytes on the same path, and a history without them reads the path as carrying less
1432        // than it does.
1433        // One feedback format per stream (RFC 8888 section 6): with RFC 8888 negotiated the
1434        // TWCC sender does not number the stream, and no number is looked for.
1435        let feedback = negotiated_congestion_feedback(info);
1436        let tmmbr = stream_negotiated_tmmbr(info);
1437        let hdr_ext_id = if feedback == Some(CongestionFeedbackFormat::TransportCc) {
1438            stream_supports_twcc(info).unwrap_or_default()
1439        } else {
1440            0
1441        };
1442        // Another stream may bring what a probe cluster needs (an RTX stream to pad on).
1443        self.probe_unanswered = false;
1444        self.probe_chain_changed = true;
1445        for ssrc in flow_ssrcs(info) {
1446            self.streams.insert(
1447                ssrc,
1448                LocalStream {
1449                    hdr_ext_id,
1450                    feedback,
1451                    tmmbr,
1452                },
1453            );
1454        }
1455        if !self.local_ssrcs.contains(&info.ssrc) {
1456            self.local_ssrcs.push(info.ssrc);
1457        }
1458    }
1459
1460    fn unbind_local_stream(&mut self, info: &StreamInfo) {
1461        for ssrc in flow_ssrcs(info) {
1462            self.streams.remove(&ssrc);
1463            self.ecn_counters.remove(&ssrc);
1464            self.never_sent.remove(&ssrc);
1465        }
1466        self.local_ssrcs.retain(|ssrc| *ssrc != info.ssrc);
1467    }
1468
1469    /// A remote stream that negotiated `ccm tmmbr` can be asked for a limit
1470    /// ([`TmmbrControl`]); one that did not is never sent a TMMBR (RFC 5104 section 7.2).
1471    fn bind_remote_stream(&mut self, info: &StreamInfo) {
1472        self.tmmbr_requests
1473            .bind(info.ssrc, stream_negotiated_tmmbr(info));
1474    }
1475
1476    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
1477        self.tmmbr_requests.unbind(info.ssrc);
1478    }
1479}