Skip to main content

rtci_interceptor/cc/
feedback_cadence.rs

1//! How often congestion control feedback is generated.
2
3use crate::rtcp_session::{RtcpBandwidth, RtcpBandwidthShare, RtcpSessionControl};
4use crate::stream_info::StreamInfo;
5use crate::{Packet, TaggedPacket};
6use shared::marshal::MarshalSize;
7use std::collections::{HashMap, VecDeque};
8use std::time::{Duration, Instant};
9
10/// The share of the rate it is sized to that congestion control feedback may take: the 5%
11/// RFC 3550 section 6.2 recommends for RTCP.
12pub(crate) const FEEDBACK_SHARE: f64 = 0.05;
13/// The window the received media bit rate is measured over.
14const RATE_WINDOW: Duration = Duration::from_secs(2);
15const RATE_BUCKET: Duration = Duration::from_millis(250);
16/// What goes out with a feedback packet in the minimal compound RTCP packet it travels in
17/// without reduced-size RTCP (RFC 4585 section 3.1): a receiver report and an SDES with a
18/// short CNAME.
19const COMPOUND_OCTETS: f64 = 28.0;
20/// UDP over IPv4, which RFC 3550 section 6.2 counts in the size of an RTCP packet.
21const LOWER_LAYER_OCTETS: f64 = 28.0;
22/// The size assumed for a feedback packet before one has been built.
23const INITIAL_FEEDBACK_OCTETS: f64 = 40.0;
24/// The shortest interval the rate-sized cadences go to, however high the rate.
25pub(crate) const MIN_ADAPTIVE_INTERVAL: Duration = Duration::from_millis(50);
26/// The longest interval the rate-sized cadences stretch to while media flows: a sender's
27/// estimator works as well with a report every 50 ms as every 250 ms, and markedly worse with
28/// one a second (`gcc_feedback_rate.rs`); libwebrtc holds its transport feedback to the same
29/// range.
30pub(crate) const MAX_ADAPTIVE_INTERVAL: Duration = Duration::from_millis(250);
31/// draft-ietf-rmcat-gcc-02 section 3: "at least once every 30 ms if audio-only or
32/// multi-stream".
33pub const PER_FRAME_INTERVAL: Duration = Duration::from_millis(30);
34/// draft-ietf-rmcat-gcc-02 section 3: "If the feedback overhead needs to be limited this
35/// interval can be increased to 100 ms".
36pub const PER_FRAME_MAX_INTERVAL: Duration = Duration::from_millis(100);
37/// libwebrtc `transport_sequence_number_feedback_generator.cc`: `kDefaultInterval`, the
38/// interval until a send estimate is known.
39const SEND_ESTIMATE_DEFAULT_INTERVAL: Duration = Duration::from_millis(100);
40/// libwebrtc `OnSendBandwidthEstimateChanged`: `kTwccReportSize`, "Ipv4(20B) + UDP(8B) +
41/// SRTP(10B) + AverageTwccReport(30B)", the size its interval is computed with.
42const SEND_ESTIMATE_REPORT_OCTETS: f64 = 68.0;
43
44/// When a congestion control feedback generator (transport-wide feedback, RFC 8888) builds
45/// its next report, while its interval is not fixed.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
47pub enum CongestionFeedbackCadence {
48    /// The default: the interval in which a share (5%) of the media RECEIVED holds one
49    /// feedback packet, between 50 ms and the generator's ceiling (250 ms).
50    ///
51    /// **No specification has this form: it is the engine's choice**, kept because every
52    /// form the texts give measured worse in the capacity instrument
53    /// (`tests/capacity_instrument.rs`, each against this one on the same seeds): the drafts'
54    /// 30 ms ([`Self::PerFrame`]), 100 ms always, 30 to 100 ms by the media received and 30
55    /// to 100 ms by the endpoint's own send estimate each broke the merge-point rule of
56    /// `docs/capacity-instrument.md` (every form that reports more often than 50 ms costs
57    /// the picture behind a short queue and after an outage; 100 ms always costs the audio
58    /// behind a long one). The `Performance` behaviour profile takes it with 2.5% and 500 ms.
59    #[default]
60    ReceivedMedia,
61    /// The drafts' cadence (the `StrictRfc` behaviour profile). draft-ietf-rmcat-gcc-02
62    /// section 3: "The RECOMMENDED feedback interval is once per received video frame or at
63    /// least once every 30 ms if audio-only or multi-stream. If the feedback overhead needs
64    /// to be limited this interval can be increased to 100 ms";
65    /// draft-holmer-rmcat-transport-wide-cc-extensions-01 section 3: "It is recommended that
66    /// a feedback message is sent for every frame received, but in cases of low uplink
67    /// bandwidth it is acceptable to send them less frequently".
68    ///
69    /// A session whose only reported stream is one video stream is reported when a frame of
70    /// it ends (the RTP marker), and after [`PER_FRAME_MAX_INTERVAL`] without one; any other
71    /// session (audio alone, audio beside video, several streams) every
72    /// [`PER_FRAME_INTERVAL`]. The overhead "needs to be limited" when the feedback would
73    /// take more than the RTCP bandwidth gives this endpoint (RFC 4585 section 3.2: "FB
74    /// messages are part of the RTCP control streams and thus subject to the RTCP bandwidth
75    /// constraints"; RFC 3550 section 6.2: 5% of the session bandwidth, shared equally by the
76    /// members): the interval is then the time in which this endpoint's share of the RTCP
77    /// bandwidth ([`RtcpBandwidthShare`], from the RTCP session) holds one feedback packet,
78    /// up to [`PER_FRAME_MAX_INTERVAL`] and no longer.
79    PerFrame,
80    /// libwebrtc's cadence (the `Chrome` behaviour profile): the interval in which 5% of the
81    /// endpoint's own send estimate holds one 68-octet report, between 50 and 250 ms; 100 ms
82    /// until an estimate is known
83    /// (`modules/remote_bitrate_estimator/transport_sequence_number_feedback_generator.cc`,
84    /// `OnSendBandwidthEstimateChanged`, fed from `call/call.cc` `OnTargetTransferRate`). The
85    /// estimate is the congestion controller's ([`SendEstimate`](crate::SendEstimate)); the
86    /// share and the ceiling are the generator's (`with_feedback_share`,
87    /// `with_max_adaptive_interval`).
88    SendEstimate,
89}
90
91/// The interval between two feedback packets of a generator (TWCC or RFC 8888): fixed, or
92/// one of the forms of [`CongestionFeedbackCadence`].
93pub(crate) struct FeedbackCadence {
94    /// The fixed interval, when not adaptive.
95    floor: Duration,
96    adaptive: bool,
97    form: CongestionFeedbackCadence,
98    /// The share of the rate the feedback may take ([`FEEDBACK_SHARE`] unless set).
99    share: f64,
100    /// The longest rate-sized interval ([`MAX_ADAPTIVE_INTERVAL`] unless set).
101    max_interval: Duration,
102    /// `b=` lines of the session, as the RTCP session is told them.
103    negotiated: RtcpBandwidth,
104    /// Whether reduced-size RTCP was negotiated (RFC 5506): a report can leave on its own.
105    reduced_size: bool,
106    buckets: VecDeque<(Instant, u64)>,
107    first_media: Option<Instant>,
108    /// A running mean of the size of the feedback built, RTCP octets.
109    feedback_octets: f64,
110    /// The congestion controller's estimate for this endpoint's sending, bits per second.
111    send_estimate: Option<f64>,
112    /// This endpoint's share of the RTCP bandwidth, bits per second.
113    rtcp_share: Option<f64>,
114    /// The reported media streams by SSRC: whether each is video.
115    streams: HashMap<u32, bool>,
116    /// When feedback was last built.
117    last_feedback: Option<Instant>,
118}
119
120impl FeedbackCadence {
121    pub(crate) fn new(floor: Duration, adaptive: bool) -> Self {
122        Self {
123            floor,
124            adaptive,
125            form: CongestionFeedbackCadence::default(),
126            share: FEEDBACK_SHARE,
127            max_interval: MAX_ADAPTIVE_INTERVAL,
128            negotiated: RtcpBandwidth::default(),
129            reduced_size: false,
130            buckets: VecDeque::new(),
131            first_media: None,
132            feedback_octets: INITIAL_FEEDBACK_OCTETS,
133            send_estimate: None,
134            rtcp_share: None,
135            streams: HashMap::new(),
136            last_feedback: None,
137        }
138    }
139
140    /// The form the interval takes while it is not fixed.
141    pub(crate) fn with_form(mut self, form: CongestionFeedbackCadence) -> Self {
142        self.form = form;
143        self
144    }
145
146    /// A remote media stream the generator reports on was bound.
147    pub(crate) fn bind_remote(&mut self, info: &StreamInfo) {
148        let video = info.mime_type.to_ascii_lowercase().starts_with("video/");
149        self.streams.insert(info.ssrc, video);
150    }
151
152    /// It was unbound.
153    pub(crate) fn unbind_remote(&mut self, info: &StreamInfo) {
154        self.streams.remove(&info.ssrc);
155    }
156
157    /// draft-ietf-rmcat-gcc-02 section 3: whether the session is one video stream (reported
158    /// per frame) rather than "audio-only or multi-stream".
159    fn single_video_stream(&self) -> bool {
160        self.streams.len() == 1 && self.streams.values().all(|video| *video)
161    }
162
163    /// The share of the media received the feedback may take, and the longest adaptive
164    /// interval (`TwccReceiverBuilder::with_feedback_share`, `with_max_adaptive_interval`).
165    pub(crate) fn with_limits(mut self, share: f64, max_interval: Duration) -> Self {
166        self.share = share.clamp(0.001, 1.0);
167        self.max_interval = max_interval.max(MIN_ADAPTIVE_INTERVAL);
168        self
169    }
170
171    /// Whether no interval was configured at all: the generator is off.
172    pub(crate) fn is_off(&self) -> bool {
173        self.floor.is_zero()
174    }
175
176    /// Something arrived. An RTP packet is the media the feedback reports on; what the RTCP
177    /// session and the congestion controller say on their way application-ward is read off
178    /// any packet. Returns whether a report is due now: with
179    /// [`CongestionFeedbackCadence::PerFrame`], the packet ended a frame of a session's only
180    /// video stream and the last report is at least the stretched interval ago.
181    pub(crate) fn on_packet(&mut self, message: &TaggedPacket) -> bool {
182        if let Some(share) = message.message.custom::<RtcpBandwidthShare>() {
183            self.rtcp_share = Some(share.bits_per_second);
184        }
185        if let Some(estimate) = message.message.custom::<crate::SendEstimate>() {
186            self.send_estimate = Some(estimate.bits_per_second);
187        }
188        let Packet::Rtp(packet) = &message.message.packet else {
189            return false;
190        };
191        let now = message.now;
192        let frame_ended =
193            packet.header.marker && self.streams.get(&packet.header.ssrc).copied() == Some(true);
194        let octets = packet.marshal_size() as u64;
195        self.first_media.get_or_insert(now);
196        match self.buckets.back_mut() {
197            Some((start, sum)) if now.saturating_duration_since(*start) < RATE_BUCKET => {
198                *sum += octets;
199            }
200            _ => self.buckets.push_back((now, octets)),
201        }
202        while self
203            .buckets
204            .front()
205            .is_some_and(|(start, _)| now.saturating_duration_since(*start) > RATE_WINDOW)
206        {
207            self.buckets.pop_front();
208        }
209        self.adaptive
210            && !self.floor.is_zero()
211            && self.form == CongestionFeedbackCadence::PerFrame
212            && frame_ended
213            && self.single_video_stream()
214            && self.last_feedback.is_none_or(|last| {
215                now.saturating_duration_since(last) >= self.share_interval().unwrap_or_default()
216            })
217    }
218
219    /// Feedback was built at `now` (or there was nothing to report then).
220    pub(crate) fn reported(&mut self, now: Instant) {
221        self.last_feedback = Some(now);
222    }
223
224    /// A feedback packet with what travels with it, octets on the wire.
225    fn packet_octets(&self) -> f64 {
226        self.feedback_octets
227            + LOWER_LAYER_OCTETS
228            + if self.reduced_size {
229                0.0
230            } else {
231                COMPOUND_OCTETS
232            }
233    }
234
235    /// The interval in which this endpoint's share of the RTCP bandwidth holds one feedback
236    /// packet, no longer than [`PER_FRAME_MAX_INTERVAL`]; `None` while the session has not
237    /// said what the share is.
238    fn share_interval(&self) -> Option<Duration> {
239        let share = self.rtcp_share?;
240        if share <= 0.0 {
241            return Some(PER_FRAME_MAX_INTERVAL);
242        }
243        let seconds = self.packet_octets() * 8.0 / share;
244        Some(Duration::from_secs_f64(
245            seconds.min(PER_FRAME_MAX_INTERVAL.as_secs_f64()),
246        ))
247    }
248
249    /// Something written towards the wire: what the session is told about its bandwidth and
250    /// packet form is read on its way past.
251    pub(crate) fn on_write(&mut self, message: &TaggedPacket) {
252        match message.message.custom::<RtcpSessionControl>() {
253            Some(RtcpSessionControl::Bandwidth(bandwidth)) => self.negotiated = *bandwidth,
254            Some(RtcpSessionControl::ReducedSize(reduced_size)) => {
255                self.reduced_size = *reduced_size;
256            }
257            _ => {}
258        }
259    }
260
261    /// A feedback packet of `octets` was built.
262    pub(crate) fn on_feedback(&mut self, octets: usize) {
263        self.feedback_octets += (octets as f64 - self.feedback_octets) / 8.0;
264    }
265
266    fn media_bits_per_second(&self, now: Instant) -> f64 {
267        let Some(first) = self.first_media else {
268            return 0.0;
269        };
270        let octets: u64 = self
271            .buckets
272            .iter()
273            .filter(|(start, _)| now.saturating_duration_since(*start) <= RATE_WINDOW)
274            .map(|(_, sum)| *sum)
275            .sum();
276        let span = now
277            .saturating_duration_since(first)
278            .min(RATE_WINDOW)
279            .as_secs_f64()
280            .max(RATE_BUCKET.as_secs_f64());
281        octets as f64 * 8.0 / span
282    }
283
284    /// The interval to the next feedback packet, as of `now`.
285    pub(crate) fn interval(&self, now: Instant) -> Duration {
286        if !self.adaptive || self.floor.is_zero() {
287            return self.floor;
288        }
289        match self.form {
290            CongestionFeedbackCadence::PerFrame => {
291                // One video stream: a frame's end brings the report; this is the wait for a
292                // frame that does not end. Otherwise "at least once every 30 ms".
293                let base = if self.single_video_stream() {
294                    PER_FRAME_MAX_INTERVAL
295                } else {
296                    PER_FRAME_INTERVAL
297                };
298                base.max(self.share_interval().unwrap_or_default())
299            }
300            CongestionFeedbackCadence::SendEstimate => {
301                let Some(estimate) = self.send_estimate else {
302                    return SEND_ESTIMATE_DEFAULT_INTERVAL;
303                };
304                let share = self.share * estimate;
305                if share <= 0.0 {
306                    return self.max_interval;
307                }
308                Duration::from_secs_f64(
309                    (SEND_ESTIMATE_REPORT_OCTETS * 8.0 / share)
310                        .min(self.max_interval.as_secs_f64()),
311                )
312                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
313            }
314            CongestionFeedbackCadence::ReceivedMedia => {
315                let share = match self.negotiated.rr {
316                    Some(rr) => rr as f64,
317                    None => self.share * self.media_bits_per_second(now),
318                };
319                if share <= 0.0 {
320                    return self.max_interval;
321                }
322                Duration::from_secs_f64(
323                    (self.packet_octets() * 8.0 / share).min(self.max_interval.as_secs_f64()),
324                )
325                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
326            }
327        }
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use crate::{Attribute, AttributedPacket};
335    use shared::TransportContext;
336    use std::sync::Arc;
337
338    /// The received-media form (the default).
339    fn received_media(floor: Duration, adaptive: bool) -> FeedbackCadence {
340        FeedbackCadence::new(floor, adaptive)
341    }
342
343    /// The drafts' form.
344    fn per_frame() -> FeedbackCadence {
345        FeedbackCadence::new(Duration::from_millis(100), true)
346            .with_form(CongestionFeedbackCadence::PerFrame)
347    }
348
349    fn media(now: Instant, octets: usize) -> TaggedPacket {
350        TaggedPacket {
351            now,
352            transport: TransportContext::default(),
353            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
354                header: rtp::header::Header {
355                    version: 2,
356                    ..Default::default()
357                },
358                payload: vec![0u8; octets - 12].into(),
359            })),
360        }
361    }
362
363    /// `bits_per_second` of media received for three seconds.
364    fn after_media(cadence: &mut FeedbackCadence, bits_per_second: f64) -> Instant {
365        let epoch = Instant::now();
366        let octets = 500usize;
367        let spacing = Duration::from_secs_f64(octets as f64 * 8.0 / bits_per_second);
368        let mut at = Duration::ZERO;
369        while at < Duration::from_secs(3) {
370            cadence.on_packet(&media(epoch + at, octets));
371            at += spacing;
372        }
373        epoch + Duration::from_secs(3)
374    }
375
376    /// At 64 kbit/s of media 5% is 3.2 kbit/s, and a 40-octet report in a minimal compound
377    /// packet with its lower layers is 96 octets: one every 0.24 s.
378    #[test]
379    fn the_interval_holds_the_feedback_in_five_percent_of_the_media() {
380        let mut cadence = received_media(Duration::from_millis(100), true);
381        let now = after_media(&mut cadence, 64_000.0);
382        let interval = cadence.interval(now).as_secs_f64();
383        assert!((0.22..=0.25).contains(&interval), "{interval}");
384    }
385
386    /// With much media the interval stops at 50 ms; with little, at 250 ms.
387    #[test]
388    fn the_interval_is_held_between_50_and_250_ms() {
389        let mut fast = received_media(Duration::from_millis(100), true);
390        let now = after_media(&mut fast, 5_000_000.0);
391        assert_eq!(MIN_ADAPTIVE_INTERVAL, fast.interval(now));
392        let mut slow = received_media(Duration::from_millis(100), true);
393        let now = after_media(&mut slow, 16_000.0);
394        assert_eq!(MAX_ADAPTIVE_INTERVAL, slow.interval(now));
395        let idle = received_media(Duration::from_millis(100), true);
396        assert_eq!(MAX_ADAPTIVE_INTERVAL, idle.interval(Instant::now()));
397    }
398
399    /// Reduced-size RTCP (RFC 5506) takes the report without the compound packet around it,
400    /// and the interval shortens with it.
401    #[test]
402    fn reduced_size_rtcp_shortens_the_interval() {
403        let mut compound = received_media(Duration::from_millis(50), true);
404        let now = after_media(&mut compound, 100_000.0);
405        let mut reduced = received_media(Duration::from_millis(50), true);
406        let then = after_media(&mut reduced, 100_000.0);
407        reduced.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(then));
408        assert!(reduced.interval(then) < compound.interval(now).mul_f64(0.8));
409    }
410
411    /// `b=RR` (RFC 3556) replaces the 5%.
412    #[test]
413    fn negotiated_receiver_rtcp_bandwidth_sets_the_interval() {
414        let mut cadence = received_media(Duration::from_millis(50), true);
415        let now = after_media(&mut cadence, 64_000.0);
416        let before = cadence.interval(now);
417        cadence.on_write(
418            &RtcpSessionControl::Bandwidth(RtcpBandwidth {
419                session: None,
420                rs: Some(8_000),
421                rr: Some(24_000),
422            })
423            .into_packet(now),
424        );
425        let after = cadence.interval(now);
426        assert!(after < before.mul_f64(0.5), "{before:?} -> {after:?}");
427    }
428
429    /// Media this endpoint sends is not what the feedback reports on.
430    #[test]
431    fn media_sent_does_not_count() {
432        let mut cadence = received_media(Duration::from_millis(100), true);
433        let now = Instant::now();
434        for n in 0..1_000u64 {
435            cadence.on_write(&media(now + Duration::from_millis(n), 1_200));
436        }
437        assert_eq!(
438            MAX_ADAPTIVE_INTERVAL,
439            cadence.interval(now + Duration::from_secs(1))
440        );
441    }
442
443    /// A smaller share and a longer ceiling (the `Performance` profile's 2.5% and 500 ms):
444    /// at 32 kbit/s of media a 40-octet report with its lower layers (68 octets) fits 2.5%
445    /// once every 0.68 s, held to 500 ms; the default holds it to 250 ms.
446    #[test]
447    fn a_smaller_share_lengthens_the_interval_up_to_its_ceiling() {
448        let mut cadence = received_media(Duration::from_millis(100), true)
449            .with_limits(0.025, Duration::from_millis(500));
450        let now = after_media(&mut cadence, 32_000.0);
451        cadence.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
452        assert_eq!(Duration::from_millis(500), cadence.interval(now));
453        let mut default = received_media(Duration::from_millis(100), true);
454        let then = after_media(&mut default, 32_000.0);
455        assert_eq!(MAX_ADAPTIVE_INTERVAL, default.interval(then));
456        // At 300 kbit/s the share, not the ceiling, sets it: 68 * 8 / 7500 = 72 ms.
457        let mut faster = received_media(Duration::from_millis(100), true)
458            .with_limits(0.025, Duration::from_millis(500));
459        let now = after_media(&mut faster, 300_000.0);
460        faster.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
461        let interval = faster.interval(now).as_secs_f64();
462        assert!((0.065..=0.08).contains(&interval), "{interval}");
463    }
464
465    fn stream(ssrc: u32, mime_type: &str) -> StreamInfo {
466        StreamInfo {
467            ssrc,
468            mime_type: mime_type.to_owned(),
469            ..Default::default()
470        }
471    }
472
473    fn packet(now: Instant, ssrc: u32, marker: bool) -> TaggedPacket {
474        TaggedPacket {
475            now,
476            transport: TransportContext::default(),
477            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
478                header: rtp::header::Header {
479                    version: 2,
480                    ssrc,
481                    marker,
482                    ..Default::default()
483                },
484                payload: vec![0u8; 100].into(),
485            })),
486        }
487    }
488
489    /// What the RTCP session and the congestion controller attach on the way up.
490    fn carrier<T: Send + Sync + 'static>(now: Instant, value: T) -> TaggedPacket {
491        TaggedPacket {
492            now,
493            transport: TransportContext::default(),
494            message: AttributedPacket::new(Packet::Rtcp(vec![]))
495                .with(Attribute::Custom(Arc::new(value))),
496        }
497    }
498
499    /// draft-ietf-rmcat-gcc-02 section 3: "once per received video frame". A session of one
500    /// video stream is reported when a frame ends (the marker), and after 100 ms without.
501    #[test]
502    fn one_video_stream_is_reported_when_a_frame_ends() {
503        let mut cadence = per_frame();
504        cadence.bind_remote(&stream(1, "video/VP8"));
505        let now = Instant::now();
506        assert!(!cadence.on_packet(&packet(now, 1, false)));
507        assert!(cadence.on_packet(&packet(now, 1, true)), "the frame ended");
508        // A packet of another SSRC (the stream's RTX, say) ends no frame of it.
509        assert!(!cadence.on_packet(&packet(now, 2, true)));
510        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
511    }
512
513    /// "or at least once every 30 ms if audio-only or multi-stream".
514    #[test]
515    fn audio_only_and_several_streams_are_reported_every_30_ms() {
516        let now = Instant::now();
517        let mut audio = per_frame();
518        audio.bind_remote(&stream(1, "audio/opus"));
519        assert_eq!(PER_FRAME_INTERVAL, audio.interval(now));
520        assert!(
521            !audio.on_packet(&packet(now, 1, true)),
522            "a talk spurt's marker"
523        );
524
525        let mut both = per_frame();
526        both.bind_remote(&stream(1, "audio/opus"));
527        both.bind_remote(&stream(2, "video/VP8"));
528        assert_eq!(PER_FRAME_INTERVAL, both.interval(now));
529        assert!(
530            !both.on_packet(&packet(now, 2, true)),
531            "the timer reports it"
532        );
533        // The audio stream ends: one video stream is left, reported per frame.
534        both.unbind_remote(&stream(1, "audio/opus"));
535        assert!(both.on_packet(&packet(now, 2, true)));
536    }
537
538    /// "If the feedback overhead needs to be limited this interval can be increased to 100
539    /// ms": where this endpoint's share of the RTCP bandwidth does not hold a feedback packet
540    /// (40 octets, 96 with the minimal compound packet and lower layers) every 30 ms, the
541    /// interval is the time in which it holds one, 100 ms at most.
542    #[test]
543    fn the_interval_grows_to_100_ms_where_the_rtcp_bandwidth_does_not_hold_it() {
544        let now = Instant::now();
545        let mut cadence = per_frame();
546        cadence.bind_remote(&stream(1, "audio/opus"));
547        let share = |bits_per_second: f64| carrier(now, RtcpBandwidthShare { bits_per_second });
548        // 96 octets every 30 ms are 25.6 kbit/s: a share of 100 kbit/s holds them.
549        cadence.on_packet(&share(100_000.0));
550        assert_eq!(PER_FRAME_INTERVAL, cadence.interval(now));
551        // 15.36 kbit/s hold one every 50 ms.
552        cadence.on_packet(&share(15_360.0));
553        assert_eq!(Duration::from_millis(50), cadence.interval(now));
554        // 3.8 kbit/s (an audio call's) would hold one every 202 ms: 100 ms, the draft's most.
555        cadence.on_packet(&share(3_800.0));
556        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
557        cadence.on_packet(&share(0.0));
558        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
559
560        // One video stream: a frame that ends sooner after the last report than the share
561        // holds is left to the next one.
562        let mut video = per_frame();
563        video.bind_remote(&stream(1, "video/VP8"));
564        video.on_packet(&share(15_360.0));
565        video.reported(now);
566        let at = |ms: u64| now + Duration::from_millis(ms);
567        assert!(!video.on_packet(&packet(at(33), 1, true)));
568        assert!(video.on_packet(&packet(at(66), 1, true)));
569    }
570
571    /// libwebrtc `OnSendBandwidthEstimateChanged`: 100 ms until an estimate is known, then the
572    /// time in which 5% of the send estimate holds 68 octets, between 50 and 250 ms.
573    #[test]
574    fn the_send_estimate_form_is_libwebrtcs_interval() {
575        let now = Instant::now();
576        let mut cadence = FeedbackCadence::new(Duration::from_millis(100), true)
577            .with_form(CongestionFeedbackCadence::SendEstimate);
578        cadence.bind_remote(&stream(1, "video/VP8"));
579        assert_eq!(Duration::from_millis(100), cadence.interval(now));
580        assert!(
581            !cadence.on_packet(&packet(now, 1, true)),
582            "no per-frame report"
583        );
584        let estimate = |bits_per_second: f64| carrier(now, crate::SendEstimate { bits_per_second });
585        cadence.on_packet(&estimate(1_000_000.0));
586        assert_eq!(MIN_ADAPTIVE_INTERVAL, cadence.interval(now));
587        // 68 * 8 / (0.05 * 100 000) = 108.8 ms.
588        cadence.on_packet(&estimate(100_000.0));
589        assert_eq!(Duration::from_micros(108_800), cadence.interval(now));
590        cadence.on_packet(&estimate(20_000.0));
591        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
592        // The media received does not move it.
593        let now = after_media(&mut cadence, 5_000_000.0);
594        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
595    }
596
597    /// The fixed setting ignores all of it.
598    #[test]
599    fn a_fixed_interval_stays_fixed() {
600        let mut cadence = received_media(Duration::from_millis(100), false);
601        let now = after_media(&mut cadence, 64_000.0);
602        assert_eq!(Duration::from_millis(100), cadence.interval(now));
603    }
604}