rtci-interceptor 0.1.0

Sans-I/O RTP/RTCP interceptor pipeline for WebRTC: RTCP reports, NACK, TWCC, congestion control, pacing, FEC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
//! GCC (Google Congestion Control) sender-side bandwidth estimator.
//!
//! Reads TWCC feedback packets generated by the remote [`TwccReceiverInterceptor`] and
//! estimates available send bandwidth with the engine's GCC estimator ([`Gcc`], the one
//! [`configure_congestion_control`] and the default interceptors run), following
//! draft-ietf-rmcat-gcc-02
//! (Holmer et al., "A Google Congestion Control Algorithm for Real-Time Communication").
//! (RFC 8698 is NADA, a different algorithm, and is not what this implements.)
//!
//! What this module adds is the shape: a pull-style [`GccHandle`] an application polls, in a
//! chain without a pacer. The estimator is the same in both shapes. Until v0.22.0+brainwires.6
//! this interceptor had an estimator of its own (a trendline filter and one AIMD estimate),
//! which departed from the draft in three ways that this scenario shows: a link capped at
//! 300 kbit/s had its estimate cut to the floor by a second of loss and climb back at 8% a
//! second, over and over.
//!
//! - Section 6: the loss-based estimate As_hat is its own ("As long as less than 2% of the
//!   packets have been lost As_hat(i) will be increased as As_hat(i) = 1.05(As_hat(i-1))",
//!   "The actual sending rate is set as the minimum between As_hat and A_hat"). The old
//!   estimator applied the loss cut to the delay-based estimate, which only climbs 8% a second.
//! - Section 5.5: on over-use "A_hat(i) = beta * R_hat(i)", the received rate. The old one
//!   multiplied its estimate by 0.85.
//! - Section 5.5: "A_hat(i) < 1.5 * R_hat(i)". The old one had no such bound: its estimate
//!   climbed to the maximum whatever was sent. Now the estimate is not increased past the
//!   bound, and one that is above it is held.
//!
//! What an application polling the handle notices: the estimate no longer runs ahead of what
//! is sent (it is not increased past one and a half times the rate the receiver reports as
//! arriving); an estimate once reached is kept while the application sends less (audio
//! alone, a camera turned off), and is lowered by over-use, by loss and by feedback that
//! stops while packets are sent, which halves it ([`Gcc::with_feedback_timeout`]), and by
//! nothing else ([`ReceivedRateBound`]); a REMB or a TMMBR from the peer bounds it.
//!
//! [`Gcc`]: crate::Gcc
//! [`Gcc::with_feedback_timeout`]: crate::Gcc::with_feedback_timeout
//! [`ReceivedRateBound`]: crate::ReceivedRateBound
//! [`configure_congestion_control`]: https://docs.rs/rtc
//!
//! # Chain position
//!
//! GCC must sit **nearer the wire** than [`TwccSenderInterceptor`] so that `handle_write`
//! sees packets after the TWCC sequence number has already been stamped. Put it in
//! [`Slot::CongestionControl`](crate::Slot::CongestionControl), below
//! [`Slot::TwccSender`](crate::Slot::TwccSender):
//!
//! ```text
//! Registry::new()
//!     .with(Slot::CongestionControl, PassThroughInterceptor::new().with(gcc_builder.build()))
//!     .with(Slot::TwccSender, TwccSenderBuilder::new().build())
//! ```
//!
//! Writes walk away from the application toward the wire: TwccSender stamps first, then
//! GCC reads it. TWCC feedback reads reach GCC first, on their way to the application.
//!
//! GCC is a nested interceptor, so it needs an inner end: use
//! [`PassThroughInterceptor`](crate::PassThroughInterceptor), never
//! [`NoopInterceptor`](crate::NoopInterceptor). The latter is the chain's RTCP terminus; wrapped
//! in this slot, the first one inbound packets reach, it would end every RTCP packet nothing
//! marked (NACKs, receiver reports, PLI and FIR) before any other interceptor or the application
//! saw it.
//!
//! # Usage
//!
//! ```ignore
//! use rtci_interceptor::{
//!     GccInterceptorBuilder, Interceptor, PassThroughInterceptor, Registry, Slot,
//!     TwccSenderBuilder,
//! };
//!
//! let (gcc_builder, gcc_handle) = GccInterceptorBuilder::new();
//! let chain = Registry::new()
//!     .with(Slot::CongestionControl, PassThroughInterceptor::new().with(gcc_builder.build()))
//!     .with(Slot::TwccSender, TwccSenderBuilder::new().build())
//!     .build();
//!
//! // In the application polling loop:
//! if let Some(bps) = gcc_handle.target_bitrate_bps() {
//!     encoder.set_bitrate(bps);
//! }
//! ```
//!
//! [`TwccSenderInterceptor`]: crate::TwccSenderInterceptor
//! [`TwccReceiverInterceptor`]: crate::TwccReceiverInterceptor

