Skip to main content

rtci_interceptor/gcc/
estimator.rs

1//! `Gcc`: the delay half and the loss half, combined.
2
3use super::loss::LossController;
4use super::overuse::{OveruseDetector, Usage};
5use super::queue_limit::QueueLimitDetector;
6use super::rate_calc::RateCalculator;
7use super::rate_control::{RateController, ReceivedRateBound};
8use super::slope::SlopeEstimator;
9use super::threshold::ThresholdTimeBase;
10use crate::cc::estimator::{BandwidthEstimator, EstimatorStats};
11use crate::rtpfb::acknowledgement::PacketReport;
12use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
13use std::time::{Duration, Instant};
14
15/// The most delay-gradient readings the trend is scaled by before it meets the threshold.
16///
17/// The detector compares `min(readings, 60) × m(i)` against the adaptive threshold, as pion's
18/// `adaptiveThreshold.compare` and libwebrtc's `OveruseDetector::Detect` do: the Kalman estimate
19/// `m(i)` is a per-group delay gradient, a few milliseconds when a link is oversubscribed by half
20/// again, while the threshold starts at 12.5 ms (draft-ietf-rmcat-gcc-02 5.4). Compared unscaled,
21/// a sender at 1.8 times a 600 kbit/s link never reads as overusing.
22const MAX_SCALED_DELTAS: u32 = 60;
23
24/// Rate to start from when nothing is known yet.
25pub const DEFAULT_INITIAL_BITRATE: f64 = 300_000.0;
26/// Floor. Below this a video call is not worth having.
27pub const DEFAULT_MIN_BITRATE: f64 = 100_000.0;
28/// Ceiling.
29pub const DEFAULT_MAX_BITRATE: f64 = 100_000_000.0;
30
31/// How long feedback may be missing, while packets are being sent, before the target is cut.
32///
33/// RFC 8888 section 5 has the congestion control algorithm specify its response to lost
34/// feedback, and asks that several consecutive lost feedback packets rapidly reduce the sending
35/// rate; RFC 8836 requirement 10 treats an unexpected lack of backchannel information as
36/// possible over-use. Feedback is sent every 100 ms at most (draft-ietf-rmcat-gcc-02
37/// section 3), so half a second is five reports in a row.
38pub const DEFAULT_FEEDBACK_TIMEOUT: Duration = Duration::from_millis(500);
39
40/// What the target is multiplied by each time [`DEFAULT_FEEDBACK_TIMEOUT`] passes without
41/// feedback.
42pub const FEEDBACK_TIMEOUT_DECREASE: f64 = 0.5;
43
44/// How long a probe result stands in for the received rate in the bound of the estimate by
45/// one and a half times what is received (section 5.5). A sender that follows the target is
46/// received at the new rate within a window of the received-rate measurement and the bound
47/// is the draft's again. A sender with less to send than the target is probed again every
48/// five seconds: the result stands until the next one is due and has had its second to
49/// arrive, so the estimate rests on a measurement no older than that instead of falling back
50/// to one and a half times what the application happens to send and jumping up again with
51/// every probe. A probe that confirms the estimate renews it; over-use lowers it with the
52/// estimate.
53pub const PROBE_RESULT_HOLD: Duration = Duration::from_secs(6);
54
55/// A probe result at least this share of the estimate confirms it (see
56/// [`PROBE_RESULT_HOLD`]): the cluster arrived at about the rate the estimate already is.
57pub const PROBE_CONFIRMS_ESTIMATE: f64 = 0.9;
58
59/// A pause in sending up to this long keeps the estimate (RFC 8836 section 2, requirement
60/// 5a: the flow regains its share fast).
61pub const PAUSE_KEEPS_SHARE: Duration = Duration::from_secs(2);
62/// Beyond [`PAUSE_KEEPS_SHARE`], each such stretch of pause halves the estimate the flow resumes
63/// at (requirement 5a: less aggressively the longer the interruption).
64pub const PAUSE_HALVING: Duration = Duration::from_secs(10);
65
66/// Google Congestion Control.
67///
68/// # The two halves
69///
70/// ```text
71/// reports ─┬─▶ SlopeEstimator ─▶ OveruseDetector ─▶ RateController ─┐
72///          │   group, filter      usage + adaptive   AIMD           ├─▶ min ─▶ target
73///          │                      threshold                         │
74///          ├─▶ RateCalculator ────────────────────────────────────▶─┘
75///          │   what is actually arriving
76///          └─▶ LossController ────────────────────────────────────▶─┘
77/// ```
78///
79/// The two are combined by **`min`**: whichever signal is more pessimistic wins. A path can be
80/// congested in either way independently — a deep buffer queues without losing, a shallow or lossy
81/// one loses without queueing — so neither half alone is sufficient and taking the lower of the two
82/// is the only combination that responds to both.
83///
84/// # Deliberate divergences from upstream
85///
86/// - **D3 — one clamp.** Applied once, here, from configuration. Upstream clamps inside the loss
87///   controller to a hard-coded 100 kb/s–100 Mb/s *and* again in the rate controller to the
88///   configured range, and the two disagree.
89/// - **D4 — loss may move the target alone.** See [`LossController`].
90/// - **No hidden headroom.** [`target_bitrate`](Self::target_bitrate) is what the pacer is asked
91///   for. Upstream's pacer silently multiplies by 1.5, so its reported target and its wire rate
92///   differ by half again.
93/// - **No clock.** Every instant is a parameter, which is what makes a bitrate trajectory
94///   reproducible.
95pub struct Gcc {
96    /// The delay-based detection of each codepoint the sent flows carry, by DSCP (RFC 8836
97    /// section 2, requirement 9; [`Gcc::on_flow_codepoints`]): one for all of them while they
98    /// share one, which is every flow of a connection whose encodings and channels keep the
99    /// default priority (`low`: DSCP 0).
100    paths: std::collections::BTreeMap<u8, DelayPath>,
101    /// The DSCP of each sent stream, by SSRC; a stream not named is DSCP 0.
102    codepoints: std::collections::HashMap<u32, u8>,
103    rate: RateCalculator,
104    delay_control: RateController,
105    loss_control: LossController,
106    min: f64,
107    max: f64,
108    target: f64,
109    /// One report's arrival on the receiver's clock and the local instant it is placed at, so
110    /// later arrivals can be placed on this endpoint's timeline for the received-rate window.
111    arrival_anchor: Option<(Duration, Instant)>,
112    /// The newest arrival placed so far.
113    newest_arrival: Option<Instant>,
114    /// The range the application configured; `min` and `max` are this, narrowed by the limits
115    /// from outside.
116    configured: (f64, f64),
117    /// The starting estimate, which a long pause in sending falls back towards.
118    initial: f64,
119    /// When feedback was last read, once any has been.
120    last_feedback: Option<Instant>,
121    /// When a packet was last sent.
122    last_sent: Option<Instant>,
123    /// When a packet that per-packet feedback will report was last sent.
124    last_reported_sent: Option<Instant>,
125    /// When the missing-feedback cut next applies: set while packets sent after the last
126    /// feedback are waiting for theirs.
127    feedback_deadline: Option<Instant>,
128    feedback_timeout: Duration,
129    /// Whether the loss-based estimate is held at or below the delay-based one.
130    loss_capped_by_delay: bool,
131    /// Smoothed interval between feedback reports, as the receiver actually sends them.
132    feedback_interval: Option<Duration>,
133    round_trip_time: Option<Duration>,
134    /// When the last probe result was taken.
135    probed_at: Option<Instant>,
136    /// Whether a loss out of a queue at its limit is over-use (see
137    /// [`with_loss_at_queue_limit_as_overuse`](Self::with_loss_at_queue_limit_as_overuse)).
138    loss_at_queue_limit_is_overuse: bool,
139    queue_limit: QueueLimitDetector,
140    threshold_time_base: ThresholdTimeBase,
141    /// How the last feedback read the path (the detector's signal, over-use too for a loss
142    /// out of a queue at its limit).
143    usage: Usage,
144}
145
146/// The delay half's grouping, filter and detector over the packets of one DSCP (RFC 8836
147/// section 2, requirement 9): flows marked differently may wait in different queues of a
148/// bottleneck that honours the marking, and the arrival times of one queue say nothing of the
149/// growth of another's. Each codepoint's packets are grouped and filtered on their own, and
150/// the path reads over-used when any of its queues grows ([`combine_usage`]). Where the
151/// bottleneck does not honour the marking, every codepoint sees the one queue and reads the
152/// same.
153struct DelayPath {
154    slope: SlopeEstimator,
155    detector: OveruseDetector,
156    /// Delay-gradient readings so far, capped at [`MAX_SCALED_DELTAS`].
157    deltas: u32,
158}
159
160impl DelayPath {
161    fn new(time_base: ThresholdTimeBase) -> Self {
162        Self {
163            slope: SlopeEstimator::new(),
164            detector: OveruseDetector::new().with_threshold_time_base(time_base),
165            deltas: 0,
166        }
167    }
168}
169
170/// The reading of a path whose codepoints read `usages`: over-used when any queue grows (more
171/// is sent than one of them carries), else under-used when any drains (hold: room is being
172/// given back somewhere), else normal. With one codepoint, its reading.
173fn combine_usage(usages: impl Iterator<Item = Usage>) -> Usage {
174    usages.fold(Usage::Normal, |combined, usage| match (combined, usage) {
175        (Usage::Over, _) | (_, Usage::Over) => Usage::Over,
176        (Usage::Under, _) | (_, Usage::Under) => Usage::Under,
177        _ => Usage::Normal,
178    })
179}
180
181impl Default for Gcc {
182    fn default() -> Self {
183        Self::new(
184            DEFAULT_INITIAL_BITRATE,
185            DEFAULT_MIN_BITRATE,
186            DEFAULT_MAX_BITRATE,
187        )
188    }
189}
190
191impl Gcc {
192    /// RFC 8836 section 2, requirement 5a: after a pause in sending the flow "SHOULD [...]
193    /// regain [its previous share] fast, but [...] less aggressively the longer the
194    /// interruption". A pause up to [`PAUSE_KEEPS_SHARE`] keeps the estimate; a longer one
195    /// halves it for every [`PAUSE_HALVING`] beyond that (the path may have changed meanwhile),
196    /// down to the starting estimate at most, from where the controller (and bandwidth probing)
197    /// climbs again.
198    fn resume_after(&mut self, pause: Duration) {
199        let Some(beyond) = pause.checked_sub(PAUSE_KEEPS_SHARE) else {
200            return;
201        };
202        let factor = 0.5f64.powf(beyond.as_secs_f64() / PAUSE_HALVING.as_secs_f64());
203        let floor = self.initial.min(self.target);
204        let resumed = (self.target * factor).max(floor).clamp(self.min, self.max);
205        if resumed < self.target {
206            self.target = resumed;
207            self.delay_control.set_target(resumed);
208            self.delay_control.reset_convergence();
209            self.loss_control.cap(resumed);
210        }
211    }
212    /// An estimator starting at `initial`, held within `min..=max`.
213    pub fn new(initial: f64, min: f64, max: f64) -> Self {
214        let initial = initial.clamp(min, max);
215        Self {
216            paths: std::collections::BTreeMap::from([(
217                0,
218                DelayPath::new(ThresholdTimeBase::default()),
219            )]),
220            codepoints: std::collections::HashMap::new(),
221            rate: RateCalculator::default(),
222            delay_control: RateController::new(initial, min, max),
223            loss_control: LossController::new(initial, min, max),
224            min,
225            max,
226            target: initial,
227            arrival_anchor: None,
228            newest_arrival: None,
229            configured: (min, max),
230            initial,
231            last_feedback: None,
232            last_sent: None,
233            last_reported_sent: None,
234            feedback_deadline: None,
235            feedback_timeout: DEFAULT_FEEDBACK_TIMEOUT,
236            loss_capped_by_delay: true,
237            feedback_interval: None,
238            round_trip_time: None,
239            probed_at: None,
240            loss_at_queue_limit_is_overuse: true,
241            queue_limit: QueueLimitDetector::new(),
242            threshold_time_base: ThresholdTimeBase::default(),
243            usage: Usage::Normal,
244        }
245    }
246
247    /// Whether a packet lost out of a queue at its limit counts as over-use for the
248    /// delay-based controller (the default), or only for the loss-based one as
249    /// draft-ietf-rmcat-gcc-02 has it.
250    ///
251    /// The draft's over-use signal is the delay *gradient*: a queue that is growing. A
252    /// tail-drop queue that has filled to its limit no longer grows, whatever is sent into
253    /// it: the gradient is zero, the detector reads normal and the delay-based estimate keeps
254    /// climbing, while the loss-based controller holds anywhere between 2% and 10% loss
255    /// (section 6). A flow in that state never yields. Measured on a shared FIFO bottleneck
256    /// (`rtci-interceptor/tests/rfc8836_multi_flow.rs`): a second flow joining an established
257    /// one fell to the floor, and against a Reno-like transfer `Gcc` took 97% of the path,
258    /// both against RFC 8836 section 2 (requirements 2a, a MUST, and 3). With the default, a
259    /// feedback batch that lost a packet while every packet of it that arrived waited near the
260    /// highest queueing delay seen of late ([`QueueLimitDetector`]) is over-use: the
261    /// estimate backs off as from a growing queue, and the queue drains. Loss with little or
262    /// no queue (a radio link, a policer) is left to the loss-based controller, as before.
263    /// `false` is the draft as written.
264    pub fn with_loss_at_queue_limit_as_overuse(mut self, enabled: bool) -> Self {
265        self.loss_at_queue_limit_is_overuse = enabled;
266        self
267    }
268
269    /// Whether over-use lowers the estimate at most once per round trip (libwebrtc's form) or
270    /// on every update while it lasts, as draft-ietf-rmcat-gcc-02 section 5.5 has it (the
271    /// default). See
272    /// [`RateController::with_one_decrease_per_round_trip`].
273    pub fn with_one_decrease_per_round_trip(mut self, enabled: bool) -> Self {
274        self.delay_control = self.delay_control.with_one_decrease_per_round_trip(enabled);
275        self
276    }
277
278    /// What the bound of the estimate by the received rate (draft-ietf-rmcat-gcc-02 section
279    /// 5.5, `A_hat(i) < 1.5 * R_hat(i)`) does to an estimate above it: nothing but stop its
280    /// increase ([`ReceivedRateBound::LimitsIncrease`], the default), or bring it down to
281    /// the bound ([`ReceivedRateBound::Clamps`]). See [`ReceivedRateBound`].
282    ///
283    /// With the default an application that sends less than the estimate (audio alone, a
284    /// camera turned off, the first moments of a call) keeps the estimate it had: it is
285    /// lowered by over-use, by loss, and by feedback that stops while packets it covers are
286    /// sent, and by nothing else.
287    pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
288        self.delay_control = self
289            .delay_control
290            .with_received_rate_bound(received_rate_bound);
291        self
292    }
293
294    /// How long feedback may be missing, while packets are being sent, before the target is
295    /// halved (and halved again each time the same period passes).
296    pub fn with_feedback_timeout(mut self, feedback_timeout: Duration) -> Self {
297        self.feedback_timeout = feedback_timeout;
298        self
299    }
300
301    /// The time step of the adaptive threshold (draft-ietf-rmcat-gcc-02 section 5.4):
302    /// the draft's [`ThresholdTimeBase::Arrival`] (the default), libwebrtc's
303    /// [`ThresholdTimeBase::ArrivalCapped`] or [`ThresholdTimeBase::Departure`].
304    pub fn with_threshold_time_base(mut self, time_base: ThresholdTimeBase) -> Self {
305        self.threshold_time_base = time_base;
306        for path in self.paths.values_mut() {
307            path.detector = path.detector.with_threshold_time_base(time_base);
308        }
309        self
310    }
311
312    /// See [`ThresholdTimeBase`]: the time step of the adaptive threshold (draft-ietf-rmcat-gcc-02
313    /// section 5.4), the arrival gaps by default.
314    pub fn threshold_time_base(&self) -> ThresholdTimeBase {
315        self.threshold_time_base
316    }
317
318    /// Whether the loss-based estimate As_hat is held at or below the delay-based estimate
319    /// A_hat after every update (the default), or left free with only the minimum of the two
320    /// taken as the sending rate.
321    ///
322    /// draft-ietf-rmcat-gcc-02 section 6 has the loss-based controller work from the available
323    /// bandwidth estimate of the delay-based one. Left free, As_hat grows 5% per interval
324    /// whenever loss is under 2%, whatever the path carries: after five quiet seconds it is
325    /// several times the rate being sent, and `As_hat(i) = As_hat(i-1)(1 - 0.5p)` then has to
326    /// cut it back through all of that before the sending rate moves at all. Capped, a loss
327    /// cut is taken from the rate actually being sent, and the climb back starts from there.
328    pub fn with_loss_estimate_capped_by_delay_estimate(mut self, capped: bool) -> Self {
329        self.loss_capped_by_delay = capped;
330        self
331    }
332
333    /// How long feedback may be missing before the target is cut: the configured timeout, or
334    /// three of the receiver's own feedback intervals when those are longer.
335    ///
336    /// A receiver that keeps its feedback inside the RTCP bandwidth (RFC 3550 section 6.2; at
337    /// 100 kbit/s of media that is a few packets per second) reports every few hundred
338    /// milliseconds, not every hundred. Its regular rhythm is not missing feedback.
339    fn effective_feedback_timeout(&self) -> Duration {
340        self.feedback_interval
341            .map_or(self.feedback_timeout, |interval| {
342                self.feedback_timeout.max(interval * 3)
343            })
344    }
345
346    /// Bring both controllers and the target into the current range.
347    fn apply_range(&mut self) {
348        self.delay_control.set_bounds(self.min, self.max);
349        self.loss_control.set_bounds(self.min, self.max);
350        self.target = self.target.clamp(self.min, self.max);
351    }
352
353    /// Place an arrival on the receiver's clock onto this endpoint's timeline.
354    ///
355    /// Only differences between arrivals mean anything, so the first one seen is pinned to the
356    /// instant its feedback was read and every later one keeps its distance from it.
357    fn place_arrival(&mut self, now: Instant, arrival: Duration) -> Instant {
358        let (anchor_arrival, anchor_instant) = *self.arrival_anchor.get_or_insert((arrival, now));
359        if arrival >= anchor_arrival {
360            anchor_instant + (arrival - anchor_arrival)
361        } else {
362            anchor_instant
363                .checked_sub(anchor_arrival - arrival)
364                .unwrap_or(anchor_instant)
365        }
366    }
367
368    /// The delay-based half's current target, in bits per second.
369    pub fn delay_based_bitrate(&self) -> f64 {
370        self.delay_control.target()
371    }
372
373    /// The loss-based half's current target, in bits per second.
374    pub fn loss_based_bitrate(&self) -> f64 {
375        self.loss_control.target()
376    }
377}
378
379impl BandwidthEstimator for Gcc {
380    /// RFC 6679 section 7.3.3: CE marks counted by the receiver's ECN reports go to the
381    /// loss-based controller as losses would; the target can only fall by them.
382    fn on_congestion_marks(&mut self, now: Instant, marked: u64, packets: u64) {
383        if marked == 0 || packets == 0 {
384            return;
385        }
386        let packets = packets.min(usize::MAX as u64) as usize;
387        let marked = (marked.min(packets as u64)) as usize;
388        self.loss_control.update(now, marked, packets);
389        let loss_target = self.loss_control.target();
390        self.target = self.target.min(loss_target).clamp(self.min, self.max);
391    }
392
393    fn on_reports(&mut self, now: Instant, reports: &[PacketReport]) {
394        if reports.is_empty() {
395            return;
396        }
397        // A probe's measurement stands in for the received rate until the received rate has
398        // had its window to follow.
399        if let Some(probed_at) = self.probed_at
400            && now.saturating_duration_since(probed_at) > PROBE_RESULT_HOLD
401        {
402            self.probed_at = None;
403            self.delay_control.set_measured_rate(None);
404        }
405
406        // Delay: group, filter, detect (each codepoint on its own), control.
407        for report in reports {
408            // The received rate is what arrived per unit of the *receiver's* time
409            // (draft-ietf-rmcat-gcc-02 5.5). Counting acknowledged bytes at the instant their
410            // feedback was read instead measures one more feedback interval of bytes than of
411            // time, which reads 20 to 25% high at a 100 ms cadence — enough that backing off to
412            // 0.85 of it lands above the link.
413            if report.arrived
414                && let Some(arrival) = report.arrival
415            {
416                let at = self.place_arrival(now, arrival);
417                self.rate.add(at, report.size);
418                self.newest_arrival = Some(self.newest_arrival.map_or(at, |newest| newest.max(at)));
419            }
420            let codepoint = self.codepoints.get(&report.ssrc).copied().unwrap_or(0);
421            let time_base = self.threshold_time_base;
422            let path = self
423                .paths
424                .entry(codepoint)
425                .or_insert_with(|| DelayPath::new(time_base));
426            if let Some(trend) = path.slope.accumulate(report) {
427                path.deltas = (path.deltas + 1).min(MAX_SCALED_DELTAS);
428                path.detector.update_with_arrival(
429                    trend.at,
430                    trend.arrival,
431                    trend.estimate_ms * f64::from(path.deltas),
432                );
433            }
434        }
435        let mut usage = combine_usage(self.paths.values().map(|path| path.detector.usage()));
436
437        let received = self
438            .newest_arrival
439            .and_then(|newest| self.rate.rate_bits_per_second(newest));
440        // A loss out of a queue at its limit: the queue would be growing, had it room.
441        if self.queue_limit.on_reports(now, reports) && self.loss_at_queue_limit_is_overuse {
442            usage = Usage::Over;
443        }
444        self.usage = usage;
445        let delay_target = self.delay_control.update(now, usage, received);
446
447        // Loss: a fraction over this batch. A packet that arrived marked ECN-CE counts as one
448        // that did not: "a CE mark is a congestion signal" (RFC 8888 section 7 with RFC 6679
449        // section 7.3.3: the sender reacts to it as to a lost packet, without retransmitting).
450        let lost = reports
451            .iter()
452            .filter(|report| !report.arrived || report.ecn == Ecn::Ce)
453            .count();
454        self.loss_control.update(now, lost, reports.len());
455        if self.loss_capped_by_delay {
456            self.loss_control.cap(delay_target);
457        }
458        let loss_target = self.loss_control.target();
459        log::debug!(
460            "gcc: feedback of {} packets, {lost} lost; loss average {:?}, delay target {delay_target:.0}, loss target {loss_target:.0}",
461            reports.len(),
462            self.loss_control.average_loss(),
463        );
464
465        // Whichever half is more pessimistic wins, clamped once (D3).
466        self.target = delay_target.min(loss_target).clamp(self.min, self.max);
467
468        // Feedback arrived: the missing-feedback clock starts again when the next packet
469        // leaves.
470        if let Some(last) = self.last_feedback {
471            let interval = now.saturating_duration_since(last);
472            self.feedback_interval = Some(match self.feedback_interval {
473                Some(previous) => previous.mul_f64(0.8) + interval.mul_f64(0.2),
474                None => interval,
475            });
476        }
477        self.last_feedback = Some(now);
478        self.feedback_deadline = None;
479    }
480
481    /// A packet that no per-packet feedback will report: the flow is not paused, and its
482    /// feedback is not awaited.
483    fn on_unreported_packet_sent(&mut self, now: Instant, _size: usize) {
484        if let Some(last) = self.last_sent {
485            self.resume_after(now.saturating_duration_since(last));
486        }
487        self.last_sent = Some(now);
488    }
489
490    fn on_packet_sent(&mut self, now: Instant, size: usize) {
491        self.on_unreported_packet_sent(now, size);
492        self.last_reported_sent = Some(now);
493        // Only once feedback has a rhythm (two reports) is its absence unexpected: a receiver
494        // that never sends any is handled by the receiver-report fallback, and one that has
495        // sent a single report has not yet shown how often it reports.
496        if self.feedback_interval.is_some() && self.feedback_deadline.is_none() {
497            self.feedback_deadline = Some(now + self.effective_feedback_timeout());
498        }
499    }
500
501    /// RFC 8836 section 2, requirement 9: each codepoint's packets get a delay detection of
502    /// their own ([`DelayPath`]). A codepoint no stream carries any longer is dropped; one
503    /// that appears starts fresh.
504    fn on_flow_codepoints(&mut self, codepoints: &[(u32, u8)]) {
505        self.codepoints = codepoints
506            .iter()
507            .copied()
508            .filter(|(_, dscp)| *dscp != 0)
509            .collect();
510        let used: std::collections::BTreeSet<u8> = self.codepoints.values().copied().collect();
511        self.paths
512            .retain(|codepoint, _| *codepoint == 0 || used.contains(codepoint));
513    }
514
515    fn on_round_trip_time(&mut self, _now: Instant, round_trip_time: Duration) {
516        self.round_trip_time = Some(round_trip_time);
517        self.delay_control.set_round_trip_time(round_trip_time);
518    }
519
520    fn min_bitrate(&self) -> Option<f64> {
521        Some(self.min)
522    }
523
524    fn max_bitrate(&self) -> Option<f64> {
525        Some(self.max)
526    }
527
528    fn usage(&self) -> Usage {
529        self.usage
530    }
531
532    fn set_external_bounds(&mut self, min: Option<f64>, max: Option<f64>) {
533        let (configured_min, configured_max) = self.configured;
534        self.max = max.map_or(configured_max, |max| max.min(configured_max));
535        // A limit below the floor wins: the floor is a preference, the limit is not.
536        self.min = min.unwrap_or(configured_min).min(self.max);
537        self.apply_range();
538    }
539
540    fn on_receiver_report(&mut self, now: Instant, fraction_lost: f64) {
541        // No per-packet feedback: the delay-based controller has nothing to run on, and the
542        // loss-based one runs on the fraction lost the receiver reports (section 7).
543        self.loss_control.update_fraction(now, fraction_lost);
544        self.target = self.loss_control.target().clamp(self.min, self.max);
545        self.delay_control.set_target(self.target);
546    }
547
548    fn on_probe_result(&mut self, now: Instant, bits_per_second: f64) {
549        if !bits_per_second.is_finite() || bits_per_second <= 0.0 {
550            return;
551        }
552        if bits_per_second <= self.target {
553            // A probe only ever raises the estimate: one that came out well below it says the
554            // cluster met a queue, which the delay-based controller hears about by itself.
555            // One that the path carried at about the estimate confirms it: the measurement is
556            // renewed, so that an application sending less than the target keeps resting on
557            // it rather than falling back, once the last raise is older than the hold, to one
558            // and a half times what it sends (and from there, by the same bound, lower with
559            // every update).
560            if bits_per_second >= PROBE_CONFIRMS_ESTIMATE * self.target {
561                self.delay_control.set_measured_rate(Some(bits_per_second));
562                self.probed_at = Some(now);
563            }
564            return;
565        }
566        // The path carried the cluster at this rate. Both halves start from it, the climb
567        // from here is multiplicative again, and for a while the measurement stands in for
568        // the received rate, which only follows once the application sends at the new target.
569        self.delay_control.set_target(bits_per_second);
570        self.delay_control.reset_convergence();
571        self.delay_control.set_measured_rate(Some(bits_per_second));
572        self.probed_at = Some(now);
573        self.loss_control.raise(bits_per_second);
574        self.target = self
575            .delay_control
576            .target()
577            .min(self.loss_control.target())
578            .clamp(self.min, self.max);
579    }
580
581    /// A new path (another candidate pair selected) starts the estimate over from the starting
582    /// estimate. The estimate describes the path it was measured on (RFC 8836 section 2,
583    /// requirement 1d: the flow reacts to a change of the path; draft-ietf-rmcat-gcc-02 says
584    /// nothing of it). Kept, it is right for a change between like paths and wrong in either
585    /// direction otherwise: too high for a slower network, and, after an outage that the
586    /// missing feedback halved it through, far too low for the network the connection came
587    /// back on. libwebrtc starts over as well
588    /// (`call/rtp_transport_controller_send.cc:356-357`, `OnNetworkRouteChanged`: "If it is,
589    /// restart BWE.", `restart_bwe = IsRelevantRouteChange(old_route, network_route)`, sent
590    /// to the controller at line 393 as `msg.restart_bwe`).
591    fn on_path_change(&mut self, _now: Instant) {
592        // Delay measurements across two paths mean nothing, and neither does where the old
593        // path converged.
594        let time_base = self.threshold_time_base;
595        for path in self.paths.values_mut() {
596            *path = DelayPath::new(time_base);
597        }
598        self.rate = RateCalculator::default();
599        self.arrival_anchor = None;
600        self.newest_arrival = None;
601        self.queue_limit = QueueLimitDetector::new();
602        self.delay_control.reset_convergence();
603        self.usage = Usage::Normal;
604        self.feedback_deadline = None;
605        self.target = self.initial.clamp(self.min, self.max);
606        self.delay_control.set_target(self.target);
607        self.delay_control.set_measured_rate(None);
608        self.probed_at = None;
609        self.loss_control.cap(self.target);
610        self.loss_control.raise(self.target);
611        self.last_sent = None;
612        self.last_reported_sent = None;
613    }
614
615    fn handle_timeout(&mut self, now: Instant) {
616        // Packets were sent and nothing has been heard about them for a whole timeout: treat
617        // it as over-use. Halve, and again for each further timeout without feedback.
618        while let Some(deadline) = self.feedback_deadline
619            && now >= deadline
620        {
621            self.target = (self.target * FEEDBACK_TIMEOUT_DECREASE).clamp(self.min, self.max);
622            self.delay_control.set_target(self.target);
623            self.loss_control.cap(self.target);
624            // Keep counting only while packets are still going out.
625            let timeout = self.effective_feedback_timeout();
626            self.feedback_deadline = self
627                .last_reported_sent
628                .is_some_and(|sent| sent + timeout > deadline)
629                .then(|| deadline + timeout);
630        }
631    }
632
633    fn poll_timeout(&self) -> Option<Instant> {
634        self.feedback_deadline
635    }
636
637    fn target_bitrate(&self) -> f64 {
638        self.target
639    }
640
641    fn stats(&self) -> EstimatorStats {
642        EstimatorStats {
643            delay_based_bitrate: Some(self.delay_control.target()),
644            loss_based_bitrate: Some(self.loss_control.target()),
645            packet_loss: self.loss_control.average_loss(),
646            round_trip_time: self.round_trip_time,
647        }
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
655    use std::time::Duration;
656
657    fn report(id: u64, departure: Instant, arrival_ms: Option<u64>) -> PacketReport {
658        PacketReport {
659            ssrc: 1,
660            id,
661            rtp_sequence_number: id as u16,
662            is_twcc: true,
663            twcc_sequence_number: id as u16,
664            size: 1500,
665            arrived: arrival_ms.is_some(),
666            departure,
667            arrival: arrival_ms.map(Duration::from_millis),
668            ecn: Ecn::default(),
669        }
670    }
671
672    /// RFC 8836 section 2, requirement 5a: a short pause keeps the estimate, a long one brings
673    /// it down, the more the longer the pause, never below the starting estimate.
674    #[test]
675    fn a_pause_in_sending_keeps_the_estimate_and_a_long_one_lowers_it() {
676        let epoch = Instant::now();
677        let resumed_after = |pause: Duration| {
678            let mut gcc = Gcc::new(300_000.0, 100_000.0, 10_000_000.0);
679            gcc.on_probe_result(epoch, 2_000_000.0);
680            gcc.on_packet_sent(epoch, 1200);
681            gcc.on_packet_sent(epoch + pause, 1200);
682            gcc.target_bitrate()
683        };
684        assert_eq!(resumed_after(Duration::from_millis(500)), 2_000_000.0);
685        assert_eq!(resumed_after(PAUSE_KEEPS_SHARE), 2_000_000.0);
686        let twelve = resumed_after(PAUSE_KEEPS_SHARE + PAUSE_HALVING);
687        assert!((twelve - 1_000_000.0).abs() < 1.0, "{twelve}");
688        let long = resumed_after(Duration::from_secs(120));
689        assert_eq!(long, 300_000.0, "down to the starting estimate, not below");
690    }
691
692    /// `usage` is the reading of the last feedback: normal at the start, over-use while
693    /// packets sent 10 ms apart arrive 40 ms apart (a growing queue, which lowers the target),
694    /// and not over-use once they arrive as they left.
695    #[test]
696    fn usage_follows_the_last_feedback() {
697        let epoch = Instant::now();
698        let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
699        assert_eq!(Usage::Normal, gcc.usage());
700        let mut id = 0u64;
701        let mut arrival_ms = 50u64;
702        let mut seen = false;
703        // Two seconds of a growing queue, a batch of ten packets every 100 ms.
704        for batch in 0..20u64 {
705            let reports: Vec<PacketReport> = (0..10u64)
706                .map(|n| {
707                    id += 1;
708                    arrival_ms += 40;
709                    report(
710                        id,
711                        epoch + Duration::from_millis(100 * batch + 10 * n),
712                        Some(arrival_ms),
713                    )
714                })
715                .collect();
716            gcc.on_reports(epoch + Duration::from_millis(100 * (batch + 1)), &reports);
717            seen |= gcc.usage() == Usage::Over;
718        }
719        assert!(seen, "a growing queue reads as over-use");
720        assert!(gcc.target_bitrate() < 1_000_000.0, "and lowers the target");
721        // Five seconds in which packets arrive as far apart as they left.
722        for batch in 20..70u64 {
723            let reports: Vec<PacketReport> = (0..10u64)
724                .map(|n| {
725                    id += 1;
726                    arrival_ms += 10;
727                    report(
728                        id,
729                        epoch + Duration::from_millis(100 * batch + 10 * n),
730                        Some(arrival_ms),
731                    )
732                })
733                .collect();
734            gcc.on_reports(epoch + Duration::from_millis(100 * (batch + 1)), &reports);
735        }
736        assert_ne!(
737            Usage::Over,
738            gcc.usage(),
739            "a queue that no longer grows does not"
740        );
741    }
742
743    /// RFC 8836 section 2, requirement 9: "The algorithm SHOULD attempt to leverage DSCP
744    /// markings when they're available." Video marked AF41 (SSRC 1) waits in a queue that grows
745    /// (sent 10 ms apart, arriving 20 ms apart); audio marked EF (SSRC 2) is sent 5 ms after
746    /// each video packet and goes through a queue that stays at 500 ms. Told the codepoints,
747    /// the estimator reads the path exactly as it reads the video alone, after every batch
748    /// (the audio's arrivals, interleaved, do not enter the video's delay signal), and that
749    /// reading is over-use. The precondition: the audio arrives after the video packet before
750    /// it for the first batches, so a signal that mixed the two would take its arrivals in.
751    #[test]
752    fn each_codepoints_queue_is_read_on_its_own() {
753        let epoch = Instant::now();
754        let packet = |ssrc: u32, id: u64, departure_ms: u64, arrival_ms: u64| PacketReport {
755            ssrc,
756            id,
757            rtp_sequence_number: id as u16,
758            is_twcc: true,
759            twcc_sequence_number: id as u16,
760            size: 1200,
761            arrived: true,
762            departure: epoch + Duration::from_millis(departure_ms),
763            arrival: Some(Duration::from_millis(arrival_ms)),
764            ecn: Ecn::default(),
765        };
766        let mut alone = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
767        let mut marked = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
768        marked.on_flow_codepoints(&[(1, 34), (2, 46)]);
769        let (mut id, mut over, mut audio_after_video) = (0u64, false, 0);
770        for batch in 0..20u64 {
771            let mut video = Vec::new();
772            let mut both = Vec::new();
773            for n in 0..10u64 {
774                let k = batch * 10 + n;
775                let video_arrival = 50 + 20 * k;
776                id += 1;
777                let v = packet(1, id, 10 * k, video_arrival);
778                video.push(v.clone());
779                both.push(v);
780                id += 1;
781                let audio_arrival = 10 * k + 5 + 500;
782                audio_after_video += usize::from(audio_arrival > video_arrival);
783                both.push(packet(2, id, 10 * k + 5, audio_arrival));
784            }
785            let now = epoch + Duration::from_millis(100 * (batch + 1));
786            alone.on_reports(now, &video);
787            marked.on_reports(now, &both);
788            assert_eq!(alone.usage(), marked.usage(), "after batch {batch}");
789            over |= marked.usage() == Usage::Over;
790        }
791        assert!(over, "the video's growing queue reads as over-use");
792        assert!(
793            audio_after_video >= 20,
794            "the precondition: interleaved arrivals ({audio_after_video})"
795        );
796    }
797
798    /// Without codepoints (every flow DSCP 0, the default priority) the estimator keeps one
799    /// delay signal, as before requirement 9 was read; and codepoints a flow no longer carries
800    /// are forgotten.
801    #[test]
802    fn flows_of_one_codepoint_share_one_delay_signal() {
803        let mut gcc = Gcc::default();
804        assert_eq!(gcc.paths.len(), 1);
805        gcc.on_flow_codepoints(&[(1, 34), (2, 46), (3, 0)]);
806        assert_eq!(
807            gcc.codepoints,
808            std::collections::HashMap::from([(1, 34), (2, 46)])
809        );
810        gcc.on_flow_codepoints(&[(1, 0), (2, 0)]);
811        assert!(gcc.codepoints.is_empty());
812        assert_eq!(gcc.paths.keys().copied().collect::<Vec<_>>(), vec![0]);
813    }
814
815    /// Empty feedback says nothing and must not move anything.
816    #[test]
817    fn empty_feedback_changes_nothing() {
818        let epoch = Instant::now();
819        let mut gcc = Gcc::default();
820        let before = gcc.target_bitrate();
821
822        gcc.on_reports(epoch, &[]);
823
824        assert_eq!(before, gcc.target_bitrate());
825    }
826
827    /// RFC 8888 section 7 / RFC 6679 section 7.3.3: a packet the receiver reports as arrived
828    /// with ECN-CE is a congestion signal, answered as a loss is. Every packet arrives, and
829    /// promptly; three in twenty carry the mark; the loss-based half backs off. The same
830    /// arrivals without marks leave it where it was or higher.
831    #[test]
832    fn congestion_experienced_marks_lower_the_target_as_losses_do() {
833        let run = |marked: bool| {
834            let epoch = Instant::now();
835            let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
836            for batch in 0..20u64 {
837                let at = epoch + Duration::from_millis(batch * 200);
838                let reports: Vec<PacketReport> = (0..20)
839                    .map(|index| {
840                        let id = batch * 20 + index;
841                        let departure = at + Duration::from_millis(index * 10);
842                        let mut report = report(id, departure, Some(batch * 200 + index * 10 + 20));
843                        if marked && index % 7 == 0 {
844                            report.ecn = Ecn::Ce;
845                        }
846                        report
847                    })
848                    .collect();
849                gcc.on_reports(at + Duration::from_millis(200), &reports);
850            }
851            gcc.loss_based_bitrate()
852        };
853
854        let marked = run(true);
855        let clean = run(false);
856        assert!(marked < 1_000_000.0, "15% marked: {marked}");
857        assert!(clean >= 1_000_000.0, "no marks, no losses: {clean}");
858        assert!(marked < 0.8 * clean, "{marked} vs {clean}");
859    }
860
861    /// RFC 6679 section 7.3.3: CE marks counted by RFC 6679 ECN reports (no per-packet
862    /// marks) bring the target down as the same share of losses would; reports without marks
863    /// leave it where it was.
864    #[test]
865    fn ce_marks_from_ecn_counters_lower_the_target_as_losses_do() {
866        let epoch = Instant::now();
867        let run = |marked: u64| {
868            let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
869            for batch in 0..20u64 {
870                gcc.on_congestion_marks(epoch + Duration::from_millis(batch * 200), marked, 20);
871            }
872            gcc.target_bitrate()
873        };
874        let marked = run(3);
875        let clean = run(0);
876        assert!(marked < 0.8 * 1_000_000.0, "15% marked: {marked}");
877        assert_eq!(clean, 1_000_000.0, "no marks: {clean}");
878    }
879
880    /// RFC 5104 section 5: after a TMMBR raises (or lifts) the limit, "the sender ... SHALL
881    /// use congestion control" to go up: the target does not jump to the new limit but climbs
882    /// by the estimator's own increase as feedback shows the path carries it.
883    #[test]
884    fn a_raised_limit_is_climbed_to_by_congestion_control_not_jumped_to() {
885        let epoch = Instant::now();
886        let mut gcc = Gcc::new(300_000.0, 50_000.0, 10_000_000.0);
887        gcc.set_external_bounds(None, Some(300_000.0));
888        let mut id = 0u64;
889        let mut batch = |gcc: &mut Gcc, index: u64| {
890            let at = epoch + Duration::from_millis(index * 100);
891            let reports: Vec<PacketReport> = (0..10)
892                .map(|n| {
893                    id += 1;
894                    let departure = at + Duration::from_millis(n * 10);
895                    report(id, departure, Some(index * 100 + n * 10 + 20))
896                })
897                .collect();
898            gcc.on_reports(at + Duration::from_millis(100), &reports);
899        };
900        for index in 0..20 {
901            batch(&mut gcc, index);
902        }
903        assert!(gcc.target_bitrate() <= 300_000.0);
904
905        gcc.set_external_bounds(None, Some(5_000_000.0));
906        let right_after = gcc.target_bitrate();
907        assert!(
908            right_after <= 300_000.0 * 1.01,
909            "no jump to the new limit: {right_after}"
910        );
911        for index in 20..60 {
912            batch(&mut gcc, index);
913        }
914        let later = gcc.target_bitrate();
915        assert!(
916            later > right_after,
917            "the target climbs: {right_after} -> {later}"
918        );
919        assert!(
920            later < 5_000_000.0,
921            "by the increase, not to the limit: {later}"
922        );
923    }
924
925    /// The more pessimistic half wins. Here loss is catastrophic while delay is quiet, so the
926    /// combined target must follow loss — which is the whole point of the `min`.
927    #[test]
928    fn the_more_pessimistic_half_wins() {
929        let epoch = Instant::now();
930        let mut gcc = Gcc::default();
931
932        let mut at;
933        for batch in 0..20u64 {
934            at = epoch + Duration::from_millis(batch * 200);
935            // Half the packets vanish; the ones that arrive do so promptly.
936            let reports: Vec<PacketReport> = (0..10)
937                .map(|index| {
938                    let id = batch * 10 + index;
939                    let departure = at + Duration::from_millis(index * 10);
940                    let arrival = (index % 2 == 0).then(|| batch * 200 + index * 10 + 20);
941                    report(id, departure, arrival)
942                })
943                .collect();
944            gcc.on_reports(at, &reports);
945        }
946
947        assert!(
948            gcc.target_bitrate() <= gcc.loss_based_bitrate() + 1.0,
949            "the combined target must not exceed the loss half: {} vs {}",
950            gcc.target_bitrate(),
951            gcc.loss_based_bitrate()
952        );
953        assert!(
954            gcc.target_bitrate() < DEFAULT_INITIAL_BITRATE,
955            "50% loss must bring the target down, got {}",
956            gcc.target_bitrate()
957        );
958    }
959
960    /// One clamp, applied once at the combination point (D3).
961    #[test]
962    fn the_target_stays_within_configured_bounds() {
963        let epoch = Instant::now();
964        let mut gcc = Gcc::new(200_000.0, 150_000.0, 250_000.0);
965
966        let mut at;
967        for batch in 0..50u64 {
968            at = epoch + Duration::from_millis(batch * 200);
969            let reports: Vec<PacketReport> = (0..10)
970                .map(|index| {
971                    let id = batch * 10 + index;
972                    let departure = at + Duration::from_millis(index * 10);
973                    report(id, departure, Some(batch * 200 + index * 10 + 20))
974                })
975                .collect();
976            gcc.on_reports(at, &reports);
977
978            assert!(
979                (150_000.0..=250_000.0).contains(&gcc.target_bitrate()),
980                "target left its bounds: {}",
981                gcc.target_bitrate()
982            );
983        }
984    }
985
986    /// The stats expose both halves, so an application can see *why* the target is where it is
987    /// rather than only what it is.
988    #[test]
989    fn stats_report_both_halves() {
990        let epoch = Instant::now();
991        let mut gcc = Gcc::default();
992        gcc.on_reports(epoch, &[report(0, epoch, Some(20)), report(1, epoch, None)]);
993
994        let stats = gcc.stats();
995        assert!(stats.delay_based_bitrate.is_some());
996        assert!(stats.loss_based_bitrate.is_some());
997        assert!(stats.packet_loss.is_some());
998    }
999}