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    slope: SlopeEstimator,
97    detector: OveruseDetector,
98    rate: RateCalculator,
99    delay_control: RateController,
100    loss_control: LossController,
101    min: f64,
102    max: f64,
103    target: f64,
104    /// Delay-gradient readings so far, capped at [`MAX_SCALED_DELTAS`].
105    deltas: u32,
106    /// One report's arrival on the receiver's clock and the local instant it is placed at, so
107    /// later arrivals can be placed on this endpoint's timeline for the received-rate window.
108    arrival_anchor: Option<(Duration, Instant)>,
109    /// The newest arrival placed so far.
110    newest_arrival: Option<Instant>,
111    /// The range the application configured; `min` and `max` are this, narrowed by the limits
112    /// from outside.
113    configured: (f64, f64),
114    /// The starting estimate, which a long pause in sending falls back towards.
115    initial: f64,
116    /// When feedback was last read, once any has been.
117    last_feedback: Option<Instant>,
118    /// When a packet was last sent.
119    last_sent: Option<Instant>,
120    /// When a packet that per-packet feedback will report was last sent.
121    last_reported_sent: Option<Instant>,
122    /// When the missing-feedback cut next applies: set while packets sent after the last
123    /// feedback are waiting for theirs.
124    feedback_deadline: Option<Instant>,
125    feedback_timeout: Duration,
126    /// Whether the loss-based estimate is held at or below the delay-based one.
127    loss_capped_by_delay: bool,
128    /// Smoothed interval between feedback reports, as the receiver actually sends them.
129    feedback_interval: Option<Duration>,
130    round_trip_time: Option<Duration>,
131    /// When the last probe result was taken.
132    probed_at: Option<Instant>,
133    /// Whether a loss out of a queue at its limit is over-use (see
134    /// [`with_loss_at_queue_limit_as_overuse`](Self::with_loss_at_queue_limit_as_overuse)).
135    loss_at_queue_limit_is_overuse: bool,
136    queue_limit: QueueLimitDetector,
137    threshold_time_base: ThresholdTimeBase,
138    /// How the last feedback read the path (the detector's signal, over-use too for a loss
139    /// out of a queue at its limit).
140    usage: Usage,
141}
142
143impl Default for Gcc {
144    fn default() -> Self {
145        Self::new(
146            DEFAULT_INITIAL_BITRATE,
147            DEFAULT_MIN_BITRATE,
148            DEFAULT_MAX_BITRATE,
149        )
150    }
151}
152
153impl Gcc {
154    /// RFC 8836 section 2, requirement 5a: after a pause in sending the flow "SHOULD [...]
155    /// regain [its previous share] fast, but [...] less aggressively the longer the
156    /// interruption". A pause up to [`PAUSE_KEEPS_SHARE`] keeps the estimate; a longer one
157    /// halves it for every [`PAUSE_HALVING`] beyond that (the path may have changed meanwhile),
158    /// down to the starting estimate at most, from where the controller (and bandwidth probing)
159    /// climbs again.
160    fn resume_after(&mut self, pause: Duration) {
161        let Some(beyond) = pause.checked_sub(PAUSE_KEEPS_SHARE) else {
162            return;
163        };
164        let factor = 0.5f64.powf(beyond.as_secs_f64() / PAUSE_HALVING.as_secs_f64());
165        let floor = self.initial.min(self.target);
166        let resumed = (self.target * factor).max(floor).clamp(self.min, self.max);
167        if resumed < self.target {
168            self.target = resumed;
169            self.delay_control.set_target(resumed);
170            self.delay_control.reset_convergence();
171            self.loss_control.cap(resumed);
172        }
173    }
174    /// An estimator starting at `initial`, held within `min..=max`.
175    pub fn new(initial: f64, min: f64, max: f64) -> Self {
176        let initial = initial.clamp(min, max);
177        Self {
178            slope: SlopeEstimator::new(),
179            detector: OveruseDetector::new(),
180            rate: RateCalculator::default(),
181            delay_control: RateController::new(initial, min, max),
182            loss_control: LossController::new(initial, min, max),
183            min,
184            max,
185            target: initial,
186            deltas: 0,
187            arrival_anchor: None,
188            newest_arrival: None,
189            configured: (min, max),
190            initial,
191            last_feedback: None,
192            last_sent: None,
193            last_reported_sent: None,
194            feedback_deadline: None,
195            feedback_timeout: DEFAULT_FEEDBACK_TIMEOUT,
196            loss_capped_by_delay: true,
197            feedback_interval: None,
198            round_trip_time: None,
199            probed_at: None,
200            loss_at_queue_limit_is_overuse: true,
201            queue_limit: QueueLimitDetector::new(),
202            threshold_time_base: ThresholdTimeBase::default(),
203            usage: Usage::Normal,
204        }
205    }
206
207    /// Whether a packet lost out of a queue at its limit counts as over-use for the
208    /// delay-based controller (the default), or only for the loss-based one as
209    /// draft-ietf-rmcat-gcc-02 has it.
210    ///
211    /// The draft's over-use signal is the delay *gradient*: a queue that is growing. A
212    /// tail-drop queue that has filled to its limit no longer grows, whatever is sent into
213    /// it: the gradient is zero, the detector reads normal and the delay-based estimate keeps
214    /// climbing, while the loss-based controller holds anywhere between 2% and 10% loss
215    /// (section 6). A flow in that state never yields. Measured on a shared FIFO bottleneck
216    /// (`rtci-interceptor/tests/rfc8836_multi_flow.rs`): a second flow joining an established
217    /// one fell to the floor, and against a Reno-like transfer `Gcc` took 97% of the path,
218    /// both against RFC 8836 section 2 (requirements 2a, a MUST, and 3). With the default, a
219    /// feedback batch that lost a packet while every packet of it that arrived waited near the
220    /// highest queueing delay seen of late ([`QueueLimitDetector`]) is over-use: the
221    /// estimate backs off as from a growing queue, and the queue drains. Loss with little or
222    /// no queue (a radio link, a policer) is left to the loss-based controller, as before.
223    /// `false` is the draft as written.
224    pub fn with_loss_at_queue_limit_as_overuse(mut self, enabled: bool) -> Self {
225        self.loss_at_queue_limit_is_overuse = enabled;
226        self
227    }
228
229    /// Whether over-use lowers the estimate at most once per round trip (libwebrtc's form) or
230    /// on every update while it lasts, as draft-ietf-rmcat-gcc-02 section 5.5 has it (the
231    /// default). See
232    /// [`RateController::with_one_decrease_per_round_trip`].
233    pub fn with_one_decrease_per_round_trip(mut self, enabled: bool) -> Self {
234        self.delay_control = self.delay_control.with_one_decrease_per_round_trip(enabled);
235        self
236    }
237
238    /// What the bound of the estimate by the received rate (draft-ietf-rmcat-gcc-02 section
239    /// 5.5, `A_hat(i) < 1.5 * R_hat(i)`) does to an estimate above it: nothing but stop its
240    /// increase ([`ReceivedRateBound::LimitsIncrease`], the default), or bring it down to
241    /// the bound ([`ReceivedRateBound::Clamps`]). See [`ReceivedRateBound`].
242    ///
243    /// With the default an application that sends less than the estimate (audio alone, a
244    /// camera turned off, the first moments of a call) keeps the estimate it had: it is
245    /// lowered by over-use, by loss, and by feedback that stops while packets it covers are
246    /// sent, and by nothing else.
247    pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
248        self.delay_control = self
249            .delay_control
250            .with_received_rate_bound(received_rate_bound);
251        self
252    }
253
254    /// How long feedback may be missing, while packets are being sent, before the target is
255    /// halved (and halved again each time the same period passes).
256    pub fn with_feedback_timeout(mut self, feedback_timeout: Duration) -> Self {
257        self.feedback_timeout = feedback_timeout;
258        self
259    }
260
261    /// The time step of the adaptive threshold (draft-ietf-rmcat-gcc-02 section 5.4):
262    /// the draft's [`ThresholdTimeBase::Arrival`] (the default), libwebrtc's
263    /// [`ThresholdTimeBase::ArrivalCapped`] or [`ThresholdTimeBase::Departure`].
264    pub fn with_threshold_time_base(mut self, time_base: ThresholdTimeBase) -> Self {
265        self.threshold_time_base = time_base;
266        self.detector = self.detector.with_threshold_time_base(time_base);
267        self
268    }
269
270    /// See [`ThresholdTimeBase`]: the time step of the adaptive threshold (draft-ietf-rmcat-gcc-02
271    /// section 5.4), the arrival gaps by default.
272    pub fn threshold_time_base(&self) -> ThresholdTimeBase {
273        self.threshold_time_base
274    }
275
276    /// Whether the loss-based estimate As_hat is held at or below the delay-based estimate
277    /// A_hat after every update (the default), or left free with only the minimum of the two
278    /// taken as the sending rate.
279    ///
280    /// draft-ietf-rmcat-gcc-02 section 6 has the loss-based controller work from the available
281    /// bandwidth estimate of the delay-based one. Left free, As_hat grows 5% per interval
282    /// whenever loss is under 2%, whatever the path carries: after five quiet seconds it is
283    /// several times the rate being sent, and `As_hat(i) = As_hat(i-1)(1 - 0.5p)` then has to
284    /// cut it back through all of that before the sending rate moves at all. Capped, a loss
285    /// cut is taken from the rate actually being sent, and the climb back starts from there.
286    pub fn with_loss_estimate_capped_by_delay_estimate(mut self, capped: bool) -> Self {
287        self.loss_capped_by_delay = capped;
288        self
289    }
290
291    /// How long feedback may be missing before the target is cut: the configured timeout, or
292    /// three of the receiver's own feedback intervals when those are longer.
293    ///
294    /// A receiver that keeps its feedback inside the RTCP bandwidth (RFC 3550 section 6.2; at
295    /// 100 kbit/s of media that is a few packets per second) reports every few hundred
296    /// milliseconds, not every hundred. Its regular rhythm is not missing feedback.
297    fn effective_feedback_timeout(&self) -> Duration {
298        self.feedback_interval
299            .map_or(self.feedback_timeout, |interval| {
300                self.feedback_timeout.max(interval * 3)
301            })
302    }
303
304    /// Bring both controllers and the target into the current range.
305    fn apply_range(&mut self) {
306        self.delay_control.set_bounds(self.min, self.max);
307        self.loss_control.set_bounds(self.min, self.max);
308        self.target = self.target.clamp(self.min, self.max);
309    }
310
311    /// Place an arrival on the receiver's clock onto this endpoint's timeline.
312    ///
313    /// Only differences between arrivals mean anything, so the first one seen is pinned to the
314    /// instant its feedback was read and every later one keeps its distance from it.
315    fn place_arrival(&mut self, now: Instant, arrival: Duration) -> Instant {
316        let (anchor_arrival, anchor_instant) = *self.arrival_anchor.get_or_insert((arrival, now));
317        if arrival >= anchor_arrival {
318            anchor_instant + (arrival - anchor_arrival)
319        } else {
320            anchor_instant
321                .checked_sub(anchor_arrival - arrival)
322                .unwrap_or(anchor_instant)
323        }
324    }
325
326    /// The delay-based half's current target, in bits per second.
327    pub fn delay_based_bitrate(&self) -> f64 {
328        self.delay_control.target()
329    }
330
331    /// The loss-based half's current target, in bits per second.
332    pub fn loss_based_bitrate(&self) -> f64 {
333        self.loss_control.target()
334    }
335}
336
337impl BandwidthEstimator for Gcc {
338    /// RFC 6679 section 7.3.3: CE marks counted by the receiver's ECN reports go to the
339    /// loss-based controller as losses would; the target can only fall by them.
340    fn on_congestion_marks(&mut self, now: Instant, marked: u64, packets: u64) {
341        if marked == 0 || packets == 0 {
342            return;
343        }
344        let packets = packets.min(usize::MAX as u64) as usize;
345        let marked = (marked.min(packets as u64)) as usize;
346        self.loss_control.update(now, marked, packets);
347        let loss_target = self.loss_control.target();
348        self.target = self.target.min(loss_target).clamp(self.min, self.max);
349    }
350
351    fn on_reports(&mut self, now: Instant, reports: &[PacketReport]) {
352        if reports.is_empty() {
353            return;
354        }
355        // A probe's measurement stands in for the received rate until the received rate has
356        // had its window to follow.
357        if let Some(probed_at) = self.probed_at
358            && now.saturating_duration_since(probed_at) > PROBE_RESULT_HOLD
359        {
360            self.probed_at = None;
361            self.delay_control.set_measured_rate(None);
362        }
363
364        // Delay: group, filter, detect, control.
365        let mut usage = self.detector.usage();
366        for report in reports {
367            // The received rate is what arrived per unit of the *receiver's* time
368            // (draft-ietf-rmcat-gcc-02 5.5). Counting acknowledged bytes at the instant their
369            // feedback was read instead measures one more feedback interval of bytes than of
370            // time, which reads 20 to 25% high at a 100 ms cadence — enough that backing off to
371            // 0.85 of it lands above the link.
372            if report.arrived
373                && let Some(arrival) = report.arrival
374            {
375                let at = self.place_arrival(now, arrival);
376                self.rate.add(at, report.size);
377                self.newest_arrival = Some(self.newest_arrival.map_or(at, |newest| newest.max(at)));
378            }
379            if let Some(trend) = self.slope.accumulate(report) {
380                self.deltas = (self.deltas + 1).min(MAX_SCALED_DELTAS);
381                usage = self.detector.update_with_arrival(
382                    trend.at,
383                    trend.arrival,
384                    trend.estimate_ms * f64::from(self.deltas),
385                );
386            }
387        }
388
389        let received = self
390            .newest_arrival
391            .and_then(|newest| self.rate.rate_bits_per_second(newest));
392        // A loss out of a queue at its limit: the queue would be growing, had it room.
393        if self.queue_limit.on_reports(now, reports) && self.loss_at_queue_limit_is_overuse {
394            usage = Usage::Over;
395        }
396        self.usage = usage;
397        let delay_target = self.delay_control.update(now, usage, received);
398
399        // Loss: a fraction over this batch. A packet that arrived marked ECN-CE counts as one
400        // that did not: "a CE mark is a congestion signal" (RFC 8888 section 7 with RFC 6679
401        // section 7.3.3: the sender reacts to it as to a lost packet, without retransmitting).
402        let lost = reports
403            .iter()
404            .filter(|report| !report.arrived || report.ecn == Ecn::Ce)
405            .count();
406        self.loss_control.update(now, lost, reports.len());
407        if self.loss_capped_by_delay {
408            self.loss_control.cap(delay_target);
409        }
410        let loss_target = self.loss_control.target();
411        log::debug!(
412            "gcc: feedback of {} packets, {lost} lost; loss average {:?}, delay target {delay_target:.0}, loss target {loss_target:.0}",
413            reports.len(),
414            self.loss_control.average_loss(),
415        );
416
417        // Whichever half is more pessimistic wins, clamped once (D3).
418        self.target = delay_target.min(loss_target).clamp(self.min, self.max);
419
420        // Feedback arrived: the missing-feedback clock starts again when the next packet
421        // leaves.
422        if let Some(last) = self.last_feedback {
423            let interval = now.saturating_duration_since(last);
424            self.feedback_interval = Some(match self.feedback_interval {
425                Some(previous) => previous.mul_f64(0.8) + interval.mul_f64(0.2),
426                None => interval,
427            });
428        }
429        self.last_feedback = Some(now);
430        self.feedback_deadline = None;
431    }
432
433    /// A packet that no per-packet feedback will report: the flow is not paused, and its
434    /// feedback is not awaited.
435    fn on_unreported_packet_sent(&mut self, now: Instant, _size: usize) {
436        if let Some(last) = self.last_sent {
437            self.resume_after(now.saturating_duration_since(last));
438        }
439        self.last_sent = Some(now);
440    }
441
442    fn on_packet_sent(&mut self, now: Instant, size: usize) {
443        self.on_unreported_packet_sent(now, size);
444        self.last_reported_sent = Some(now);
445        // Only once feedback has a rhythm (two reports) is its absence unexpected: a receiver
446        // that never sends any is handled by the receiver-report fallback, and one that has
447        // sent a single report has not yet shown how often it reports.
448        if self.feedback_interval.is_some() && self.feedback_deadline.is_none() {
449            self.feedback_deadline = Some(now + self.effective_feedback_timeout());
450        }
451    }
452
453    fn on_round_trip_time(&mut self, _now: Instant, round_trip_time: Duration) {
454        self.round_trip_time = Some(round_trip_time);
455        self.delay_control.set_round_trip_time(round_trip_time);
456    }
457
458    fn min_bitrate(&self) -> Option<f64> {
459        Some(self.min)
460    }
461
462    fn max_bitrate(&self) -> Option<f64> {
463        Some(self.max)
464    }
465
466    fn usage(&self) -> Usage {
467        self.usage
468    }
469
470    fn set_external_bounds(&mut self, min: Option<f64>, max: Option<f64>) {
471        let (configured_min, configured_max) = self.configured;
472        self.max = max.map_or(configured_max, |max| max.min(configured_max));
473        // A limit below the floor wins: the floor is a preference, the limit is not.
474        self.min = min.unwrap_or(configured_min).min(self.max);
475        self.apply_range();
476    }
477
478    fn on_receiver_report(&mut self, now: Instant, fraction_lost: f64) {
479        // No per-packet feedback: the delay-based controller has nothing to run on, and the
480        // loss-based one runs on the fraction lost the receiver reports (section 7).
481        self.loss_control.update_fraction(now, fraction_lost);
482        self.target = self.loss_control.target().clamp(self.min, self.max);
483        self.delay_control.set_target(self.target);
484    }
485
486    fn on_probe_result(&mut self, now: Instant, bits_per_second: f64) {
487        if !bits_per_second.is_finite() || bits_per_second <= 0.0 {
488            return;
489        }
490        if bits_per_second <= self.target {
491            // A probe only ever raises the estimate: one that came out well below it says the
492            // cluster met a queue, which the delay-based controller hears about by itself.
493            // One that the path carried at about the estimate confirms it: the measurement is
494            // renewed, so that an application sending less than the target keeps resting on
495            // it rather than falling back, once the last raise is older than the hold, to one
496            // and a half times what it sends (and from there, by the same bound, lower with
497            // every update).
498            if bits_per_second >= PROBE_CONFIRMS_ESTIMATE * self.target {
499                self.delay_control.set_measured_rate(Some(bits_per_second));
500                self.probed_at = Some(now);
501            }
502            return;
503        }
504        // The path carried the cluster at this rate. Both halves start from it, the climb
505        // from here is multiplicative again, and for a while the measurement stands in for
506        // the received rate, which only follows once the application sends at the new target.
507        self.delay_control.set_target(bits_per_second);
508        self.delay_control.reset_convergence();
509        self.delay_control.set_measured_rate(Some(bits_per_second));
510        self.probed_at = Some(now);
511        self.loss_control.raise(bits_per_second);
512        self.target = self
513            .delay_control
514            .target()
515            .min(self.loss_control.target())
516            .clamp(self.min, self.max);
517    }
518
519    /// A new path (another candidate pair selected) starts the estimate over from the starting
520    /// estimate. The estimate describes the path it was measured on (RFC 8836 section 2,
521    /// requirement 1d: the flow reacts to a change of the path; draft-ietf-rmcat-gcc-02 says
522    /// nothing of it). Kept, it is right for a change between like paths and wrong in either
523    /// direction otherwise: too high for a slower network, and, after an outage that the
524    /// missing feedback halved it through, far too low for the network the connection came
525    /// back on. libwebrtc starts over as well
526    /// (`call/rtp_transport_controller_send.cc:356-357`, `OnNetworkRouteChanged`: "If it is,
527    /// restart BWE.", `restart_bwe = IsRelevantRouteChange(old_route, network_route)`, sent
528    /// to the controller at line 393 as `msg.restart_bwe`).
529    fn on_path_change(&mut self, _now: Instant) {
530        // Delay measurements across two paths mean nothing, and neither does where the old
531        // path converged.
532        self.slope = SlopeEstimator::new();
533        self.detector = OveruseDetector::new().with_threshold_time_base(self.threshold_time_base);
534        self.rate = RateCalculator::default();
535        self.deltas = 0;
536        self.arrival_anchor = None;
537        self.newest_arrival = None;
538        self.queue_limit = QueueLimitDetector::new();
539        self.delay_control.reset_convergence();
540        self.usage = Usage::Normal;
541        self.feedback_deadline = None;
542        self.target = self.initial.clamp(self.min, self.max);
543        self.delay_control.set_target(self.target);
544        self.delay_control.set_measured_rate(None);
545        self.probed_at = None;
546        self.loss_control.cap(self.target);
547        self.loss_control.raise(self.target);
548        self.last_sent = None;
549        self.last_reported_sent = None;
550    }
551
552    fn handle_timeout(&mut self, now: Instant) {
553        // Packets were sent and nothing has been heard about them for a whole timeout: treat
554        // it as over-use. Halve, and again for each further timeout without feedback.
555        while let Some(deadline) = self.feedback_deadline
556            && now >= deadline
557        {
558            self.target = (self.target * FEEDBACK_TIMEOUT_DECREASE).clamp(self.min, self.max);
559            self.delay_control.set_target(self.target);
560            self.loss_control.cap(self.target);
561            // Keep counting only while packets are still going out.
562            let timeout = self.effective_feedback_timeout();
563            self.feedback_deadline = self
564                .last_reported_sent
565                .is_some_and(|sent| sent + timeout > deadline)
566                .then(|| deadline + timeout);
567        }
568    }
569
570    fn poll_timeout(&self) -> Option<Instant> {
571        self.feedback_deadline
572    }
573
574    fn target_bitrate(&self) -> f64 {
575        self.target
576    }
577
578    fn stats(&self) -> EstimatorStats {
579        EstimatorStats {
580            delay_based_bitrate: Some(self.delay_control.target()),
581            loss_based_bitrate: Some(self.loss_control.target()),
582            packet_loss: self.loss_control.average_loss(),
583            round_trip_time: self.round_trip_time,
584        }
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
592    use std::time::Duration;
593
594    fn report(id: u64, departure: Instant, arrival_ms: Option<u64>) -> PacketReport {
595        PacketReport {
596            ssrc: 1,
597            id,
598            rtp_sequence_number: id as u16,
599            is_twcc: true,
600            twcc_sequence_number: id as u16,
601            size: 1500,
602            arrived: arrival_ms.is_some(),
603            departure,
604            arrival: arrival_ms.map(Duration::from_millis),
605            ecn: Ecn::default(),
606        }
607    }
608
609    /// RFC 8836 section 2, requirement 5a: a short pause keeps the estimate, a long one brings
610    /// it down, the more the longer the pause, never below the starting estimate.
611    #[test]
612    fn a_pause_in_sending_keeps_the_estimate_and_a_long_one_lowers_it() {
613        let epoch = Instant::now();
614        let resumed_after = |pause: Duration| {
615            let mut gcc = Gcc::new(300_000.0, 100_000.0, 10_000_000.0);
616            gcc.on_probe_result(epoch, 2_000_000.0);
617            gcc.on_packet_sent(epoch, 1200);
618            gcc.on_packet_sent(epoch + pause, 1200);
619            gcc.target_bitrate()
620        };
621        assert_eq!(resumed_after(Duration::from_millis(500)), 2_000_000.0);
622        assert_eq!(resumed_after(PAUSE_KEEPS_SHARE), 2_000_000.0);
623        let twelve = resumed_after(PAUSE_KEEPS_SHARE + PAUSE_HALVING);
624        assert!((twelve - 1_000_000.0).abs() < 1.0, "{twelve}");
625        let long = resumed_after(Duration::from_secs(120));
626        assert_eq!(long, 300_000.0, "down to the starting estimate, not below");
627    }
628
629    /// `usage` is the reading of the last feedback: normal at the start, over-use while
630    /// packets sent 10 ms apart arrive 40 ms apart (a growing queue, which lowers the target),
631    /// and not over-use once they arrive as they left.
632    #[test]
633    fn usage_follows_the_last_feedback() {
634        let epoch = Instant::now();
635        let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
636        assert_eq!(Usage::Normal, gcc.usage());
637        let mut id = 0u64;
638        let mut arrival_ms = 50u64;
639        let mut seen = false;
640        // Two seconds of a growing queue, a batch of ten packets every 100 ms.
641        for batch in 0..20u64 {
642            let reports: Vec<PacketReport> = (0..10u64)
643                .map(|n| {
644                    id += 1;
645                    arrival_ms += 40;
646                    report(
647                        id,
648                        epoch + Duration::from_millis(100 * batch + 10 * n),
649                        Some(arrival_ms),
650                    )
651                })
652                .collect();
653            gcc.on_reports(epoch + Duration::from_millis(100 * (batch + 1)), &reports);
654            seen |= gcc.usage() == Usage::Over;
655        }
656        assert!(seen, "a growing queue reads as over-use");
657        assert!(gcc.target_bitrate() < 1_000_000.0, "and lowers the target");
658        // Five seconds in which packets arrive as far apart as they left.
659        for batch in 20..70u64 {
660            let reports: Vec<PacketReport> = (0..10u64)
661                .map(|n| {
662                    id += 1;
663                    arrival_ms += 10;
664                    report(
665                        id,
666                        epoch + Duration::from_millis(100 * batch + 10 * n),
667                        Some(arrival_ms),
668                    )
669                })
670                .collect();
671            gcc.on_reports(epoch + Duration::from_millis(100 * (batch + 1)), &reports);
672        }
673        assert_ne!(
674            Usage::Over,
675            gcc.usage(),
676            "a queue that no longer grows does not"
677        );
678    }
679
680    /// Empty feedback says nothing and must not move anything.
681    #[test]
682    fn empty_feedback_changes_nothing() {
683        let epoch = Instant::now();
684        let mut gcc = Gcc::default();
685        let before = gcc.target_bitrate();
686
687        gcc.on_reports(epoch, &[]);
688
689        assert_eq!(before, gcc.target_bitrate());
690    }
691
692    /// RFC 8888 section 7 / RFC 6679 section 7.3.3: a packet the receiver reports as arrived
693    /// with ECN-CE is a congestion signal, answered as a loss is. Every packet arrives, and
694    /// promptly; three in twenty carry the mark; the loss-based half backs off. The same
695    /// arrivals without marks leave it where it was or higher.
696    #[test]
697    fn congestion_experienced_marks_lower_the_target_as_losses_do() {
698        let run = |marked: bool| {
699            let epoch = Instant::now();
700            let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
701            for batch in 0..20u64 {
702                let at = epoch + Duration::from_millis(batch * 200);
703                let reports: Vec<PacketReport> = (0..20)
704                    .map(|index| {
705                        let id = batch * 20 + index;
706                        let departure = at + Duration::from_millis(index * 10);
707                        let mut report = report(id, departure, Some(batch * 200 + index * 10 + 20));
708                        if marked && index % 7 == 0 {
709                            report.ecn = Ecn::Ce;
710                        }
711                        report
712                    })
713                    .collect();
714                gcc.on_reports(at + Duration::from_millis(200), &reports);
715            }
716            gcc.loss_based_bitrate()
717        };
718
719        let marked = run(true);
720        let clean = run(false);
721        assert!(marked < 1_000_000.0, "15% marked: {marked}");
722        assert!(clean >= 1_000_000.0, "no marks, no losses: {clean}");
723        assert!(marked < 0.8 * clean, "{marked} vs {clean}");
724    }
725
726    /// RFC 6679 section 7.3.3: CE marks counted by RFC 6679 ECN reports (no per-packet
727    /// marks) bring the target down as the same share of losses would; reports without marks
728    /// leave it where it was.
729    #[test]
730    fn ce_marks_from_ecn_counters_lower_the_target_as_losses_do() {
731        let epoch = Instant::now();
732        let run = |marked: u64| {
733            let mut gcc = Gcc::new(1_000_000.0, 100_000.0, 10_000_000.0);
734            for batch in 0..20u64 {
735                gcc.on_congestion_marks(epoch + Duration::from_millis(batch * 200), marked, 20);
736            }
737            gcc.target_bitrate()
738        };
739        let marked = run(3);
740        let clean = run(0);
741        assert!(marked < 0.8 * 1_000_000.0, "15% marked: {marked}");
742        assert_eq!(clean, 1_000_000.0, "no marks: {clean}");
743    }
744
745    /// RFC 5104 section 5: after a TMMBR raises (or lifts) the limit, "the sender ... SHALL
746    /// use congestion control" to go up: the target does not jump to the new limit but climbs
747    /// by the estimator's own increase as feedback shows the path carries it.
748    #[test]
749    fn a_raised_limit_is_climbed_to_by_congestion_control_not_jumped_to() {
750        let epoch = Instant::now();
751        let mut gcc = Gcc::new(300_000.0, 50_000.0, 10_000_000.0);
752        gcc.set_external_bounds(None, Some(300_000.0));
753        let mut id = 0u64;
754        let mut batch = |gcc: &mut Gcc, index: u64| {
755            let at = epoch + Duration::from_millis(index * 100);
756            let reports: Vec<PacketReport> = (0..10)
757                .map(|n| {
758                    id += 1;
759                    let departure = at + Duration::from_millis(n * 10);
760                    report(id, departure, Some(index * 100 + n * 10 + 20))
761                })
762                .collect();
763            gcc.on_reports(at + Duration::from_millis(100), &reports);
764        };
765        for index in 0..20 {
766            batch(&mut gcc, index);
767        }
768        assert!(gcc.target_bitrate() <= 300_000.0);
769
770        gcc.set_external_bounds(None, Some(5_000_000.0));
771        let right_after = gcc.target_bitrate();
772        assert!(
773            right_after <= 300_000.0 * 1.01,
774            "no jump to the new limit: {right_after}"
775        );
776        for index in 20..60 {
777            batch(&mut gcc, index);
778        }
779        let later = gcc.target_bitrate();
780        assert!(
781            later > right_after,
782            "the target climbs: {right_after} -> {later}"
783        );
784        assert!(
785            later < 5_000_000.0,
786            "by the increase, not to the limit: {later}"
787        );
788    }
789
790    /// The more pessimistic half wins. Here loss is catastrophic while delay is quiet, so the
791    /// combined target must follow loss — which is the whole point of the `min`.
792    #[test]
793    fn the_more_pessimistic_half_wins() {
794        let epoch = Instant::now();
795        let mut gcc = Gcc::default();
796
797        let mut at;
798        for batch in 0..20u64 {
799            at = epoch + Duration::from_millis(batch * 200);
800            // Half the packets vanish; the ones that arrive do so promptly.
801            let reports: Vec<PacketReport> = (0..10)
802                .map(|index| {
803                    let id = batch * 10 + index;
804                    let departure = at + Duration::from_millis(index * 10);
805                    let arrival = (index % 2 == 0).then(|| batch * 200 + index * 10 + 20);
806                    report(id, departure, arrival)
807                })
808                .collect();
809            gcc.on_reports(at, &reports);
810        }
811
812        assert!(
813            gcc.target_bitrate() <= gcc.loss_based_bitrate() + 1.0,
814            "the combined target must not exceed the loss half: {} vs {}",
815            gcc.target_bitrate(),
816            gcc.loss_based_bitrate()
817        );
818        assert!(
819            gcc.target_bitrate() < DEFAULT_INITIAL_BITRATE,
820            "50% loss must bring the target down, got {}",
821            gcc.target_bitrate()
822        );
823    }
824
825    /// One clamp, applied once at the combination point (D3).
826    #[test]
827    fn the_target_stays_within_configured_bounds() {
828        let epoch = Instant::now();
829        let mut gcc = Gcc::new(200_000.0, 150_000.0, 250_000.0);
830
831        let mut at;
832        for batch in 0..50u64 {
833            at = epoch + Duration::from_millis(batch * 200);
834            let reports: Vec<PacketReport> = (0..10)
835                .map(|index| {
836                    let id = batch * 10 + index;
837                    let departure = at + Duration::from_millis(index * 10);
838                    report(id, departure, Some(batch * 200 + index * 10 + 20))
839                })
840                .collect();
841            gcc.on_reports(at, &reports);
842
843            assert!(
844                (150_000.0..=250_000.0).contains(&gcc.target_bitrate()),
845                "target left its bounds: {}",
846                gcc.target_bitrate()
847            );
848        }
849    }
850
851    /// The stats expose both halves, so an application can see *why* the target is where it is
852    /// rather than only what it is.
853    #[test]
854    fn stats_report_both_halves() {
855        let epoch = Instant::now();
856        let mut gcc = Gcc::default();
857        gcc.on_reports(epoch, &[report(0, epoch, Some(20)), report(1, epoch, None)]);
858
859        let stats = gcc.stats();
860        assert!(stats.delay_based_bitrate.is_some());
861        assert!(stats.loss_based_bitrate.is_some());
862        assert!(stats.packet_loss.is_some());
863    }
864}