use crate::cc::estimator::EstimatorStats;
use crate::cc::interceptor::{
    CongestionControlBuilder, CongestionControlHandle, CongestionControlInterceptor,
};
use crate::gcc::estimator::{DEFAULT_INITIAL_BITRATE, Gcc};
use crate::gcc::rate_control::ReceivedRateBound;
use crate::stream_info::StreamInfo;
use crate::{Interceptor, Packet, TaggedPacket, interceptor};
use rtcp::transport_feedbacks::transport_layer_cc::TransportLayerCc;
use sansio::Protocol;
use shared::error::Error;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};

/// Shared state written by [`GccInterceptor`] and read by [`GccHandle`].
pub struct GccShared {
    /// The target for the original media, in bits per second: the estimate less the NACK
    /// responder's retransmission reserve (RFC 4588 section 7). `None` until the first TWCC
    /// feedback has been processed.
    pub target_bitrate_bps: Option<u32>,
    /// Latest estimated available send bandwidth, in bits per second: what the original media
    /// and the retransmissions share. `None` until the first TWCC feedback has been processed.
    pub estimate_bps: Option<u32>,
    /// The retransmission reserve the NACK responder announced last
    /// ([`RetransmissionReserve`](crate::RetransmissionReserve)), in bits per second.
    pub retransmission_reserve_bps: f64,
    /// The estimator's two halves and its smoothed loss.
    pub stats: EstimatorStats,
}

impl GccShared {
    /// The target for the original media: the estimate less the reserve, never under the
    /// controller's `minimum` (what the application set to carry its media at the least).
    fn update_target(&mut self, minimum: u32) {
        self.target_bitrate_bps = self.estimate_bps.map(|estimate| {
            let lowered = (f64::from(estimate) - self.retransmission_reserve_bps).max(0.0) as u32;
            lowered.max(minimum.min(estimate))
        });
    }
}

/// Read-only handle to the latest GCC bandwidth estimate.
///
/// Clone-able and thread-safe — share freely across application threads.
#[derive(Clone)]
pub struct GccHandle {
    inner: Arc<Mutex<GccShared>>,
}

impl GccHandle {
    fn shared(&self) -> std::sync::MutexGuard<'_, GccShared> {
        self.inner.lock().unwrap_or_else(|e| {
            log::warn!("gcc: shared mutex poisoned, recovering last estimate");
            e.into_inner()
        })
    }

    /// The target an encoder follows, in bps: the estimate less the retransmission reserve
    /// the NACK responder holds while it repairs (RFC 4588 section 7: "the sender SHOULD NOT
    /// send retransmission packets without reducing the packet rate and bitrate of the
    /// original stream"), never under the minimum bit rate
    /// ([`GccInterceptorBuilder::with_min_bitrate`]). The estimate itself while nothing is
    /// being repaired, and in a chain without a NACK responder. `None` if no TWCC feedback has been processed yet.
    pub fn target_bitrate_bps(&self) -> Option<u32> {
        self.shared().target_bitrate_bps
    }

    /// The latest estimated available send bandwidth in bps, which the original media and
    /// the retransmissions share; `None` if no TWCC feedback has been processed yet.
    pub fn estimate_bps(&self) -> Option<u32> {
        self.shared().estimate_bps
    }

    /// The estimator's two halves (draft-ietf-rmcat-gcc-02 sections 5 and 6: the estimate is
    /// the lower of the delay-based and the loss-based one), its smoothed loss fraction and
    /// the round-trip time it works with.
    pub fn stats(&self) -> EstimatorStats {
        self.shared().stats
    }
}

/// Builder for [`GccInterceptor`].
///
/// Create with [`GccInterceptorBuilder::new`], which returns `(builder, handle)`.
pub struct GccInterceptorBuilder<P> {
    min_bitrate_bps: u32,
    max_bitrate_bps: u32,
    received_rate_bound: ReceivedRateBound,
    shared: Arc<Mutex<GccShared>>,
    _phantom: PhantomData<P>,
}

impl<P> GccInterceptorBuilder<P> {
    /// Create a new builder and the associated [`GccHandle`].
    ///
    /// The handle can be shared with the application so it can read the
    /// latest bitrate estimate each polling tick.
    pub fn new() -> (Self, GccHandle) {
        let shared = Arc::new(Mutex::new(GccShared {
            target_bitrate_bps: None,
            estimate_bps: None,
            retransmission_reserve_bps: 0.0,
            stats: EstimatorStats::default(),
        }));
        let handle = GccHandle {
            inner: shared.clone(),
        };
        let builder = Self {
            min_bitrate_bps: 30_000,
            max_bitrate_bps: 2_500_000,
            received_rate_bound: ReceivedRateBound::default(),
            shared,
            _phantom: PhantomData,
        };
        (builder, handle)
    }

