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