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