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    shared: Arc<Mutex<GccShared>>,
174    _phantom: PhantomData<P>,
175}
176
177impl<P> GccInterceptorBuilder<P> {
178    /// Create a new builder and the associated [`GccHandle`].
179    ///
180    /// The handle can be shared with the application so it can read the
181    /// latest bitrate estimate each polling tick.
182    pub fn new() -> (Self, GccHandle) {
183        let shared = Arc::new(Mutex::new(GccShared {
184            target_bitrate_bps: None,
185            estimate_bps: None,
186            retransmission_reserve_bps: 0.0,
187            stats: EstimatorStats::default(),
188        }));
189        let handle = GccHandle {
190            inner: shared.clone(),
191        };
192        let builder = Self {
193            min_bitrate_bps: 30_000,
194            max_bitrate_bps: 2_500_000,
195            received_rate_bound: ReceivedRateBound::default(),
196            shared,
197            _phantom: PhantomData,
198        };
199        (builder, handle)
200    }
201
202    /// Minimum send rate floor (default 30 kbps).
203    pub fn with_min_bitrate(mut self, bps: u32) -> Self {
204        self.min_bitrate_bps = bps;
205        self
206    }
207
208    /// Maximum send rate ceiling (default 2.5 Mbps).
209    pub fn with_max_bitrate(mut self, bps: u32) -> Self {
210        self.max_bitrate_bps = bps;
211        self
212    }
213
214    /// What the bound of the estimate by the received rate does to an estimate above it
215    /// ([`Gcc::with_received_rate_bound`](crate::Gcc::with_received_rate_bound)): by default
216    /// it only stops the increase, so the estimate is kept while the application sends less
217    /// than it.
218    pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
219        self.received_rate_bound = received_rate_bound;
220        self
221    }
222
223    /// Build the interceptor factory closure.
224    pub fn build(self) -> impl FnOnce(P) -> GccInterceptor<P> {
225        move |inner| {
226            let (min, max) = (
227                f64::from(self.min_bitrate_bps),
228                f64::from(self.max_bitrate_bps).max(f64::from(self.min_bitrate_bps)),
229            );
230            // The estimate starts at 300 kbit/s, and starts over from there on a new path.
231            let estimator = Gcc::new(DEFAULT_INITIAL_BITRATE, min, max)
232                .with_received_rate_bound(self.received_rate_bound);
233            let (control, handle) = CongestionControlBuilder::new(estimator).build_with_handle();
234            GccInterceptor {
235                inner,
236                control,
237                handle,
238                min_bitrate_bps: self.min_bitrate_bps,
239                fed_back: false,
240                shared: self.shared,
241            }
242        }
243    }
244}
245
246/// Sender-side GCC bandwidth estimator interceptor.
247///
248/// Every outgoing RTP packet (stamped with its transport-wide sequence number) and every
249/// incoming RTCP packet goes through the engine's congestion control interceptor
250/// ([`CongestionControlInterceptor`] around [`Gcc`]); the resulting estimate is written to
251/// the [`GccHandle`] shared state.
252#[derive(Interceptor)]
253pub struct GccInterceptor<P> {
254    #[next]
255    inner: P,
256
257    /// The send history, the feedback ingest and the estimator.
258    control: CongestionControlInterceptor<Gcc>,
259    handle: CongestionControlHandle,
260    /// The estimator's floor.
261    min_bitrate_bps: u32,
262    /// Whether transport-wide feedback has been read (the handle reports nothing before).
263    fed_back: bool,
264
265    /// Shared state — written here, read via [`GccHandle`].
266    shared: Arc<Mutex<GccShared>>,
267}
268
269#[interceptor]
270impl<P: Interceptor> GccInterceptor<P> {
271    /// Outgoing packets pass the controller, which records each RTP packet's size and
272    /// departure under its transport-wide sequence number.
273    ///
274    /// Must be inner to [`TwccSenderInterceptor`](crate::TwccSenderInterceptor) so the sequence number has
275    /// already been stamped by the time this method is called.
276    #[overrides]
277    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
278        // The NACK responder's retransmission reserve, which the target for the original
279        // media leaves out.
280        if let Some(reserve) = msg.message.custom::<crate::RetransmissionReserve>()
281            && reserve.bits_per_second.is_finite()
282        {
283            let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());
284            shared.retransmission_reserve_bps = reserve.bits_per_second.max(0.0);
285            shared.update_target(self.min_bitrate_bps);
286        }
287        self.control.handle_write(msg)?;
288        self.forward()
289    }
290
291    /// Incoming packets pass the controller, which reads the transport-wide feedback (and the
292    /// receiver reports, REMB and TMMBR) and announces the estimate on the packet that moved
293    /// it, so that the NACK responder holds the retransmissions to it (it lowers the
294    /// attribute by its reserve on the way to the application).
295    #[overrides]
296    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
297        if let Packet::Rtcp(ref packets) = msg.message.packet
298            && packets
299                .iter()
300                .any(|packet| packet.as_any().is::<TransportLayerCc>())
301        {
302            self.fed_back = true;
303        }
304        self.control.handle_read(msg)?;
305        self.forward()
306    }
307
308    /// The controller's own deadlines (feedback that stops while packets are sent).
309    #[overrides]
310    fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
311        self.control.handle_timeout(now)?;
312        self.forward()?;
313        self.inner.handle_timeout(now)
314    }
315
316    #[overrides]
317    fn poll_timeout(&mut self) -> Option<Self::Time> {
318        match (self.control.poll_timeout(), self.inner.poll_timeout()) {
319            (Some(a), Some(b)) => Some(a.min(b)),
320            (a, b) => a.or(b),
321        }
322    }
323
324    /// Register a local stream with the controller.
325    #[overrides]
326    fn bind_local_stream(&mut self, info: &StreamInfo) {
327        self.control.bind_local_stream(info);
328        self.inner.bind_local_stream(info);
329    }
330
331    /// Remove a local stream.
332    #[overrides]
333    fn unbind_local_stream(&mut self, info: &StreamInfo) {
334        self.control.unbind_local_stream(info);
335        self.inner.unbind_local_stream(info);
336    }
337
338    #[overrides]
339    fn bind_remote_stream(&mut self, info: &StreamInfo) {
340        self.control.bind_remote_stream(info);
341        self.inner.bind_remote_stream(info);
342    }
343
344    #[overrides]
345    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
346        self.control.unbind_remote_stream(info);
347        self.inner.unbind_remote_stream(info);
348    }
349}
350
351impl<P: Interceptor> GccInterceptor<P> {
352    /// Hands on what the controller let through or made (either way), and publishes its
353    /// estimate to the handle.
354    fn forward(&mut self) -> Result<(), Error> {
355        if self.fed_back {
356            let mut shared = self.shared.lock().unwrap_or_else(|e| {
357                log::warn!("gcc: shared mutex poisoned, recovering to publish estimate");
358                e.into_inner()
359            });
360            shared.estimate_bps = Some(self.handle.target_bitrate() as u32);
361            shared.stats = self.handle.stats();
362            shared.update_target(self.min_bitrate_bps);
363        }
364        while let Some(msg) = self.control.poll_write() {
365            self.inner.handle_write(msg)?;
366        }
367        while let Some(msg) = self.control.poll_read() {
368            self.inner.handle_read(msg)?;
369        }
370        Ok(())
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::AttributedPacket;
378    use crate::{
379        NoopInterceptor, PassThroughInterceptor, RTPHeaderExtension, Registry, Slot,
380        twcc::TRANSPORT_CC_URI,
381    };
382    use rtcp::transport_feedbacks::transport_layer_cc::{
383        PacketStatusChunk, RecvDelta, RunLengthChunk, StatusChunkTypeTcc, SymbolTypeTcc,
384    };
385    use sansio::Protocol;
386    use shared::{TransportContext, TransportMessage};
387    use std::time::Duration;
388    use std::time::Instant;
389
390    fn stream_info_with_twcc(ssrc: u32) -> StreamInfo {
391        StreamInfo {
392            ssrc,
393            rtp_header_extensions: vec![RTPHeaderExtension {
394                uri: TRANSPORT_CC_URI.to_string(),
395                id: 5,
396            }],
397            ..Default::default()
398        }
399    }
400
401    fn make_rtp(ssrc: u32, rtp_seq: u16, now: Instant) -> TaggedPacket {
402        TransportMessage {
403            now,
404            transport: TransportContext::default(),
405            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
406                header: rtp::header::Header {
407                    ssrc,
408                    sequence_number: rtp_seq,
409                    ..Default::default()
410                },
411                // A packet of a 300 kbit/s stream at fifty packets a second: the estimate
412                // stays within one and a half times what the receiver reports as arriving.
413                payload: bytes::Bytes::from(vec![0u8; 750]),
414            })),
415        }
416    }
417
418    fn make_twcc_feedback(
419        base_seq: u16,
420        recv_times_us: &[i64], // per-packet receive times in microseconds (absolute)
421        now: Instant,
422    ) -> TaggedPacket {
423        let base_recv_us = recv_times_us.first().copied().unwrap_or(0);
424        // reference_time is 24-bit in 64ms units.
425        let reference_time = (base_recv_us / 64_000) as u32;
426        let base_ref_us = reference_time as i64 * 64_000;
427
428        let mut deltas = Vec::new();
429        let mut prev_us = base_ref_us;
430        for &t in recv_times_us {
431            let delta_us = t - prev_us;
432            deltas.push(RecvDelta {
433                type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
434                delta: delta_us,
435            });
436            prev_us = t;
437        }
438
439        let chunk = PacketStatusChunk::RunLengthChunk(RunLengthChunk {
440            type_tcc: StatusChunkTypeTcc::RunLengthChunk,
441            packet_status_symbol: SymbolTypeTcc::PacketReceivedSmallDelta,
442            run_length: recv_times_us.len() as u16,
443        });
444
445        let fb = TransportLayerCc {
446            sender_ssrc: 0,
447            media_ssrc: 0,
448            base_sequence_number: base_seq,
449            packet_status_count: recv_times_us.len() as u16,
450            reference_time,
451            fb_pkt_count: 0,
452            packet_chunks: vec![chunk],
453            recv_deltas: deltas,
454        };
455
456        TransportMessage {
457            now,
458            transport: TransportContext::default(),
459            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
460        }
461    }
462
463    /// Build a chain with TwccSender (outer) → GccInterceptor (inner).
464    ///
465    /// GCC must be inner so `handle_write` sees TWCC-stamped packets.
466    fn make_chain() -> (impl crate::Interceptor, GccHandle) {
467        use crate::TwccSenderBuilder;
468        let (gcc_builder, handle) = GccInterceptorBuilder::new();
469        // GCC sits nearer the wire than TwccSender, so writes are stamped before GCC sees them.
470        let chain = Registry::new()
471            .with(
472                Slot::CongestionControl,
473                PassThroughInterceptor::new().with(gcc_builder.build()),
474            )
475            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
476            .build();
477        (chain, handle)
478    }
479
480    #[test]
481    fn test_handle_returns_estimate_after_feedback() {
482        let (mut chain, handle) = make_chain();
483        let ssrc = 1001u32;
484        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
485
486        let base = Instant::now();
487        // Send 5 packets; TwccSender will stamp seq 0..4.
488        for i in 0..5u16 {
489            chain
490                .handle_write(make_rtp(
491                    ssrc,
492                    i,
493                    base + Duration::from_millis(i as u64 * 33),
494                ))
495                .unwrap();
496        }
497
498        // Feed back receive times: 33ms inter-packet spacing, 20ms constant one-way delay.
499        // Units: microseconds.  20ms = 20_000µs; spacing 33ms = 33_000µs.
500        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
501
502        chain
503            .handle_read(make_twcc_feedback(
504                0,
505                &recv_us,
506                base + Duration::from_millis(200),
507            ))
508            .unwrap();
509
510        assert!(
511            handle.target_bitrate_bps().is_some(),
512            "should have an estimate after feedback"
513        );
514
515        // The estimate rides out on the feedback packet, so a pacer in the chain follows it.
516        let feedback = chain.poll_read().expect("the feedback carries on");
517        let announced = match feedback
518            .message
519            .get(&crate::Attribute::TargetBitrateChanged {
520                bits_per_second: 0.0,
521            }) {
522            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
523                Some(*bits_per_second as u32)
524            }
525            _ => None,
526        };
527        assert_eq!(handle.target_bitrate_bps(), announced);
528    }
529
530    /// RFC 4588 section 7: the target the handle reports for the original media is the
531    /// estimate less the retransmission reserve the NACK responder sends down the write leg;
532    /// the estimate itself stays readable, and the feedback announces it unlowered (the
533    /// responder lowers it on its way to the application, a pacer paces at it).
534    #[test]
535    fn the_target_leaves_out_the_retransmission_reserve() {
536        let (mut chain, handle) = make_chain();
537        let ssrc = 1001u32;
538        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
539        let base = Instant::now();
540        for i in 0..5u16 {
541            chain
542                .handle_write(make_rtp(
543                    ssrc,
544                    i,
545                    base + Duration::from_millis(i as u64 * 33),
546                ))
547                .unwrap();
548        }
549        while chain.poll_write().is_some() {}
550        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
551        chain
552            .handle_read(make_twcc_feedback(
553                0,
554                &recv_us,
555                base + Duration::from_millis(200),
556            ))
557            .unwrap();
558        let estimate = handle.estimate_bps().expect("an estimate");
559        assert_eq!(Some(estimate), handle.target_bitrate_bps());
560
561        let reserve = |bits_per_second: f64| TaggedPacket {
562            now: base + Duration::from_millis(250),
563            transport: TransportContext::default(),
564            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(crate::Attribute::Custom(
565                Arc::new(crate::RetransmissionReserve { bits_per_second }),
566            )),
567        };
568        chain.handle_write(reserve(100_000.0)).unwrap();
569        assert_eq!(Some(estimate), handle.estimate_bps());
570        assert_eq!(Some(estimate - 100_000), handle.target_bitrate_bps());
571
572        let announced = chain.poll_read().and_then(|feedback| {
573            match feedback
574                .message
575                .get(&crate::Attribute::TargetBitrateChanged {
576                    bits_per_second: 0.0,
577                }) {
578                Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
579                    Some(*bits_per_second as u32)
580                }
581                _ => None,
582            }
583        });
584        assert_eq!(
585            Some(estimate),
586            announced,
587            "the feedback carries the estimate"
588        );
589
590        chain.handle_write(reserve(0.0)).unwrap();
591        assert_eq!(Some(estimate), handle.target_bitrate_bps(), "released");
592    }
593
594    /// A new path (inbound packets between new addresses, three in a row: an ICE restart, a
595    /// move to another network) restarts the estimate from the start rate, and the packets
596    /// sent into the old path before it no longer count: twenty lost there and five received
597    /// on the new path are no loss of the new path's (counted, 80 % would cut the estimate to
598    /// 60 %).
599    #[test]
600    fn a_new_path_starts_over_and_the_old_paths_losses_do_not_count() {
601        use rtcp::transport_feedbacks::transport_layer_cc::RecvDelta;
602        let (mut chain, handle) = make_chain();
603        let ssrc = 1001u32;
604        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
605        let base = Instant::now();
606        let at = |ms: u64| base + Duration::from_millis(ms);
607        for i in 0..10u16 {
608            chain
609                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
610                .unwrap();
611        }
612        let recv_us: Vec<i64> = (0..10).map(|i: i64| i * 20_000 + 20_000).collect();
613        chain
614            .handle_read(make_twcc_feedback(0, &recv_us, at(250)))
615            .unwrap();
616        // Into the old path, which is gone.
617        for i in 10..30u16 {
618            chain
619                .handle_write(make_rtp(ssrc, i, at(300 + i as u64 * 20)))
620                .unwrap();
621        }
622        let new_path = TransportContext {
623            local_addr: "10.0.9.1:5000".parse().unwrap(),
624            peer_addr: "10.0.0.2:5000".parse().unwrap(),
625            ..Default::default()
626        };
627        for k in 0..3u64 {
628            chain
629                .handle_read(TaggedPacket {
630                    now: at(1_000 + k),
631                    transport: new_path,
632                    message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
633                        rtcp::receiver_report::ReceiverReport {
634                            ssrc: 42,
635                            ..Default::default()
636                        },
637                    )])),
638                })
639                .unwrap();
640        }
641        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
642        for i in 30..35u16 {
643            chain
644                .handle_write(make_rtp(ssrc, i, at(1_000 + i as u64 * 20)))
645                .unwrap();
646        }
647        while chain.poll_write().is_some() {}
648        while chain.poll_read().is_some() {}
649        // Feedback on the new path: 10..29 lost, 30..34 received 20 ms apart.
650        let reference_time = (1_600_000i64 / 64_000) as u32;
651        let mut recv = reference_time as i64 * 64_000;
652        let deltas = (0..5)
653            .map(|k| {
654                let t = 1_620_000 + k * 20_000;
655                let delta = t - recv;
656                recv = t;
657                RecvDelta {
658                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
659                    delta,
660                }
661            })
662            .collect();
663        let run = |symbol, run_length| {
664            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
665                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
666                packet_status_symbol: symbol,
667                run_length,
668            })
669        };
670        let fb = TransportLayerCc {
671            base_sequence_number: 10,
672            packet_status_count: 25,
673            reference_time,
674            packet_chunks: vec![
675                run(SymbolTypeTcc::PacketNotReceived, 20),
676                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
677            ],
678            recv_deltas: deltas,
679            ..Default::default()
680        };
681        chain
682            .handle_read(TaggedPacket {
683                now: at(1_800),
684                transport: new_path,
685                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
686            })
687            .unwrap();
688        let estimate = handle.estimate_bps().unwrap();
689        assert!(
690            estimate >= 300_000,
691            "cut to {estimate} for the old path's losses"
692        );
693    }
694
695    /// The peer connection's word that it selected another candidate pair
696    /// ([`crate::PathChanged`]) is a new path also when every packet keeps its addresses (a
697    /// TURN relay that keeps them, an application that hands datagrams over with one
698    /// placeholder pair): the estimate starts over from the start rate, announced on the
699    /// carrier for a pacer, and twenty packets sent into the old path before it are no loss of
700    /// the new path's (counted, 80 % would cut the estimate to 60 %).
701    #[test]
702    fn the_peer_connections_path_change_starts_over_with_the_same_addresses() {
703        let (mut chain, handle) = make_chain();
704        let ssrc = 1001u32;
705        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
706        let base = Instant::now();
707        let at = |ms: u64| base + Duration::from_millis(ms);
708        for i in 0..10u16 {
709            chain
710                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
711                .unwrap();
712        }
713        // Climb a while above the start rate, on feedback of a clean path.
714        let mut next = 10u16;
715        for round in 0..30u64 {
716            let first = next - 10;
717            let recv_us: Vec<i64> = (0..10)
718                .map(|k: i64| (round as i64 * 200_000) + k * 20_000 + 20_000)
719                .collect();
720            chain
721                .handle_read(make_twcc_feedback(first, &recv_us, at(round * 200 + 250)))
722                .unwrap();
723            for i in next..next + 10 {
724                chain
725                    .handle_write(make_rtp(
726                        ssrc,
727                        i,
728                        at((round + 1) * 200 + (i - next) as u64 * 20),
729                    ))
730                    .unwrap();
731            }
732            next += 10;
733        }
734        while chain.poll_write().is_some() {}
735        while chain.poll_read().is_some() {}
736        let climbed = handle.estimate_bps().unwrap();
737        assert!(climbed > 300_000, "climbed to {climbed}");
738        // Packets `next - 10 .. next + 20` go into the old path, which is gone.
739        for i in next..next + 20 {
740            chain
741                .handle_write(make_rtp(ssrc, i, at(6_400 + (i - next) as u64 * 20)))
742                .unwrap();
743        }
744        let lost_from = next - 10;
745        next += 20;
746        chain
747            .handle_read(crate::PathChanged.into_packet(at(7_000), None))
748            .unwrap();
749        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
750        let carrier = chain.poll_read().expect("the carrier goes on");
751        assert!(carrier.message.custom::<crate::PathChanged>().is_some());
752        let announced = match carrier
753            .message
754            .get(&crate::Attribute::TargetBitrateChanged {
755                bits_per_second: 0.0,
756            }) {
757            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
758                Some(*bits_per_second as u32)
759            }
760            _ => None,
761        };
762        assert_eq!(Some(300_000), announced, "announced for a pacer");
763        for i in next..next + 5 {
764            chain
765                .handle_write(make_rtp(ssrc, i, at(7_000 + (i - next) as u64 * 20)))
766                .unwrap();
767        }
768        while chain.poll_write().is_some() {}
769        // Feedback on the new path, on the same addresses as ever: the thirty packets of the
770        // old path lost, the five of the new one received 20 ms apart.
771        let reference_time = (7_600_000i64 / 64_000) as u32;
772        let mut recv = reference_time as i64 * 64_000;
773        let deltas = (0..5)
774            .map(|k| {
775                let t = 7_620_000 + k * 20_000;
776                let delta = t - recv;
777                recv = t;
778                RecvDelta {
779                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
780                    delta,
781                }
782            })
783            .collect();
784        let run = |symbol, run_length| {
785            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
786                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
787                packet_status_symbol: symbol,
788                run_length,
789            })
790        };
791        let fb = TransportLayerCc {
792            base_sequence_number: lost_from,
793            packet_status_count: 35,
794            reference_time,
795            packet_chunks: vec![
796                run(SymbolTypeTcc::PacketNotReceived, 30),
797                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
798            ],
799            recv_deltas: deltas,
800            ..Default::default()
801        };
802        chain
803            .handle_read(TaggedPacket {
804                now: at(7_800),
805                transport: TransportContext::default(),
806                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
807            })
808            .unwrap();
809        let estimate = handle.estimate_bps().unwrap();
810        assert!(
811            estimate >= 300_000,
812            "cut to {estimate} for the old path's losses"
813        );
814    }
815
816    /// The target rides with the controller's minimum (`MinimumTarget`), so the NACK
817    /// responder knows where the original media cannot be lowered further.
818    #[test]
819    fn the_target_carries_the_controllers_minimum() {
820        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
821        let mut chain = Registry::new()
822            .with(
823                Slot::CongestionControl,
824                PassThroughInterceptor::new().with(gcc_builder.with_min_bitrate(123_000).build()),
825            )
826            .with(Slot::TwccSender, crate::TwccSenderBuilder::new().build())
827            .build();
828        let ssrc = 1001u32;
829        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
830        let base = Instant::now();
831        for i in 0..5u16 {
832            chain
833                .handle_write(make_rtp(
834                    ssrc,
835                    i,
836                    base + Duration::from_millis(i as u64 * 33),
837                ))
838                .unwrap();
839        }
840        while chain.poll_write().is_some() {}
841        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
842        chain
843            .handle_read(make_twcc_feedback(
844                0,
845                &recv_us,
846                base + Duration::from_millis(200),
847            ))
848            .unwrap();
849        let feedback = chain.poll_read().expect("the feedback carries on");
850        assert_eq!(
851            Some(&crate::MinimumTarget {
852                bits_per_second: 123_000.0
853            }),
854            feedback.message.custom::<crate::MinimumTarget>()
855        );
856    }
857
858    #[test]
859    fn test_no_estimate_before_feedback() {
860        let (mut chain, handle) = make_chain();
861        let ssrc = 2001u32;
862        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
863        chain
864            .handle_write(make_rtp(ssrc, 0, Instant::now()))
865            .unwrap();
866        // No feedback yet.
867        assert!(handle.target_bitrate_bps().is_none());
868    }
869
870    #[test]
871    fn test_non_twcc_rtcp_passes_through() {
872        let (mut chain, handle) = make_chain();
873        let rtcp_pkt = TransportMessage {
874            now: Instant::now(),
875            transport: TransportContext::default(),
876            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
877                rtcp::receiver_report::ReceiverReport {
878                    ssrc: 42,
879                    ..Default::default()
880                },
881            )])),
882        };
883        // Should not panic; non-TWCC RTCP is forwarded.
884        chain.handle_read(rtcp_pkt).unwrap();
885        assert!(handle.target_bitrate_bps().is_none());
886    }
887
888    #[test]
889    fn test_unbind_removes_stream() {
890        let (mut chain, _handle) = make_chain();
891        let ssrc = 3001u32;
892        let info = stream_info_with_twcc(ssrc);
893        chain.bind_local_stream(&info);
894        chain.unbind_remote_stream(&info); // unbind (remote stream - no-op here)
895        chain.unbind_local_stream(&info);
896        // No panic — stream was removed cleanly.
897    }
898
899    #[test]
900    fn test_send_time_not_recorded_without_twcc_ext() {
901        // RTP sent on an SSRC not bound with TWCC should not populate send_times.
902        let (mut chain, _handle) = make_chain();
903        let ssrc = 4001u32;
904        // Bind WITHOUT TWCC ext.
905        let info = StreamInfo {
906            ssrc,
907            rtp_header_extensions: vec![],
908            ..Default::default()
909        };
910        chain.bind_local_stream(&info);
911        // Just verify no panic and no estimate without TWCC feedback.
912        chain
913            .handle_write(make_rtp(ssrc, 1, Instant::now()))
914            .unwrap();
915    }
916
917    #[test]
918    fn test_builder_custom_bitrate_bounds() {
919        let (builder, _handle) = GccInterceptorBuilder::<()>::new();
920        let builder = builder
921            .with_min_bitrate(100_000)
922            .with_max_bitrate(5_000_000);
923        assert_eq!(builder.min_bitrate_bps, 100_000);
924        assert_eq!(builder.max_bitrate_bps, 5_000_000);
925    }
926
927    #[test]
928    fn test_gcc_handle_clone_shares_state() {
929        let (_builder, handle) = GccInterceptorBuilder::<()>::new();
930        let handle2 = handle.clone();
931        assert!(handle.target_bitrate_bps().is_none());
932        assert!(handle2.target_bitrate_bps().is_none());
933        // Write through the shared mutex.
934        handle.inner.lock().unwrap().estimate_bps = Some(500_000);
935        handle.inner.lock().unwrap().update_target(0);
936        assert_eq!(handle2.target_bitrate_bps(), Some(500_000));
937    }
938
939    /// Counts the inbound RTCP packets that reach its slot and passes everything on.
940    #[derive(Default)]
941    struct RtcpSeen {
942        seen: std::sync::Arc<std::sync::atomic::AtomicUsize>,
943        reads: std::collections::VecDeque<TaggedPacket>,
944        writes: std::collections::VecDeque<TaggedPacket>,
945    }
946
947    impl sansio::Protocol<TaggedPacket, TaggedPacket, ()> for RtcpSeen {
948        type Rout = TaggedPacket;
949        type Wout = TaggedPacket;
950        type Eout = ();
951        type Error = shared::error::Error;
952        type Time = Instant;
953
954        fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
955            if matches!(msg.message.packet, Packet::Rtcp(_)) {
956                self.seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
957            }
958            self.reads.push_back(msg);
959            Ok(())
960        }
961        fn poll_read(&mut self) -> Option<TaggedPacket> {
962            self.reads.pop_front()
963        }
964        fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
965            self.writes.push_back(msg);
966            Ok(())
967        }
968        fn poll_write(&mut self) -> Option<TaggedPacket> {
969            self.writes.pop_front()
970        }
971    }
972
973    impl crate::Interceptor for RtcpSeen {
974        fn bind_local_stream(&mut self, _info: &StreamInfo) {}
975        fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
976        fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
977        fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
978    }
979
980    fn pli() -> TaggedPacket {
981        use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
982        TaggedPacket {
983            now: Instant::now(),
984            transport: TransportContext::default(),
985            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(PictureLossIndication {
986                sender_ssrc: 1,
987                media_ssrc: 1001,
988            })])),
989        }
990    }
991
992    /// GCC in its slot around `inner`, an RTCP observer application-ward of it, and the
993    /// key-frame request interceptor that delivers PLI to the application. Returns how many
994    /// inbound RTCP packets the observer saw and how many packets the application read.
995    fn pli_through_gcc_slot<I: crate::Interceptor + 'static>(inner: I) -> (usize, usize) {
996        use crate::{KeyFrameRequestInterceptor, TwccSenderBuilder};
997        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
998        let observer = RtcpSeen::default();
999        let seen = observer.seen.clone();
1000        let mut chain = Registry::new()
1001            .with(Slot::CongestionControl, inner.with(gcc_builder.build()))
1002            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
1003            .with(Slot::from(3_500), observer)
1004            .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
1005            .build();
1006        // The first inbound packet carries the starting estimate for the chain (an attribute:
1007        // a terminus passes a marked packet on); the key-frame request comes after it.
1008        chain
1009            .handle_read(TaggedPacket {
1010                now: Instant::now(),
1011                transport: TransportContext::default(),
1012                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
1013                    rtcp::receiver_report::ReceiverReport {
1014                        ssrc: 42,
1015                        ..Default::default()
1016                    },
1017                )])),
1018            })
1019            .unwrap();
1020        while chain.poll_read().is_some() {}
1021        let before = seen.load(std::sync::atomic::Ordering::SeqCst);
1022        chain.handle_read(pli()).unwrap();
1023        let mut delivered = 0;
1024        while chain.poll_read().is_some() {
1025            delivered += 1;
1026        }
1027        (
1028            seen.load(std::sync::atomic::Ordering::SeqCst) - before,
1029            delivered,
1030        )
1031    }
1032
1033    /// With GCC registered the documented way (around a pass-through), inbound RTCP GCC doesn't
1034    /// consume reaches the interceptors after its slot, and a key-frame request reaches the
1035    /// application.
1036    #[test]
1037    fn rtcp_passes_the_gcc_slot() {
1038        assert_eq!(
1039            (1, 1),
1040            pli_through_gcc_slot(PassThroughInterceptor::new()),
1041            "the observer saw the PLI and the application read it"
1042        );
1043    }
1044
1045    /// Why the inner end must not be the terminus: around `NoopInterceptor` (the recipe this
1046    /// module used to document), the PLI ends in GCC's slot, the first one it reaches.
1047    #[test]
1048    fn noop_inside_the_gcc_slot_ends_rtcp_there() {
1049        assert_eq!((0, 0), pli_through_gcc_slot(NoopInterceptor::new()));
1050    }
1051}