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