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