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