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