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