    /// Minimum send rate floor (default 30 kbps).
    pub fn with_min_bitrate(mut self, bps: u32) -> Self {
        self.min_bitrate_bps = bps;
        self
    }

    /// Maximum send rate ceiling (default 2.5 Mbps).
    pub fn with_max_bitrate(mut self, bps: u32) -> Self {
        self.max_bitrate_bps = bps;
        self
    }

    /// What the bound of the estimate by the received rate does to an estimate above it
    /// ([`Gcc::with_received_rate_bound`](crate::Gcc::with_received_rate_bound)): by default
    /// it only stops the increase, so the estimate is kept while the application sends less
    /// than it.
    pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
        self.received_rate_bound = received_rate_bound;
        self
    }

    /// Build the interceptor factory closure.
    pub fn build(self) -> impl FnOnce(P) -> GccInterceptor<P> {
        move |inner| {
            let (min, max) = (
                f64::from(self.min_bitrate_bps),
                f64::from(self.max_bitrate_bps).max(f64::from(self.min_bitrate_bps)),
            );
            // The estimate starts at 300 kbit/s, and starts over from there on a new path.
            let estimator = Gcc::new(DEFAULT_INITIAL_BITRATE, min, max)
                .with_received_rate_bound(self.received_rate_bound);
            let (control, handle) = CongestionControlBuilder::new(estimator).build_with_handle();
            GccInterceptor {
                inner,
                control,
                handle,
                min_bitrate_bps: self.min_bitrate_bps,
                fed_back: false,
                shared: self.shared,
            }
        }
    }
}

/// Sender-side GCC bandwidth estimator interceptor.
///
/// Every outgoing RTP packet (stamped with its transport-wide sequence number) and every
/// incoming RTCP packet goes through the engine's congestion control interceptor
/// ([`CongestionControlInterceptor`] around [`Gcc`]); the resulting estimate is written to
/// the [`GccHandle`] shared state.
#[derive(Interceptor)]
pub struct GccInterceptor<P> {
    #[next]
    inner: P,

    /// The send history, the feedback ingest and the estimator.
    control: CongestionControlInterceptor<Gcc>,
    handle: CongestionControlHandle,
    /// The estimator's floor.
    min_bitrate_bps: u32,
    /// Whether transport-wide feedback has been read (the handle reports nothing before).
    fed_back: bool,

    /// Shared state — written here, read via [`GccHandle`].
    shared: Arc<Mutex<GccShared>>,
}

#[interceptor]
impl<P: Interceptor> GccInterceptor<P> {
    /// Outgoing packets pass the controller, which records each RTP packet's size and
    /// departure under its transport-wide sequence number.
    ///
    /// Must be inner to [`TwccSenderInterceptor`](crate::TwccSenderInterceptor) so the sequence number has
    /// already been stamped by the time this method is called.
    #[overrides]
    fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
        // The NACK responder's retransmission reserve, which the target for the original
        // media leaves out.
        if let Some(reserve) = msg.message.custom::<crate::RetransmissionReserve>()
            && reserve.bits_per_second.is_finite()
        {
            let mut shared = self.shared.lock().unwrap_or_else(|e| e.into_inner());
            shared.retransmission_reserve_bps = reserve.bits_per_second.max(0.0);
            shared.update_target(self.min_bitrate_bps);
        }
        self.control.handle_write(msg)?;
        self.forward()
    }

    /// Incoming packets pass the controller, which reads the transport-wide feedback (and the
    /// receiver reports, REMB and TMMBR) and announces the estimate on the packet that moved
    /// it, so that the NACK responder holds the retransmissions to it (it lowers the
    /// attribute by its reserve on the way to the application).
    #[overrides]
    fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
        if let Packet::Rtcp(ref packets) = msg.message.packet
            && packets
                .iter()
                .any(|packet| packet.as_any().is::<TransportLayerCc>())
        {
            self.fed_back = true;
        }
        self.control.handle_read(msg)?;
        self.forward()
    }

    /// The controller's own deadlines (feedback that stops while packets are sent).
    #[overrides]
    fn handle_timeout(&mut self, now: Self::Time) -> Result<(), Self::Error> {
        self.control.handle_timeout(now)?;
        self.forward()?;
        self.inner.handle_timeout(now)
    }

    #[overrides]
    fn poll_timeout(&mut self) -> Option<Self::Time> {
        match (self.control.poll_timeout(), self.inner.poll_timeout()) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }

    /// Register a local stream with the controller.
    #[overrides]
    fn bind_local_stream(&mut self, info: &StreamInfo) {
        self.control.bind_local_stream(info);
        self.inner.bind_local_stream(info);
    }

    /// Remove a local stream.
    #[overrides]
    fn unbind_local_stream(&mut self, info: &StreamInfo) {
        self.control.unbind_local_stream(info);
        self.inner.unbind_local_stream(info);
    }

    #[overrides]
    fn bind_remote_stream(&mut self, info: &StreamInfo) {
        self.control.bind_remote_stream(info);
        self.inner.bind_remote_stream(info);
    }

    #[overrides]
    fn unbind_remote_stream(&mut self, info: &StreamInfo) {
        self.control.unbind_remote_stream(info);
        self.inner.unbind_remote_stream(info);
    }
}

