rtci_interceptor/cc/probe.rs
1//! Bandwidth probing: short bursts above the target rate, and the capacity their arrival shows.
2//!
3//! A delay-based controller finds out that a path has room only by using it, and climbs a few
4//! percent a second (8% in `Gcc`): from 300 kbit/s to 2.5 Mbit/s takes most of half a minute.
5//! A probe asks the question directly. A cluster of packets leaves at a multiple of the target
6//! for some milliseconds; if the receiver reports them arriving as closely spaced as they left,
7//! the path carries that rate and the estimate moves there at once.
8//!
9//! RFC 8836 section 2 asks that a congestion controller "adapt as quickly as possible to
10//! initial network conditions" and "allow for different modes of adaptation", naming "probing
11//! during setup" as one (requirement 4, both SHOULD); draft-ietf-rmcat-gcc-02 has no probing at
12//! all. It is what libwebrtc does, in outline. The peer connection's default interceptor set
13//! probes (a SHOULD is met by default); `DefaultInterceptorOptions::bandwidth_probing` turns it
14//! off, and a chain built by hand probes only with
15//! [`CongestionControlBuilder::with_bandwidth_probing`](crate::CongestionControlBuilder::with_bandwidth_probing).
16//!
17//! The parts:
18//!
19//! - [`ProbeController`] decides when a cluster is sent and at what rate: two at the start
20//! (three and six times the starting rate), a further one at twice the result while results
21//! keep confirming the rate probed, and one every few seconds while the application sends
22//! less than the target allows, when nothing else would show that the path has grown; and,
23//! for a few seconds after the target dropped by a third or more, the rate before the drop.
24//! - [`ProbeRequest`] is what travels through the chain: the congestion controller announces
25//! it on the read leg, the pacer releases the next packets at its rate and marks them
26//! ([`ProbePacket`]), and the NACK responder fills the cluster with padding-only packets on
27//! the RTX stream when the application's own media is not enough: they carry no media, so a
28//! receiver never has a packet twice.
29//! - [`probe_estimate`] turns the receiver's reports on a cluster into a bit rate.
30//!
31//! In a chain without a pacer nothing releases a cluster at its rate. The NACK responder's
32//! padding is then the cluster: it leaves as one burst with the cluster's mark, and
33//! [`burst_estimate`] reads the rate of the narrowest link from how far apart the burst
34//! arrived, never more than the rate asked for. Where nothing sends a cluster at all (no
35//! pacer and no RTX stream to pad on), the congestion controller stops asking after the first
36//! cluster that no packet left for, until another stream starts to send: a request that can
37//! have no result is not made again.
38
39use crate::rtpfb::acknowledgement::PacketReport;
40use crate::{Attribute, AttributedPacket, Packet, TaggedPacket, Usage};
41use shared::TransportContext;
42use std::sync::Arc;
43use std::time::{Duration, Instant};
44
45/// How long a cluster lasts at its rate, at least.
46pub const PROBE_MIN_DURATION: Duration = Duration::from_millis(15);
47/// How many packets a cluster has, at least.
48pub const PROBE_MIN_PACKETS: usize = 5;
49/// The size a probe packet is taken to have when a cluster is sized.
50const PROBE_PACKET_OCTETS: usize = 1200;
51/// The most a cluster asks for, whatever its rate.
52pub const PROBE_MAX_OCTETS: usize = 64_000;
53/// The clusters at the start, as multiples of the starting rate.
54const INITIAL_PROBES: [f64; 2] = [3.0, 6.0];
55/// The next cluster after a result, as a multiple of it.
56const FURTHER_PROBE: f64 = 2.0;
57/// A result confirms the rate probed when it reaches this share of it: the path was not the
58/// limit, and probing goes on.
59const FURTHER_PROBE_THRESHOLD: f64 = 0.7;
60/// How often a cluster is sent while the application sends less than the target.
61pub const PROBE_APPLICATION_LIMITED_INTERVAL: Duration = Duration::from_secs(5);
62/// The share of the target below which the sender counts as application limited.
63const APPLICATION_LIMITED_SHARE: f64 = 0.65;
64/// How long a cluster's reports are waited for before it is given up.
65pub const PROBE_RESULT_TIMEOUT: Duration = Duration::from_secs(1);
66/// The least time between two clusters.
67const PROBE_SPACING: Duration = Duration::from_millis(100);
68/// The target falling below this share of its recent high is a large drop.
69const LARGE_DROP_SHARE: f64 = 0.66;
70/// How long the recent high of the target is remembered for drop detection.
71const LARGE_DROP_WINDOW: Duration = Duration::from_secs(2);
72/// How long after a large drop the old rate is probed for.
73pub const PROBE_AFTER_DROP_TIMEOUT: Duration = Duration::from_secs(5);
74/// The first probe after a large drop waits this long: the back-off has to take effect.
75const PROBE_AFTER_DROP_DELAY: Duration = Duration::from_secs(1);
76/// And they are this far apart.
77const PROBE_AFTER_DROP_INTERVAL: Duration = Duration::from_secs(1);
78/// A probe after a drop asks for this share of the rate before it.
79const PROBE_AFTER_DROP_SHARE: f64 = 0.85;
80/// How long the rate before a large drop is remembered as the rate the path had, for
81/// recovery probing ([`ProbeController::with_recovery_probing`]): the highest such rate of
82/// this long.
83pub const PROBE_DROP_MEMORY: Duration = Duration::from_secs(60);
84/// How often a recovery cluster is sent while the target is below the remembered rate
85/// ([`ProbeController::with_recovery_probing`]).
86pub const PROBE_RECOVERY_INTERVAL: Duration = Duration::from_secs(5);
87/// [`AfterDropProbe::Libwebrtc`]: how long after the sender stopped being application limited
88/// a drop is still probed (libwebrtc `kAlrEndedTimeout`).
89const ALR_ENDED_TIMEOUT: Duration = Duration::from_secs(3);
90/// [`AfterDropProbe::Libwebrtc`]: the least time between two probes after a drop (libwebrtc
91/// `kMinTimeBetweenAlrProbes`).
92const LIBWEBRTC_DROP_PROBE_INTERVAL: Duration = Duration::from_secs(5);
93/// [`AfterDropProbe::Libwebrtc`]: the probe is asked only when 95% of it is above the
94/// estimate (libwebrtc `kProbeUncertainty`).
95const LIBWEBRTC_PROBE_UNCERTAINTY: f64 = 0.05;
96
97/// What is probed for after a large drop of the target
98/// ([`ProbeController::with_after_drop_probe`]).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
100pub enum AfterDropProbe {
101 /// The engine's form, and the default. A drop of the target below two thirds of its high
102 /// of the last two seconds is followed, from a second on and once a second for five
103 /// seconds, by a cluster at 85% of that high while the target is still below it, whether
104 /// or not the sender is application limited.
105 ///
106 /// No specification says how to probe after a drop (RFC 8836 section 2, 1f, asks only
107 /// that a flow regain its share quickly), so the default is the form the capacity
108 /// instrument measured best (`tests/capacity_instrument.rs`; the default chain, a
109 /// 2.5 Mbit/s path that drops to 300 kbit/s for 20 s; 1000 calls in each of the two
110 /// reference cells and 200 in six others, each form against this one by the merge-point
111 /// rule of `docs/capacity-instrument.md`). Without a probe ([`Off`](Self::Off)) and with
112 /// libwebrtc's ([`Libwebrtc`](Self::Libwebrtc), which never fires for a sender that
113 /// keeps up with its target, so the two measure alike) seven figures are worse: with
114 /// both directions limited the oldest picture is 3.07 s against 2.64 s, with 5% of the
115 /// feedback lost the rate is not back within 20 s in 30 (24) of 200 calls against 2, and
116 /// the target 15 to 25 s after the limit is 1205 against 1278 kbit/s. Asking for the
117 /// highest rate of the last minute instead of the last drop's own high (the rate before
118 /// the limit, not the peak of the controller's sawtooth under it) makes fifteen figures
119 /// worse (audio packets lost 27 -> 35 a call, behind a 1000 ms queue over 2 s without a
120 /// new picture in 33 of 200 calls against 6) and was not taken. What this form costs
121 /// against no probe: behind a 1000 ms queue 96 audio packets lost a call against 66, and
122 /// under a limit that lasts a minute 74 against 45.
123 #[default]
124 Repeated,
125 /// libwebrtc's form (`ProbeController::RequestProbe`, goog_cc `probe_controller.cc`): a
126 /// drop is one update of the estimate below two thirds of the one before it; one cluster
127 /// at 85% of the estimate before the drop, asked when the delay-based detector has
128 /// returned to normal after the drop ([`ProbeController::set_usage`]: under-use, then
129 /// normal), only while the sender is application limited or was within the last three
130 /// seconds, within five seconds of the drop, at most once in five seconds, and only when
131 /// 95% of that rate is above the estimate.
132 Libwebrtc,
133 /// No probe after a drop: the climb back is the delay-based controller's.
134 Off,
135}
136
137/// A probe cluster the congestion controller asks for.
138///
139/// Carried as an [`Attribute::Custom`] on an empty RTCP packet on the read leg
140/// ([`ProbeRequest::into_packet`]), from the congestion controller towards the application:
141/// the pacer and the NACK responder read it on its way past.
142#[derive(Debug, Clone, Copy, PartialEq)]
143pub struct ProbeRequest {
144 /// Which cluster this is; the packets sent for it carry the same number.
145 pub cluster: u32,
146 /// The rate the cluster leaves at, bits per second.
147 pub bits_per_second: f64,
148 /// How much the cluster holds, octets on the wire.
149 pub octets: usize,
150}
151
152impl ProbeRequest {
153 /// The packet that carries this application-ward from where it is read at `now`.
154 pub fn into_packet(self, now: Instant) -> TaggedPacket {
155 TaggedPacket {
156 now,
157 transport: TransportContext::default(),
158 message: AttributedPacket::new(Packet::Rtcp(vec![]))
159 .with(Attribute::Custom(Arc::new(self))),
160 }
161 }
162}
163
164/// How much padding a probe cluster needs, from the pacer that sends it.
165///
166/// The pacer reads a [`ProbeRequest`] first on its way application-ward and adds this to the
167/// same carrier: the cluster's size less the media and retransmissions already waiting in its
168/// queue, which leave first, at the cluster's rate and with its mark, and so fill the cluster
169/// in place of padding. The NACK responder makes that much padding and no more (none at all
170/// while a backlog waits, as during the pacer's pause): padding made for a cluster that media
171/// fills never leaves in it, and each such packet uses up a sequence number of the RTX stream.
172/// Without a pacer in the chain there is no such attribute and the responder fills the whole
173/// cluster.
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct ProbeFill {
176 /// The cluster this is about ([`ProbeRequest::cluster`]).
177 pub cluster: u32,
178 /// The padding wanted, octets on the wire.
179 pub octets: usize,
180}
181
182/// The mark of an RTP packet the pacer released as part of a probe cluster, as an
183/// [`Attribute::Custom`] on its way to the wire.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct ProbePacket {
186 /// The cluster it belongs to.
187 pub cluster: u32,
188}
189
190/// How much a cluster at `bits_per_second` holds.
191pub(crate) fn cluster_octets(bits_per_second: f64) -> usize {
192 let by_duration = (bits_per_second * PROBE_MIN_DURATION.as_secs_f64() / 8.0) as usize;
193 by_duration.clamp(PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS, PROBE_MAX_OCTETS)
194}
195
196/// The bit rate a path showed it carries, from the reports on the packets of one cluster.
197///
198/// The cluster left at the send rate and arrived at the receive rate; the path carries the
199/// lower of the two. The send rate is taken over all but the last packet and the span from
200/// the first departure to the last, the receive rate over all but the first packet and the
201/// span of the arrivals, so that each is octets over the time they took. When the packets
202/// arrived more than a tenth slower than they left, the bottleneck was reached and held them
203/// apart: the estimate is 95% of the receive rate, to stay below it.
204///
205/// `None` when fewer than four packets of the cluster arrived with a time, or their times do
206/// not span anything: too little to measure.
207pub fn probe_estimate(reports: &[PacketReport]) -> Option<f64> {
208 let arrived: Vec<(Instant, Duration, usize)> = reports
209 .iter()
210 .filter(|report| report.arrived)
211 .filter_map(|report| Some((report.departure, report.arrival?, report.size)))
212 .collect();
213 if arrived.len() < 4 {
214 return None;
215 }
216 let total: usize = arrived.iter().map(|(_, _, size)| size).sum();
217
218 let (first_sent, last_sent) =
219 arrived
220 .iter()
221 .fold(None, |span: Option<(Instant, Instant)>, (sent, _, _)| {
222 Some(span.map_or((*sent, *sent), |(first, last)| {
223 (first.min(*sent), last.max(*sent))
224 }))
225 })?;
226 let last_sent_size = arrived
227 .iter()
228 .filter(|(sent, _, _)| *sent == last_sent)
229 .map(|(_, _, size)| *size)
230 .next_back()?;
231 let (first_arrival, last_arrival) =
232 arrived
233 .iter()
234 .fold(None, |span: Option<(Duration, Duration)>, (_, at, _)| {
235 Some(span.map_or((*at, *at), |(first, last)| (first.min(*at), last.max(*at))))
236 })?;
237 let first_arrival_size = arrived
238 .iter()
239 .find(|(_, at, _)| *at == first_arrival)
240 .map(|(_, _, size)| *size)?;
241
242 let send_span = last_sent
243 .saturating_duration_since(first_sent)
244 .as_secs_f64();
245 let receive_span = last_arrival.saturating_sub(first_arrival).as_secs_f64();
246 if receive_span <= 0.0 {
247 return None;
248 }
249 let receive_rate = (total - first_arrival_size) as f64 * 8.0 / receive_span;
250 // Packets that left in the same instant have no send rate to compare with: the arrivals
251 // alone say what the path did with them.
252 if send_span <= 0.0 {
253 return Some(receive_rate * 0.95);
254 }
255 let send_rate = (total - last_sent_size) as f64 * 8.0 / send_span;
256 if receive_rate < 0.9 * send_rate {
257 Some(receive_rate * 0.95)
258 } else {
259 Some(send_rate.min(receive_rate))
260 }
261}
262
263/// The bit rate a path showed it carries, from the reports on a cluster that left as one burst
264/// (a chain without a pacer: the NACK responder's padding, written in the same instant).
265///
266/// Such a cluster has no send rate. What the path did with it is the measurement: packets
267/// that left together arrive as far apart as the narrowest link takes to send each, so the
268/// octets after the first over the span of the arrivals is that link's rate (95% of it is
269/// taken, as [`probe_estimate`] takes of a cluster the bottleneck held apart). The cluster was
270/// asked for at `asked` bits per second and nothing was sent to show more than that: the
271/// result is never above it, and it is `asked` itself when the arrivals span no time the
272/// receiver's clock resolves.
273///
274/// A known limit of this measurement: a path that delivers the burst as one aggregate (a
275/// Wi-Fi or cellular link that hands several packets over at once behind the narrow link)
276/// shows no spread, or less than the narrow link made, and is credited with up to the rate
277/// asked for although it carries less. Nothing was sent at that rate, so the cluster cannot
278/// contradict it; the estimate is then above the path until the delay-based controller's
279/// over-use detection brings it down, a few feedback reports after the media follows it. A
280/// paced cluster does not have the limit (its packets leave at the rate asked for, and the
281/// path either carries them so or delays them). The credit is not held to a multiple of
282/// what the path carried in the last second: at the start, which is where the clusters
283/// matter, the path has carried next to nothing yet.
284///
285/// `None` when fewer than four packets of the cluster arrived with a time.
286pub fn burst_estimate(reports: &[PacketReport], asked: f64) -> Option<f64> {
287 let arrived: Vec<(Duration, usize)> = reports
288 .iter()
289 .filter(|report| report.arrived)
290 .filter_map(|report| Some((report.arrival?, report.size)))
291 .collect();
292 if arrived.len() < 4 {
293 return None;
294 }
295 let total: usize = arrived.iter().map(|(_, size)| size).sum();
296 let first = arrived.iter().min_by_key(|(at, _)| *at)?;
297 let last = arrived.iter().max_by_key(|(at, _)| *at)?;
298 let span = last.0.saturating_sub(first.0).as_secs_f64();
299 if span <= 0.0 {
300 return Some(asked);
301 }
302 Some(((total - first.1) as f64 * 8.0 / span * 0.95).min(asked))
303}
304
305/// Decides when a probe cluster is sent and at what rate.
306#[derive(Debug)]
307pub struct ProbeController {
308 next_cluster: u32,
309 /// Rates still to probe from the start-up sequence.
310 initial: Vec<f64>,
311 started: bool,
312 /// The cluster awaiting its result: its number, its rate and when it was asked for.
313 outstanding: Option<(u32, f64, Instant)>,
314 last_probe: Option<Instant>,
315 /// A further cluster owed after a result that confirmed its rate.
316 further: Option<f64>,
317 max_bitrate: f64,
318 /// What is probed for after a large drop (see
319 /// [`with_after_drop_probe`](Self::with_after_drop_probe)).
320 after_drop: AfterDropProbe,
321 /// The highest target of the last [`LARGE_DROP_WINDOW`], and when it was.
322 peak: Option<(f64, Instant)>,
323 /// The last large drop: the target before it, and when it happened.
324 drop: Option<(f64, Instant)>,
325 /// Whether the outstanding cluster probes for the rate before a drop.
326 drop_probe: bool,
327 /// When [`poll`](Self::poll) was last called.
328 polled_at: Option<Instant>,
329 /// Whether clusters leave as bursts of padding ([`set_unpaced`](Self::set_unpaced)).
330 unpaced: bool,
331 /// The target at the last [`poll`](Self::poll).
332 last_target: Option<f64>,
333 /// [`AfterDropProbe::Libwebrtc`]: the last update of the target below two thirds of the
334 /// one before it: the target before it, and when.
335 step_drop: Option<(f64, Instant)>,
336 /// [`AfterDropProbe::Libwebrtc`]: when a probe after a drop was last asked for.
337 last_drop_probe: Option<Instant>,
338 /// Whether the sender is application limited, and when it last stopped being so.
339 application_limited: bool,
340 application_limited_ended: Option<Instant>,
341 /// The estimator's reading of the path ([`set_usage`](Self::set_usage)), and whether it
342 /// has returned from under-use to normal since the last poll.
343 usage: Usage,
344 recovered_from_overuse: bool,
345 /// Whether the rate before a large drop is probed back towards for as long as it is
346 /// remembered ([`with_recovery_probing`](Self::with_recovery_probing)).
347 recovery: bool,
348 /// The highest rate the target had before a large drop of the last
349 /// [`PROBE_DROP_MEMORY`], and when that drop was.
350 remembered: Option<(f64, Instant)>,
351 /// When the last recovery cluster was asked for.
352 last_recovery: Option<Instant>,
353}
354
355impl ProbeController {
356 /// A controller for an estimator that starts at `initial_bitrate` and never goes above
357 /// `max_bitrate`.
358 pub fn new(initial_bitrate: f64, max_bitrate: f64) -> Self {
359 Self {
360 next_cluster: 1,
361 initial: INITIAL_PROBES
362 .iter()
363 .rev()
364 .map(|multiple| initial_bitrate * multiple)
365 .collect(),
366 started: false,
367 outstanding: None,
368 last_probe: None,
369 further: None,
370 max_bitrate,
371 after_drop: AfterDropProbe::default(),
372 peak: None,
373 drop: None,
374 drop_probe: false,
375 polled_at: None,
376 unpaced: false,
377 last_target: None,
378 step_drop: None,
379 last_drop_probe: None,
380 application_limited: false,
381 application_limited_ended: None,
382 usage: Usage::Normal,
383 recovered_from_overuse: false,
384 recovery: false,
385 remembered: None,
386 last_recovery: None,
387 }
388 }
389
390 /// Whether the path is probed back towards the rate it carried before a large drop for as
391 /// long as that rate is remembered: recovery probing. Off by default.
392 ///
393 /// A capacity that fell and comes back (a cellular link out of a tunnel, a competing
394 /// transfer that ends after half a minute) leaves a sender that keeps up with its target
395 /// at the bottom of the delay-based controller's climb: 8% a second, about 18 s from
396 /// 250 kbit/s to 1 Mbit/s. Nothing else asks: the probes after a drop
397 /// ([`with_after_drop_probe`](Self::with_after_drop_probe)) end five seconds after it, and
398 /// the periodic ones are for a sender that sends less than its target. With this, the
399 /// target before a large drop (below two thirds of its high of the last two seconds) is
400 /// remembered for [`PROBE_DROP_MEMORY`] (the highest such rate, through the smaller
401 /// drops of the time under the limit), and while the target is below 85% of it and the
402 /// estimator does not read the path as over-used ([`set_usage`](Self::set_usage)),
403 /// a cluster at twice the target is asked for every [`PROBE_RECOVERY_INTERVAL`], with
404 /// further ones at twice the result while results confirm the rate probed. A cluster the
405 /// path does not carry changes nothing (a probe only ever raises the estimate).
406 ///
407 /// No specification asks for it (RFC 8836 section 2 names probing at the start only;
408 /// draft-ietf-rmcat-gcc-02 has no probing), and libwebrtc does not do it: its periodic
409 /// probes are for an application-limited sender, its probe after a drop is one cluster
410 /// within five seconds. It is a performance choice: it puts a cluster above the target
411 /// into a path that may still be limited, every five seconds for up to a minute. Not for
412 /// a chain whose clusters leave as bursts ([`set_unpaced`](Self::set_unpaced)).
413 ///
414 /// Measured on the capacity instrument (`tests/capacity_instrument.rs`; the default
415 /// chain, a 2.5 Mbit/s path that drops to 300 kbit/s for 20 s, 200 calls a cell, without
416 /// the setting against with it). WHAT IT GAINS: the target is back at 1 Mbit/s 4.9 s
417 /// after the limit went (5.4 s at most) instead of 17.3 s, and at the 2.5 Mbit/s maximum
418 /// through the window 15 to 25 s after it instead of 1283 kbit/s on average; the same
419 /// behind a 100 ms queue (17.6 -> 5.0 s) and with both directions limited (16.2 -> 4.8 s);
420 /// behind a 1000 ms queue in nine calls of ten (median 17.6 -> 5.0 s, the slowest tenth
421 /// 17.5 s: the deep queue is still draining when the first clusters come). The five
422 /// seconds are the interval: the wait is anywhere up to it. WHAT IT COSTS: under the
423 /// limit the target is 238 kbit/s against 246 (3%), behind a 100 ms queue 52 audio
424 /// packets are lost a call against 41 and 201 packets dropped at the queue against 159;
425 /// the counts of calls with an old picture, a freeze or an audio gap do not move in any
426 /// cell. WHERE IT GAINS NOTHING: a limit that outlasts the minute the rate is remembered
427 /// (held 60 s: 17.6 s against 16.9 s, and the rate not back within 20 s in 33 of 200
428 /// calls against 14). As bursts in a chain without a pacer the gain was the same and
429 /// the calls with an old picture rose in every cell that had any (both directions
430 /// limited 25 -> 31 of 200), which is why it is the paced chain's only.
431 pub fn with_recovery_probing(mut self, enabled: bool) -> Self {
432 self.recovery = enabled;
433 self
434 }
435
436 /// What is probed for after a large drop of the target: [`AfterDropProbe`].
437 pub fn with_after_drop_probe(mut self, after_drop: AfterDropProbe) -> Self {
438 self.after_drop = after_drop;
439 self
440 }
441
442 /// The estimator's reading of the path now
443 /// ([`BandwidthEstimator::usage`](crate::BandwidthEstimator::usage)).
444 /// [`AfterDropProbe::Libwebrtc`] asks for its cluster when the reading returns from
445 /// under-use to normal: the queue an over-use left has drained (libwebrtc
446 /// `DelayBasedBwe`: `recovered_from_overuse`).
447 pub fn set_usage(&mut self, usage: Usage) {
448 if self.usage == Usage::Under && usage == Usage::Normal {
449 self.recovered_from_overuse = true;
450 }
451 self.usage = usage;
452 }
453
454 /// Whether the rate the target had before a large drop is probed for, for a few seconds
455 /// after it: `true` is [`AfterDropProbe::Repeated`] (the default), `false`
456 /// [`AfterDropProbe::Off`]; [`with_after_drop_probe`](Self::with_after_drop_probe) names
457 /// libwebrtc's form too.
458 ///
459 /// A short burst of competing traffic, or a moment of loss, makes the delay-based
460 /// controller back off by a third or more; once it has passed, the climb back is the
461 /// controller's additive increase near the old operating point, half a packet per
462 /// response time, and takes tens of seconds (23 s after a 2 s burst at half the capacity,
463 /// in `rtci-interceptor/tests/rfc8836_multi_flow.rs`), against RFC 8836 section 2
464 /// (requirement 1f: the flow "regains its share quickly"). With this, a drop of the
465 /// target below two thirds of its high of the last two seconds is followed, from a second
466 /// on and once a second for five seconds, by a cluster at 85% of the rate before the drop
467 /// while the target is still below that. A result above the target raises it (as every
468 /// probe does); one below it changes nothing: the competing traffic is still there.
469 pub fn with_probe_after_drop(mut self, enabled: bool) -> Self {
470 self.after_drop = if enabled {
471 AfterDropProbe::Repeated
472 } else {
473 AfterDropProbe::Off
474 };
475 self
476 }
477
478 /// Whether this chain's clusters leave as one burst of padding (no pacer: the congestion
479 /// controller says so when it measures a cluster whose packets left in one instant).
480 ///
481 /// Then the rate before a large drop is not probed for. A paced cluster is the media
482 /// already waiting, released faster for a few milliseconds, with padding only for what
483 /// is missing; a burst is five packets of padding on top of the media, at once. After a
484 /// drop that is 160 ms of a 300 kbit/s link put into the queue that caused the drop, once
485 /// a second. Measured on the capacity instrument (200 calls a cell, a 2.5 Mbit/s path
486 /// that drops to 300 kbit/s): with such bursts 7 of 200 calls of ParolNet's chain were
487 /// over 2 s without a new picture against 3 without them, 172 retransmissions a call
488 /// against 142, and behind a 1000 ms queue the audio paused for over a second in 72 of
489 /// 200 calls against 21. The start-up clusters and those of an application-limited
490 /// sender are still asked for.
491 pub fn set_unpaced(&mut self, unpaced: bool) {
492 self.unpaced = unpaced;
493 }
494
495 /// The path changed and the estimator started over at `start_bitrate`: probing starts over
496 /// too, as at the beginning of the call, and what was noted of the old path is dropped.
497 ///
498 /// The start-up clusters are owed again, at three and six times `start_bitrate` and on
499 /// while the new path carries what is asked (RFC 8836 section 2, requirement 4: the
500 /// conditions of a new path are initial conditions). The target's recent high, the drop
501 /// below it and the cluster awaiting its result belong to the path that was left: the
502 /// estimator's fall back to its starting rate is not a drop of the path's capacity, and
503 /// the rate "before" it is the old path's.
504 ///
505 /// Without this an outage ended by an ICE restart left the call at the estimator's 8% a
506 /// second on the new path (traced on the capacity instrument's outage cell, the default
507 /// chain: 1 Mbit/s 15.1 s after the new pair). While nothing is acknowledged the
508 /// estimator halves at every feedback timeout, each halving a large drop, and the probe
509 /// for the rate before the last of them (133 kbit/s, asked into the dead path half a
510 /// second before the new pair) was still awaiting its result when the path changed. It
511 /// held the controller's one slot for the half second in which the sender, still sending
512 /// at the old path's floor, counted as application limited against the new starting
513 /// rate; after it nothing was due. Without the probe after a drop that
514 /// application-limited cluster did find the path (1.0 s), but only in the calls where
515 /// one happened to be due (134 of 200; 12 to 13 s in the others).
516 ///
517 /// libwebrtc does the same on a network route change: `ProbeController::Reset`
518 /// (goog_cc `probe_controller.cc`) returns to its initial state and forgets the rate
519 /// before the last large drop, and the constraints set next start the exponential probes
520 /// again (`GoogCcNetworkController::OnNetworkRouteChange`).
521 pub fn on_path_change(&mut self, now: Instant, start_bitrate: f64) {
522 self.initial = INITIAL_PROBES
523 .iter()
524 .rev()
525 .map(|multiple| start_bitrate * multiple)
526 .collect();
527 self.started = false;
528 self.outstanding = None;
529 self.last_probe = None;
530 self.further = None;
531 self.peak = None;
532 self.drop = None;
533 self.drop_probe = false;
534 self.last_target = None;
535 self.step_drop = None;
536 // libwebrtc's `Reset` counts the change as the time of its last probe after a drop.
537 self.last_drop_probe = Some(now);
538 self.application_limited_ended = None;
539 self.usage = Usage::Normal;
540 self.recovered_from_overuse = false;
541 // The rate remembered for recovery probing was the old path's.
542 self.remembered = None;
543 self.last_recovery = None;
544 }
545
546 /// The ceiling of what is probed for: the estimator's own maximum, or a limit from
547 /// outside it (REMB, TMMBR, the session bit rate).
548 pub fn set_max_bitrate(&mut self, max_bitrate: f64) {
549 self.max_bitrate = max_bitrate;
550 }
551
552 /// The cluster to send now, if one is due.
553 ///
554 /// `target` is the current target bit rate and `sending` the rate the application is
555 /// sending at; `media_flowing` is whether a packet has left yet (a probe before the
556 /// first one would measure nothing the receiver reports).
557 pub fn poll(
558 &mut self,
559 now: Instant,
560 target: f64,
561 sending: f64,
562 media_flowing: bool,
563 ) -> Option<ProbeRequest> {
564 self.polled_at = Some(now);
565 if !media_flowing {
566 return None;
567 }
568 self.track_drops(now, target);
569 self.track_application_limited(now, target, sending);
570 let recovered_from_overuse = std::mem::take(&mut self.recovered_from_overuse);
571 if let Some((_, _, asked)) = self.outstanding {
572 if now.saturating_duration_since(asked) < PROBE_RESULT_TIMEOUT {
573 return None;
574 }
575 // Its reports never came: the cluster is given up, and with it the sequence it
576 // was part of.
577 self.outstanding = None;
578 self.further = None;
579 self.drop_probe = false;
580 }
581 if self
582 .last_probe
583 .is_some_and(|last| now.saturating_duration_since(last) < PROBE_SPACING)
584 {
585 return None;
586 }
587
588 self.started = true;
589 let rate = if let Some(rate) = self.initial.pop() {
590 Some(rate)
591 } else if let Some(rate) = self.further.take() {
592 Some(rate)
593 } else if let Some((before, at)) = self.drop
594 && self.after_drop == AfterDropProbe::Repeated
595 && !self.unpaced
596 && now.saturating_duration_since(at) >= PROBE_AFTER_DROP_DELAY
597 && target < PROBE_AFTER_DROP_SHARE * before
598 && self
599 .last_probe
600 .is_none_or(|last| now.saturating_duration_since(last) >= PROBE_AFTER_DROP_INTERVAL)
601 {
602 // The rate before a large drop, while the drop is recent: if what caused it has
603 // gone, the path carries it again.
604 self.drop_probe = true;
605 Some(PROBE_AFTER_DROP_SHARE * before)
606 } else if let Some(rate) = self.libwebrtc_drop_probe(now, target, recovered_from_overuse) {
607 self.drop_probe = true;
608 self.last_drop_probe = Some(now);
609 Some(rate)
610 } else if self.recovery_due(now, target) {
611 // Below the rate the path carried before a large drop that is still remembered:
612 // what limited it may have gone, and a sender at its target is not asked by
613 // anything else.
614 self.last_recovery = Some(now);
615 Some(target * FURTHER_PROBE)
616 } else if sending < APPLICATION_LIMITED_SHARE * target
617 && self.last_probe.is_none_or(|last| {
618 now.saturating_duration_since(last) >= PROBE_APPLICATION_LIMITED_INTERVAL
619 })
620 {
621 // Sending less than the target allows, the delay-based controller learns nothing
622 // about the room above what is sent.
623 Some(target * FURTHER_PROBE)
624 } else {
625 None
626 }?;
627
628 let rate = rate.min(self.max_bitrate);
629 if rate <= target {
630 // Nothing above the target is allowed, so there is nothing to ask.
631 self.drop_probe = false;
632 return None;
633 }
634 let cluster = self.next_cluster;
635 self.next_cluster = self.next_cluster.wrapping_add(1).max(1);
636 self.outstanding = Some((cluster, rate, now));
637 self.last_probe = Some(now);
638 Some(ProbeRequest {
639 cluster,
640 bits_per_second: rate,
641 octets: cluster_octets(rate),
642 })
643 }
644
645 /// Whether a recovery cluster is due: the setting, paced clusters, a remembered rate the
646 /// target is well below, no over-use, and the interval since the drop or the last one.
647 fn recovery_due(&self, now: Instant, target: f64) -> bool {
648 let Some(at) = self.recovery_deadline() else {
649 return false;
650 };
651 let Some((before, _)) = self.remembered else {
652 return false;
653 };
654 now >= at && self.usage != Usage::Over && target < PROBE_AFTER_DROP_SHARE * before
655 }
656
657 /// When the next recovery cluster may be asked for, while a rate is remembered.
658 fn recovery_deadline(&self) -> Option<Instant> {
659 if !self.recovery || self.unpaced {
660 return None;
661 }
662 let (_, dropped) = self.remembered?;
663 let since = self.last_recovery.map_or(dropped, |last| last.max(dropped));
664 Some(since + PROBE_RECOVERY_INTERVAL)
665 }
666
667 /// libwebrtc's probe after a drop (`ProbeController::RequestProbe`), when it is due: the
668 /// detector has just returned to normal, the sender is or was lately application limited,
669 /// the drop is under five seconds old, the last such probe over five seconds, and 95% of
670 /// the rate to ask for is above the target.
671 fn libwebrtc_drop_probe(
672 &self,
673 now: Instant,
674 target: f64,
675 recovered_from_overuse: bool,
676 ) -> Option<f64> {
677 if self.after_drop != AfterDropProbe::Libwebrtc || self.unpaced || !recovered_from_overuse {
678 return None;
679 }
680 let limited = self.application_limited
681 || self
682 .application_limited_ended
683 .is_some_and(|ended| now.saturating_duration_since(ended) < ALR_ENDED_TIMEOUT);
684 let (before, at) = self.step_drop?;
685 let rate = PROBE_AFTER_DROP_SHARE * before;
686 (limited
687 && (1.0 - LIBWEBRTC_PROBE_UNCERTAINTY) * rate > target
688 && now.saturating_duration_since(at) < PROBE_AFTER_DROP_TIMEOUT
689 && self.last_drop_probe.is_none_or(|last| {
690 now.saturating_duration_since(last) > LIBWEBRTC_DROP_PROBE_INTERVAL
691 }))
692 .then_some(rate)
693 }
694
695 /// Whether the sender is application limited, and when it stopped being so.
696 fn track_application_limited(&mut self, now: Instant, target: f64, sending: f64) {
697 let limited = sending < APPLICATION_LIMITED_SHARE * target;
698 if self.application_limited && !limited {
699 self.application_limited_ended = Some(now);
700 }
701 self.application_limited = limited;
702 }
703
704 /// Follows the target's recent high, and notes a large drop below it.
705 fn track_drops(&mut self, now: Instant, target: f64) {
706 // libwebrtc's drop: one update below two thirds of the one before it.
707 if let Some(last) = self.last_target
708 && target < LARGE_DROP_SHARE * last
709 {
710 self.step_drop = Some((last, now));
711 }
712 self.last_target = Some(target);
713 if self
714 .remembered
715 .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_DROP_MEMORY)
716 {
717 self.remembered = None;
718 }
719 match self.peak {
720 Some((peak, at))
721 if target < peak && now.saturating_duration_since(at) <= LARGE_DROP_WINDOW =>
722 {
723 if target < LARGE_DROP_SHARE * peak {
724 self.drop = Some((peak, now));
725 self.peak = Some((target, now));
726 // The highest rate before a drop of the last minute stays the one
727 // remembered: the smaller drops under a limit (the controller's own
728 // sawtooth) do not replace the rate the path had before it.
729 if self.remembered.is_none_or(|(before, _)| peak >= before) {
730 self.remembered = Some((peak, now));
731 }
732 }
733 }
734 _ => self.peak = Some((target, now)),
735 }
736 if self
737 .drop
738 .is_some_and(|(_, at)| now.saturating_duration_since(at) > PROBE_AFTER_DROP_TIMEOUT)
739 {
740 self.drop = None;
741 }
742 }
743
744 /// The number of the cluster whose result is awaited.
745 pub fn outstanding(&self) -> Option<u32> {
746 self.outstanding.map(|(cluster, _, _)| cluster)
747 }
748
749 /// The rate `cluster` was asked for at, while its result is awaited.
750 pub fn asked_rate(&self, cluster: u32) -> Option<f64> {
751 self.outstanding
752 .filter(|(outstanding, _, _)| *outstanding == cluster)
753 .map(|(_, rate, _)| rate)
754 }
755
756 /// The result of `cluster`: `estimate` bits per second. Returns the estimate when it is
757 /// the outstanding cluster's, for the estimator to take.
758 pub fn on_result(&mut self, cluster: u32, estimate: f64) -> Option<f64> {
759 let (outstanding, rate, _) = self.outstanding?;
760 if outstanding != cluster {
761 return None;
762 }
763 self.outstanding = None;
764 // The path carried what was asked of it: it may carry more. Not after a probe for the
765 // rate before a drop: that asks only whether the path is back where it was.
766 let drop_probe = std::mem::take(&mut self.drop_probe);
767 if !drop_probe && estimate >= FURTHER_PROBE_THRESHOLD * rate && self.initial.is_empty() {
768 let next = estimate * FURTHER_PROBE;
769 if next <= self.max_bitrate * FURTHER_PROBE {
770 self.further = Some(next);
771 }
772 }
773 Some(estimate)
774 }
775
776 /// When [`poll`](Self::poll) next has something to say without anything else happening.
777 ///
778 /// Never an instant `poll` has already been called at or after: a deadline that passed
779 /// with nothing to send (no media flowing, a sender that is no longer application
780 /// limited, a target that recovered by itself) waits for the next write instead of
781 /// asking to be woken again at once.
782 pub fn poll_timeout(&self) -> Option<Instant> {
783 self.deadlines()
784 .into_iter()
785 .flatten()
786 .filter(|deadline| self.polled_at.is_none_or(|polled| *deadline > polled))
787 .min()
788 }
789
790 /// The instants something may be due: a result to give up, the next cluster of a
791 /// sequence or of an application-limited sender, the next probe after a drop, the next
792 /// recovery cluster.
793 fn deadlines(&self) -> [Option<Instant>; 3] {
794 if !self.started {
795 return [None, None, None];
796 }
797 if let Some((_, _, asked)) = self.outstanding {
798 return [Some(asked + PROBE_RESULT_TIMEOUT), None, None];
799 }
800 let Some(last) = self.last_probe else {
801 return [None, None, None];
802 };
803 let next = if !self.initial.is_empty() || self.further.is_some() {
804 last + PROBE_SPACING
805 } else {
806 last + PROBE_APPLICATION_LIMITED_INTERVAL
807 };
808 let after_drop = self
809 .drop
810 .filter(|_| self.after_drop == AfterDropProbe::Repeated && !self.unpaced)
811 .map(|(_, at)| (at + PROBE_AFTER_DROP_DELAY).max(last + PROBE_AFTER_DROP_INTERVAL));
812 let recovery = self
813 .recovery_deadline()
814 .map(|at| at.max(last + PROBE_SPACING));
815 [Some(next), after_drop, recovery]
816 }
817}
818
819#[cfg(test)]
820mod tests {
821 use super::*;
822 use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
823
824 fn report(id: u64, departure: Instant, arrival_us: u64, size: usize) -> PacketReport {
825 PacketReport {
826 ssrc: 1,
827 id,
828 rtp_sequence_number: id as u16,
829 is_twcc: true,
830 twcc_sequence_number: id as u16,
831 size,
832 arrived: true,
833 departure,
834 arrival: Some(Duration::from_micros(arrival_us)),
835 ecn: Ecn::NotEct,
836 }
837 }
838
839 /// Six 1200-octet packets sent 2 ms apart (4.8 Mbit/s) that arrive 2 ms apart: the path
840 /// carried the cluster, and the estimate is the rate it was sent at.
841 #[test]
842 fn a_cluster_that_arrives_as_it_left_shows_its_own_rate() {
843 let epoch = Instant::now();
844 let reports: Vec<PacketReport> = (0..6u64)
845 .map(|i| {
846 report(
847 i,
848 epoch + Duration::from_millis(2 * i),
849 50_000 + 2_000 * i,
850 1200,
851 )
852 })
853 .collect();
854 let estimate = probe_estimate(&reports).expect("measurable");
855 assert!((estimate - 4_800_000.0).abs() < 1_000.0, "{estimate}");
856 }
857
858 /// The same cluster through a 2.4 Mbit/s bottleneck arrives 4 ms apart: the estimate is
859 /// 95% of the rate it arrived at, not the rate it was sent at.
860 #[test]
861 fn a_cluster_spread_out_by_the_bottleneck_shows_the_bottleneck() {
862 let epoch = Instant::now();
863 let reports: Vec<PacketReport> = (0..6u64)
864 .map(|i| {
865 report(
866 i,
867 epoch + Duration::from_millis(2 * i),
868 50_000 + 4_000 * i,
869 1200,
870 )
871 })
872 .collect();
873 let estimate = probe_estimate(&reports).expect("measurable");
874 assert!(
875 (estimate - 0.95 * 2_400_000.0).abs() < 1_000.0,
876 "{estimate}"
877 );
878 }
879
880 /// Three arrivals are not a measurement, and neither are packets without arrival times.
881 #[test]
882 fn too_few_arrivals_give_no_estimate() {
883 let epoch = Instant::now();
884 let mut reports: Vec<PacketReport> = (0..3u64)
885 .map(|i| {
886 report(
887 i,
888 epoch + Duration::from_millis(2 * i),
889 50_000 + 2_000 * i,
890 1200,
891 )
892 })
893 .collect();
894 assert_eq!(None, probe_estimate(&reports));
895 let mut lost = report(3, epoch + Duration::from_millis(6), 0, 1200);
896 lost.arrived = false;
897 lost.arrival = None;
898 reports.push(lost);
899 assert_eq!(None, probe_estimate(&reports));
900 }
901
902 /// At the start: three times the starting rate, then six times, each once its predecessor
903 /// has a result, and nothing before media flows.
904 #[test]
905 fn the_start_probes_at_three_and_six_times_the_starting_rate() {
906 let epoch = Instant::now();
907 let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
908 assert_eq!(None, controller.poll(epoch, 300_000.0, 0.0, false));
909
910 let first = controller
911 .poll(epoch, 300_000.0, 300_000.0, true)
912 .expect("first cluster");
913 assert_eq!(900_000.0, first.bits_per_second);
914 assert_eq!(
915 PROBE_MIN_PACKETS * PROBE_PACKET_OCTETS,
916 first.octets,
917 "five packets at least"
918 );
919 assert_eq!(
920 None,
921 controller.poll(
922 epoch + Duration::from_millis(200),
923 300_000.0,
924 300_000.0,
925 true
926 ),
927 "one cluster at a time"
928 );
929
930 assert_eq!(
931 Some(900_000.0),
932 controller.on_result(first.cluster, 900_000.0)
933 );
934 let second = controller
935 .poll(
936 epoch + Duration::from_millis(200),
937 900_000.0,
938 300_000.0,
939 true,
940 )
941 .expect("second cluster");
942 assert_eq!(1_800_000.0, second.bits_per_second);
943 }
944
945 /// A result that confirms the rate probed is followed by a cluster at twice the result; one
946 /// that shows the bottleneck is not.
947 #[test]
948 fn probing_goes_on_while_the_path_carries_what_is_asked() {
949 let epoch = Instant::now();
950 let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
951 let mut now = epoch;
952 let mut target = 300_000.0;
953 let mut asked = Vec::new();
954 // The path carries 2.5 Mbit/s.
955 for _ in 0..8 {
956 if let Some(request) = controller.poll(now, target, target, true) {
957 asked.push(request.bits_per_second);
958 let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
959 target = controller
960 .on_result(request.cluster, estimate)
961 .expect("the outstanding cluster");
962 }
963 now += Duration::from_millis(150);
964 }
965 assert_eq!(
966 vec![900_000.0, 1_800_000.0, 3_600_000.0],
967 asked,
968 "the third cluster found the bottleneck (2.375 of 3.6 Mbit/s) and ended the sequence"
969 );
970 assert_eq!(2_375_000.0, target);
971 }
972
973 /// While the application sends less than the target allows, a cluster goes out every five
974 /// seconds; at the target, none.
975 #[test]
976 fn an_application_limited_sender_probes_every_few_seconds() {
977 let epoch = Instant::now();
978 let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
979 // The start-up sequence, answered with the bottleneck at once.
980 for at in [epoch, epoch + Duration::from_millis(150)] {
981 let request = controller
982 .poll(at, 300_000.0, 300_000.0, true)
983 .expect("start-up cluster");
984 controller.on_result(request.cluster, 500_000.0);
985 }
986
987 let later = epoch + Duration::from_secs(6);
988 assert_eq!(
989 None,
990 controller.poll(later, 1_000_000.0, 1_000_000.0, true),
991 "sending at the target: the delay-based controller is asking already"
992 );
993 let request = controller
994 .poll(later, 1_000_000.0, 200_000.0, true)
995 .expect("application limited");
996 assert_eq!(2_000_000.0, request.bits_per_second);
997 controller.on_result(request.cluster, 1_200_000.0);
998 assert_eq!(
999 None,
1000 controller.poll(later + Duration::from_secs(1), 1_000_000.0, 200_000.0, true),
1001 "not again within five seconds"
1002 );
1003 }
1004
1005 /// Nothing is probed above the ceiling, and a cluster whose reports never come is given up.
1006 #[test]
1007 fn the_ceiling_and_the_timeout_end_a_probe() {
1008 let epoch = Instant::now();
1009 let mut controller = ProbeController::new(300_000.0, 600_000.0);
1010 let request = controller
1011 .poll(epoch, 300_000.0, 300_000.0, true)
1012 .expect("capped cluster");
1013 assert_eq!(600_000.0, request.bits_per_second);
1014 assert_eq!(Some(request.cluster), controller.outstanding());
1015 assert_eq!(
1016 Some(epoch + PROBE_RESULT_TIMEOUT),
1017 controller.poll_timeout()
1018 );
1019
1020 let after = epoch + PROBE_RESULT_TIMEOUT;
1021 // Given up; the next of the start-up sequence is capped at the ceiling too, which the
1022 // target has reached by then.
1023 assert_eq!(None, controller.poll(after, 600_000.0, 600_000.0, true));
1024 assert_eq!(None, controller.outstanding());
1025 }
1026
1027 /// Settles a controller after its start-up sequence: two clusters answered at the
1028 /// bottleneck, so no further cluster is owed.
1029 fn settled(epoch: Instant) -> ProbeController {
1030 let mut controller = ProbeController::new(300_000.0, 100_000_000.0);
1031 for at in [epoch, epoch + Duration::from_millis(150)] {
1032 let request = controller
1033 .poll(at, 300_000.0, 300_000.0, true)
1034 .expect("start-up cluster");
1035 controller.on_result(request.cluster, 500_000.0);
1036 }
1037 controller
1038 }
1039
1040 /// RFC 8836 section 2 (1f): after a large drop of the target (a burst of competing
1041 /// traffic), the rate before it is probed for, from a second after the drop and once a
1042 /// second, and a result never asks for a further cluster above it.
1043 #[test]
1044 fn a_large_drop_is_followed_by_a_probe_at_the_rate_before_it() {
1045 let epoch = Instant::now();
1046 let mut controller = settled(epoch);
1047 let at = |ms: u64| epoch + Duration::from_millis(ms);
1048 // At 2 Mbit/s, sending at the target, for a while.
1049 for ms in (1_000..2_000).step_by(100) {
1050 assert_eq!(
1051 None,
1052 controller.poll(at(ms), 2_000_000.0, 2_000_000.0, true)
1053 );
1054 }
1055 // Down to 900 kbit/s: a drop of more than a third.
1056 assert_eq!(None, controller.poll(at(2_000), 900_000.0, 900_000.0, true));
1057 assert_eq!(
1058 None,
1059 controller.poll(at(2_500), 900_000.0, 900_000.0, true),
1060 "the back-off is given a second first"
1061 );
1062 assert_eq!(Some(at(3_000)), controller.poll_timeout());
1063 let request = controller
1064 .poll(at(3_000), 900_000.0, 900_000.0, true)
1065 .expect("the rate before the drop");
1066 assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1067 // The path carries it again: the estimator takes it, and nothing above it is asked.
1068 assert_eq!(
1069 Some(1_700_000.0),
1070 controller.on_result(request.cluster, 1_700_000.0)
1071 );
1072 assert_eq!(
1073 None,
1074 controller.poll(at(3_200), 1_700_000.0, 1_700_000.0, true)
1075 );
1076 assert_eq!(
1077 None,
1078 controller.poll(at(4_500), 1_700_000.0, 1_700_000.0, true)
1079 );
1080 }
1081
1082 /// While the competing traffic is still there the probe shows less than the rate before
1083 /// the drop: it is asked again a second later, and not after the drop is five seconds old.
1084 #[test]
1085 fn probes_after_a_drop_stop_after_a_few_seconds() {
1086 let epoch = Instant::now();
1087 let mut controller = settled(epoch);
1088 let at = |ms: u64| epoch + Duration::from_millis(ms);
1089 assert_eq!(
1090 None,
1091 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1092 );
1093 assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
1094 let mut probes = 0;
1095 for ms in (1_200..9_000).step_by(100) {
1096 if let Some(request) = controller.poll(at(ms), 900_000.0, 900_000.0, true) {
1097 probes += 1;
1098 assert!(ms <= 1_100 + 5_000, "at {ms} ms");
1099 controller.on_result(request.cluster, 950_000.0);
1100 }
1101 }
1102 assert!((3..=5).contains(&probes), "{probes} probes");
1103 }
1104
1105 /// A chain whose clusters leave as bursts ([`ProbeController::set_unpaced`]) is not probed
1106 /// after a large drop, and names no deadline for it; the same drop is probed once the
1107 /// clusters are paced.
1108 #[test]
1109 fn a_drop_is_not_probed_while_clusters_leave_as_bursts() {
1110 let epoch = Instant::now();
1111 let mut controller = settled(epoch);
1112 controller.set_unpaced(true);
1113 let at = |ms: u64| epoch + Duration::from_millis(ms);
1114 assert_eq!(
1115 None,
1116 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1117 );
1118 for ms in (1_100..4_000).step_by(100) {
1119 assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
1120 assert!(
1121 controller
1122 .poll_timeout()
1123 .is_none_or(|next| next > at(ms) + Duration::from_secs(1)),
1124 "a deadline for a probe that will not be asked for, at {ms} ms"
1125 );
1126 }
1127 controller.set_unpaced(false);
1128 let request = controller
1129 .poll(at(4_000), 900_000.0, 900_000.0, true)
1130 .expect("paced clusters: the rate before the drop");
1131 assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1132 }
1133
1134 /// A path change starts probing over: the start-up clusters again, from the rate the
1135 /// estimator starts over at, and nothing of the old path's drop. The script is an outage
1136 /// ended by an ICE restart, as the default chain's estimator goes through it: at
1137 /// 2.5 Mbit/s, then halved every half second while nothing is acknowledged (each halving
1138 /// a large drop), a probe for the rate before the last one asked into the dead path, and
1139 /// the new path while that probe still awaits its result.
1140 #[test]
1141 fn a_path_change_starts_probing_over_and_forgets_the_drop() {
1142 let epoch = Instant::now();
1143 let mut controller = settled(epoch);
1144 let at = |ms: u64| epoch + Duration::from_millis(ms);
1145 for ms in (1_000..2_000).step_by(100) {
1146 assert_eq!(
1147 None,
1148 controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
1149 );
1150 }
1151 // The outage: 1250, 625, 312, 156 kbit/s, then the floor.
1152 let mut target = 2_500_000.0;
1153 for ms in (2_000..4_500).step_by(500) {
1154 target = f64::max(target / 2.0, 100_000.0);
1155 assert_eq!(None, controller.poll(at(ms), target, target, true));
1156 }
1157 assert_eq!(100_000.0, target);
1158 let stale = controller
1159 .poll(at(5_000), target, target, true)
1160 .expect("the rate before the last halving");
1161 assert_eq!(0.85 * 156_250.0, stale.bits_per_second);
1162
1163 // The new path, 300 ms later: the estimator starts over at 300 kbit/s.
1164 controller.on_path_change(at(5_300), 300_000.0);
1165 assert_eq!(None, controller.outstanding(), "the old path's cluster");
1166 assert_eq!(None, controller.poll_timeout(), "nothing of the old path");
1167 let first = controller
1168 .poll(at(5_300), 300_000.0, 100_000.0, true)
1169 .expect("the first start-up cluster, at once");
1170 assert_eq!(900_000.0, first.bits_per_second);
1171 assert_eq!(
1172 None,
1173 controller.on_result(stale.cluster, 120_000.0),
1174 "a late result of the old path's cluster is nobody's"
1175 );
1176 assert_eq!(
1177 Some(900_000.0),
1178 controller.on_result(first.cluster, 900_000.0)
1179 );
1180 let second = controller
1181 .poll(at(5_450), 900_000.0, 300_000.0, true)
1182 .expect("the second start-up cluster");
1183 assert_eq!(1_800_000.0, second.bits_per_second);
1184 // The new path carries it: a further cluster, as at the start of the call.
1185 assert_eq!(
1186 Some(1_800_000.0),
1187 controller.on_result(second.cluster, 1_800_000.0)
1188 );
1189 let third = controller
1190 .poll(at(5_600), 1_800_000.0, 900_000.0, true)
1191 .expect("a further cluster");
1192 assert_eq!(3_600_000.0, third.bits_per_second);
1193 // It found the bottleneck. From here on the sender is at its target, and nothing of
1194 // the old path's drops is probed for in the seconds that follow.
1195 assert_eq!(
1196 Some(2_375_000.0),
1197 controller.on_result(third.cluster, 2_375_000.0)
1198 );
1199 for ms in (5_700..12_000).step_by(100) {
1200 assert_eq!(
1201 None,
1202 controller.poll(at(ms), 2_375_000.0, 2_375_000.0, true),
1203 "at {ms} ms"
1204 );
1205 }
1206 }
1207
1208 /// The estimator's fall to its starting rate at a path change is not a drop to probe
1209 /// after: from 2.5 Mbit/s to 300 kbit/s on a new path that carries no more than the
1210 /// start-up clusters show, no cluster asks for the old path's rate.
1211 #[test]
1212 fn the_fall_to_the_starting_rate_at_a_path_change_is_not_a_drop() {
1213 let epoch = Instant::now();
1214 let mut controller = settled(epoch);
1215 let at = |ms: u64| epoch + Duration::from_millis(ms);
1216 for ms in (1_000..2_000).step_by(100) {
1217 assert_eq!(
1218 None,
1219 controller.poll(at(ms), 2_500_000.0, 2_500_000.0, true)
1220 );
1221 }
1222 controller.on_path_change(at(2_000), 300_000.0);
1223 let mut asked = Vec::new();
1224 for ms in (2_000..10_000).step_by(100) {
1225 if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1226 asked.push(request.bits_per_second);
1227 // The new path is narrow: every cluster shows 350 kbit/s.
1228 controller.on_result(request.cluster, 350_000.0);
1229 }
1230 }
1231 assert_eq!(
1232 vec![900_000.0, 1_800_000.0],
1233 asked,
1234 "the start-up clusters, and no probe for 85% of 2.5 Mbit/s"
1235 );
1236 }
1237
1238 /// [`AfterDropProbe::Libwebrtc`] across a path change: neither the old path's drop nor the
1239 /// estimator's fall to its starting rate is probed after, however often the new path's
1240 /// detector returns from under-use to normal (libwebrtc's `Reset` forgets the rate before
1241 /// the drop and counts the change as the time of its last such probe). The start-up
1242 /// clusters are all that is asked in the five seconds a drop stays eligible.
1243 #[test]
1244 fn libwebrtcs_probe_after_a_drop_is_not_asked_across_a_path_change() {
1245 let epoch = Instant::now();
1246 let mut controller = dropped_libwebrtc(epoch);
1247 let at = |ms: u64| epoch + Duration::from_millis(ms);
1248 controller.set_usage(Usage::Over);
1249 assert_eq!(None, controller.poll(at(1_200), 900_000.0, 450_000.0, true));
1250 controller.on_path_change(at(1_300), 300_000.0);
1251 let mut asked = Vec::new();
1252 for ms in (1_300..6_300).step_by(100) {
1253 recover_from_overuse(&mut controller);
1254 if let Some(request) = controller.poll(at(ms), 300_000.0, 150_000.0, true) {
1255 asked.push(request.bits_per_second);
1256 controller.on_result(request.cluster, 350_000.0);
1257 }
1258 }
1259 assert_eq!(vec![900_000.0, 1_800_000.0], asked);
1260 }
1261
1262 /// A controller with libwebrtc's probe after a drop, settled, application limited (it
1263 /// sends half its target) at 2 Mbit/s until 1 s and dropped to 900 kbit/s at 1.1 s.
1264 fn dropped_libwebrtc(epoch: Instant) -> ProbeController {
1265 let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
1266 let at = |ms: u64| epoch + Duration::from_millis(ms);
1267 assert_eq!(
1268 None,
1269 controller.poll(at(1_000), 2_000_000.0, 1_000_000.0, true)
1270 );
1271 assert_eq!(None, controller.poll(at(1_100), 900_000.0, 450_000.0, true));
1272 controller
1273 }
1274
1275 /// The detector's way back to normal after an over-use: over, under, normal.
1276 fn recover_from_overuse(controller: &mut ProbeController) {
1277 controller.set_usage(Usage::Over);
1278 controller.set_usage(Usage::Under);
1279 controller.set_usage(Usage::Normal);
1280 }
1281
1282 /// [`AfterDropProbe::Libwebrtc`]: nothing is asked until the detector has returned from
1283 /// under-use to normal; then one cluster at 85% of the target before the drop, which is
1284 /// not followed up, and no second one within five seconds.
1285 #[test]
1286 fn libwebrtcs_probe_after_a_drop_is_one_cluster_once_overuse_has_ended() {
1287 let epoch = Instant::now();
1288 let mut controller = dropped_libwebrtc(epoch);
1289 let at = |ms: u64| epoch + Duration::from_millis(ms);
1290 controller.set_usage(Usage::Over);
1291 for ms in (1_200..3_000).step_by(100) {
1292 assert_eq!(
1293 None,
1294 controller.poll(at(ms), 900_000.0, 450_000.0, true),
1295 "still over-used at {ms} ms"
1296 );
1297 }
1298 controller.set_usage(Usage::Under);
1299 assert_eq!(None, controller.poll(at(3_000), 900_000.0, 450_000.0, true));
1300 controller.set_usage(Usage::Normal);
1301 let request = controller
1302 .poll(at(3_100), 900_000.0, 450_000.0, true)
1303 .expect("back to normal: the rate before the drop");
1304 assert_eq!(0.85 * 2_000_000.0, request.bits_per_second);
1305 assert_eq!(
1306 Some(1_700_000.0),
1307 controller.on_result(request.cluster, 1_700_000.0)
1308 );
1309 assert_eq!(
1310 None,
1311 controller.poll(at(3_300), 1_700_000.0, 850_000.0, true),
1312 "no further cluster above it"
1313 );
1314 // A second drop and recovery a moment later: not within five seconds of the probe.
1315 assert_eq!(None, controller.poll(at(3_400), 900_000.0, 450_000.0, true));
1316 recover_from_overuse(&mut controller);
1317 assert_eq!(None, controller.poll(at(3_600), 900_000.0, 450_000.0, true));
1318 }
1319
1320 /// [`AfterDropProbe::Libwebrtc`] does not probe a sender that keeps up with its target
1321 /// (not application limited, nor lately), nor one whose target is within 5% of the rate
1322 /// it would ask for, nor a drop that is five seconds old.
1323 #[test]
1324 fn libwebrtcs_probe_after_a_drop_has_its_conditions() {
1325 let epoch = Instant::now();
1326 let at = |ms: u64| epoch + Duration::from_millis(ms);
1327
1328 // A sender at its target.
1329 let mut controller = settled(epoch).with_after_drop_probe(AfterDropProbe::Libwebrtc);
1330 assert_eq!(
1331 None,
1332 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1333 );
1334 assert_eq!(None, controller.poll(at(1_100), 900_000.0, 900_000.0, true));
1335 recover_from_overuse(&mut controller);
1336 assert_eq!(None, controller.poll(at(1_300), 900_000.0, 900_000.0, true));
1337
1338 // The target is back at 1.65 Mbit/s: 95% of 1.7 Mbit/s is not above it.
1339 let mut controller = dropped_libwebrtc(epoch);
1340 recover_from_overuse(&mut controller);
1341 assert_eq!(
1342 None,
1343 controller.poll(at(1_300), 1_650_000.0, 825_000.0, true)
1344 );
1345
1346 // The detector is back to normal only once the drop is over five seconds old: no
1347 // cluster at the rate before the drop (the one asked meanwhile is the
1348 // application-limited sender's, at twice the target).
1349 let mut controller = dropped_libwebrtc(epoch);
1350 let mut asked = Vec::new();
1351 for ms in (1_200..7_000).step_by(100) {
1352 if ms == 6_200 {
1353 recover_from_overuse(&mut controller);
1354 }
1355 if let Some(request) = controller.poll(at(ms), 900_000.0, 450_000.0, true) {
1356 asked.push(request.bits_per_second);
1357 controller.on_result(request.cluster, 950_000.0);
1358 }
1359 }
1360 assert_eq!(vec![1_800_000.0], asked);
1361 }
1362
1363 /// `with_probe_after_drop(false)`: a drop is left to the delay-based controller's climb.
1364 #[test]
1365 fn without_the_option_a_drop_is_not_probed() {
1366 let epoch = Instant::now();
1367 let mut controller = settled(epoch).with_probe_after_drop(false);
1368 let at = |ms: u64| epoch + Duration::from_millis(ms);
1369 assert_eq!(
1370 None,
1371 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1372 );
1373 for ms in (1_100..8_000).step_by(100) {
1374 assert_eq!(None, controller.poll(at(ms), 900_000.0, 900_000.0, true));
1375 }
1376 }
1377
1378 /// A controller with recovery probing and without the probes after a drop (so that every
1379 /// cluster seen is a recovery cluster), settled, at 2 Mbit/s until 1 s and dropped to
1380 /// 300 kbit/s at 1.1 s.
1381 fn dropped_with_recovery(epoch: Instant) -> ProbeController {
1382 let mut controller = settled(epoch)
1383 .with_probe_after_drop(false)
1384 .with_recovery_probing(true);
1385 let at = |ms: u64| epoch + Duration::from_millis(ms);
1386 assert_eq!(
1387 None,
1388 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1389 );
1390 assert_eq!(None, controller.poll(at(1_100), 300_000.0, 300_000.0, true));
1391 controller
1392 }
1393
1394 /// Recovery probing: after a large drop a sender at its target is asked for a cluster at
1395 /// twice the target every five seconds, from five seconds after the drop, for as long as
1396 /// the rate before the drop is remembered (a minute), and not after.
1397 #[test]
1398 fn recovery_probing_asks_twice_the_target_every_five_seconds_for_a_minute() {
1399 let epoch = Instant::now();
1400 let mut controller = dropped_with_recovery(epoch);
1401 let at = |ms: u64| epoch + Duration::from_millis(ms);
1402 let mut asked = Vec::new();
1403 for ms in (1_200..90_000).step_by(100) {
1404 if ms == 5_300 {
1405 assert_eq!(
1406 Some(at(6_100)),
1407 controller.poll_timeout(),
1408 "the first recovery cluster's instant is a deadline"
1409 );
1410 }
1411 if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1412 assert_eq!(600_000.0, request.bits_per_second, "at {ms} ms");
1413 asked.push(ms);
1414 // The path is still limited: the cluster shows less than the target.
1415 controller.on_result(request.cluster, 285_000.0);
1416 }
1417 }
1418 let expected: Vec<u64> = (0..12).map(|n| 6_100 + 5_000 * n).collect();
1419 assert_eq!(
1420 expected, asked,
1421 "every 5 s from 5 s after the drop, for 60 s"
1422 );
1423 }
1424
1425 /// The rate remembered for recovery probing is the path's: after a path change the
1426 /// start-up clusters look for the new path's rate, and when they show it to be narrow
1427 /// nothing goes on asking for the rate the old path had.
1428 #[test]
1429 fn recovery_probing_forgets_the_old_paths_rate_at_a_path_change() {
1430 let epoch = Instant::now();
1431 let mut controller = dropped_with_recovery(epoch);
1432 let at = |ms: u64| epoch + Duration::from_millis(ms);
1433 controller.on_path_change(at(2_000), 300_000.0);
1434 let mut asked = Vec::new();
1435 for ms in (2_000..30_000).step_by(100) {
1436 if let Some(request) = controller.poll(at(ms), 300_000.0, 300_000.0, true) {
1437 asked.push(request.bits_per_second);
1438 controller.on_result(request.cluster, 285_000.0);
1439 }
1440 }
1441 assert_eq!(
1442 vec![900_000.0, 1_800_000.0],
1443 asked,
1444 "the start-up clusters, and no recovery cluster for the old path's 2 Mbit/s"
1445 );
1446 }
1447
1448 /// Without the setting (the default) nothing is asked of a sender at its target once the
1449 /// probes after the drop have ended.
1450 #[test]
1451 fn without_recovery_probing_a_sender_at_its_target_is_not_probed_after_the_drop() {
1452 let epoch = Instant::now();
1453 let mut controller = settled(epoch).with_probe_after_drop(false);
1454 let at = |ms: u64| epoch + Duration::from_millis(ms);
1455 assert_eq!(
1456 None,
1457 controller.poll(at(1_000), 2_000_000.0, 2_000_000.0, true)
1458 );
1459 for ms in (1_100..30_000).step_by(100) {
1460 assert_eq!(
1461 None,
1462 controller.poll(at(ms), 300_000.0, 300_000.0, true),
1463 "at {ms} ms"
1464 );
1465 }
1466 }
1467
1468 /// A recovery cluster the path carries is followed by clusters at twice the result until
1469 /// one shows the bottleneck: the rate before the drop is back within a second.
1470 #[test]
1471 fn a_recovery_cluster_the_path_carries_is_followed_up() {
1472 let epoch = Instant::now();
1473 let mut controller = dropped_with_recovery(epoch);
1474 let at = |ms: u64| epoch + Duration::from_millis(ms);
1475 let mut target = 300_000.0;
1476 let mut asked = Vec::new();
1477 // The path carries 2.5 Mbit/s again.
1478 for ms in (1_200..8_000).step_by(100) {
1479 if let Some(request) = controller.poll(at(ms), target, target, true) {
1480 asked.push((ms, request.bits_per_second));
1481 let estimate = request.bits_per_second.min(2_500_000.0 * 0.95);
1482 target = controller
1483 .on_result(request.cluster, estimate)
1484 .expect("the outstanding cluster");
1485 }
1486 }
1487 assert_eq!(
1488 vec![
1489 (6_100, 600_000.0),
1490 (6_200, 1_200_000.0),
1491 (6_300, 2_400_000.0),
1492 (6_400, 4_750_000.0)
1493 ],
1494 asked
1495 );
1496 assert_eq!(2_375_000.0, target);
1497 }
1498
1499 /// No recovery cluster while the estimator reads over-use; the one that was due goes out
1500 /// when it no longer does.
1501 #[test]
1502 fn recovery_probing_waits_while_the_path_is_overused() {
1503 let epoch = Instant::now();
1504 let mut controller = dropped_with_recovery(epoch);
1505 let at = |ms: u64| epoch + Duration::from_millis(ms);
1506 controller.set_usage(Usage::Over);
1507 for ms in (1_200..9_000).step_by(100) {
1508 assert_eq!(
1509 None,
1510 controller.poll(at(ms), 300_000.0, 300_000.0, true),
1511 "at {ms} ms"
1512 );
1513 }
1514 controller.set_usage(Usage::Normal);
1515 let request = controller
1516 .poll(at(9_000), 300_000.0, 300_000.0, true)
1517 .expect("no over-use: the cluster that was due");
1518 assert_eq!(600_000.0, request.bits_per_second);
1519 }
1520
1521 /// The smaller drops under a limit (the controller's own sawtooth) do not replace the
1522 /// rate remembered from before it: a target above 85% of the sawtooth's peak is still
1523 /// probed, and one above 85% of the rate before the limit is not.
1524 #[test]
1525 fn recovery_probing_remembers_the_rate_before_the_limit_through_smaller_drops() {
1526 let epoch = Instant::now();
1527 let mut controller = dropped_with_recovery(epoch);
1528 let at = |ms: u64| epoch + Duration::from_millis(ms);
1529 // A sawtooth under the limit: up to 350 kbit/s, cut to 220 kbit/s (a large drop).
1530 assert_eq!(None, controller.poll(at(2_000), 350_000.0, 350_000.0, true));
1531 assert_eq!(None, controller.poll(at(2_100), 220_000.0, 220_000.0, true));
1532 // 400 kbit/s is above the sawtooth's peak and far below the 2 Mbit/s before the limit.
1533 let request = (2_200..8_000)
1534 .step_by(100)
1535 .find_map(|ms| controller.poll(at(ms), 400_000.0, 400_000.0, true))
1536 .expect("still below the remembered rate");
1537 assert_eq!(800_000.0, request.bits_per_second);
1538 controller.on_result(request.cluster, 380_000.0);
1539 // At 1.8 Mbit/s (over 85% of 2 Mbit/s) there is nothing left to recover.
1540 for ms in (8_000..20_000).step_by(100) {
1541 assert_eq!(
1542 None,
1543 controller.poll(at(ms), 1_800_000.0, 1_800_000.0, true),
1544 "at {ms} ms"
1545 );
1546 }
1547 }
1548
1549 /// A chain whose clusters leave as bursts is not probed for recovery, and names no
1550 /// deadline for it.
1551 #[test]
1552 fn recovery_probing_is_not_for_clusters_that_leave_as_bursts() {
1553 let epoch = Instant::now();
1554 let mut controller = dropped_with_recovery(epoch);
1555 controller.set_unpaced(true);
1556 let at = |ms: u64| epoch + Duration::from_millis(ms);
1557 for ms in (1_200..20_000).step_by(100) {
1558 assert_eq!(
1559 None,
1560 controller.poll(at(ms), 300_000.0, 300_000.0, true),
1561 "at {ms} ms"
1562 );
1563 // The one deadline left is the application-limited cluster's, five seconds after
1564 // the start-up sequence.
1565 assert!(
1566 controller
1567 .poll_timeout()
1568 .is_none_or(|next| next == at(5_150)),
1569 "a deadline for a cluster that will not be asked for, at {ms} ms"
1570 );
1571 }
1572 }
1573
1574 /// A deadline that came with nothing to send (here: an application-limited probe falls due
1575 /// while the sender has caught up with its target) is not asked for again: a driver that
1576 /// sleeps until `poll_timeout` would otherwise be woken at once, over and over.
1577 #[test]
1578 fn a_deadline_that_passed_with_nothing_due_is_not_asked_again() {
1579 let epoch = Instant::now();
1580 let mut controller = settled(epoch);
1581 let due = controller
1582 .poll_timeout()
1583 .expect("the next application-limited probe");
1584 assert_eq!(None, controller.poll(due, 1_000_000.0, 1_000_000.0, true));
1585 assert!(
1586 controller.poll_timeout().is_none_or(|next| next > due),
1587 "{:?}",
1588 controller.poll_timeout()
1589 );
1590 // Not flowing at all: nothing to wake for either.
1591 let later = due + Duration::from_secs(10);
1592 assert_eq!(None, controller.poll(later, 1_000_000.0, 0.0, false));
1593 assert!(controller.poll_timeout().is_none_or(|next| next > later));
1594 }
1595}