Skip to main content

rtci_interceptor/gcc/twcc_gcc/
mod.rs

1//! GCC (Google Congestion Control) sender-side bandwidth estimator.
2//!
3//! Reads TWCC feedback packets generated by the remote [`TwccReceiverInterceptor`] and
4//! estimates available send bandwidth with the engine's GCC estimator ([`Gcc`], the one
5//! [`configure_congestion_control`] and the default interceptors run), following
6//! draft-ietf-rmcat-gcc-02
7//! (Holmer et al., "A Google Congestion Control Algorithm for Real-Time Communication").
8//! (RFC 8698 is NADA, a different algorithm, and is not what this implements.)
9//!
10//! What this module adds is the shape: a pull-style [`GccHandle`] an application polls, in a
11//! chain without a pacer. The estimator is the same in both shapes. Until v0.22.0+brainwires.6
12//! this interceptor had an estimator of its own (a trendline filter and one AIMD estimate),
13//! which departed from the draft in three ways that this scenario shows: a link capped at
14//! 300 kbit/s had its estimate cut to the floor by a second of loss and climb back at 8% a
15//! second, over and over.
16//!
17//! - Section 6: the loss-based estimate As_hat is its own ("As long as less than 2% of the
18//!   packets have been lost As_hat(i) will be increased as As_hat(i) = 1.05(As_hat(i-1))",
19//!   "The actual sending rate is set as the minimum between As_hat and A_hat"). The old
20//!   estimator applied the loss cut to the delay-based estimate, which only climbs 8% a second.
21//! - Section 5.5: on over-use "A_hat(i) = beta * R_hat(i)", the received rate. The old one
22//!   multiplied its estimate by 0.85.
23//! - Section 5.5: "A_hat(i) < 1.5 * R_hat(i)". The old one had no such bound: its estimate
24//!   climbed to the maximum whatever was sent. Now the estimate is not increased past the
25//!   bound, and one that is above it is held.
26//!
27//! What an application polling the handle notices: the estimate no longer runs ahead of what
28//! is sent (it is not increased past one and a half times the rate the receiver reports as
29//! arriving); an estimate once reached is kept while the application sends less (audio
30//! alone, a camera turned off), and is lowered by over-use, by loss and by feedback that
31//! stops while packets are sent, which halves it ([`Gcc::with_feedback_timeout`]), and by
32//! nothing else ([`ReceivedRateBound`]); a REMB or a TMMBR from the peer bounds it.
33//!
34//! [`Gcc`]: crate::Gcc
35//! [`Gcc::with_feedback_timeout`]: crate::Gcc::with_feedback_timeout
36//! [`ReceivedRateBound`]: crate::ReceivedRateBound
37//! [`configure_congestion_control`]: https://docs.rs/rtc
38//!
39//! # In a peer connection: use the default interceptors' handle instead
40//!
41//! The `rtci` peer connection's default interceptors already run this estimator; the
42//! supported way to read their target is `register_default_interceptors_with_handles` and
43//! `DefaultInterceptorHandles::congestion_control` ([`CongestionControlHandle::target_bitrate`]).
44//! [`GccInterceptorBuilder`]'s documentation (this module is not public, so that is where
45//! users read it) says what replacing the default controller with a [`GccInterceptor`] loses.
46//!
47//! # Chain position
48//!
49//! GCC must sit **nearer the wire** than [`TwccSenderInterceptor`] so that `handle_write`
50//! sees packets after the TWCC sequence number has already been stamped. Put it in
51//! [`Slot::CongestionControl`](crate::Slot::CongestionControl), below
52//! [`Slot::TwccSender`](crate::Slot::TwccSender):
53//!
54//! ```text
55//! Registry::new()
56//!     .with(Slot::CongestionControl, PassThroughInterceptor::new().with(gcc_builder.build()))
57//!     .with(Slot::TwccSender, TwccSenderBuilder::new().build())
58//! ```
59//!
60//! Writes walk away from the application toward the wire: TwccSender stamps first, then
61//! GCC reads it. TWCC feedback reads reach GCC first, on their way to the application.
62//!
63//! GCC is a nested interceptor, so it needs an inner end: use
64//! [`PassThroughInterceptor`](crate::PassThroughInterceptor), never
65//! [`NoopInterceptor`](crate::NoopInterceptor). The latter is the chain's RTCP terminus; wrapped
66//! in this slot, the first one inbound packets reach, it would end every RTCP packet nothing
67//! marked (NACKs, receiver reports, PLI and FIR) before any other interceptor or the application
68//! saw it.
69//!
70//! # Usage
71//!
72//! [`GccInterceptorBuilder::build`] returns a factory: a closure that takes the inner
73//! interceptor and returns the [`GccInterceptor`] around it. [`Interceptor::with`] applies it
74//! (`inner.with(builder.build())`), and the result goes in a slot like any interceptor. The
75//! compiled example is on [`GccInterceptorBuilder`].
76//!
77//! [`TwccSenderInterceptor`]: crate::TwccSenderInterceptor
78//! [`TwccReceiverInterceptor`]: crate::TwccReceiverInterceptor
79//! [`Interceptor::with`]: crate::Interceptor::with
80
81use crate::cc::estimator::EstimatorStats;
82use crate::cc::interceptor::{
83    CongestionControlBuilder, CongestionControlHandle, CongestionControlInterceptor,
84};
85use crate::gcc::estimator::{DEFAULT_INITIAL_BITRATE, Gcc};
86use crate::gcc::rate_control::ReceivedRateBound;
87use crate::stream_info::StreamInfo;
88use crate::{Interceptor, Packet, TaggedPacket, interceptor};
89use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
90use sansio::Protocol;
91use shared::error::Error;
92use std::marker::PhantomData;
93use std::sync::{Arc, Mutex};
94
95/// Shared state written by [`GccInterceptor`] and read by [`GccHandle`].
96pub struct GccShared {
97    /// The target for the original media, in bits per second: the estimate less the NACK
98    /// responder's retransmission reserve (RFC 4588 section 7). `None` until the first TWCC
99    /// feedback has been processed.
100    pub target_bitrate_bps: Option<u32>,
101    /// Latest estimated available send bandwidth, in bits per second: what the original media
102    /// and the retransmissions share. `None` until the first TWCC feedback has been processed.
103    pub estimate_bps: Option<u32>,
104    /// The retransmission reserve the NACK responder announced last
105    /// ([`RetransmissionReserve`](crate::RetransmissionReserve)), in bits per second.
106    pub retransmission_reserve_bps: f64,
107    /// The estimator's two halves and its smoothed loss.
108    pub stats: EstimatorStats,
109}
110
111impl GccShared {
112    /// The target for the original media: the estimate less the reserve, never under the
113    /// controller's `minimum` (what the application set to carry its media at the least).
114    fn update_target(&mut self, minimum: u32) {
115        self.target_bitrate_bps = self.estimate_bps.map(|estimate| {
116            let lowered = (f64::from(estimate) - self.retransmission_reserve_bps).max(0.0) as u32;
117            lowered.max(minimum.min(estimate))
118        });
119    }
120}
121
122/// Read-only handle to the latest GCC bandwidth estimate.
123///
124/// Clone-able and thread-safe — share freely across application threads.
125#[derive(Clone)]
126pub struct GccHandle {
127    inner: Arc<Mutex<GccShared>>,
128}
129
130impl GccHandle {
131    fn shared(&self) -> std::sync::MutexGuard<'_, GccShared> {
132        self.inner.lock().unwrap_or_else(|e| {
133            log::warn!("gcc: shared mutex poisoned, recovering last estimate");
134            e.into_inner()
135        })
136    }
137
138    /// The target an encoder follows, in bps: the estimate less the retransmission reserve
139    /// the NACK responder holds while it repairs (RFC 4588 section 7: "the sender SHOULD NOT
140    /// send retransmission packets without reducing the packet rate and bitrate of the
141    /// original stream"), never under the minimum bit rate
142    /// ([`GccInterceptorBuilder::with_min_bitrate`]). The estimate itself while nothing is
143    /// being repaired, and in a chain without a NACK responder. `None` if no TWCC feedback has been processed yet.
144    pub fn target_bitrate_bps(&self) -> Option<u32> {
145        self.shared().target_bitrate_bps
146    }
147
148    /// The latest estimated available send bandwidth in bps, which the original media and
149    /// the retransmissions share; `None` if no TWCC feedback has been processed yet.
150    pub fn estimate_bps(&self) -> Option<u32> {
151        self.shared().estimate_bps
152    }
153
154    /// The estimator's two halves (draft-ietf-rmcat-gcc-02 sections 5 and 6: the estimate is
155    /// the lower of the delay-based and the loss-based one), its smoothed loss fraction and
156    /// the round-trip time it works with.
157    pub fn stats(&self) -> EstimatorStats {
158        self.shared().stats
159    }
160}
161
162/// Builder for [`GccInterceptor`], for a chain assembled by hand.
163///
164/// Create with [`GccInterceptorBuilder::new`], which returns `(builder, handle)`;
165/// [`build`](Self::build) returns a factory closure for [`Interceptor::with`].
166///
167/// # In a peer connection: use the default interceptors' handle instead
168///
169/// The `rtci` peer connection's default interceptors already run this estimator ([`Gcc`] in a
170/// [`CongestionControlInterceptor`], one per transport, with the pacer, the circuit breaker
171/// and the behaviour profile's settings). **The supported way to read the target there** is
172/// `rtci`'s `register_default_interceptors_with_handles` (or
173/// `register_default_interceptors_with_options`), which returns `DefaultInterceptorHandles`:
174/// `congestion_control` ([`CongestionControlHandle::target_bitrate`], the first transport's
175/// target; every transport's in `transports`), and per encoding, with the pacer's pause as 0,
176/// `RTCRtpSender::target_bitrates`.
177///
178/// A [`GccInterceptor`] put in [`Slot::CongestionControl`](crate::Slot::CongestionControl)
179/// of that registry replaces the controller registered there (a slot holds one interceptor):
180/// it is then one estimator for every transport, without the circuit breaker link or the
181/// profile's settings (only what this builder sets), and
182/// `DefaultInterceptorHandles::congestion_control` no longer reads a controller in the chain.
183///
184/// # In a chain assembled by hand
185///
186/// Put it in [`Slot::CongestionControl`](crate::Slot::CongestionControl), nearer the wire
187/// than [`Slot::TwccSender`](crate::Slot::TwccSender), around a
188/// [`PassThroughInterceptor`](crate::PassThroughInterceptor) (never a
189/// [`NoopInterceptor`](crate::NoopInterceptor), the chain's RTCP terminus):
190///
191/// ```
192/// use rtci_interceptor::{
193///     GccInterceptorBuilder, Interceptor, PassThroughInterceptor, Registry, Slot,
194///     TwccSenderBuilder,
195/// };
196///
197/// let (gcc_builder, gcc_handle) = GccInterceptorBuilder::new();
198/// let gcc = PassThroughInterceptor::new().with(gcc_builder.with_max_bitrate(1_500_000).build());
199/// let chain = Registry::new()
200///     .with(Slot::CongestionControl, gcc)
201///     .with(Slot::TwccSender, TwccSenderBuilder::new().build())
202///     .build();
203///
204/// // In the application's polling loop: `None` until the first transport-wide feedback.
205/// if let Some(bits_per_second) = gcc_handle.target_bitrate_bps() {
206///     // the encoder's target
207///     # let _ = bits_per_second;
208/// }
209/// # let _ = chain;
210/// ```
211pub struct GccInterceptorBuilder<P> {
212    min_bitrate_bps: u32,
213    max_bitrate_bps: u32,
214    received_rate_bound: ReceivedRateBound,
215    bandwidth_probing: bool,
216    shared: Arc<Mutex<GccShared>>,
217    _phantom: PhantomData<P>,
218}
219
220impl<P> GccInterceptorBuilder<P> {
221    /// Create a new builder and the associated [`GccHandle`].
222    ///
223    /// The handle can be shared with the application so it can read the
224    /// latest bitrate estimate each polling tick.
225    pub fn new() -> (Self, GccHandle) {
226        let shared = Arc::new(Mutex::new(GccShared {
227            target_bitrate_bps: None,
228            estimate_bps: None,
229            retransmission_reserve_bps: 0.0,
230            stats: EstimatorStats::default(),
231        }));
232        let handle = GccHandle {
233            inner: shared.clone(),
234        };
235        let builder = Self {
236            min_bitrate_bps: 30_000,
237            max_bitrate_bps: 2_500_000,
238            received_rate_bound: ReceivedRateBound::default(),
239            bandwidth_probing: true,
240            shared,
241            _phantom: PhantomData,
242        };
243        (builder, handle)
244    }
245
246    /// Minimum send rate floor (default 30 kbps).
247    pub fn with_min_bitrate(mut self, bps: u32) -> Self {
248        self.min_bitrate_bps = bps;
249        self
250    }
251
252    /// Maximum send rate ceiling (default 2.5 Mbps).
253    pub fn with_max_bitrate(mut self, bps: u32) -> Self {
254        self.max_bitrate_bps = bps;
255        self
256    }
257
258    /// What the bound of the estimate by the received rate does to an estimate above it
259    /// ([`Gcc::with_received_rate_bound`](crate::Gcc::with_received_rate_bound)): by default
260    /// it only stops the increase, so the estimate is kept while the application sends less
261    /// than it.
262    pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
263        self.received_rate_bound = received_rate_bound;
264        self
265    }
266
267    /// Whether the path is probed for capacity above the estimate (the default), as the peer
268    /// connection's default interceptors do
269    /// ([`CongestionControlBuilder::with_bandwidth_probing`]): two clusters at the start, at
270    /// three and six times the 300 kbit/s the estimate starts at, and further ones while the
271    /// path carries what is asked, so an open path is found within a second instead of by
272    /// the 8% a second of draft-ietf-rmcat-gcc-02 section 5.5 (300 kbit/s to 2.5 Mbit/s: 28 s).
273    /// RFC 8836 section 2, requirement 4: the algorithm "SHOULD adapt as quickly as possible
274    /// to initial network conditions at the start of a flow".
275    ///
276    /// This chain has no pacer. A cluster is the NACK responder's padding on the RTX stream,
277    /// sent as one burst and measured by how far apart the path delivers it
278    /// ([`burst_estimate`](crate::burst_estimate)); it needs a
279    /// [`NackResponderInterceptor`](crate::NackResponderInterceptor) in the chain and RTX
280    /// negotiated for the stream. Without them no cluster can be sent: the first one asked
281    /// for goes unanswered and no more are asked, and the estimate climbs as the draft has it.
282    /// Clusters are asked for at the start and while the application sends less than the
283    /// target allows; not after a large drop of the target, which a chain with the pacer
284    /// probes too (a burst of padding into the queue that caused the drop costs more than it
285    /// finds: [`ProbeController::set_unpaced`](crate::ProbeController::set_unpaced)).
286    ///
287    /// A call that finds the path's rate at the start meets a later capacity collapse from
288    /// that rate, and loses more at it than one that was still climbing (about twice the
289    /// retransmissions when 2.5 Mbit/s drop to 300 kbit/s; the changelog has the measured
290    /// figures). `with_bandwidth_probing(false)` is the start without probes.
291    pub fn with_bandwidth_probing(mut self, bandwidth_probing: bool) -> Self {
292        self.bandwidth_probing = bandwidth_probing;
293        self
294    }
295
296    /// The interceptor factory: a closure that takes the inner interceptor `P` (a
297    /// [`PassThroughInterceptor`](crate::PassThroughInterceptor), never a
298    /// [`NoopInterceptor`](crate::NoopInterceptor)) and returns the [`GccInterceptor`] around
299    /// it. Apply it with [`Interceptor::with`]:
300    /// `PassThroughInterceptor::new().with(builder.build())`.
301    pub fn build(self) -> impl FnOnce(P) -> GccInterceptor<P> {
302        move |inner| {
303            let (min, max) = (
304                f64::from(self.min_bitrate_bps),
305                f64::from(self.max_bitrate_bps).max(f64::from(self.min_bitrate_bps)),
306            );
307            // The estimate starts at 300 kbit/s, and starts over from there on a new path.
308            let estimator = Gcc::new(DEFAULT_INITIAL_BITRATE, min, max)
309                .with_received_rate_bound(self.received_rate_bound);
310            let (control, handle) = CongestionControlBuilder::new(estimator)
311                .with_bandwidth_probing(self.bandwidth_probing)
312                .build_with_handle();
313            GccInterceptor {
314                inner,
315                control,
316                handle,
317                min_bitrate_bps: self.min_bitrate_bps,
318                fed_back: false,
319                shared: self.shared,
320            }
321        }
322    }
323}
324
325/// Sender-side GCC bandwidth estimator interceptor.
326///
327/// Every outgoing RTP packet (stamped with its transport-wide sequence number) and every
328/// incoming RTCP packet goes through the engine's congestion control interceptor
329/// ([`CongestionControlInterceptor`] around [`Gcc`]); the resulting estimate is written to
330/// the [`GccHandle`] shared state.
331#[derive(Interceptor)]
332pub struct GccInterceptor<P> {
333    #[next]
334    inner: P,
335
336    /// The send history, the feedback ingest and the estimator.
337    control: CongestionControlInterceptor<Gcc>,
338    handle: CongestionControlHandle,
339    /// The estimator's floor.
340    min_bitrate_bps: u32,
341    /// Whether transport-wide feedback has been read (the handle reports nothing before).
342    fed_back: bool,
343
344    /// Shared state — written here, read via [`GccHandle`].
345    shared: Arc<Mutex<GccShared>>,
346}
347
348#[interceptor]
349impl<P: Interceptor> GccInterceptor<P> {
350    /// Outgoing packets pass the controller, which records each RTP packet's size and
351    /// departure under its transport-wide sequence number.
352    ///
353    /// Must be inner to [`TwccSenderInterceptor`](crate::TwccSenderInterceptor) so the sequence number has
354    /// already been stamped by the time this method is called.
355    #[overrides]
356    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
357        // The NACK responder's retransmission reserve, which the target for the original
358        // media leaves out.
359        if let Some(reserve) = msg.message.custom::<crate::RetransmissionReserve>()
360            && reserve.bits_per_second.is_finite()
361        {
362            let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());
363            shared.retransmission_reserve_bps = reserve.bits_per_second.max(0.0);
364            shared.update_target(self.min_bitrate_bps);
365        }
366        self.control.handle_write(msg)?;
367        self.forward()
368    }
369
370    /// Incoming packets pass the controller, which reads the transport-wide feedback (and the
371    /// receiver reports, REMB and TMMBR) and announces the estimate on the packet that moved
372    /// it, so that the NACK responder holds the retransmissions to it (it lowers the
373    /// attribute by its reserve on the way to the application).
374    #[overrides]
375    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
376        if let Packet::Rtcp(ref packets) = msg.message.packet
377            && packets
378                .iter()
379                .any(|packet| packet.as_any().is::<TransportLayerCc>())
380        {
381            self.fed_back = true;
382        }
383        self.control.handle_read(msg)?;
384        self.forward()
385    }
386
387    /// The controller's own deadlines (feedback that stops while packets are sent).
388    #[overrides]
389    fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
390        self.control.handle_timeout(now)?;
391        self.forward()?;
392        self.inner.handle_timeout(now)
393    }
394
395    #[overrides]
396    fn poll_timeout(&mut self) -> Option<Self::Time> {
397        match (self.control.poll_timeout(), self.inner.poll_timeout()) {
398            (Some(a), Some(b)) => Some(a.min(b)),
399            (a, b) => a.or(b),
400        }
401    }
402
403    /// Register a local stream with the controller.
404    #[overrides]
405    fn bind_local_stream(&mut self, info: &StreamInfo) {
406        self.control.bind_local_stream(info);
407        self.inner.bind_local_stream(info);
408    }
409
410    /// Remove a local stream.
411    #[overrides]
412    fn unbind_local_stream(&mut self, info: &StreamInfo) {
413        self.control.unbind_local_stream(info);
414        self.inner.unbind_local_stream(info);
415    }
416
417    #[overrides]
418    fn bind_remote_stream(&mut self, info: &StreamInfo) {
419        self.control.bind_remote_stream(info);
420        self.inner.bind_remote_stream(info);
421    }
422
423    #[overrides]
424    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
425        self.control.unbind_remote_stream(info);
426        self.inner.unbind_remote_stream(info);
427    }
428}
429
430impl<P: Interceptor> GccInterceptor<P> {
431    /// Hands on what the controller let through or made (either way), and publishes its
432    /// estimate to the handle.
433    fn forward(&mut self) -> Result<(), Error> {
434        if self.fed_back {
435            let mut shared = self.shared.lock().unwrap_or_else(|e| {
436                log::warn!("gcc: shared mutex poisoned, recovering to publish estimate");
437                e.into_inner()
438            });
439            shared.estimate_bps = Some(self.handle.target_bitrate() as u32);
440            shared.stats = self.handle.stats();
441            shared.update_target(self.min_bitrate_bps);
442        }
443        while let Some(msg) = self.control.poll_write() {
444            self.inner.handle_write(msg)?;
445        }
446        while let Some(msg) = self.control.poll_read() {
447            self.inner.handle_read(msg)?;
448        }
449        Ok(())
450    }
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use crate::AttributedPacket;
457    use crate::{
458        NoopInterceptor, PassThroughInterceptor, RTPHeaderExtension, Registry, Slot,
459        twcc::TRANSPORT_CC_URI,
460    };
461    use rtcp::transport_feedbacks::transport_layer_cc::{
462        PacketStatusChunk, RecvDelta, RunLengthChunk, StatusChunkTypeTcc, SymbolTypeTcc,
463    };
464    use sansio::Protocol;
465    use shared::{TransportContext, TransportMessage};
466    use std::time::Duration;
467    use std::time::Instant;
468
469    fn stream_info_with_twcc(ssrc: u32) -> StreamInfo {
470        StreamInfo {
471            ssrc,
472            rtp_header_extensions: vec![RTPHeaderExtension {
473                uri: TRANSPORT_CC_URI.to_string(),
474                id: 5,
475            }],
476            ..Default::default()
477        }
478    }
479
480    fn make_rtp(ssrc: u32, rtp_seq: u16, now: Instant) -> TaggedPacket {
481        TransportMessage {
482            now,
483            transport: TransportContext::default(),
484            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
485                header: rtp::header::Header {
486                    ssrc,
487                    sequence_number: rtp_seq,
488                    ..Default::default()
489                },
490                // A packet of a 300 kbit/s stream at fifty packets a second: the estimate
491                // stays within one and a half times what the receiver reports as arriving.
492                payload: bytes::Bytes::from(vec![0u8; 750]),
493            })),
494        }
495    }
496
497    fn make_twcc_feedback(
498        base_seq: u16,
499        recv_times_us: &[i64], // per-packet receive times in microseconds (absolute)
500        now: Instant,
501    ) -> TaggedPacket {
502        let base_recv_us = recv_times_us.first().copied().unwrap_or(0);
503        // reference_time is 24-bit in 64ms units.
504        let reference_time = (base_recv_us / 64_000) as u32;
505        let base_ref_us = reference_time as i64 * 64_000;
506
507        let mut deltas = Vec::new();
508        let mut prev_us = base_ref_us;
509        for &t in recv_times_us {
510            let delta_us = t - prev_us;
511            deltas.push(RecvDelta {
512                type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
513                delta: delta_us,
514            });
515            prev_us = t;
516        }
517
518        let chunk = PacketStatusChunk::RunLengthChunk(RunLengthChunk {
519            type_tcc: StatusChunkTypeTcc::RunLengthChunk,
520            packet_status_symbol: SymbolTypeTcc::PacketReceivedSmallDelta,
521            run_length: recv_times_us.len() as u16,
522        });
523
524        let fb = TransportLayerCc {
525            sender_ssrc: 0,
526            media_ssrc: 0,
527            base_sequence_number: base_seq,
528            packet_status_count: recv_times_us.len() as u16,
529            reference_time,
530            fb_pkt_count: 0,
531            packet_chunks: vec![chunk],
532            recv_deltas: deltas,
533        };
534
535        TransportMessage {
536            now,
537            transport: TransportContext::default(),
538            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
539        }
540    }
541
542    /// Build a chain with TwccSender (outer) → GccInterceptor (inner).
543    ///
544    /// GCC must be inner so `handle_write` sees TWCC-stamped packets.
545    fn make_chain() -> (impl crate::Interceptor, GccHandle) {
546        use crate::TwccSenderBuilder;
547        let (gcc_builder, handle) = GccInterceptorBuilder::new();
548        // GCC sits nearer the wire than TwccSender, so writes are stamped before GCC sees them.
549        let chain = Registry::new()
550            .with(
551                Slot::CongestionControl,
552                PassThroughInterceptor::new().with(gcc_builder.build()),
553            )
554            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
555            .build();
556        (chain, handle)
557    }
558
559    /// The next packet on the read leg that is not a probe request: the feedback. The
560    /// controller's requests come first (each on a carrier of its own: the builder probes by
561    /// default, and the first cluster is asked for with the first packets written).
562    fn next_feedback(chain: &mut impl crate::Interceptor) -> Option<TaggedPacket> {
563        while let Some(read) = chain.poll_read() {
564            if read.message.custom::<crate::ProbeRequest>().is_none() {
565                return Some(read);
566            }
567        }
568        None
569    }
570
571    #[test]
572    fn test_handle_returns_estimate_after_feedback() {
573        let (mut chain, handle) = make_chain();
574        let ssrc = 1001u32;
575        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
576
577        let base = Instant::now();
578        // Send 5 packets; TwccSender will stamp seq 0..4.
579        for i in 0..5u16 {
580            chain
581                .handle_write(make_rtp(
582                    ssrc,
583                    i,
584                    base + Duration::from_millis(i as u64 * 33),
585                ))
586                .unwrap();
587        }
588
589        // Feed back receive times: 33ms inter-packet spacing, 20ms constant one-way delay.
590        // Units: microseconds.  20ms = 20_000µs; spacing 33ms = 33_000µs.
591        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
592
593        chain
594            .handle_read(make_twcc_feedback(
595                0,
596                &recv_us,
597                base + Duration::from_millis(200),
598            ))
599            .unwrap();
600
601        assert!(
602            handle.target_bitrate_bps().is_some(),
603            "should have an estimate after feedback"
604        );
605
606        // The estimate rides out on the feedback packet, so a pacer in the chain follows it.
607        let feedback = next_feedback(&mut chain).expect("the feedback carries on");
608        let announced = match feedback
609            .message
610            .get(&crate::Attribute::TargetBitrateChanged {
611                bits_per_second: 0.0,
612            }) {
613            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
614                Some(*bits_per_second as u32)
615            }
616            _ => None,
617        };
618        assert_eq!(handle.target_bitrate_bps(), announced);
619    }
620
621    /// RFC 4588 section 7: the target the handle reports for the original media is the
622    /// estimate less the retransmission reserve the NACK responder sends down the write leg;
623    /// the estimate itself stays readable, and the feedback announces it unlowered (the
624    /// responder lowers it on its way to the application, a pacer paces at it).
625    #[test]
626    fn the_target_leaves_out_the_retransmission_reserve() {
627        let (mut chain, handle) = make_chain();
628        let ssrc = 1001u32;
629        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
630        let base = Instant::now();
631        for i in 0..5u16 {
632            chain
633                .handle_write(make_rtp(
634                    ssrc,
635                    i,
636                    base + Duration::from_millis(i as u64 * 33),
637                ))
638                .unwrap();
639        }
640        while chain.poll_write().is_some() {}
641        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
642        chain
643            .handle_read(make_twcc_feedback(
644                0,
645                &recv_us,
646                base + Duration::from_millis(200),
647            ))
648            .unwrap();
649        let estimate = handle.estimate_bps().expect("an estimate");
650        assert_eq!(Some(estimate), handle.target_bitrate_bps());
651
652        let reserve = |bits_per_second: f64| TaggedPacket {
653            now: base + Duration::from_millis(250),
654            transport: TransportContext::default(),
655            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(crate::Attribute::Custom(
656                Arc::new(crate::RetransmissionReserve { bits_per_second }),
657            )),
658        };
659        chain.handle_write(reserve(100_000.0)).unwrap();
660        assert_eq!(Some(estimate), handle.estimate_bps());
661        assert_eq!(Some(estimate - 100_000), handle.target_bitrate_bps());
662
663        let announced = next_feedback(&mut chain).and_then(|feedback| {
664            match feedback
665                .message
666                .get(&crate::Attribute::TargetBitrateChanged {
667                    bits_per_second: 0.0,
668                }) {
669                Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
670                    Some(*bits_per_second as u32)
671                }
672                _ => None,
673            }
674        });
675        assert_eq!(
676            Some(estimate),
677            announced,
678            "the feedback carries the estimate"
679        );
680
681        chain.handle_write(reserve(0.0)).unwrap();
682        assert_eq!(Some(estimate), handle.target_bitrate_bps(), "released");
683    }
684
685    /// A new path (inbound packets between new addresses, three in a row: an ICE restart, a
686    /// move to another network) restarts the estimate from the start rate, and the packets
687    /// sent into the old path before it no longer count: twenty lost there and five received
688    /// on the new path are no loss of the new path's (counted, 80 % would cut the estimate to
689    /// 60 %).
690    #[test]
691    fn a_new_path_starts_over_and_the_old_paths_losses_do_not_count() {
692        use rtcp::transport_feedbacks::transport_layer_cc::RecvDelta;
693        let (mut chain, handle) = make_chain();
694        let ssrc = 1001u32;
695        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
696        let base = Instant::now();
697        let at = |ms: u64| base + Duration::from_millis(ms);
698        for i in 0..10u16 {
699            chain
700                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
701                .unwrap();
702        }
703        let recv_us: Vec<i64> = (0..10).map(|i: i64| i * 20_000 + 20_000).collect();
704        chain
705            .handle_read(make_twcc_feedback(0, &recv_us, at(250)))
706            .unwrap();
707        // Into the old path, which is gone.
708        for i in 10..30u16 {
709            chain
710                .handle_write(make_rtp(ssrc, i, at(300 + i as u64 * 20)))
711                .unwrap();
712        }
713        let new_path = TransportContext {
714            local_addr: "10.0.9.1:5000".parse().unwrap(),
715            peer_addr: "10.0.0.2:5000".parse().unwrap(),
716            ..Default::default()
717        };
718        for k in 0..3u64 {
719            chain
720                .handle_read(TaggedPacket {
721                    now: at(1_000 + k),
722                    transport: new_path,
723                    message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
724                        rtcp::receiver_report::ReceiverReport {
725                            ssrc: 42,
726                            ..Default::default()
727                        },
728                    )])),
729                })
730                .unwrap();
731        }
732        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
733        for i in 30..35u16 {
734            chain
735                .handle_write(make_rtp(ssrc, i, at(1_000 + i as u64 * 20)))
736                .unwrap();
737        }
738        while chain.poll_write().is_some() {}
739        while chain.poll_read().is_some() {}
740        // Feedback on the new path: 10..29 lost, 30..34 received 20 ms apart.
741        let reference_time = (1_600_000i64 / 64_000) as u32;
742        let mut recv = reference_time as i64 * 64_000;
743        let deltas = (0..5)
744            .map(|k| {
745                let t = 1_620_000 + k * 20_000;
746                let delta = t - recv;
747                recv = t;
748                RecvDelta {
749                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
750                    delta,
751                }
752            })
753            .collect();
754        let run = |symbol, run_length| {
755            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
756                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
757                packet_status_symbol: symbol,
758                run_length,
759            })
760        };
761        let fb = TransportLayerCc {
762            base_sequence_number: 10,
763            packet_status_count: 25,
764            reference_time,
765            packet_chunks: vec![
766                run(SymbolTypeTcc::PacketNotReceived, 20),
767                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
768            ],
769            recv_deltas: deltas,
770            ..Default::default()
771        };
772        chain
773            .handle_read(TaggedPacket {
774                now: at(1_800),
775                transport: new_path,
776                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
777            })
778            .unwrap();
779        let estimate = handle.estimate_bps().unwrap();
780        assert!(
781            estimate >= 300_000,
782            "cut to {estimate} for the old path's losses"
783        );
784    }
785
786    /// The peer connection's word that it selected another candidate pair
787    /// ([`crate::PathChanged`]) is a new path also when every packet keeps its addresses (a
788    /// TURN relay that keeps them, an application that hands datagrams over with one
789    /// placeholder pair): the estimate starts over from the start rate, announced on the
790    /// carrier for a pacer, and twenty packets sent into the old path before it are no loss of
791    /// the new path's (counted, 80 % would cut the estimate to 60 %).
792    #[test]
793    fn the_peer_connections_path_change_starts_over_with_the_same_addresses() {
794        let (mut chain, handle) = make_chain();
795        let ssrc = 1001u32;
796        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
797        let base = Instant::now();
798        let at = |ms: u64| base + Duration::from_millis(ms);
799        for i in 0..10u16 {
800            chain
801                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
802                .unwrap();
803        }
804        // Climb a while above the start rate, on feedback of a clean path.
805        let mut next = 10u16;
806        for round in 0..30u64 {
807            let first = next - 10;
808            let recv_us: Vec<i64> = (0..10)
809                .map(|k: i64| (round as i64 * 200_000) + k * 20_000 + 20_000)
810                .collect();
811            chain
812                .handle_read(make_twcc_feedback(first, &recv_us, at(round * 200 + 250)))
813                .unwrap();
814            for i in next..next + 10 {
815                chain
816                    .handle_write(make_rtp(
817                        ssrc,
818                        i,
819                        at((round + 1) * 200 + (i - next) as u64 * 20),
820                    ))
821                    .unwrap();
822            }
823            next += 10;
824        }
825        while chain.poll_write().is_some() {}
826        while chain.poll_read().is_some() {}
827        let climbed = handle.estimate_bps().unwrap();
828        assert!(climbed > 300_000, "climbed to {climbed}");
829        // Packets `next - 10 .. next + 20` go into the old path, which is gone.
830        for i in next..next + 20 {
831            chain
832                .handle_write(make_rtp(ssrc, i, at(6_400 + (i - next) as u64 * 20)))
833                .unwrap();
834        }
835        let lost_from = next - 10;
836        next += 20;
837        chain
838            .handle_read(crate::PathChanged.into_packet(at(7_000), None))
839            .unwrap();
840        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
841        let carrier = chain.poll_read().expect("the carrier goes on");
842        assert!(carrier.message.custom::<crate::PathChanged>().is_some());
843        let announced = match carrier
844            .message
845            .get(&crate::Attribute::TargetBitrateChanged {
846                bits_per_second: 0.0,
847            }) {
848            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
849                Some(*bits_per_second as u32)
850            }
851            _ => None,
852        };
853        assert_eq!(Some(300_000), announced, "announced for a pacer");
854        for i in next..next + 5 {
855            chain
856                .handle_write(make_rtp(ssrc, i, at(7_000 + (i - next) as u64 * 20)))
857                .unwrap();
858        }
859        while chain.poll_write().is_some() {}
860        // Feedback on the new path, on the same addresses as ever: the thirty packets of the
861        // old path lost, the five of the new one received 20 ms apart.
862        let reference_time = (7_600_000i64 / 64_000) as u32;
863        let mut recv = reference_time as i64 * 64_000;
864        let deltas = (0..5)
865            .map(|k| {
866                let t = 7_620_000 + k * 20_000;
867                let delta = t - recv;
868                recv = t;
869                RecvDelta {
870                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
871                    delta,
872                }
873            })
874            .collect();
875        let run = |symbol, run_length| {
876            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
877                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
878                packet_status_symbol: symbol,
879                run_length,
880            })
881        };
882        let fb = TransportLayerCc {
883            base_sequence_number: lost_from,
884            packet_status_count: 35,
885            reference_time,
886            packet_chunks: vec![
887                run(SymbolTypeTcc::PacketNotReceived, 30),
888                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
889            ],
890            recv_deltas: deltas,
891            ..Default::default()
892        };
893        chain
894            .handle_read(TaggedPacket {
895                now: at(7_800),
896                transport: TransportContext::default(),
897                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
898            })
899            .unwrap();
900        let estimate = handle.estimate_bps().unwrap();
901        assert!(
902            estimate >= 300_000,
903            "cut to {estimate} for the old path's losses"
904        );
905    }
906
907    /// The two ends do not take a new path into use at the same instant: what this endpoint
908    /// sends after its own change and before the path carries media to the other end (here a
909    /// burst of twenty-four packets, a probe cluster's worth) is lost, and is no loss of the
910    /// new path's either. Counted, twenty-four of the first thirty-nine packets would lower
911    /// the estimate that has just started over (the loss-based controller's 10 %). A packet
912    /// lost after one that arrived is a loss as ever
913    /// (`rtpfb::history::tests::a_loss_before_anything_arrived_on_a_new_path_is_not_reported`).
914    #[test]
915    fn packets_sent_before_a_new_path_carried_anything_are_not_its_loss() {
916        let feedback = |base_sequence_number: u16, lost: u16, received_us: &[i64], now| {
917            let reference_time = (received_us[0] / 64_000) as u32;
918            let mut recv = reference_time as i64 * 64_000;
919            let recv_deltas = received_us
920                .iter()
921                .map(|t| {
922                    let delta = t - recv;
923                    recv = *t;
924                    RecvDelta {
925                        type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
926                        delta,
927                    }
928                })
929                .collect();
930            let run = |symbol, run_length| {
931                PacketStatusChunk::RunLengthChunk(RunLengthChunk {
932                    type_tcc: StatusChunkTypeTcc::RunLengthChunk,
933                    packet_status_symbol: symbol,
934                    run_length,
935                })
936            };
937            let mut packet_chunks = Vec::new();
938            if lost > 0 {
939                packet_chunks.push(run(SymbolTypeTcc::PacketNotReceived, lost));
940            }
941            packet_chunks.push(run(
942                SymbolTypeTcc::PacketReceivedSmallDelta,
943                received_us.len() as u16,
944            ));
945            TaggedPacket {
946                now,
947                transport: TransportContext::default(),
948                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(TransportLayerCc {
949                    base_sequence_number,
950                    packet_status_count: lost + received_us.len() as u16,
951                    reference_time,
952                    packet_chunks,
953                    recv_deltas,
954                    ..Default::default()
955                })])),
956            }
957        };
958        // The estimate after the first feedback on the new path, and after the next one,
959        // which makes the losses the first one named final.
960        let (before, after) = {
961            let (mut chain, handle) = make_chain();
962            let ssrc = 1001u32;
963            chain.bind_local_stream(&stream_info_with_twcc(ssrc));
964            let base = Instant::now();
965            let at = |ms: u64| base + Duration::from_millis(ms);
966            // A clean path first, so that the loss average is zero as after a call's start.
967            for i in 0..10u16 {
968                chain
969                    .handle_write(make_rtp(ssrc, i, at(u64::from(i) * 20)))
970                    .unwrap();
971            }
972            let recv_us: Vec<i64> = (0..10).map(|k: i64| k * 20_000 + 20_000).collect();
973            chain
974                .handle_read(make_twcc_feedback(0, &recv_us, at(250)))
975                .unwrap();
976            chain
977                .handle_read(crate::PathChanged.into_packet(at(7_000), None))
978                .unwrap();
979            // 10..34 at the instant of the change: the path does not carry them.
980            for i in 10..34u16 {
981                chain.handle_write(make_rtp(ssrc, i, at(7_000))).unwrap();
982            }
983            // 34..42 arrive.
984            for i in 34..42u16 {
985                chain
986                    .handle_write(make_rtp(ssrc, i, at(7_010 + u64::from(i - 34) * 20)))
987                    .unwrap();
988            }
989            while chain.poll_write().is_some() {}
990            let received: Vec<i64> = (0..8).map(|k: i64| 7_030_000 + k * 20_000).collect();
991            chain
992                .handle_read(feedback(10, 24, &received, at(7_250)))
993                .unwrap();
994            let before = handle.estimate_bps().unwrap();
995            // 42..57 arrive: the feedback after which the losses the first one named are
996            // final.
997            for i in 42..57u16 {
998                chain
999                    .handle_write(make_rtp(ssrc, i, at(7_200 + u64::from(i - 42) * 20)))
1000                    .unwrap();
1001            }
1002            while chain.poll_write().is_some() {}
1003            let received: Vec<i64> = (0..15).map(|k: i64| 7_220_000 + k * 20_000).collect();
1004            chain
1005                .handle_read(feedback(42, 0, &received, at(7_550)))
1006                .unwrap();
1007            (before, handle.estimate_bps().unwrap())
1008        };
1009        assert!(before >= 300_000, "{before}");
1010        assert!(
1011            after >= before,
1012            "cut from {before} to {after} for packets sent before the path carried anything"
1013        );
1014    }
1015
1016    /// The target rides with the controller's minimum (`MinimumTarget`), so the NACK
1017    /// responder knows where the original media cannot be lowered further.
1018    #[test]
1019    fn the_target_carries_the_controllers_minimum() {
1020        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
1021        let mut chain = Registry::new()
1022            .with(
1023                Slot::CongestionControl,
1024                PassThroughInterceptor::new().with(gcc_builder.with_min_bitrate(123_000).build()),
1025            )
1026            .with(Slot::TwccSender, crate::TwccSenderBuilder::new().build())
1027            .build();
1028        let ssrc = 1001u32;
1029        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
1030        let base = Instant::now();
1031        for i in 0..5u16 {
1032            chain
1033                .handle_write(make_rtp(
1034                    ssrc,
1035                    i,
1036                    base + Duration::from_millis(i as u64 * 33),
1037                ))
1038                .unwrap();
1039        }
1040        while chain.poll_write().is_some() {}
1041        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
1042        chain
1043            .handle_read(make_twcc_feedback(
1044                0,
1045                &recv_us,
1046                base + Duration::from_millis(200),
1047            ))
1048            .unwrap();
1049        let feedback = next_feedback(&mut chain).expect("the feedback carries on");
1050        assert_eq!(
1051            Some(&crate::MinimumTarget {
1052                bits_per_second: 123_000.0
1053            }),
1054            feedback.message.custom::<crate::MinimumTarget>()
1055        );
1056    }
1057
1058    #[test]
1059    fn test_no_estimate_before_feedback() {
1060        let (mut chain, handle) = make_chain();
1061        let ssrc = 2001u32;
1062        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
1063        chain
1064            .handle_write(make_rtp(ssrc, 0, Instant::now()))
1065            .unwrap();
1066        // No feedback yet.
1067        assert!(handle.target_bitrate_bps().is_none());
1068    }
1069
1070    #[test]
1071    fn test_non_twcc_rtcp_passes_through() {
1072        let (mut chain, handle) = make_chain();
1073        let rtcp_pkt = TransportMessage {
1074            now: Instant::now(),
1075            transport: TransportContext::default(),
1076            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1077                rtcp::receiver_report::ReceiverReport {
1078                    ssrc: 42,
1079                    ..Default::default()
1080                },
1081            )])),
1082        };
1083        // Should not panic; non-TWCC RTCP is forwarded.
1084        chain.handle_read(rtcp_pkt).unwrap();
1085        assert!(handle.target_bitrate_bps().is_none());
1086    }
1087
1088    #[test]
1089    fn test_unbind_removes_stream() {
1090        let (mut chain, _handle) = make_chain();
1091        let ssrc = 3001u32;
1092        let info = stream_info_with_twcc(ssrc);
1093        chain.bind_local_stream(&info);
1094        chain.unbind_remote_stream(&info); // unbind (remote stream - no-op here)
1095        chain.unbind_local_stream(&info);
1096        // No panic — stream was removed cleanly.
1097    }
1098
1099    #[test]
1100    fn test_send_time_not_recorded_without_twcc_ext() {
1101        // RTP sent on an SSRC not bound with TWCC should not populate send_times.
1102        let (mut chain, _handle) = make_chain();
1103        let ssrc = 4001u32;
1104        // Bind WITHOUT TWCC ext.
1105        let info = StreamInfo {
1106            ssrc,
1107            rtp_header_extensions: vec![],
1108            ..Default::default()
1109        };
1110        chain.bind_local_stream(&info);
1111        // Just verify no panic and no estimate without TWCC feedback.
1112        chain
1113            .handle_write(make_rtp(ssrc, 1, Instant::now()))
1114            .unwrap();
1115    }
1116
1117    #[test]
1118    fn test_builder_custom_bitrate_bounds() {
1119        let (builder, _handle) = GccInterceptorBuilder::<()>::new();
1120        let builder = builder
1121            .with_min_bitrate(100_000)
1122            .with_max_bitrate(5_000_000);
1123        assert_eq!(builder.min_bitrate_bps, 100_000);
1124        assert_eq!(builder.max_bitrate_bps, 5_000_000);
1125    }
1126
1127    #[test]
1128    fn test_gcc_handle_clone_shares_state() {
1129        let (_builder, handle) = GccInterceptorBuilder::<()>::new();
1130        let handle2 = handle.clone();
1131        assert!(handle.target_bitrate_bps().is_none());
1132        assert!(handle2.target_bitrate_bps().is_none());
1133        // Write through the shared mutex.
1134        handle.inner.lock().unwrap().estimate_bps = Some(500_000);
1135        handle.inner.lock().unwrap().update_target(0);
1136        assert_eq!(handle2.target_bitrate_bps(), Some(500_000));
1137    }
1138
1139    /// Counts the inbound RTCP packets that reach its slot and passes everything on.
1140    #[derive(Default)]
1141    struct RtcpSeen {
1142        seen: std::sync::Arc<std::sync::atomic::AtomicUsize>,
1143        reads: std::collections::VecDeque<TaggedPacket>,
1144        writes: std::collections::VecDeque<TaggedPacket>,
1145    }
1146
1147    impl sansio::Protocol<TaggedPacket, TaggedPacket, ()> for RtcpSeen {
1148        type Rout = TaggedPacket;
1149        type Wout = TaggedPacket;
1150        type Eout = ();
1151        type Error = shared::error::Error;
1152        type Time = Instant;
1153
1154        fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1155            if matches!(msg.message.packet, Packet::Rtcp(_)) {
1156                self.seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1157            }
1158            self.reads.push_back(msg);
1159            Ok(())
1160        }
1161        fn poll_read(&mut self) -> Option<TaggedPacket> {
1162            self.reads.pop_front()
1163        }
1164        fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
1165            self.writes.push_back(msg);
1166            Ok(())
1167        }
1168        fn poll_write(&mut self) -> Option<TaggedPacket> {
1169            self.writes.pop_front()
1170        }
1171    }
1172
1173    impl crate::Interceptor for RtcpSeen {
1174        fn bind_local_stream(&mut self, _info: &StreamInfo) {}
1175        fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
1176        fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
1177        fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
1178    }
1179
1180    fn pli() -> TaggedPacket {
1181        use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
1182        TaggedPacket {
1183            now: Instant::now(),
1184            transport: TransportContext::default(),
1185            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(PictureLossIndication {
1186                sender_ssrc: 1,
1187                media_ssrc: 1001,
1188            })])),
1189        }
1190    }
1191
1192    /// GCC in its slot around `inner`, an RTCP observer application-ward of it, and the
1193    /// key-frame request interceptor that delivers PLI to the application. Returns how many
1194    /// inbound RTCP packets the observer saw and how many packets the application read.
1195    fn pli_through_gcc_slot<I: crate::Interceptor + 'static>(inner: I) -> (usize, usize) {
1196        use crate::{KeyFrameRequestInterceptor, TwccSenderBuilder};
1197        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
1198        let observer = RtcpSeen::default();
1199        let seen = observer.seen.clone();
1200        let mut chain = Registry::new()
1201            .with(Slot::CongestionControl, inner.with(gcc_builder.build()))
1202            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
1203            .with(Slot::from(3_500), observer)
1204            .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
1205            .build();
1206        // The first inbound packet carries the starting estimate for the chain (an attribute:
1207        // a terminus passes a marked packet on); the key-frame request comes after it.
1208        chain
1209            .handle_read(TaggedPacket {
1210                now: Instant::now(),
1211                transport: TransportContext::default(),
1212                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1213                    rtcp::receiver_report::ReceiverReport {
1214                        ssrc: 42,
1215                        ..Default::default()
1216                    },
1217                )])),
1218            })
1219            .unwrap();
1220        while chain.poll_read().is_some() {}
1221        let before = seen.load(std::sync::atomic::Ordering::SeqCst);
1222        chain.handle_read(pli()).unwrap();
1223        let mut delivered = 0;
1224        while chain.poll_read().is_some() {
1225            delivered += 1;
1226        }
1227        (
1228            seen.load(std::sync::atomic::Ordering::SeqCst) - before,
1229            delivered,
1230        )
1231    }
1232
1233    /// With GCC registered the documented way (around a pass-through), inbound RTCP GCC doesn't
1234    /// consume reaches the interceptors after its slot, and a key-frame request reaches the
1235    /// application.
1236    #[test]
1237    fn rtcp_passes_the_gcc_slot() {
1238        assert_eq!(
1239            (1, 1),
1240            pli_through_gcc_slot(PassThroughInterceptor::new()),
1241            "the observer saw the PLI and the application read it"
1242        );
1243    }
1244
1245    /// Why the inner end must not be the terminus: around `NoopInterceptor` (the recipe this
1246    /// module used to document), the PLI ends in GCC's slot, the first one it reaches.
1247    #[test]
1248    fn noop_inside_the_gcc_slot_ends_rtcp_there() {
1249        assert_eq!((0, 0), pli_through_gcc_slot(NoopInterceptor::new()));
1250    }
1251}