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