rtci-interceptor 0.5.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
//! How often congestion control feedback is generated.

use crate::rtcp_session::{RtcpBandwidth, RtcpBandwidthShare, RtcpSessionControl};
use crate::stream_info::StreamInfo;
use crate::{Packet, TaggedPacket};
use shared::marshal::MarshalSize;
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

/// The share of the rate it is sized to that congestion control feedback may take: the 5%
/// RFC 3550 section 6.2 recommends for RTCP.
pub(crate) const FEEDBACK_SHARE: f64 = 0.05;
/// The window the received media bit rate is measured over.
const RATE_WINDOW: Duration = Duration::from_secs(2);
const RATE_BUCKET: Duration = Duration::from_millis(250);
/// What goes out with a feedback packet in the minimal compound RTCP packet it travels in
/// without reduced-size RTCP (RFC 4585 section 3.1): a receiver report and an SDES with a
/// short CNAME.
const COMPOUND_OCTETS: f64 = 28.0;
/// UDP over IPv4, which RFC 3550 section 6.2 counts in the size of an RTCP packet.
const LOWER_LAYER_OCTETS: f64 = 28.0;
/// The size assumed for a feedback packet before one has been built.
const INITIAL_FEEDBACK_OCTETS: f64 = 40.0;
/// The shortest interval the rate-sized cadences go to, however high the rate.
pub(crate) const MIN_ADAPTIVE_INTERVAL: Duration = Duration::from_millis(50);
/// The longest interval the rate-sized cadences stretch to while media flows: a sender's
/// estimator works as well with a report every 50 ms as every 250 ms, and markedly worse with
/// one a second (`gcc_feedback_rate.rs`); libwebrtc holds its transport feedback to the same
/// range.
pub(crate) const MAX_ADAPTIVE_INTERVAL: Duration = Duration::from_millis(250);
/// draft-ietf-rmcat-gcc-02 section 3: "at least once every 30 ms if audio-only or
/// multi-stream".
pub const PER_FRAME_INTERVAL: Duration = Duration::from_millis(30);
/// draft-ietf-rmcat-gcc-02 section 3: "If the feedback overhead needs to be limited this
/// interval can be increased to 100 ms".
pub const PER_FRAME_MAX_INTERVAL: Duration = Duration::from_millis(100);
/// libwebrtc `transport_sequence_number_feedback_generator.cc`: `kDefaultInterval`, the
/// interval until a send estimate is known.
const SEND_ESTIMATE_DEFAULT_INTERVAL: Duration = Duration::from_millis(100);
/// libwebrtc `OnSendBandwidthEstimateChanged`: `kTwccReportSize`, "Ipv4(20B) + UDP(8B) +
/// SRTP(10B) + AverageTwccReport(30B)", the size its interval is computed with.
const SEND_ESTIMATE_REPORT_OCTETS: f64 = 68.0;

/// When a congestion control feedback generator (transport-wide feedback, RFC 8888) builds
/// its next report, while its interval is not fixed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CongestionFeedbackCadence {
    /// The default: the interval in which a share (5%) of the media RECEIVED holds one
    /// feedback packet, between 50 ms and the generator's ceiling (250 ms).
    ///
    /// **No specification has this form: it is the engine's choice**, kept because every
    /// form the texts give measured worse in the capacity instrument
    /// (`tests/capacity_instrument.rs`, each against this one on the same seeds): the drafts'
    /// 30 ms ([`Self::PerFrame`]), 100 ms always, 30 to 100 ms by the media received and 30
    /// to 100 ms by the endpoint's own send estimate each broke the merge-point rule of
    /// `docs/capacity-instrument.md` (every form that reports more often than 50 ms costs
    /// the picture behind a short queue and after an outage; 100 ms always costs the audio
    /// behind a long one). The `Performance` behaviour profile takes it with 2.5% and 500 ms.
    #[default]
    ReceivedMedia,
    /// The drafts' cadence (the `StrictRfc` behaviour profile). draft-ietf-rmcat-gcc-02
    /// section 3: "The RECOMMENDED feedback interval is once per received video frame or at
    /// least once every 30 ms if audio-only or multi-stream. If the feedback overhead needs
    /// to be limited this interval can be increased to 100 ms";
    /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3: "It is recommended that
    /// a feedback message is sent for every frame received, but in cases of low uplink
    /// bandwidth it is acceptable to send them less frequently".
    ///
    /// A session whose only reported stream is one video stream is reported when a frame of
    /// it ends (the RTP marker), and after [`PER_FRAME_MAX_INTERVAL`] without one; any other
    /// session (audio alone, audio beside video, several streams) every
    /// [`PER_FRAME_INTERVAL`]. The overhead "needs to be limited" when the feedback would
    /// take more than the RTCP bandwidth gives this endpoint (RFC 4585 section 3.2: "FB
    /// messages are part of the RTCP control streams and thus subject to the RTCP bandwidth
    /// constraints"; RFC 3550 section 6.2: 5% of the session bandwidth, shared equally by the
    /// members): the interval is then the time in which this endpoint's share of the RTCP
    /// bandwidth ([`RtcpBandwidthShare`], from the RTCP session) holds one feedback packet,
    /// up to [`PER_FRAME_MAX_INTERVAL`] and no longer.
    PerFrame,
    /// libwebrtc's cadence (the `Chrome` behaviour profile): the interval in which 5% of the
    /// endpoint's own send estimate holds one 68-octet report, between 50 and 250 ms; 100 ms
    /// until an estimate is known
    /// (`modules/remote_bitrate_estimator/transport_sequence_number_feedback_generator.cc`,
    /// `OnSendBandwidthEstimateChanged`, fed from `call/call.cc` `OnTargetTransferRate`). The
    /// estimate is the congestion controller's ([`SendEstimate`](crate::SendEstimate)); the
    /// share and the ceiling are the generator's (`with_feedback_share`,
    /// `with_max_adaptive_interval`).
    SendEstimate,
}