impl<P: Interceptor> GccInterceptor<P> {
    /// Hands on what the controller let through or made (either way), and publishes its
    /// estimate to the handle.
    fn forward(&mut self) -> Result<(), Error> {
        if self.fed_back {
            let mut shared = self.shared.lock().unwrap_or_else(|e| {
                log::warn!("gcc: shared mutex poisoned, recovering to publish estimate");
                e.into_inner()
            });
            shared.estimate_bps = Some(self.handle.target_bitrate() as u32);
            shared.stats = self.handle.stats();
            shared.update_target(self.min_bitrate_bps);
        }
        while let Some(msg) = self.control.poll_write() {
            self.inner.handle_write(msg)?;
        }
        while let Some(msg) = self.control.poll_read() {
            self.inner.handle_read(msg)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AttributedPacket;
    use crate::{
        NoopInterceptor, PassThroughInterceptor, RTPHeaderExtension, Registry, Slot,
        twcc::TRANSPORT_CC_URI,
    };
    use rtcp::transport_feedbacks::transport_layer_cc::{
        PacketStatusChunk, RecvDelta, RunLengthChunk, StatusChunkTypeTcc, SymbolTypeTcc,
    };
    use sansio::Protocol;
    use shared::{TransportContext, TransportMessage};
    use std::time::Duration;
    use std::time::Instant;

    fn stream_info_with_twcc(ssrc: u32) -> StreamInfo {
        StreamInfo {
            ssrc,
            rtp_header_extensions: vec![RTPHeaderExtension {
                uri: TRANSPORT_CC_URI.to_string(),
                id: 5,
            }],
            ..Default::default()
        }
    }

    fn make_rtp(ssrc: u32, rtp_seq: u16, now: Instant) -> TaggedPacket {
        TransportMessage {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
                header: rtp::header::Header {
                    ssrc,
                    sequence_number: rtp_seq,
                    ..Default::default()
                },
                // A packet of a 300 kbit/s stream at fifty packets a second: the estimate
                // stays within one and a half times what the receiver reports as arriving.
                payload: bytes::Bytes::from(vec![0u8; 750]),
            })),
        }
    }

    fn make_twcc_feedback(
        base_seq: u16,
        recv_times_us: &[i64], // per-packet receive times in microseconds (absolute)
        now: Instant,
    ) -> TaggedPacket {
        let base_recv_us = recv_times_us.first().copied().unwrap_or(0);
        // reference_time is 24-bit in 64ms units.
        let reference_time = (base_recv_us / 64_000) as u32;
        let base_ref_us = reference_time as i64 * 64_000;

        let mut deltas = Vec::new();
        let mut prev_us = base_ref_us;
        for &t in recv_times_us {
            let delta_us = t - prev_us;
            deltas.push(RecvDelta {
                type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
                delta: delta_us,
            });
            prev_us = t;
        }

        let chunk = PacketStatusChunk::RunLengthChunk(RunLengthChunk {
            type_tcc: StatusChunkTypeTcc::RunLengthChunk,
            packet_status_symbol: SymbolTypeTcc::PacketReceivedSmallDelta,
            run_length: recv_times_us.len() as u16,
        });

        let fb = TransportLayerCc {
            sender_ssrc: 0,
            media_ssrc: 0,
            base_sequence_number: base_seq,
            packet_status_count: recv_times_us.len() as u16,
            reference_time,
            fb_pkt_count: 0,
            packet_chunks: vec![chunk],
            recv_deltas: deltas,
        };

        TransportMessage {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
        }
    }

    /// Build a chain with TwccSender (outer) → GccInterceptor (inner).
    ///
    /// GCC must be inner so `handle_write` sees TWCC-stamped packets.
    fn make_chain() -> (impl crate::Interceptor, GccHandle) {
        use crate::TwccSenderBuilder;
        let (gcc_builder, handle) = GccInterceptorBuilder::new();
        // GCC sits nearer the wire than TwccSender, so writes are stamped before GCC sees them.
        let chain = Registry::new()
            .with(
                Slot::CongestionControl,
                PassThroughInterceptor::new().with(gcc_builder.build()),
            )
            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
            .build();
        (chain, handle)
    }

    #[test]
    fn test_handle_returns_estimate_after_feedback() {
        let (mut chain, handle) = make_chain();
        let ssrc = 1001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));

        let base = Instant::now();
        // Send 5 packets; TwccSender will stamp seq 0..4.
        for i in 0..5u16 {
            chain
                .handle_write(make_rtp(
                    ssrc,
                    i,
                    base + Duration::from_millis(i as u64 * 33),
                ))
                .unwrap();
        }

        // Feed back receive times: 33ms inter-packet spacing, 20ms constant one-way delay.
        // Units: microseconds.  20ms = 20_000µs; spacing 33ms = 33_000µs.
        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();

        chain
            .handle_read(make_twcc_feedback(
                0,
                &recv_us,
                base + Duration::from_millis(200),
            ))
            .unwrap();

        assert!(
            handle.target_bitrate_bps().is_some(),
            "should have an estimate after feedback"
        );

        // The estimate rides out on the feedback packet, so a pacer in the chain follows it.
        let feedback = chain.poll_read().expect("the feedback carries on");
        let announced = match feedback
            .message
            .get(&crate::Attribute::TargetBitrateChanged {
                bits_per_second: 0.0,
            }) {
            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
                Some(*bits_per_second as u32)
            }
            _ => None,
        };
        assert_eq!(handle.target_bitrate_bps(), announced);
    }

    /// RFC 4588 section 7: the target the handle reports for the original media is the
    /// estimate less the retransmission reserve the NACK responder sends down the write leg;
    /// the estimate itself stays readable, and the feedback announces it unlowered (the
    /// responder lowers it on its way to the application, a pacer paces at it).
    #[test]
    fn the_target_leaves_out_the_retransmission_reserve() {
        let (mut chain, handle) = make_chain();
        let ssrc = 1001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
        let base = Instant::now();
        for i in 0..5u16 {
            chain
                .handle_write(make_rtp(
                    ssrc,
                    i,
                    base + Duration::from_millis(i as u64 * 33),
                ))
                .unwrap();
        }
        while chain.poll_write().is_some() {}
        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
        chain
            .handle_read(make_twcc_feedback(
                0,
                &recv_us,
                base + Duration::from_millis(200),
            ))
            .unwrap();
        let estimate = handle.estimate_bps().expect("an estimate");
        assert_eq!(Some(estimate), handle.target_bitrate_bps());

        let reserve = |bits_per_second: f64| TaggedPacket {
            now: base + Duration::from_millis(250),
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![])).with(crate::Attribute::Custom(
                Arc::new(crate::RetransmissionReserve { bits_per_second }),
            )),
        };
        chain.handle_write(reserve(100_000.0)).unwrap();
        assert_eq!(Some(estimate), handle.estimate_bps());
        assert_eq!(Some(estimate - 100_000), handle.target_bitrate_bps());

        let announced = chain.poll_read().and_then(|feedback| {
            match feedback
                .message
                .get(&crate::Attribute::TargetBitrateChanged {
                    bits_per_second: 0.0,
                }) {
                Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
                    Some(*bits_per_second as u32)
                }
                _ => None,
            }
        });
        assert_eq!(
            Some(estimate),
            announced,
            "the feedback carries the estimate"
        );

        chain.handle_write(reserve(0.0)).unwrap();
        assert_eq!(Some(estimate), handle.target_bitrate_bps(), "released");
    }

    /// A new path (inbound packets between new addresses, three in a row: an ICE restart, a
    /// move to another network) restarts the estimate from the start rate, and the packets
    /// sent into the old path before it no longer count: twenty lost there and five received
    /// on the new path are no loss of the new path's (counted, 80 % would cut the estimate to
    /// 60 %).
    #[test]
    fn a_new_path_starts_over_and_the_old_paths_losses_do_not_count() {
        use rtcp::transport_feedbacks::transport_layer_cc::RecvDelta;
        let (mut chain, handle) = make_chain();
        let ssrc = 1001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
        let base = Instant::now();
        let at = |ms: u64| base + Duration::from_millis(ms);
        for i in 0..10u16 {
            chain
                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
                .unwrap();
        }
        let recv_us: Vec<i64> = (0..10).map(|i: i64| i * 20_000 + 20_000).collect();
        chain
            .handle_read(make_twcc_feedback(0, &recv_us, at(250)))
            .unwrap();
        // Into the old path, which is gone.
        for i in 10..30u16 {
            chain
                .handle_write(make_rtp(ssrc, i, at(300 + i as u64 * 20)))
                .unwrap();
        }
        let new_path = TransportContext {
            local_addr: "10.0.9.1:5000".parse().unwrap(),
            peer_addr: "10.0.0.2:5000".parse().unwrap(),
            ..Default::default()
        };
        for k in 0..3u64 {
            chain
                .handle_read(TaggedPacket {
                    now: at(1_000 + k),
                    transport: new_path,
                    message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
                        rtcp::receiver_report::ReceiverReport {
                            ssrc: 42,
                            ..Default::default()
                        },
                    )])),
                })
                .unwrap();
        }
        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
        for i in 30..35u16 {
            chain
                .handle_write(make_rtp(ssrc, i, at(1_000 + i as u64 * 20)))
                .unwrap();
        }
        while chain.poll_write().is_some() {}
        while chain.poll_read().is_some() {}
        // Feedback on the new path: 10..29 lost, 30..34 received 20 ms apart.
        let reference_time = (1_600_000i64 / 64_000) as u32;
        let mut recv = reference_time as i64 * 64_000;
        let deltas = (0..5)
            .map(|k| {
                let t = 1_620_000 + k * 20_000;
                let delta = t - recv;
                recv = t;
                RecvDelta {
                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
                    delta,
                }
            })
            .collect();
        let run = |symbol, run_length| {
            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
                packet_status_symbol: symbol,
                run_length,
            })
        };
        let fb = TransportLayerCc {
            base_sequence_number: 10,
            packet_status_count: 25,
            reference_time,
            packet_chunks: vec![
                run(SymbolTypeTcc::PacketNotReceived, 20),
                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
            ],
            recv_deltas: deltas,
            ..Default::default()
        };
        chain
            .handle_read(TaggedPacket {
                now: at(1_800),
                transport: new_path,
                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
            })
            .unwrap();
        let estimate = handle.estimate_bps().unwrap();
        assert!(
            estimate >= 300_000,
            "cut to {estimate} for the old path's losses"
        );
    }

    /// The peer connection's word that it selected another candidate pair
    /// ([`crate::PathChanged`]) is a new path also when every packet keeps its addresses (a
    /// TURN relay that keeps them, an application that hands datagrams over with one
    /// placeholder pair): the estimate starts over from the start rate, announced on the
    /// carrier for a pacer, and twenty packets sent into the old path before it are no loss of
    /// the new path's (counted, 80 % would cut the estimate to 60 %).
    #[test]
    fn the_peer_connections_path_change_starts_over_with_the_same_addresses() {
        let (mut chain, handle) = make_chain();
        let ssrc = 1001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
        let base = Instant::now();
        let at = |ms: u64| base + Duration::from_millis(ms);
        for i in 0..10u16 {
            chain
                .handle_write(make_rtp(ssrc, i, at(i as u64 * 20)))
                .unwrap();
        }
        // Climb a while above the start rate, on feedback of a clean path.
        let mut next = 10u16;
        for round in 0..30u64 {
            let first = next - 10;
            let recv_us: Vec<i64> = (0..10)
                .map(|k: i64| (round as i64 * 200_000) + k * 20_000 + 20_000)
                .collect();
            chain
                .handle_read(make_twcc_feedback(first, &recv_us, at(round * 200 + 250)))
                .unwrap();
            for i in next..next + 10 {
                chain
                    .handle_write(make_rtp(
                        ssrc,
                        i,
                        at((round + 1) * 200 + (i - next) as u64 * 20),
                    ))
                    .unwrap();
            }
            next += 10;
        }
        while chain.poll_write().is_some() {}
        while chain.poll_read().is_some() {}
        let climbed = handle.estimate_bps().unwrap();
        assert!(climbed > 300_000, "climbed to {climbed}");
        // Packets `next - 10 .. next + 20` go into the old path, which is gone.
        for i in next..next + 20 {
            chain
                .handle_write(make_rtp(ssrc, i, at(6_400 + (i - next) as u64 * 20)))
                .unwrap();
        }
        let lost_from = next - 10;
        next += 20;
        chain
            .handle_read(crate::PathChanged.into_packet(at(7_000), None))
            .unwrap();
        assert_eq!(Some(300_000), handle.estimate_bps(), "the start rate");
        let carrier = chain.poll_read().expect("the carrier goes on");
        assert!(carrier.message.custom::<crate::PathChanged>().is_some());
        let announced = match carrier
            .message
            .get(&crate::Attribute::TargetBitrateChanged {
                bits_per_second: 0.0,
            }) {
            Some(crate::Attribute::TargetBitrateChanged { bits_per_second }) => {
                Some(*bits_per_second as u32)
            }
            _ => None,
        };
        assert_eq!(Some(300_000), announced, "announced for a pacer");
        for i in next..next + 5 {
            chain
                .handle_write(make_rtp(ssrc, i, at(7_000 + (i - next) as u64 * 20)))
                .unwrap();
        }
        while chain.poll_write().is_some() {}
        // Feedback on the new path, on the same addresses as ever: the thirty packets of the
        // old path lost, the five of the new one received 20 ms apart.
        let reference_time = (7_600_000i64 / 64_000) as u32;
        let mut recv = reference_time as i64 * 64_000;
        let deltas = (0..5)
            .map(|k| {
                let t = 7_620_000 + k * 20_000;
                let delta = t - recv;
                recv = t;
                RecvDelta {
                    type_tcc_packet: SymbolTypeTcc::PacketReceivedSmallDelta,
                    delta,
                }
            })
            .collect();
        let run = |symbol, run_length| {
            PacketStatusChunk::RunLengthChunk(RunLengthChunk {
                type_tcc: StatusChunkTypeTcc::RunLengthChunk,
                packet_status_symbol: symbol,
                run_length,
            })
        };
        let fb = TransportLayerCc {
            base_sequence_number: lost_from,
            packet_status_count: 35,
            reference_time,
            packet_chunks: vec![
                run(SymbolTypeTcc::PacketNotReceived, 30),
                run(SymbolTypeTcc::PacketReceivedSmallDelta, 5),
            ],
            recv_deltas: deltas,
            ..Default::default()
        };
        chain
            .handle_read(TaggedPacket {
                now: at(7_800),
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(fb)])),
            })
            .unwrap();
        let estimate = handle.estimate_bps().unwrap();
        assert!(
            estimate >= 300_000,
            "cut to {estimate} for the old path's losses"
        );
    }

    /// The target rides with the controller's minimum (`MinimumTarget`), so the NACK
    /// responder knows where the original media cannot be lowered further.
    #[test]
    fn the_target_carries_the_controllers_minimum() {
        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
        let mut chain = Registry::new()
            .with(
                Slot::CongestionControl,
                PassThroughInterceptor::new().with(gcc_builder.with_min_bitrate(123_000).build()),
            )
            .with(Slot::TwccSender, crate::TwccSenderBuilder::new().build())
            .build();
        let ssrc = 1001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
        let base = Instant::now();
        for i in 0..5u16 {
            chain
                .handle_write(make_rtp(
                    ssrc,
                    i,
                    base + Duration::from_millis(i as u64 * 33),
                ))
                .unwrap();
        }
        while chain.poll_write().is_some() {}
        let recv_us: Vec<i64> = (0..5).map(|i: i64| i * 33_000 + 20_000).collect();
        chain
            .handle_read(make_twcc_feedback(
                0,
                &recv_us,
                base + Duration::from_millis(200),
            ))
            .unwrap();
        let feedback = chain.poll_read().expect("the feedback carries on");
        assert_eq!(
            Some(&crate::MinimumTarget {
                bits_per_second: 123_000.0
            }),
            feedback.message.custom::<crate::MinimumTarget>()
        );
    }

    #[test]
    fn test_no_estimate_before_feedback() {
        let (mut chain, handle) = make_chain();
        let ssrc = 2001u32;
        chain.bind_local_stream(&stream_info_with_twcc(ssrc));
        chain
            .handle_write(make_rtp(ssrc, 0, Instant::now()))
            .unwrap();
        // No feedback yet.
        assert!(handle.target_bitrate_bps().is_none());
    }

    #[test]
    fn test_non_twcc_rtcp_passes_through() {
        let (mut chain, handle) = make_chain();
        let rtcp_pkt = TransportMessage {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
                rtcp::receiver_report::ReceiverReport {
                    ssrc: 42,
                    ..Default::default()
                },
            )])),
        };
        // Should not panic; non-TWCC RTCP is forwarded.
        chain.handle_read(rtcp_pkt).unwrap();
        assert!(handle.target_bitrate_bps().is_none());
    }

    #[test]
    fn test_unbind_removes_stream() {
        let (mut chain, _handle) = make_chain();
        let ssrc = 3001u32;
        let info = stream_info_with_twcc(ssrc);
        chain.bind_local_stream(&info);
        chain.unbind_remote_stream(&info); // unbind (remote stream - no-op here)
        chain.unbind_local_stream(&info);
        // No panic — stream was removed cleanly.
    }

    #[test]
    fn test_send_time_not_recorded_without_twcc_ext() {
        // RTP sent on an SSRC not bound with TWCC should not populate send_times.
        let (mut chain, _handle) = make_chain();
        let ssrc = 4001u32;
        // Bind WITHOUT TWCC ext.
        let info = StreamInfo {
            ssrc,
            rtp_header_extensions: vec![],
            ..Default::default()
        };
        chain.bind_local_stream(&info);
        // Just verify no panic and no estimate without TWCC feedback.
        chain
            .handle_write(make_rtp(ssrc, 1, Instant::now()))
            .unwrap();
    }

    #[test]
    fn test_builder_custom_bitrate_bounds() {
        let (builder, _handle) = GccInterceptorBuilder::<()>::new();
        let builder = builder
            .with_min_bitrate(100_000)
            .with_max_bitrate(5_000_000);
        assert_eq!(builder.min_bitrate_bps, 100_000);
        assert_eq!(builder.max_bitrate_bps, 5_000_000);
    }

    #[test]
    fn test_gcc_handle_clone_shares_state() {
        let (_builder, handle) = GccInterceptorBuilder::<()>::new();
        let handle2 = handle.clone();
        assert!(handle.target_bitrate_bps().is_none());
        assert!(handle2.target_bitrate_bps().is_none());
        // Write through the shared mutex.
        handle.inner.lock().unwrap().estimate_bps = Some(500_000);
        handle.inner.lock().unwrap().update_target(0);
        assert_eq!(handle2.target_bitrate_bps(), Some(500_000));
    }

    /// Counts the inbound RTCP packets that reach its slot and passes everything on.
    #[derive(Default)]
    struct RtcpSeen {
        seen: std::sync::Arc<std::sync::atomic::AtomicUsize>,
        reads: std::collections::VecDeque<TaggedPacket>,
        writes: std::collections::VecDeque<TaggedPacket>,
    }

    impl sansio::Protocol<TaggedPacket, TaggedPacket, ()> for RtcpSeen {
        type Rout = TaggedPacket;
        type Wout = TaggedPacket;
        type Eout = ();
        type Error = shared::error::Error;
        type Time = Instant;

        fn handle_read(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
            if matches!(msg.message.packet, Packet::Rtcp(_)) {
                self.seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
            self.reads.push_back(msg);
            Ok(())
        }
        fn poll_read(&mut self) -> Option<TaggedPacket> {
            self.reads.pop_front()
        }
        fn handle_write(&mut self, msg: TaggedPacket) -> Result<(), Self::Error> {
            self.writes.push_back(msg);
            Ok(())
        }
        fn poll_write(&mut self) -> Option<TaggedPacket> {
            self.writes.pop_front()
        }
    }

    impl crate::Interceptor for RtcpSeen {
        fn bind_local_stream(&mut self, _info: &StreamInfo) {}
        fn unbind_local_stream(&mut self, _info: &StreamInfo) {}
        fn bind_remote_stream(&mut self, _info: &StreamInfo) {}
        fn unbind_remote_stream(&mut self, _info: &StreamInfo) {}
    }

    fn pli() -> TaggedPacket {
        use rtcp::payload_feedbacks::picture_loss_indication::PictureLossIndication;
        TaggedPacket {
            now: Instant::now(),
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(PictureLossIndication {
                sender_ssrc: 1,
                media_ssrc: 1001,
            })])),
        }
    }

    /// GCC in its slot around `inner`, an RTCP observer application-ward of it, and the
    /// key-frame request interceptor that delivers PLI to the application. Returns how many
    /// inbound RTCP packets the observer saw and how many packets the application read.
    fn pli_through_gcc_slot<I: crate::Interceptor + 'static>(inner: I) -> (usize, usize) {
        use crate::{KeyFrameRequestInterceptor, TwccSenderBuilder};
        let (gcc_builder, _handle) = GccInterceptorBuilder::new();
        let observer = RtcpSeen::default();
        let seen = observer.seen.clone();
        let mut chain = Registry::new()
            .with(Slot::CongestionControl, inner.with(gcc_builder.build()))
            .with(Slot::TwccSender, TwccSenderBuilder::new().build())
            .with(Slot::from(3_500), observer)
            .with(Slot::KeyFrameRequests, KeyFrameRequestInterceptor::new())
            .build();
        // The first inbound packet carries the starting estimate for the chain (an attribute:
        // a terminus passes a marked packet on); the key-frame request comes after it.
        chain
            .handle_read(TaggedPacket {
                now: Instant::now(),
                transport: TransportContext::default(),
                message: AttributedPacket::new(Packet::Rtcp(vec![Box::new(
                    rtcp::receiver_report::ReceiverReport {
                        ssrc: 42,
                        ..Default::default()
                    },
                )])),
            })
            .unwrap();
        while chain.poll_read().is_some() {}
        let before = seen.load(std::sync::atomic::Ordering::SeqCst);
        chain.handle_read(pli()).unwrap();
        let mut delivered = 0;
        while chain.poll_read().is_some() {
            delivered += 1;
        }
        (
            seen.load(std::sync::atomic::Ordering::SeqCst) - before,
            delivered,
        )
    }

    /// With GCC registered the documented way (around a pass-through), inbound RTCP GCC doesn't
    /// consume reaches the interceptors after its slot, and a key-frame request reaches the
    /// application.
    #[test]
    fn rtcp_passes_the_gcc_slot() {
        assert_eq!(
            (1, 1),
            pli_through_gcc_slot(PassThroughInterceptor::new()),
            "the observer saw the PLI and the application read it"
        );
    }

    /// Why the inner end must not be the terminus: around `NoopInterceptor` (the recipe this
    /// module used to document), the PLI ends in GCC's slot, the first one it reaches.
    #[test]
    fn noop_inside_the_gcc_slot_ends_rtcp_there() {
        assert_eq!((0, 0), pli_through_gcc_slot(NoopInterceptor::new()));
    }
}