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/// RFC 8836 section 2, requirement 8c, with
92/// [`TwccReceiverBuilder::with_stability_stretch`](crate::TwccReceiverBuilder::with_stability_stretch):
93/// how many reports in a row must see a stable path before the interval stretches.
94pub const STABLE_REPORTS: u32 = 4;
95/// The interarrival jitter (RFC 3550 section 6.4.1, of frame starts) under which the path
96/// counts as stable, with no packet missing.
97pub const STABLE_JITTER: Duration = Duration::from_millis(5);
98/// The queueing delay (the frame starts' transit time above the lowest seen) under which the
99/// path counts as stable: a queue that builds slowly and evenly has little jitter, and is not
100/// an equilibrium.
101pub const STABLE_QUEUE: Duration = Duration::from_millis(20);
102/// How much longer the interval is while the path is stable.
103pub const STABLE_STRETCH: f64 = 2.0;
104/// The longest a stretched interval goes to.
105pub const STABLE_MAX_INTERVAL: Duration = Duration::from_millis(500);
106
107/// One reported stream's arrivals, for the stability of the path (requirement 8c).
108#[derive(Debug, Clone, Copy, Default)]
109struct StreamArrivals {
110    clock_rate: u32,
111    /// The newest sequence number seen.
112    highest: Option<u16>,
113    /// The arrival and RTP timestamp of the last frame start (a packet of a new timestamp).
114    last_frame: Option<(Instant, u32)>,
115    /// RFC 3550 section 6.4.1's interarrival jitter of the frame starts, seconds.
116    jitter: f64,
117    /// The first frame start: its arrival and RTP timestamp, the origin of the transit times.
118    origin: Option<(Instant, u32)>,
119    /// The lowest transit time of a frame start, seconds from the origin's.
120    lowest_transit: f64,
121    /// The last frame start's transit time above the lowest: its queueing delay, seconds.
122    queued: f64,
123}
124
125/// The interval between two feedback packets of a generator (TWCC or RFC 8888): fixed, or
126/// one of the forms of [`CongestionFeedbackCadence`].
127pub(crate) struct FeedbackCadence {
128    /// The fixed interval, when not adaptive.
129    floor: Duration,
130    adaptive: bool,
131    form: CongestionFeedbackCadence,
132    /// The share of the rate the feedback may take ([`FEEDBACK_SHARE`] unless set).
133    share: f64,
134    /// The longest rate-sized interval ([`MAX_ADAPTIVE_INTERVAL`] unless set).
135    max_interval: Duration,
136    /// `b=` lines of the session, as the RTCP session is told them.
137    negotiated: RtcpBandwidth,
138    /// Whether reduced-size RTCP was negotiated (RFC 5506): a report can leave on its own.
139    reduced_size: bool,
140    buckets: VecDeque<(Instant, u64)>,
141    first_media: Option<Instant>,
142    /// A running mean of the size of the feedback built, RTCP octets.
143    feedback_octets: f64,
144    /// The congestion controller's estimate for this endpoint's sending, bits per second.
145    send_estimate: Option<f64>,
146    /// This endpoint's share of the RTCP bandwidth, bits per second.
147    rtcp_share: Option<f64>,
148    /// The reported media streams by SSRC: whether each is video.
149    streams: HashMap<u32, bool>,
150    /// When feedback was last built.
151    last_feedback: Option<Instant>,
152    /// RFC 8836 section 2, requirement 8c: the interval stretches while the path is stable.
153    stability_stretch: bool,
154    /// Each reported stream's arrivals, for the stability of the path.
155    arrivals: HashMap<u32, StreamArrivals>,
156    /// A packet went missing since the last report.
157    lost_since_report: bool,
158    /// Reports in a row that saw a stable path.
159    stable_reports: u32,
160}
161
162impl FeedbackCadence {
163    pub(crate) fn new(floor: Duration, adaptive: bool) -> Self {
164        Self {
165            floor,
166            adaptive,
167            form: CongestionFeedbackCadence::default(),
168            share: FEEDBACK_SHARE,
169            max_interval: MAX_ADAPTIVE_INTERVAL,
170            negotiated: RtcpBandwidth::default(),
171            reduced_size: false,
172            buckets: VecDeque::new(),
173            first_media: None,
174            feedback_octets: INITIAL_FEEDBACK_OCTETS,
175            send_estimate: None,
176            rtcp_share: None,
177            streams: HashMap::new(),
178            last_feedback: None,
179            stability_stretch: false,
180            arrivals: HashMap::new(),
181            lost_since_report: false,
182            stable_reports: 0,
183        }
184    }
185
186    /// RFC 8836 section 2, requirement 8c: "In areas of stability, backchannel data may be
187    /// sent more infrequently ... When the channel is unstable or has not yet reached
188    /// equilibrium after a change, backchannel feedback may be more frequent". With it, once
189    /// [`STABLE_REPORTS`] reports in a row saw no packet missing, the interarrival jitter of
190    /// every reported stream under [`STABLE_JITTER`] and no queue of [`STABLE_QUEUE`] or more
191    /// (frame starts later than the lowest transit seen), the interval is [`STABLE_STRETCH`]
192    /// times what the form gives (up to [`STABLE_MAX_INTERVAL`]); a missing packet, the jitter
193    /// or the queue going over its bound brings it back at once, a report already scheduled
194    /// at the stretched interval included ([`Self::stretched_deadline`]).
195    pub(crate) fn with_stability_stretch(mut self, stretch: bool) -> Self {
196        self.stability_stretch = stretch;
197        self
198    }
199
200    /// Whether the path reads stable now: enough stable reports, nothing missing since the
201    /// last, every stream's jitter under the bound.
202    fn stable(&self) -> bool {
203        self.stable_reports >= STABLE_REPORTS
204            && !self.lost_since_report
205            && self.jitter_low()
206            && self.queue_low()
207    }
208
209    fn jitter_low(&self) -> bool {
210        self.arrivals
211            .values()
212            .all(|stream| stream.jitter < STABLE_JITTER.as_secs_f64())
213    }
214
215    /// Whether no reported stream waits in a queue of [`STABLE_QUEUE`] or more.
216    fn queue_low(&self) -> bool {
217        self.arrivals
218            .values()
219            .all(|stream| stream.queued < STABLE_QUEUE.as_secs_f64())
220    }
221
222    /// One RTP packet of a reported stream arrived at `now`: its loss and jitter.
223    fn on_arrival(&mut self, now: Instant, header: &rtp::header::Header) {
224        let Some(stream) = self.arrivals.get_mut(&header.ssrc) else {
225            return;
226        };
227        match stream.highest {
228            Some(highest) => {
229                let ahead = header.sequence_number.wrapping_sub(highest);
230                if ahead > 1 && ahead < 0x8000 {
231                    self.lost_since_report = true;
232                }
233                if ahead > 0 && ahead < 0x8000 {
234                    stream.highest = Some(header.sequence_number);
235                }
236            }
237            None => stream.highest = Some(header.sequence_number),
238        }
239        if stream.clock_rate == 0 {
240            return;
241        }
242        if stream
243            .last_frame
244            .is_none_or(|(_, timestamp)| timestamp != header.timestamp)
245        {
246            let (origin_at, origin_timestamp) =
247                *stream.origin.get_or_insert((now, header.timestamp));
248            let transit = now.saturating_duration_since(origin_at).as_secs_f64()
249                - f64::from(header.timestamp.wrapping_sub(origin_timestamp) as i32)
250                    / f64::from(stream.clock_rate);
251            stream.lowest_transit = stream.lowest_transit.min(transit);
252            stream.queued = transit - stream.lowest_transit;
253        }
254        match stream.last_frame {
255            Some((_, timestamp)) if timestamp == header.timestamp => {}
256            Some((at, timestamp)) => {
257                let transit_change = now.saturating_duration_since(at).as_secs_f64()
258                    - f64::from(header.timestamp.wrapping_sub(timestamp) as i32)
259                        / f64::from(stream.clock_rate);
260                stream.jitter += (transit_change.abs() - stream.jitter) / 16.0;
261                stream.last_frame = Some((now, header.timestamp));
262            }
263            None => stream.last_frame = Some((now, header.timestamp)),
264        }
265    }
266
267    /// The form the interval takes while it is not fixed.
268    pub(crate) fn with_form(mut self, form: CongestionFeedbackCadence) -> Self {
269        self.form = form;
270        self
271    }
272
273    /// A remote media stream the generator reports on was bound.
274    pub(crate) fn bind_remote(&mut self, info: &StreamInfo) {
275        let video = info.mime_type.to_ascii_lowercase().starts_with("video/");
276        self.streams.insert(info.ssrc, video);
277        self.arrivals.insert(
278            info.ssrc,
279            StreamArrivals {
280                clock_rate: info.clock_rate,
281                ..Default::default()
282            },
283        );
284    }
285
286    /// It was unbound.
287    pub(crate) fn unbind_remote(&mut self, info: &StreamInfo) {
288        self.streams.remove(&info.ssrc);
289        self.arrivals.remove(&info.ssrc);
290    }
291
292    /// draft-ietf-rmcat-gcc-02 section 3: whether the session is one video stream (reported
293    /// per frame) rather than "audio-only or multi-stream".
294    fn single_video_stream(&self) -> bool {
295        self.streams.len() == 1 && self.streams.values().all(|video| *video)
296    }
297
298    /// The share of the media received the feedback may take, and the longest adaptive
299    /// interval (`TwccReceiverBuilder::with_feedback_share`, `with_max_adaptive_interval`).
300    pub(crate) fn with_limits(mut self, share: f64, max_interval: Duration) -> Self {
301        self.share = share.clamp(0.001, 1.0);
302        self.max_interval = max_interval.max(MIN_ADAPTIVE_INTERVAL);
303        self
304    }
305
306    /// Whether no interval was configured at all: the generator is off.
307    pub(crate) fn is_off(&self) -> bool {
308        self.floor.is_zero()
309    }
310
311    /// Something arrived. An RTP packet is the media the feedback reports on; what the RTCP
312    /// session and the congestion controller say on their way application-ward is read off
313    /// any packet. Returns whether a report is due now: with
314    /// [`CongestionFeedbackCadence::PerFrame`], the packet ended a frame of a session's only
315    /// video stream and the last report is at least the stretched interval ago.
316    pub(crate) fn on_packet(&mut self, message: &TaggedPacket) -> bool {
317        if let Some(share) = message.message.custom::<RtcpBandwidthShare>() {
318            self.rtcp_share = Some(share.bits_per_second);
319        }
320        if let Some(estimate) = message.message.custom::<crate::SendEstimate>() {
321            self.send_estimate = Some(estimate.bits_per_second);
322        }
323        let Packet::Rtp(packet) = &message.message.packet else {
324            return false;
325        };
326        let now = message.now;
327        if self.stability_stretch {
328            self.on_arrival(now, &packet.header);
329        }
330        let frame_ended =
331            packet.header.marker && self.streams.get(&packet.header.ssrc).copied() == Some(true);
332        let octets = packet.marshal_size() as u64;
333        self.first_media.get_or_insert(now);
334        match self.buckets.back_mut() {
335            Some((start, sum)) if now.saturating_duration_since(*start) < RATE_BUCKET => {
336                *sum += octets;
337            }
338            _ => self.buckets.push_back((now, octets)),
339        }
340        while self
341            .buckets
342            .front()
343            .is_some_and(|(start, _)| now.saturating_duration_since(*start) > RATE_WINDOW)
344        {
345            self.buckets.pop_front();
346        }
347        self.adaptive
348            && !self.floor.is_zero()
349            && self.form == CongestionFeedbackCadence::PerFrame
350            && frame_ended
351            && self.single_video_stream()
352            && self.last_feedback.is_none_or(|last| {
353                now.saturating_duration_since(last) >= self.share_interval().unwrap_or_default()
354            })
355    }
356
357    /// Feedback was built at `now` (or there was nothing to report then).
358    pub(crate) fn reported(&mut self, now: Instant) {
359        self.last_feedback = Some(now);
360        if self.stability_stretch {
361            if self.lost_since_report || !self.jitter_low() || !self.queue_low() {
362                self.stable_reports = 0;
363            } else {
364                self.stable_reports = self.stable_reports.saturating_add(1);
365            }
366            self.lost_since_report = false;
367        }
368    }
369
370    /// A feedback packet with what travels with it, octets on the wire.
371    fn packet_octets(&self) -> f64 {
372        self.feedback_octets
373            + LOWER_LAYER_OCTETS
374            + if self.reduced_size {
375                0.0
376            } else {
377                COMPOUND_OCTETS
378            }
379    }
380
381    /// The interval in which this endpoint's share of the RTCP bandwidth holds one feedback
382    /// packet, no longer than [`PER_FRAME_MAX_INTERVAL`]; `None` while the session has not
383    /// said what the share is.
384    fn share_interval(&self) -> Option<Duration> {
385        let share = self.rtcp_share?;
386        if share <= 0.0 {
387            return Some(PER_FRAME_MAX_INTERVAL);
388        }
389        let seconds = self.packet_octets() * 8.0 / share;
390        Some(Duration::from_secs_f64(
391            seconds.min(PER_FRAME_MAX_INTERVAL.as_secs_f64()),
392        ))
393    }
394
395    /// Something written towards the wire: what the session is told about its bandwidth and
396    /// packet form is read on its way past.
397    pub(crate) fn on_write(&mut self, message: &TaggedPacket) {
398        match message.message.custom::<RtcpSessionControl>() {
399            Some(RtcpSessionControl::Bandwidth(bandwidth)) => self.negotiated = *bandwidth,
400            Some(RtcpSessionControl::ReducedSize(reduced_size)) => {
401                self.reduced_size = *reduced_size;
402            }
403            _ => {}
404        }
405    }
406
407    /// A feedback packet of `octets` was built.
408    pub(crate) fn on_feedback(&mut self, octets: usize) {
409        self.feedback_octets += (octets as f64 - self.feedback_octets) / 8.0;
410    }
411
412    fn media_bits_per_second(&self, now: Instant) -> f64 {
413        let Some(first) = self.first_media else {
414            return 0.0;
415        };
416        let octets: u64 = self
417            .buckets
418            .iter()
419            .filter(|(start, _)| now.saturating_duration_since(*start) <= RATE_WINDOW)
420            .map(|(_, sum)| *sum)
421            .sum();
422        let span = now
423            .saturating_duration_since(first)
424            .min(RATE_WINDOW)
425            .as_secs_f64()
426            .max(RATE_BUCKET.as_secs_f64());
427        octets as f64 * 8.0 / span
428    }
429
430    /// The interval to the next feedback packet, as of `now`: the form's, stretched while the
431    /// path is stable ([`Self::with_stability_stretch`]).
432    pub(crate) fn interval(&self, now: Instant) -> Duration {
433        let interval = self.form_interval(now);
434        if self.stability_stretch && self.adaptive && !self.floor.is_zero() && self.stable() {
435            interval
436                .mul_f64(STABLE_STRETCH)
437                .min(STABLE_MAX_INTERVAL)
438                .max(interval)
439        } else {
440            interval
441        }
442    }
443
444    /// With the stability stretch, the latest instant the next report may wait to as of `now`:
445    /// the last report and the interval as of `now`. A report scheduled with a stretched
446    /// interval is due sooner once the path stops reading stable ("When the channel is
447    /// unstable ... backchannel feedback may be more frequent"): the generators pull their
448    /// deadline back to this on each packet. `None` without the stretch or before a report.
449    pub(crate) fn stretched_deadline(&self, now: Instant) -> Option<Instant> {
450        if !self.stability_stretch {
451            return None;
452        }
453        Some(self.last_feedback? + self.interval(now))
454    }
455
456    /// The interval the form gives, as of `now`.
457    fn form_interval(&self, now: Instant) -> Duration {
458        if !self.adaptive || self.floor.is_zero() {
459            return self.floor;
460        }
461        match self.form {
462            CongestionFeedbackCadence::PerFrame => {
463                // One video stream: a frame's end brings the report; this is the wait for a
464                // frame that does not end. Otherwise "at least once every 30 ms".
465                let base = if self.single_video_stream() {
466                    PER_FRAME_MAX_INTERVAL
467                } else {
468                    PER_FRAME_INTERVAL
469                };
470                base.max(self.share_interval().unwrap_or_default())
471            }
472            CongestionFeedbackCadence::SendEstimate => {
473                let Some(estimate) = self.send_estimate else {
474                    return SEND_ESTIMATE_DEFAULT_INTERVAL;
475                };
476                let share = self.share * estimate;
477                if share <= 0.0 {
478                    return self.max_interval;
479                }
480                Duration::from_secs_f64(
481                    (SEND_ESTIMATE_REPORT_OCTETS * 8.0 / share)
482                        .min(self.max_interval.as_secs_f64()),
483                )
484                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
485            }
486            CongestionFeedbackCadence::ReceivedMedia => {
487                let share = match self.negotiated.rr {
488                    Some(rr) => rr as f64,
489                    None => self.share * self.media_bits_per_second(now),
490                };
491                if share <= 0.0 {
492                    return self.max_interval;
493                }
494                Duration::from_secs_f64(
495                    (self.packet_octets() * 8.0 / share).min(self.max_interval.as_secs_f64()),
496                )
497                .clamp(MIN_ADAPTIVE_INTERVAL, self.max_interval)
498            }
499        }
500    }
501}
502
503#[cfg(test)]
504mod tests {
505    use super::*;
506    use crate::{Attribute, AttributedPacket};
507    use shared::TransportContext;
508    use std::sync::Arc;
509
510    /// The received-media form (the default).
511    fn received_media(floor: Duration, adaptive: bool) -> FeedbackCadence {
512        FeedbackCadence::new(floor, adaptive)
513    }
514
515    /// The drafts' form.
516    fn per_frame() -> FeedbackCadence {
517        FeedbackCadence::new(Duration::from_millis(100), true)
518            .with_form(CongestionFeedbackCadence::PerFrame)
519    }
520
521    fn media(now: Instant, octets: usize) -> TaggedPacket {
522        TaggedPacket {
523            now,
524            transport: TransportContext::default(),
525            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
526                header: rtp::header::Header {
527                    version: 2,
528                    ..Default::default()
529                },
530                payload: vec![0u8; octets - 12].into(),
531            })),
532        }
533    }
534
535    /// `bits_per_second` of media received for three seconds.
536    fn after_media(cadence: &mut FeedbackCadence, bits_per_second: f64) -> Instant {
537        let epoch = Instant::now();
538        let octets = 500usize;
539        let spacing = Duration::from_secs_f64(octets as f64 * 8.0 / bits_per_second);
540        let mut at = Duration::ZERO;
541        while at < Duration::from_secs(3) {
542            cadence.on_packet(&media(epoch + at, octets));
543            at += spacing;
544        }
545        epoch + Duration::from_secs(3)
546    }
547
548    /// At 64 kbit/s of media 5% is 3.2 kbit/s, and a 40-octet report in a minimal compound
549    /// packet with its lower layers is 96 octets: one every 0.24 s.
550    #[test]
551    fn the_interval_holds_the_feedback_in_five_percent_of_the_media() {
552        let mut cadence = received_media(Duration::from_millis(100), true);
553        let now = after_media(&mut cadence, 64_000.0);
554        let interval = cadence.interval(now).as_secs_f64();
555        assert!((0.22..=0.25).contains(&interval), "{interval}");
556    }
557
558    /// With much media the interval stops at 50 ms; with little, at 250 ms.
559    #[test]
560    fn the_interval_is_held_between_50_and_250_ms() {
561        let mut fast = received_media(Duration::from_millis(100), true);
562        let now = after_media(&mut fast, 5_000_000.0);
563        assert_eq!(MIN_ADAPTIVE_INTERVAL, fast.interval(now));
564        let mut slow = received_media(Duration::from_millis(100), true);
565        let now = after_media(&mut slow, 16_000.0);
566        assert_eq!(MAX_ADAPTIVE_INTERVAL, slow.interval(now));
567        let idle = received_media(Duration::from_millis(100), true);
568        assert_eq!(MAX_ADAPTIVE_INTERVAL, idle.interval(Instant::now()));
569    }
570
571    /// Reduced-size RTCP (RFC 5506) takes the report without the compound packet around it,
572    /// and the interval shortens with it.
573    #[test]
574    fn reduced_size_rtcp_shortens_the_interval() {
575        let mut compound = received_media(Duration::from_millis(50), true);
576        let now = after_media(&mut compound, 100_000.0);
577        let mut reduced = received_media(Duration::from_millis(50), true);
578        let then = after_media(&mut reduced, 100_000.0);
579        reduced.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(then));
580        assert!(reduced.interval(then) < compound.interval(now).mul_f64(0.8));
581    }
582
583    /// `b=RR` (RFC 3556) replaces the 5%.
584    #[test]
585    fn negotiated_receiver_rtcp_bandwidth_sets_the_interval() {
586        let mut cadence = received_media(Duration::from_millis(50), true);
587        let now = after_media(&mut cadence, 64_000.0);
588        let before = cadence.interval(now);
589        cadence.on_write(
590            &RtcpSessionControl::Bandwidth(RtcpBandwidth {
591                session: None,
592                rs: Some(8_000),
593                rr: Some(24_000),
594            })
595            .into_packet(now),
596        );
597        let after = cadence.interval(now);
598        assert!(after < before.mul_f64(0.5), "{before:?} -> {after:?}");
599    }
600
601    /// Media this endpoint sends is not what the feedback reports on.
602    #[test]
603    fn media_sent_does_not_count() {
604        let mut cadence = received_media(Duration::from_millis(100), true);
605        let now = Instant::now();
606        for n in 0..1_000u64 {
607            cadence.on_write(&media(now + Duration::from_millis(n), 1_200));
608        }
609        assert_eq!(
610            MAX_ADAPTIVE_INTERVAL,
611            cadence.interval(now + Duration::from_secs(1))
612        );
613    }
614
615    /// A smaller share and a longer ceiling (the `Performance` profile's 2.5% and 500 ms):
616    /// at 32 kbit/s of media a 40-octet report with its lower layers (68 octets) fits 2.5%
617    /// once every 0.68 s, held to 500 ms; the default holds it to 250 ms.
618    #[test]
619    fn a_smaller_share_lengthens_the_interval_up_to_its_ceiling() {
620        let mut cadence = received_media(Duration::from_millis(100), true)
621            .with_limits(0.025, Duration::from_millis(500));
622        let now = after_media(&mut cadence, 32_000.0);
623        cadence.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
624        assert_eq!(Duration::from_millis(500), cadence.interval(now));
625        let mut default = received_media(Duration::from_millis(100), true);
626        let then = after_media(&mut default, 32_000.0);
627        assert_eq!(MAX_ADAPTIVE_INTERVAL, default.interval(then));
628        // At 300 kbit/s the share, not the ceiling, sets it: 68 * 8 / 7500 = 72 ms.
629        let mut faster = received_media(Duration::from_millis(100), true)
630            .with_limits(0.025, Duration::from_millis(500));
631        let now = after_media(&mut faster, 300_000.0);
632        faster.on_write(&RtcpSessionControl::ReducedSize(true).into_packet(now));
633        let interval = faster.interval(now).as_secs_f64();
634        assert!((0.065..=0.08).contains(&interval), "{interval}");
635    }
636
637    fn stream(ssrc: u32, mime_type: &str) -> StreamInfo {
638        StreamInfo {
639            ssrc,
640            mime_type: mime_type.to_owned(),
641            ..Default::default()
642        }
643    }
644
645    fn packet(now: Instant, ssrc: u32, marker: bool) -> TaggedPacket {
646        TaggedPacket {
647            now,
648            transport: TransportContext::default(),
649            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
650                header: rtp::header::Header {
651                    version: 2,
652                    ssrc,
653                    marker,
654                    ..Default::default()
655                },
656                payload: vec![0u8; 100].into(),
657            })),
658        }
659    }
660
661    /// What the RTCP session and the congestion controller attach on the way up.
662    fn carrier<T: Send + Sync + 'static>(now: Instant, value: T) -> TaggedPacket {
663        TaggedPacket {
664            now,
665            transport: TransportContext::default(),
666            message: AttributedPacket::new(Packet::Rtcp(vec![]))
667                .with(Attribute::Custom(Arc::new(value))),
668        }
669    }
670
671    /// draft-ietf-rmcat-gcc-02 section 3: "once per received video frame". A session of one
672    /// video stream is reported when a frame ends (the marker), and after 100 ms without.
673    #[test]
674    fn one_video_stream_is_reported_when_a_frame_ends() {
675        let mut cadence = per_frame();
676        cadence.bind_remote(&stream(1, "video/VP8"));
677        let now = Instant::now();
678        assert!(!cadence.on_packet(&packet(now, 1, false)));
679        assert!(cadence.on_packet(&packet(now, 1, true)), "the frame ended");
680        // A packet of another SSRC (the stream's RTX, say) ends no frame of it.
681        assert!(!cadence.on_packet(&packet(now, 2, true)));
682        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
683    }
684
685    /// "or at least once every 30 ms if audio-only or multi-stream".
686    #[test]
687    fn audio_only_and_several_streams_are_reported_every_30_ms() {
688        let now = Instant::now();
689        let mut audio = per_frame();
690        audio.bind_remote(&stream(1, "audio/opus"));
691        assert_eq!(PER_FRAME_INTERVAL, audio.interval(now));
692        assert!(
693            !audio.on_packet(&packet(now, 1, true)),
694            "a talk spurt's marker"
695        );
696
697        let mut both = per_frame();
698        both.bind_remote(&stream(1, "audio/opus"));
699        both.bind_remote(&stream(2, "video/VP8"));
700        assert_eq!(PER_FRAME_INTERVAL, both.interval(now));
701        assert!(
702            !both.on_packet(&packet(now, 2, true)),
703            "the timer reports it"
704        );
705        // The audio stream ends: one video stream is left, reported per frame.
706        both.unbind_remote(&stream(1, "audio/opus"));
707        assert!(both.on_packet(&packet(now, 2, true)));
708    }
709
710    /// "If the feedback overhead needs to be limited this interval can be increased to 100
711    /// ms": where this endpoint's share of the RTCP bandwidth does not hold a feedback packet
712    /// (40 octets, 96 with the minimal compound packet and lower layers) every 30 ms, the
713    /// interval is the time in which it holds one, 100 ms at most.
714    #[test]
715    fn the_interval_grows_to_100_ms_where_the_rtcp_bandwidth_does_not_hold_it() {
716        let now = Instant::now();
717        let mut cadence = per_frame();
718        cadence.bind_remote(&stream(1, "audio/opus"));
719        let share = |bits_per_second: f64| carrier(now, RtcpBandwidthShare { bits_per_second });
720        // 96 octets every 30 ms are 25.6 kbit/s: a share of 100 kbit/s holds them.
721        cadence.on_packet(&share(100_000.0));
722        assert_eq!(PER_FRAME_INTERVAL, cadence.interval(now));
723        // 15.36 kbit/s hold one every 50 ms.
724        cadence.on_packet(&share(15_360.0));
725        assert_eq!(Duration::from_millis(50), cadence.interval(now));
726        // 3.8 kbit/s (an audio call's) would hold one every 202 ms: 100 ms, the draft's most.
727        cadence.on_packet(&share(3_800.0));
728        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
729        cadence.on_packet(&share(0.0));
730        assert_eq!(PER_FRAME_MAX_INTERVAL, cadence.interval(now));
731
732        // One video stream: a frame that ends sooner after the last report than the share
733        // holds is left to the next one.
734        let mut video = per_frame();
735        video.bind_remote(&stream(1, "video/VP8"));
736        video.on_packet(&share(15_360.0));
737        video.reported(now);
738        let at = |ms: u64| now + Duration::from_millis(ms);
739        assert!(!video.on_packet(&packet(at(33), 1, true)));
740        assert!(video.on_packet(&packet(at(66), 1, true)));
741    }
742
743    /// libwebrtc `OnSendBandwidthEstimateChanged`: 100 ms until an estimate is known, then the
744    /// time in which 5% of the send estimate holds 68 octets, between 50 and 250 ms.
745    #[test]
746    fn the_send_estimate_form_is_libwebrtcs_interval() {
747        let now = Instant::now();
748        let mut cadence = FeedbackCadence::new(Duration::from_millis(100), true)
749            .with_form(CongestionFeedbackCadence::SendEstimate);
750        cadence.bind_remote(&stream(1, "video/VP8"));
751        assert_eq!(Duration::from_millis(100), cadence.interval(now));
752        assert!(
753            !cadence.on_packet(&packet(now, 1, true)),
754            "no per-frame report"
755        );
756        let estimate = |bits_per_second: f64| carrier(now, crate::SendEstimate { bits_per_second });
757        cadence.on_packet(&estimate(1_000_000.0));
758        assert_eq!(MIN_ADAPTIVE_INTERVAL, cadence.interval(now));
759        // 68 * 8 / (0.05 * 100 000) = 108.8 ms.
760        cadence.on_packet(&estimate(100_000.0));
761        assert_eq!(Duration::from_micros(108_800), cadence.interval(now));
762        cadence.on_packet(&estimate(20_000.0));
763        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
764        // The media received does not move it.
765        let now = after_media(&mut cadence, 5_000_000.0);
766        assert_eq!(MAX_ADAPTIVE_INTERVAL, cadence.interval(now));
767    }
768
769    /// The fixed setting ignores all of it.
770    #[test]
771    fn a_fixed_interval_stays_fixed() {
772        let mut cadence = received_media(Duration::from_millis(100), false);
773        let now = after_media(&mut cadence, 64_000.0);
774        assert_eq!(Duration::from_millis(100), cadence.interval(now));
775    }
776
777    /// A video packet of SSRC 7 with `sequence_number` and RTP `timestamp`, 500 octets.
778    fn video(now: Instant, sequence_number: u16, timestamp: u32) -> TaggedPacket {
779        TaggedPacket {
780            now,
781            transport: TransportContext::default(),
782            message: AttributedPacket::new(Packet::Rtp(rtp::Packet {
783                header: rtp::header::Header {
784                    version: 2,
785                    ssrc: 7,
786                    sequence_number,
787                    timestamp,
788                    ..Default::default()
789                },
790                payload: vec![0u8; 488].into(),
791            })),
792        }
793    }
794
795    fn video_stream() -> StreamInfo {
796        StreamInfo {
797            ssrc: 7,
798            clock_rate: 90_000,
799            mime_type: "video/VP8".to_owned(),
800            ..Default::default()
801        }
802    }
803
804    /// Feeds both cadences `frames` frames of two packets from frame `first` on (30 a second,
805    /// the frame start arriving `wobble(frame)` late), a report every 100 ms; `skip` leaves a
806    /// sequence number out after that frame. Returns the instant after the last frame.
807    fn frames(
808        cadences: &mut [&mut FeedbackCadence],
809        epoch: Instant,
810        first: u32,
811        count: u32,
812        wobble: impl Fn(u32) -> Duration,
813        skip: Option<u32>,
814    ) -> Instant {
815        let frame_time = |frame: u32| epoch + Duration::from_nanos(33_333_333 * u64::from(frame));
816        let mut sequence = (first * 2) as u16 + u16::from(skip.is_some_and(|s| first > s));
817        for frame in first..first + count {
818            let at = frame_time(frame) + wobble(frame);
819            for part in 0..2u64 {
820                for cadence in cadences.iter_mut() {
821                    cadence.on_packet(&video(
822                        at + Duration::from_millis(part),
823                        sequence,
824                        frame * 3000,
825                    ));
826                }
827                sequence = sequence.wrapping_add(1);
828            }
829            if skip == Some(frame) {
830                sequence = sequence.wrapping_add(1);
831            }
832            if frame % 3 == 2 {
833                for cadence in cadences.iter_mut() {
834                    cadence.reported(at);
835                }
836            }
837        }
838        frame_time(first + count)
839    }
840
841    /// RFC 8836 section 2, requirement 8c: "In areas of stability, backchannel data may be sent
842    /// more infrequently so long as algorithm stability and fairness are maintained. When the
843    /// channel is unstable or has not yet reached equilibrium after a change, backchannel
844    /// feedback may be more frequent". With the stretch, after `STABLE_REPORTS` reports of a
845    /// path with no loss and no jitter, the interval is twice the form's; a missing packet
846    /// brings the form's back at once, and so does it stay until the path has been stable for
847    /// `STABLE_REPORTS` reports again. The form's own interval is the same with and without
848    /// the stretch (the precondition: both saw the same media).
849    #[test]
850    fn with_the_stability_stretch_the_interval_doubles_on_a_stable_path_only() {
851        let epoch = Instant::now();
852        let mut plain = received_media(Duration::from_millis(100), true);
853        let mut stretched =
854            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
855        plain.bind_remote(&video_stream());
856        stretched.bind_remote(&video_stream());
857        let steady = |_| Duration::ZERO;
858        let now = frames(
859            &mut [&mut plain, &mut stretched],
860            epoch,
861            0,
862            90,
863            steady,
864            None,
865        );
866        let base = plain.interval(now);
867        assert!(base < STABLE_MAX_INTERVAL / 2, "the precondition: {base:?}");
868        assert_eq!(stretched.form_interval(now), base);
869        assert_eq!(
870            stretched.interval(now),
871            base.mul_f64(STABLE_STRETCH),
872            "stable"
873        );
874
875        // A packet missing: the form's interval at once.
876        frames(
877            &mut [&mut plain, &mut stretched],
878            epoch,
879            90,
880            1,
881            steady,
882            Some(90),
883        );
884        let now = frames(
885            &mut [&mut plain, &mut stretched],
886            epoch,
887            91,
888            1,
889            steady,
890            Some(90),
891        );
892        assert_eq!(stretched.interval(now), plain.interval(now), "a loss");
893        // Stable again for fewer than STABLE_REPORTS reports: still the form's.
894        let now = frames(
895            &mut [&mut plain, &mut stretched],
896            epoch,
897            92,
898            4,
899            steady,
900            Some(90),
901        );
902        assert_eq!(
903            stretched.interval(now),
904            plain.interval(now),
905            "not yet stable again"
906        );
907        let now = frames(
908            &mut [&mut plain, &mut stretched],
909            epoch,
910            96,
911            30,
912            steady,
913            Some(90),
914        );
915        assert_eq!(
916            stretched.interval(now),
917            plain.interval(now).mul_f64(STABLE_STRETCH),
918            "stable again"
919        );
920    }
921
922    /// With frame starts arriving up to 30 ms late in turn (jitter over `STABLE_JITTER`) and no
923    /// loss, the path never reads stable: the interval stays the form's.
924    #[test]
925    fn with_the_stability_stretch_a_jittery_path_keeps_the_forms_interval() {
926        let epoch = Instant::now();
927        let mut plain = received_media(Duration::from_millis(100), true);
928        let mut stretched =
929            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
930        plain.bind_remote(&video_stream());
931        stretched.bind_remote(&video_stream());
932        let jittery =
933            |frame: u32| Duration::from_millis(if frame.is_multiple_of(2) { 0 } else { 30 });
934        let now = frames(
935            &mut [&mut plain, &mut stretched],
936            epoch,
937            0,
938            90,
939            jittery,
940            None,
941        );
942        assert!(
943            !stretched.jitter_low(),
944            "the precondition: the jitter is high"
945        );
946        assert_eq!(stretched.interval(now), plain.interval(now));
947    }
948
949    /// "When the channel is unstable or has not yet reached equilibrium after a change": a queue
950    /// that builds by a millisecond a frame has little jitter (the precondition: under
951    /// `STABLE_JITTER`), but it is no equilibrium: once the frame starts wait more than
952    /// `STABLE_QUEUE` above the lowest transit seen, the interval is the form's.
953    #[test]
954    fn with_the_stability_stretch_a_building_queue_keeps_the_forms_interval() {
955        let epoch = Instant::now();
956        let mut plain = received_media(Duration::from_millis(100), true);
957        let mut stretched =
958            received_media(Duration::from_millis(100), true).with_stability_stretch(true);
959        plain.bind_remote(&video_stream());
960        stretched.bind_remote(&video_stream());
961        let building = |frame: u32| Duration::from_millis(u64::from(frame));
962        let now = frames(
963            &mut [&mut plain, &mut stretched],
964            epoch,
965            0,
966            90,
967            building,
968            None,
969        );
970        assert!(stretched.jitter_low(), "the precondition: little jitter");
971        assert!(!stretched.queue_low(), "the precondition: a queue of 89 ms");
972        assert_eq!(stretched.interval(now), plain.interval(now));
973    }
974
975    /// RFC 8836 section 2, requirement 8c: "Backchannel data should be minimized to avoid
976    /// taking too much reverse-channel bandwidth". The default cadence keeps the feedback in 5 %
977    /// of the media received: on one call whose media goes from 2 Mbit/s to 32 kbit/s and up to
978    /// 400 kbit/s, the interval goes from its 50 ms floor to its 250 ms ceiling and back down
979    /// between them (96 octets in 5 % of 400 kbit/s: 38 ms, held at 50); each time the feedback
980    /// is at most 5 % of the media, or the ceiling's one report.
981    #[test]
982    fn the_interval_follows_the_media_rate_down_and_up_on_one_call() {
983        let mut cadence = received_media(Duration::from_millis(100), true);
984        let epoch = Instant::now();
985        let mut at = Duration::ZERO;
986        let mut run = |cadence: &mut FeedbackCadence, bits_per_second: f64| {
987            let octets = 500usize;
988            let spacing = Duration::from_secs_f64(octets as f64 * 8.0 / bits_per_second);
989            let end = at + Duration::from_secs(3);
990            while at < end {
991                cadence.on_packet(&media(epoch + at, octets));
992                at += spacing;
993            }
994            epoch + at
995        };
996        let now = run(&mut cadence, 2_000_000.0);
997        assert_eq!(cadence.interval(now), MIN_ADAPTIVE_INTERVAL, "2 Mbit/s");
998        let now = run(&mut cadence, 32_000.0);
999        assert_eq!(cadence.interval(now), MAX_ADAPTIVE_INTERVAL, "32 kbit/s");
1000        let now = run(&mut cadence, 400_000.0);
1001        let interval = cadence.interval(now);
1002        assert!(
1003            interval < MAX_ADAPTIVE_INTERVAL.mul_f64(0.3),
1004            "400 kbit/s: {interval:?}"
1005        );
1006    }
1007}