/// RFC 8836 section 2, requirement 8c, with
/// [`TwccReceiverBuilder::with_stability_stretch`](crate::TwccReceiverBuilder::with_stability_stretch):
/// how many reports in a row must see a stable path before the interval stretches.
pub const STABLE_REPORTS: u32 = 4;
/// The interarrival jitter (RFC 3550 section 6.4.1, of frame starts) under which the path
/// counts as stable, with no packet missing.
pub const STABLE_JITTER: Duration = Duration::from_millis(5);
/// The queueing delay (the frame starts' transit time above the lowest seen) under which the
/// path counts as stable: a queue that builds slowly and evenly has little jitter, and is not
/// an equilibrium.
pub const STABLE_QUEUE: Duration = Duration::from_millis(20);
/// How much longer the interval is while the path is stable.
pub const STABLE_STRETCH: f64 = 2.0;
/// The longest a stretched interval goes to.
pub const STABLE_MAX_INTERVAL: Duration = Duration::from_millis(500);

/// One reported stream's arrivals, for the stability of the path (requirement 8c).
#[derive(Debug, Clone, Copy, Default)]
struct StreamArrivals {
    clock_rate: u32,
    /// The newest sequence number seen.
    highest: Option<u16>,
    /// The arrival and RTP timestamp of the last frame start (a packet of a new timestamp).
    last_frame: Option<(Instant, u32)>,
    /// RFC 3550 section 6.4.1's interarrival jitter of the frame starts, seconds.
    jitter: f64,
    /// The first frame start: its arrival and RTP timestamp, the origin of the transit times.
    origin: Option<(Instant, u32)>,
    /// The lowest transit time of a frame start, seconds from the origin's.
    lowest_transit: f64,
    /// The last frame start's transit time above the lowest: its queueing delay, seconds.
    queued: f64,
}

/// The interval between two feedback packets of a generator (TWCC or RFC 8888): fixed, or
/// one of the forms of [`CongestionFeedbackCadence`].
pub(crate) struct FeedbackCadence {
    /// The fixed interval, when not adaptive.
    floor: Duration,
    adaptive: bool,
    form: CongestionFeedbackCadence,
    /// The share of the rate the feedback may take ([`FEEDBACK_SHARE`] unless set).
    share: f64,
    /// The longest rate-sized interval ([`MAX_ADAPTIVE_INTERVAL`] unless set).
    max_interval: Duration,
    /// `b=` lines of the session, as the RTCP session is told them.
    negotiated: RtcpBandwidth,
    /// Whether reduced-size RTCP was negotiated (RFC 5506): a report can leave on its own.
    reduced_size: bool,
    buckets: VecDeque<(Instant, u64)>,
    first_media: Option<Instant>,
    /// A running mean of the size of the feedback built, RTCP octets.
    feedback_octets: f64,
    /// The congestion controller's estimate for this endpoint's sending, bits per second.
    send_estimate: Option<f64>,
    /// This endpoint's share of the RTCP bandwidth, bits per second.
    rtcp_share: Option<f64>,
    /// The reported media streams by SSRC: whether each is video.
    streams: HashMap<u32, bool>,
    /// When feedback was last built.
    last_feedback: Option<Instant>,
    /// RFC 8836 section 2, requirement 8c: the interval stretches while the path is stable.
    stability_stretch: bool,
    /// Each reported stream's arrivals, for the stability of the path.
    arrivals: HashMap<u32, StreamArrivals>,
    /// A packet went missing since the last report.
    lost_since_report: bool,
    /// Reports in a row that saw a stable path.
    stable_reports: u32,
}

impl FeedbackCadence {
    pub(crate) fn new(floor: Duration, adaptive: bool) -> Self {
        Self {
            floor,
            adaptive,
            form: CongestionFeedbackCadence::default(),
            share: FEEDBACK_SHARE,
            max_interval: MAX_ADAPTIVE_INTERVAL,
            negotiated: RtcpBandwidth::default(),
            reduced_size: false,
            buckets: VecDeque::new(),
            first_media: None,
            feedback_octets: INITIAL_FEEDBACK_OCTETS,
            send_estimate: None,
            rtcp_share: None,
            streams: HashMap::new(),
            last_feedback: None,
            stability_stretch: false,
            arrivals: HashMap::new(),
            lost_since_report: false,
            stable_reports: 0,
        }
    }

    /// RFC 8836 section 2, requirement 8c: "In areas of stability, backchannel data may be
    /// sent more infrequently ... When the channel is unstable or has not yet reached
    /// equilibrium after a change, backchannel feedback may be more frequent". With it, once
    /// [`STABLE_REPORTS`] reports in a row saw no packet missing, the interarrival jitter of
    /// every reported stream under [`STABLE_JITTER`] and no queue of [`STABLE_QUEUE`] or more
    /// (frame starts later than the lowest transit seen), the interval is [`STABLE_STRETCH`]
    /// times what the form gives (up to [`STABLE_MAX_INTERVAL`]); a missing packet, the jitter
    /// or the queue going over its bound brings it back at once, a report already scheduled
    /// at the stretched interval included ([`Self::stretched_deadline`]).
    pub(crate) fn with_stability_stretch(mut self, stretch: bool) -> Self {
        self.stability_stretch = stretch;
        self
    }

    /// Whether the path reads stable now: enough stable reports, nothing missing since the
    /// last, every stream's jitter under the bound.
    fn stable(&self) -> bool {
        self.stable_reports >= STABLE_REPORTS
            && !self.lost_since_report
            && self.jitter_low()
            && self.queue_low()
    }

    fn jitter_low(&self) -> bool {
        self.arrivals
            .values()
            .all(|stream| stream.jitter < STABLE_JITTER.as_secs_f64())
    }

    /// Whether no reported stream waits in a queue of [`STABLE_QUEUE`] or more.
    fn queue_low(&self) -> bool {
        self.arrivals
            .values()
            .all(|stream| stream.queued < STABLE_QUEUE.as_secs_f64())
    }

    /// One RTP packet of a reported stream arrived at `now`: its loss and jitter.
    fn on_arrival(&mut self, now: Instant, header: &rtp::header::Header) {
        let Some(stream) = self.arrivals.get_mut(&header.ssrc) else {
            return;
        };
        match stream.highest {
            Some(highest) => {
                let ahead = header.sequence_number.wrapping_sub(highest);
                if ahead > 1 && ahead < 0x8000 {
                    self.lost_since_report = true;
                }
                if ahead > 0 && ahead < 0x8000 {
                    stream.highest = Some(header.sequence_number);
                }
            }
            None => stream.highest = Some(header.sequence_number),
        }
        if stream.clock_rate == 0 {
            return;
        }
        if stream
            .last_frame
            .is_none_or(|(_, timestamp)| timestamp != header.timestamp)
        {
            let (origin_at, origin_timestamp) =
                *stream.origin.get_or_insert((now, header.timestamp));
            let transit = now.saturating_duration_since(origin_at).as_secs_f64()
                - f64::from(header.timestamp.wrapping_sub(origin_timestamp) as i32)
                    / f64::from(stream.clock_rate);
            stream.lowest_transit = stream.lowest_transit.min(transit);
            stream.queued = transit - stream.lowest_transit;
        }
        match stream.last_frame {
            Some((_, timestamp)) if timestamp == header.timestamp => {}
            Some((at, timestamp)) => {
                let transit_change = now.saturating_duration_since(at).as_secs_f64()
                    - f64::from(header.timestamp.wrapping_sub(timestamp) as i32)
                        / f64::from(stream.clock_rate);
                stream.jitter += (transit_change.abs() - stream.jitter) / 16.0;
                stream.last_frame = Some((now, header.timestamp));
            }
            None => stream.last_frame = Some((now, header.timestamp)),
        }
    }

    /// The form the interval takes while it is not fixed.
    pub(crate) fn with_form(mut self, form: CongestionFeedbackCadence) -> Self {
        self.form = form;
        self
    }

    /// A remote media stream the generator reports on was bound.
    pub(crate) fn bind_remote(&mut self, info: &StreamInfo) {
        let video = info.mime_type.to_ascii_lowercase().starts_with("video/");
        self.streams.insert(info.ssrc, video);
        self.arrivals.insert(
            info.ssrc,
            StreamArrivals {
                clock_rate: info.clock_rate,
                ..Default::default()
            },
        );
    }

    /// It was unbound.
    pub(crate) fn unbind_remote(&mut self, info: &StreamInfo) {
        self.streams.remove(&info.ssrc);
        self.arrivals.remove(&info.ssrc);
    }

    /// draft-ietf-rmcat-gcc-02 section 3: whether the session is one video stream (reported
    /// per frame) rather than "audio-only or multi-stream".
    fn single_video_stream(&self) -> bool {
        self.streams.len() == 1 && self.streams.values().all(|video| *video)
    }

    /// The share of the media received the feedback may take, and the longest adaptive
    /// interval (`TwccReceiverBuilder::with_feedback_share`, `with_max_adaptive_interval`).
    pub(crate) fn with_limits(mut self, share: f64, max_interval: Duration) -> Self {
        self.share = share.clamp(0.001, 1.0);
        self.max_interval = max_interval.max(MIN_ADAPTIVE_INTERVAL);
        self
    }

    /// Whether no interval was configured at all: the generator is off.
    pub(crate) fn is_off(&self) -> bool {
        self.floor.is_zero()
    }

    /// Something arrived. An RTP packet is the media the feedback reports on; what the RTCP
    /// session and the congestion controller say on their way application-ward is read off
    /// any packet. Returns whether a report is due now: with
    /// [`CongestionFeedbackCadence::PerFrame`], the packet ended a frame of a session's only
    /// video stream and the last report is at least the stretched interval ago.
    pub(crate) fn on_packet(&mut self, message: &TaggedPacket) -> bool {
        if let Some(share) = message.message.custom::<RtcpBandwidthShare>() {
            self.rtcp_share = Some(share.bits_per_second);
        }
        if let Some(estimate) = message.message.custom::<crate::SendEstimate>() {
            self.send_estimate = Some(estimate.bits_per_second);
        }
        let Packet::Rtp(packet) = &message.message.packet else {
            return false;
        };
        let now = message.now;
        if self.stability_stretch {
            self.on_arrival(now, &packet.header);
        }
        let frame_ended =
            packet.header.marker && self.streams.get(&packet.header.ssrc).copied() == Some(true);
        let octets = packet.marshal_size() as u64;
        self.first_media.get_or_insert(now);
        match self.buckets.back_mut() {
            Some((start, sum)) if now.saturating_duration_since(*start) < RATE_BUCKET => {
                *sum += octets;
            }
            _ => self.buckets.push_back((now, octets)),
        }
        while self
            .buckets
            .front()
            .is_some_and(|(start, _)| now.saturating_duration_since(*start) > RATE_WINDOW)
        {
            self.buckets.pop_front();
        }
        self.adaptive
            && !self.floor.is_zero()
            && self.form == CongestionFeedbackCadence::PerFrame
            && frame_ended
            && self.single_video_stream()
            && self.last_feedback.is_none_or(|last| {
                now.saturating_duration_since(last) >= self.share_interval().unwrap_or_default()
            })
    }

    /// Feedback was built at `now` (or there was nothing to report then).
    pub(crate) fn reported(&mut self, now: Instant) {
        self.last_feedback = Some(now);
        if self.stability_stretch {
            if self.lost_since_report || !self.jitter_low() || !self.queue_low() {
                self.stable_reports = 0;
            } else {
                self.stable_reports = self.stable_reports.saturating_add(1);
            }
            self.lost_since_report = false;
        }
    }

    /// A feedback packet with what travels with it, octets on the wire.
    fn packet_octets(&self) -> f64 {
        self.feedback_octets
            + LOWER_LAYER_OCTETS
            + if self.reduced_size {
                0.0
            } else {
                COMPOUND_OCTETS
            }
    }

    /// The interval in which this endpoint's share of the RTCP bandwidth holds one feedback
    /// packet, no longer than [`PER_FRAME_MAX_INTERVAL`]; `None` while the session has not
    /// said what the share is.
    fn share_interval(&self) -> Option<Duration> {
        let share = self.rtcp_share?;
        if share <= 0.0 {
            return Some(PER_FRAME_MAX_INTERVAL);
        }
        let seconds = self.packet_octets() * 8.0 / share;
        Some(Duration::from_secs_f64(
            seconds.min(PER_FRAME_MAX_INTERVAL.as_secs_f64()),
        ))
    }

    /// Something written towards the wire: what the session is told about its bandwidth and
    /// packet form is read on its way past.
    pub(crate) fn on_write(&mut self, message: &TaggedPacket) {
        match message.message.custom::<RtcpSessionControl>() {
            Some(RtcpSessionControl::Bandwidth(bandwidth)) => self.negotiated = *bandwidth,
            Some(RtcpSessionControl::ReducedSize(reduced_size)) => {
                self.reduced_size = *reduced_size;
            }
            _ => {}
        }
    }

    /// A feedback packet of `octets` was built.
    pub(crate) fn on_feedback(&mut self, octets: usize) {
        self.feedback_octets += (octets as f64 - self.feedback_octets) / 8.0;
    }

    fn media_bits_per_second(&self, now: Instant) -> f64 {
        let Some(first) = self.first_media else {
            return 0.0;
        };
        let octets: u64 = self
            .buckets
            .iter()
            .filter(|(start, _)| now.saturating_duration_since(*start) <= RATE_WINDOW)
            .map(|(_, sum)| *sum)
            .sum();
        let span = now
            .saturating_duration_since(first)
            .min(RATE_WINDOW)
            .as_secs_f64()
            .max(RATE_BUCKET.as_secs_f64());
        octets as f64 * 8.0 / span
    }

    /// The interval to the next feedback packet, as of `now`: the form's, stretched while the
    /// path is stable ([`Self::with_stability_stretch`]).
    pub(crate) fn interval(&self, now: Instant) -> Duration {
        let interval = self.form_interval(now);
        if self.stability_stretch && self.adaptive && !self.floor.is_zero() && self.stable() {
            interval
                .mul_f64(STABLE_STRETCH)
                .min(STABLE_MAX_INTERVAL)
                .max(interval)
        } else {
            interval
        }
    }

    /// With the stability stretch, the latest instant the next report may wait to as of `now`:
    /// the last report and the interval as of `now`. A report scheduled with a stretched
    /// interval is due sooner once the path stops reading stable ("When the channel is
    /// unstable ... backchannel feedback may be more frequent"): the generators pull their
    /// deadline back to this on each packet. `None` without the stretch or before a report.
    pub(crate) fn stretched_deadline(&self, now: Instant) -> Option<Instant> {
        if !self.stability_stretch {
            return None;
        }
        Some(self.last_feedback? + self.interval(now))
    }

    /// The interval the form gives, as of `now`.
    fn form_interval(&self, now: Instant) -> Duration {
        if !self.adaptive || self.floor.is_zero() {
            return self.floor;
        }
        match self.form {
            CongestionFeedbackCadence::PerFrame => {
                // One video stream: a frame's end brings the report; this is the wait for a
                // frame that does not end. Otherwise "at least once every 30 ms".
                let base = if self.single_video_stream() {
                    PER_FRAME_MAX_INTERVAL
                } else {
                    PER_FRAME_INTERVAL
                };
                base.max(self.share_interval().unwrap_or_default())
            }
            CongestionFeedbackCadence::SendEstimate => {
                let Some(estimate) = self.send_estimate else {
                    return SEND_ESTIMATE_DEFAULT_INTERVAL;
                };
                let share = self.share * estimate;
                if share <= 0.0 {
                    return self.max_interval;
                }
                Duration::from_secs_f64(
                    (SEND_ESTIMATE_REPORT_OCTETS * 8.0 / share)
                        .min(self.max_interval.as_secs_f64()),
                )
                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
            }
            CongestionFeedbackCadence::ReceivedMedia => {
                let share = match self.negotiated.rr {
                    Some(rr) => rr as f64,
                    None => self.share * self.media_bits_per_second(now),
                };
                if share <= 0.0 {
                    return self.max_interval;
                }
                Duration::from_secs_f64(
                    (self.packet_octets() * 8.0 / share).min(self.max_interval.as_secs_f64()),
                )
                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Attribute, AttributedPacket};
    use shared::TransportContext;
    use std::sync::Arc;

    /// The received-media form (the default).
    fn received_media(floor: Duration, adaptive: bool) -> FeedbackCadence {
        FeedbackCadence::new(floor, adaptive)
    }

    /// The drafts' form.
    fn per_frame() -> FeedbackCadence {
        FeedbackCadence::new(Duration::from_millis(100), true)
            .with_form(CongestionFeedbackCadence::PerFrame)
    }

    fn media(now: Instant, octets: usize) -> TaggedPacket {
        TaggedPacket {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
                header: rtp::header::Header {
                    version: 2,
                    ..Default::default()
                },
                payload: vec![0u8; octets - 12].into(),
            })),
        }
    }

    /// `bits_per_second` of media received for three seconds.
    fn after_media(cadence: &mut FeedbackCadence, bits_per_second: f64) -> Instant {
        let epoch = Instant::now();
        let octets = 500usize;
        let spacing = Duration::from_secs_f64(octets as f64 * 8.0 / bits_per_second);
        let mut at = Duration::ZERO;
        while at < Duration::from_secs(3) {
            cadence.on_packet(&media(epoch + at, octets));
            at += spacing;
        }
        epoch + Duration::from_secs(3)
    }

    /// At 64 kbit/s of media 5% is 3.2 kbit/s, and a 40-octet report in a minimal compound
    /// packet with its lower layers is 96 octets: one every 0.24 s.
    #[test]
    fn the_interval_holds_the_feedback_in_five_percent_of_the_media() {
        let mut cadence = received_media(Duration::from_millis(100), true);
        let now = after_media(&mut cadence, 64_000.0);
        let interval = cadence.interval(now).as_secs_f64();
        assert!((0.22..=0.25).contains(&interval), "{interval}");
    }

    /// With much media the interval stops at 50 ms; with little, at 250 ms.
    #[test]
    fn the_interval_is_held_between_50_and_250_ms() {
        let mut fast = received_media(Duration::from_millis(100), true);
        let now = after_media(&mut fast, 5_000_000.0);
        assert_eq!(MIN_ADAPTIVE_INTERVAL, fast.interval(now));
        let mut slow = received_media(Duration::from_millis(100), true);
        let now = after_media(&mut slow, 16_000.0);
        assert_eq!(MAX_ADAPTIVE_INTERVAL, slow.interval(now));
        let idle = received_media(Duration::from_millis(100), true);
        assert_eq!(MAX_ADAPTIVE_INTERVAL, idle.interval(Instant::now()));
    }

    /// Reduced-size RTCP (RFC 5506) takes the report without the compound packet around it,
    /// and the interval shortens with it.
    #[test]
    fn reduced_size_rtcp_shortens_the_interval() {
        let mut compound = received_media(Duration::from_millis(50), true);
        let now = after_media(&mut compound, 100_000.0);
        let mut reduced = received_media(Duration::from_millis(50), true);
        let then = after_media(&mut reduced, 100_000.0);
        reduced.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(then));
        assert!(reduced.interval(then) < compound.interval(now).mul_f64(0.8));
    }

    /// `b=RR` (RFC 3556) replaces the 5%.
    #[test]
    fn negotiated_receiver_rtcp_bandwidth_sets_the_interval() {
        let mut cadence = received_media(Duration::from_millis(50), true);
        let now = after_media(&mut cadence, 64_000.0);
        let before = cadence.interval(now);
        cadence.on_write(
            &RtcpSessionControl::Bandwidth(RtcpBandwidth {
                session: None,
                rs: Some(8_000),
                rr: Some(24_000),
            })
            .into_packet(now),
        );
        let after = cadence.interval(now);
        assert!(after < before.mul_f64(0.5), "{before:?} -> {after:?}");
    }

    /// Media this endpoint sends is not what the feedback reports on.
    #[test]
    fn media_sent_does_not_count() {
        let mut cadence = received_media(Duration::from_millis(100), true);
        let now = Instant::now();
        for n in 0..1_000u64 {
            cadence.on_write(&media(now + Duration::from_millis(n), 1_200));
        }
        assert_eq!(
            MAX_ADAPTIVE_INTERVAL,
            cadence.interval(now + Duration::from_secs(1))
        );
    }

    /// A smaller share and a longer ceiling (the `Performance` profile's 2.5% and 500 ms):
    /// at 32 kbit/s of media a 40-octet report with its lower layers (68 octets) fits 2.5%
    /// once every 0.68 s, held to 500 ms; the default holds it to 250 ms.
    #[test]
    fn a_smaller_share_lengthens_the_interval_up_to_its_ceiling() {
        let mut cadence = received_media(Duration::from_millis(100), true)
            .with_limits(0.025, Duration::from_millis(500));
        let now = after_media(&mut cadence, 32_000.0);
        cadence.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
        assert_eq!(Duration::from_millis(500), cadence.interval(now));
        let mut default = received_media(Duration::from_millis(100), true);
        let then = after_media(&mut default, 32_000.0);
        assert_eq!(MAX_ADAPTIVE_INTERVAL, default.interval(then));
        // At 300 kbit/s the share, not the ceiling, sets it: 68 * 8 / 7500 = 72 ms.
        let mut faster = received_media(Duration::from_millis(100), true)
            .with_limits(0.025, Duration::from_millis(500));
        let now = after_media(&mut faster, 300_000.0);
        faster.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
        let interval = faster.interval(now).as_secs_f64();
        assert!((0.065..=0.08).contains(&interval), "{interval}");
    }

    fn stream(ssrc: u32, mime_type: &str) -> StreamInfo {
        StreamInfo {
            ssrc,
            mime_type: mime_type.to_owned(),
            ..Default::default()
        }
    }

    fn packet(now: Instant, ssrc: u32, marker: bool) -> TaggedPacket {
        TaggedPacket {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
                header: rtp::header::Header {
                    version: 2,
                    ssrc,
                    marker,
                    ..Default::default()
                },
                payload: vec![0u8; 100].into(),
            })),
        }
    }

    /// What the RTCP session and the congestion controller attach on the way up.
    fn carrier<T: Send + Sync + 'static>(now: Instant, value: T) -> TaggedPacket {
        TaggedPacket {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtcp(vec![]))
                .with(Attribute::Custom(Arc::new(value))),
        }
    }

    /// draft-ietf-rmcat-gcc-02 section 3: "once per received video frame". A session of one
    /// video stream is reported when a frame ends (the marker), and after 100 ms without.
    #[test]
    fn one_video_stream_is_reported_when_a_frame_ends() {
        let mut cadence = per_frame();
        cadence.bind_remote(&stream(1, "video/VP8"));
        let now = Instant::now();
        assert!(!cadence.on_packet(&packet(now, 1, false)));
        assert!(cadence.on_packet(&packet(now, 1, true)), "the frame ended");
        // A packet of another SSRC (the stream's RTX, say) ends no frame of it.
        assert!(!cadence.on_packet(&packet(now, 2, true)));
        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
    }

    /// "or at least once every 30 ms if audio-only or multi-stream".
    #[test]
    fn audio_only_and_several_streams_are_reported_every_30_ms() {
        let now = Instant::now();
        let mut audio = per_frame();
        audio.bind_remote(&stream(1, "audio/opus"));
        assert_eq!(PER_FRAME_INTERVAL, audio.interval(now));
        assert!(
            !audio.on_packet(&packet(now, 1, true)),
            "a talk spurt's marker"
        );

        let mut both = per_frame();
        both.bind_remote(&stream(1, "audio/opus"));
        both.bind_remote(&stream(2, "video/VP8"));
        assert_eq!(PER_FRAME_INTERVAL, both.interval(now));
        assert!(
            !both.on_packet(&packet(now, 2, true)),
            "the timer reports it"
        );
        // The audio stream ends: one video stream is left, reported per frame.
        both.unbind_remote(&stream(1, "audio/opus"));
        assert!(both.on_packet(&packet(now, 2, true)));
    }

    /// "If the feedback overhead needs to be limited this interval can be increased to 100
    /// ms": where this endpoint's share of the RTCP bandwidth does not hold a feedback packet
    /// (40 octets, 96 with the minimal compound packet and lower layers) every 30 ms, the
    /// interval is the time in which it holds one, 100 ms at most.
    #[test]
    fn the_interval_grows_to_100_ms_where_the_rtcp_bandwidth_does_not_hold_it() {
        let now = Instant::now();
        let mut cadence = per_frame();
        cadence.bind_remote(&stream(1, "audio/opus"));
        let share = |bits_per_second: f64| carrier(now, RtcpBandwidthShare { bits_per_second });
        // 96 octets every 30 ms are 25.6 kbit/s: a share of 100 kbit/s holds them.
        cadence.on_packet(&share(100_000.0));
        assert_eq!(PER_FRAME_INTERVAL, cadence.interval(now));
        // 15.36 kbit/s hold one every 50 ms.
        cadence.on_packet(&share(15_360.0));
        assert_eq!(Duration::from_millis(50), cadence.interval(now));
        // 3.8 kbit/s (an audio call's) would hold one every 202 ms: 100 ms, the draft's most.
        cadence.on_packet(&share(3_800.0));
        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
        cadence.on_packet(&share(0.0));
        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));

        // One video stream: a frame that ends sooner after the last report than the share
        // holds is left to the next one.
        let mut video = per_frame();
        video.bind_remote(&stream(1, "video/VP8"));
        video.on_packet(&share(15_360.0));
        video.reported(now);
        let at = |ms: u64| now + Duration::from_millis(ms);
        assert!(!video.on_packet(&packet(at(33), 1, true)));
        assert!(video.on_packet(&packet(at(66), 1, true)));
    }

    /// libwebrtc `OnSendBandwidthEstimateChanged`: 100 ms until an estimate is known, then the
    /// time in which 5% of the send estimate holds 68 octets, between 50 and 250 ms.
    #[test]
    fn the_send_estimate_form_is_libwebrtcs_interval() {
        let now = Instant::now();
        let mut cadence = FeedbackCadence::new(Duration::from_millis(100), true)
            .with_form(CongestionFeedbackCadence::SendEstimate);
        cadence.bind_remote(&stream(1, "video/VP8"));
        assert_eq!(Duration::from_millis(100), cadence.interval(now));
        assert!(
            !cadence.on_packet(&packet(now, 1, true)),
            "no per-frame report"
        );
        let estimate = |bits_per_second: f64| carrier(now, crate::SendEstimate { bits_per_second });
        cadence.on_packet(&estimate(1_000_000.0));
        assert_eq!(MIN_ADAPTIVE_INTERVAL, cadence.interval(now));
        // 68 * 8 / (0.05 * 100 000) = 108.8 ms.
        cadence.on_packet(&estimate(100_000.0));
        assert_eq!(Duration::from_micros(108_800), cadence.interval(now));
        cadence.on_packet(&estimate(20_000.0));
        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
        // The media received does not move it.
        let now = after_media(&mut cadence, 5_000_000.0);
        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
    }

    /// The fixed setting ignores all of it.
    #[test]
    fn a_fixed_interval_stays_fixed() {
        let mut cadence = received_media(Duration::from_millis(100), false);
        let now = after_media(&mut cadence, 64_000.0);
        assert_eq!(Duration::from_millis(100), cadence.interval(now));
    }

    /// A video packet of SSRC 7 with `sequence_number` and RTP `timestamp`, 500 octets.
    fn video(now: Instant, sequence_number: u16, timestamp: u32) -> TaggedPacket {
        TaggedPacket {
            now,
            transport: TransportContext::default(),
            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
                header: rtp::header::Header {
                    version: 2,
                    ssrc: 7,
                    sequence_number,
                    timestamp,
                    ..Default::default()
                },
                payload: vec![0u8; 488].into(),
            })),
        }
    }

    fn video_stream() -> StreamInfo {
        StreamInfo {
            ssrc: 7,
            clock_rate: 90_000,
            mime_type: "video/VP8".to_owned(),
            ..Default::default()
        }
    }

    /// Feeds both cadences `frames` frames of two packets from frame `first` on (30 a second,
    /// the frame start arriving `wobble(frame)` late), a report every 100 ms; `skip` leaves a
    /// sequence number out after that frame. Returns the instant after the last frame.
    fn frames(
        cadences: &mut [&mut FeedbackCadence],
        epoch: Instant,
        first: u32,
        count: u32,
        wobble: impl Fn(u32) -> Duration,
        skip: Option<u32>,
    ) -> Instant {
        let frame_time = |frame: u32| epoch + Duration::from_nanos(33_333_333 * u64::from(frame));
        let mut sequence = (first * 2) as u16 + u16::from(skip.is_some_and(|s| first > s));
        for frame in first..first + count {
            let at = frame_time(frame) + wobble(frame);
            for part in 0..2u64 {
                for cadence in cadences.iter_mut() {
                    cadence.on_packet(&video(
                        at + Duration::from_millis(part),
                        sequence,
                        frame * 3000,
                    ));
                }
                sequence = sequence.wrapping_add(1);
            }
            if skip == Some(frame) {
                sequence = sequence.wrapping_add(1);
            }
            if frame % 3 == 2 {
                for cadence in cadences.iter_mut() {
                    cadence.reported(at);
                }
            }
        }
        frame_time(first + count)
    }

    /// RFC 8836 section 2, requirement 8c: "In areas of stability, backchannel data may be sent
    /// more infrequently so long as algorithm stability and fairness are maintained. When the
    /// channel is unstable or has not yet reached equilibrium after a change, backchannel
    /// feedback may be more frequent". With the stretch, after `STABLE_REPORTS` reports of a
    /// path with no loss and no jitter, the interval is twice the form's; a missing packet
    /// brings the form's back at once, and so does it stay until the path has been stable for
    /// `STABLE_REPORTS` reports again. The form's own interval is the same with and without
    /// the stretch (the precondition: both saw the same media).
    #[test]
    fn with_the_stability_stretch_the_interval_doubles_on_a_stable_path_only() {
        let epoch = Instant::now();
        let mut plain = received_media(Duration::from_millis(100), true);
        let mut stretched =
            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
        plain.bind_remote(&video_stream());
        stretched.bind_remote(&video_stream());
        let steady = |_| Duration::ZERO;
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            0,
            90,
            steady,
            None,
        );
        let base = plain.interval(now);
        assert!(base < STABLE_MAX_INTERVAL / 2, "the precondition: {base:?}");
        assert_eq!(stretched.form_interval(now), base);
        assert_eq!(
            stretched.interval(now),
            base.mul_f64(STABLE_STRETCH),
            "stable"
        );

        // A packet missing: the form's interval at once.
        frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            90,
            1,
            steady,
            Some(90),
        );
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            91,
            1,
            steady,
            Some(90),
        );
        assert_eq!(stretched.interval(now), plain.interval(now), "a loss");
        // Stable again for fewer than STABLE_REPORTS reports: still the form's.
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            92,
            4,
            steady,
            Some(90),
        );
        assert_eq!(
            stretched.interval(now),
            plain.interval(now),
            "not yet stable again"
        );
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            96,
            30,
            steady,
            Some(90),
        );
        assert_eq!(
            stretched.interval(now),
            plain.interval(now).mul_f64(STABLE_STRETCH),
            "stable again"
        );
    }

    /// With frame starts arriving up to 30 ms late in turn (jitter over `STABLE_JITTER`) and no
    /// loss, the path never reads stable: the interval stays the form's.
    #[test]
    fn with_the_stability_stretch_a_jittery_path_keeps_the_forms_interval() {
        let epoch = Instant::now();
        let mut plain = received_media(Duration::from_millis(100), true);
        let mut stretched =
            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
        plain.bind_remote(&video_stream());
        stretched.bind_remote(&video_stream());
        let jittery =
            |frame: u32| Duration::from_millis(if frame.is_multiple_of(2) { 0 } else { 30 });
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            0,
            90,
            jittery,
            None,
        );
        assert!(
            !stretched.jitter_low(),
            "the precondition: the jitter is high"
        );
        assert_eq!(stretched.interval(now), plain.interval(now));
    }

    /// "When the channel is unstable or has not yet reached equilibrium after a change": a queue
    /// that builds by a millisecond a frame has little jitter (the precondition: under
    /// `STABLE_JITTER`), but it is no equilibrium: once the frame starts wait more than
    /// `STABLE_QUEUE` above the lowest transit seen, the interval is the form's.
    #[test]
    fn with_the_stability_stretch_a_building_queue_keeps_the_forms_interval() {
        let epoch = Instant::now();
        let mut plain = received_media(Duration::from_millis(100), true);
        let mut stretched =
            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
        plain.bind_remote(&video_stream());
        stretched.bind_remote(&video_stream());
        let building = |frame: u32| Duration::from_millis(u64::from(frame));
        let now = frames(
            &mut [&mut plain, &mut stretched],
            epoch,
            0,
            90,
            building,
            None,
        );
        assert!(stretched.jitter_low(), "the precondition: little jitter");
        assert!(!stretched.queue_low(), "the precondition: a queue of 89 ms");
        assert_eq!(stretched.interval(now), plain.interval(now));
    }

    /// RFC 8836 section 2, requirement 8c: "Backchannel data should be minimized to avoid
    /// taking too much reverse-channel bandwidth". The default cadence keeps the feedback in 5 %
    /// of the media received: on one call whose media goes from 2 Mbit/s to 32 kbit/s and up to
    /// 400 kbit/s, the interval goes from its 50 ms floor to its 250 ms ceiling and back down
    /// between them (96 octets in 5 % of 400 kbit/s: 38 ms, held at 50); each time the feedback
    /// is at most 5 % of the media, or the ceiling's one report.
    #[test]
    fn the_interval_follows_the_media_rate_down_and_up_on_one_call() {
        let mut cadence = received_media(Duration::from_millis(100), true);
        let epoch = Instant::now();
        let mut at = Duration::ZERO;
        let mut run = |cadence: &mut FeedbackCadence, bits_per_second: f64| {
            let octets = 500usize;
            let spacing = Duration::from_secs_f64(octets as f64 * 8.0 / bits_per_second);
            let end = at + Duration::from_secs(3);
            while at < end {
                cadence.on_packet(&media(epoch + at, octets));
                at += spacing;
            }
            epoch + at
        };
        let now = run(&mut cadence, 2_000_000.0);
        assert_eq!(cadence.interval(now), MIN_ADAPTIVE_INTERVAL, "2 Mbit/s");
        let now = run(&mut cadence, 32_000.0);
        assert_eq!(cadence.interval(now), MAX_ADAPTIVE_INTERVAL, "32 kbit/s");
        let now = run(&mut cadence, 400_000.0);
        let interval = cadence.interval(now);
        assert!(
            interval < MAX_ADAPTIVE_INTERVAL.mul_f64(0.3),
            "400 kbit/s: {interval:?}"
        );
    }
}