Skip to main content

moq_ext_adaptive/
bound.rs

1//! Rendition selection as a bound rather than a state machine.
2//!
3//! Each tick computes which renditions are allowed, and the best allowed one
4//! wins:
5//!
6//! - The publisher's delivery estimate caps the bitrate. A rung fits while the
7//!   estimate covers [`Adaptation::fit_ratio`] of its advertised bitrate.
8//! - Sustained loss lowers a ceiling one rung at a time, and emergency loss
9//!   drops it to the bottom. A clean stretch raises it one rung at a time.
10//! - The caller's [`Constraints`] exclude stalled and failed renditions.
11//! - When nothing fits, the smallest eligible rendition plays.
12//!
13//! Time enters only as hysteresis around that answer, through the hold and
14//! cooldown timers of [`Adaptation`].
15//!
16//! One ratio serves both directions. A publisher parked on a low rung has an
17//! estimate limited by what it sends, and it can still climb back.
18//!
19//! A change of network path resets everything learned on the old one.
20
21use std::{
22    cmp::Ordering,
23    collections::{BTreeMap, BTreeSet, VecDeque},
24    time::{Duration, Instant},
25};
26
27use tracing::debug;
28
29use crate::NetworkSample;
30
31/// One rendition, as the bound sees it.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Rung {
34    /// The rendition's track name.
35    pub name: String,
36    /// The advertised bitrate in bits per second, if the catalog gives one.
37    pub bitrate: Option<u64>,
38    /// Whether the publisher flagged the rendition to be avoided.
39    pub stalled: bool,
40}
41
42/// What the caller rules out, whatever the network says.
43#[derive(Debug, Clone, Default, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct Constraints {
46    /// Renditions whose decoders recently failed.
47    pub excluded: BTreeSet<String>,
48}
49
50impl Constraints {
51    /// Returns the constraints that rule out the renditions named in `excluded`.
52    #[must_use]
53    pub fn excluding(excluded: impl IntoIterator<Item = String>) -> Self {
54        Self {
55            excluded: excluded.into_iter().collect(),
56        }
57    }
58
59    /// Reports whether `rung` is neither stalled nor excluded.
60    #[must_use]
61    pub fn allows(&self, rung: &Rung) -> bool {
62        !rung.stalled && !self.excluded.contains(&rung.name)
63    }
64}
65
66/// The player's adaptation thresholds and timers.
67///
68/// The defaults are tuned together on real and simulated links.
69#[derive(Debug, Clone, Copy)]
70#[non_exhaustive]
71pub struct Adaptation {
72    /// The multiple of a rung's advertised bitrate the estimate has to cover.
73    ///
74    /// The estimate reads up to 1.6 times a capped link's rate, and encoders
75    /// send about 82% of what they advertise. At 1.25, a rung fits while the
76    /// estimate covers 1.5 times what it sends.
77    pub fit_ratio: f64,
78    /// How long the estimate is remembered, as a sliding maximum.
79    ///
80    /// The estimate refreshes ten times a second and moves with every
81    /// acknowledgement. A single low reading does not mean a smaller link, so
82    /// only a shortfall that lasts the whole window counts.
83    pub estimate_window: Duration,
84    /// Loss above which the ceiling steps down one rung.
85    ///
86    /// It has to hold for [`downgrade_hold`](Self::downgrade_hold) first.
87    pub loss_step_down: f64,
88    /// Loss above which the ceiling drops to the bottom rung at once.
89    pub loss_emergency: f64,
90    /// How long a lower target has to hold before the switch.
91    pub downgrade_hold: Duration,
92    /// How long a higher target has to hold before the switch.
93    ///
94    /// Loss also has to stay clear this long before the loss ceiling rises a
95    /// rung.
96    pub upgrade_hold: Duration,
97    /// How long after a step down no step up is taken.
98    pub post_downgrade_cooldown: Duration,
99    /// How long a rung has to play after a step up before the step counts as held.
100    ///
101    /// Each step down from a rung multiplies the hold before the next step up
102    /// to it by four, up to [`upgrade_hold_max`](Self::upgrade_hold_max). A
103    /// step up that plays this long clears the count. The estimate read on the
104    /// rung below says little about the rung above, so this lets a marginal
105    /// link settle on the rung it can carry.
106    pub trial: Duration,
107    /// The longest hold before a step up.
108    pub upgrade_hold_max: Duration,
109    /// How often the network is read while it can change the choice.
110    pub tick: Duration,
111}
112
113impl Default for Adaptation {
114    fn default() -> Self {
115        Self {
116            fit_ratio: 1.25,
117            estimate_window: Duration::from_secs(1),
118            loss_step_down: 0.10,
119            loss_emergency: 0.20,
120            downgrade_hold: Duration::from_millis(500),
121            upgrade_hold: Duration::from_secs(4),
122            post_downgrade_cooldown: Duration::from_secs(4),
123            trial: Duration::from_secs(20),
124            upgrade_hold_max: Duration::from_secs(120),
125            tick: Duration::from_millis(200),
126        }
127    }
128}
129
130/// The selection state carried from one tick to the next.
131#[derive(Debug, Default)]
132pub struct Bound {
133    adaptation: Adaptation,
134    /// The path the history below was gathered on.
135    path_generation: Option<u64>,
136    /// Recent estimates, oldest first, for the sliding maximum.
137    estimates: VecDeque<(Instant, u64)>,
138    /// The index of the best rung loss allows, or `None` when loss allows all.
139    loss_ceiling: Option<usize>,
140    /// When loss above the step-down threshold began, if it is above it.
141    lossy_since: Option<Instant>,
142    /// When loss last went clear, if it is clear.
143    clean_since: Option<Instant>,
144    /// Since when the target has been below the rung playing.
145    ///
146    /// Timed for any lower rung, so a target that wavers between two lower
147    /// rungs still reaches the hold.
148    lower_since: Option<Instant>,
149    /// Since when the target has been above the rung playing, likewise.
150    higher_since: Option<Instant>,
151    /// When the last step down landed, or was last seen still on its way.
152    ///
153    /// The cooldown runs from the landing. A switch needs a decoder and a
154    /// keyframe to land, which takes seconds on an impaired link. A cooldown
155    /// from the decision could end before the lower rung played.
156    last_downgrade: Option<Instant>,
157    /// Whether the last decision was a step down that has not landed yet.
158    downgrading: bool,
159    /// Whether a switch was on its way at the last decision.
160    in_flight: bool,
161    /// Failed tries at each rung, by name. See [`Adaptation::trial`].
162    failed_tries: BTreeMap<String, u32>,
163    /// The rung last stepped up to while its trial runs, and when it landed.
164    trial: Option<(String, Option<Instant>)>,
165}
166
167impl Bound {
168    /// Creates a bound with nothing learned yet.
169    #[must_use]
170    pub fn new(adaptation: Adaptation) -> Self {
171        Self {
172            adaptation,
173            ..Self::default()
174        }
175    }
176
177    /// Returns the hold before a step up to `rung`, lengthened by failed tries.
178    fn upgrade_hold(&self, rung: &str) -> Duration {
179        // Eight tries already put the hold far past any maximum. The cap keeps
180        // `4^tries` within `u32`.
181        let tries = self.failed_tries.get(rung).copied().unwrap_or(0).min(8);
182        self.adaptation
183            .upgrade_hold
184            .saturating_mul(4u32.pow(tries))
185            .min(self.adaptation.upgrade_hold_max)
186    }
187
188    /// Records the sample's estimate and returns the sliding maximum, if any.
189    fn estimate(&mut self, sample: &NetworkSample, now: Instant) -> Option<u64> {
190        if let Some(delivery) = sample.delivery {
191            self.estimates.push_back((now, delivery));
192        }
193        while let Some((at, _)) = self.estimates.front()
194            && now.duration_since(*at) > self.adaptation.estimate_window
195        {
196            self.estimates.pop_front();
197        }
198        self.estimates.iter().map(|(_, bps)| *bps).max()
199    }
200
201    /// Reports whether `loss` is at or above the emergency threshold.
202    fn is_emergency(&self, loss: Option<f64>) -> bool {
203        loss.is_some_and(|loss| loss >= self.adaptation.loss_emergency)
204    }
205
206    /// Drops the loss ceiling to `lowest`, the bottom eligible rung.
207    fn drop_to_bottom(&mut self, lowest: usize) {
208        self.loss_ceiling = Some(lowest);
209        self.lossy_since = None;
210        self.clean_since = None;
211    }
212
213    /// Moves the loss ceiling on this sample.
214    ///
215    /// `current` is the index of the rung playing, and `lowest` the index of
216    /// the bottom eligible rung.
217    fn follow_loss(&mut self, loss: f64, current: usize, lowest: usize, now: Instant) {
218        if self.is_emergency(Some(loss)) {
219            self.drop_to_bottom(lowest);
220            return;
221        }
222        if loss >= self.adaptation.loss_step_down {
223            self.clean_since = None;
224            let since = *self.lossy_since.get_or_insert(now);
225            if now.duration_since(since) >= self.adaptation.downgrade_hold {
226                let below = (current + 1).min(lowest);
227                self.loss_ceiling = Some(
228                    self.loss_ceiling
229                        .map_or(below, |ceiling| ceiling.max(below)),
230                );
231                // A lasting loss steps down one rung per hold.
232                self.lossy_since = Some(now);
233            }
234            return;
235        }
236        self.lossy_since = None;
237        let Some(ceiling) = self.loss_ceiling else {
238            self.clean_since = None;
239            return;
240        };
241        let since = *self.clean_since.get_or_insert(now);
242        if now.duration_since(since) >= self.adaptation.upgrade_hold {
243            // One rung at a time, and gone once it reaches the top.
244            self.loss_ceiling = ceiling.checked_sub(1);
245            self.clean_since = Some(now);
246        }
247    }
248
249    /// Picks the rendition to play.
250    ///
251    /// `rungs` is the catalog's video renditions, most expensive first: a
252    /// higher index must never cost more. `current` is the one last asked
253    /// for, on screen or on its way, and the hold timers weigh the target
254    /// against it. `on_screen` is the one playing. While the two
255    /// differ, a switch is in flight and loss is not followed: the loss then is
256    /// the old rendition's, and a step on it would stack onto the first.
257    ///
258    /// Returns `None` only when `rungs` is empty.
259    #[must_use]
260    pub fn decide(
261        &mut self,
262        rungs: &[Rung],
263        current: Option<&str>,
264        on_screen: Option<&str>,
265        constraints: &Constraints,
266        sample: &NetworkSample,
267        now: Instant,
268    ) -> Option<String> {
269        if self.path_generation != Some(sample.path_generation) {
270            if self.path_generation.is_some() {
271                debug!(
272                    generation = sample.path_generation,
273                    "the network path changed, forgetting what the old one taught",
274                );
275            }
276            *self = Self {
277                path_generation: Some(sample.path_generation),
278                ..Self::new(self.adaptation)
279            };
280        }
281
282        let eligible: Vec<usize> = rungs
283            .iter()
284            .enumerate()
285            .filter(|(_, rung)| constraints.allows(rung))
286            .map(|(index, _)| index)
287            .collect();
288        // With every rung ruled out, the smallest still plays.
289        let Some(&lowest) = eligible.last() else {
290            return rungs.last().map(|rung| rung.name.clone());
291        };
292
293        let current_index = current.and_then(|name| rungs.iter().position(|r| r.name == name));
294        let estimate = self.estimate(sample, now);
295        let in_flight = current.is_some() && current != on_screen;
296        if in_flight {
297            if self.downgrading {
298                self.last_downgrade = Some(now);
299            }
300            // An emergency still drops to the bottom at once, overriding the
301            // switch on its way.
302            if self.is_emergency(sample.loss) {
303                self.drop_to_bottom(lowest);
304            }
305        } else {
306            if std::mem::take(&mut self.in_flight) {
307                // Landed. Loss from here on is the new rendition's, and a
308                // lasting loss steps again one hold from now.
309                self.downgrading = false;
310                if self.lossy_since.is_some() {
311                    self.lossy_since = Some(now);
312                }
313            }
314            if let Some(loss) = sample.loss {
315                self.follow_loss(loss, current_index.unwrap_or(0), lowest, now);
316            }
317            // A step up that landed starts its trial, and one that played
318            // through it clears the rung's failed tries.
319            if let Some((rung, landed)) = &mut self.trial {
320                match landed {
321                    None if on_screen == Some(rung.as_str()) => *landed = Some(now),
322                    Some(at) if now.duration_since(*at) >= self.adaptation.trial => {
323                        self.failed_tries.remove(rung.as_str());
324                        self.trial = None;
325                    }
326                    _ => {}
327                }
328            }
329        }
330        self.in_flight = in_flight;
331
332        let fits = |rung: &Rung| match (estimate, rung.bitrate) {
333            (Some(estimate), Some(bitrate)) => {
334                bitrate as f64 * self.adaptation.fit_ratio <= estimate as f64
335            }
336            _ => true,
337        };
338        let target_index = eligible
339            .iter()
340            .copied()
341            .filter(|&index| self.loss_ceiling.is_none_or(|ceiling| index >= ceiling))
342            .find(|&index| fits(&rungs[index]))
343            .unwrap_or(lowest);
344        let target = &rungs[target_index].name;
345
346        // A rendition that is gone or no longer allowed is left at once.
347        let Some(current_index) = current_index.filter(|index| eligible.contains(index)) else {
348            self.lower_since = None;
349            self.higher_since = None;
350            return Some(target.clone());
351        };
352
353        match target_index.cmp(&current_index) {
354            Ordering::Equal => {
355                self.lower_since = None;
356                self.higher_since = None;
357                Some(rungs[current_index].name.clone())
358            }
359            Ordering::Greater => {
360                self.higher_since = None;
361                let emergency = self.is_emergency(sample.loss);
362                let since = *self.lower_since.get_or_insert(now);
363                if emergency || now.duration_since(since) >= self.adaptation.downgrade_hold {
364                    self.lower_since = None;
365                    self.last_downgrade = Some(now);
366                    self.downgrading = true;
367                    // The rung stepped down from counts as a failed try, and its
368                    // trial ends.
369                    let rung = rungs[current_index].name.clone();
370                    if self.trial.as_ref().is_some_and(|(trial, _)| *trial == rung) {
371                        self.trial = None;
372                    }
373                    let tries = self.failed_tries.entry(rung).or_default();
374                    *tries += 1;
375                    debug!(
376                        rung = %rungs[current_index].name,
377                        tries = *tries,
378                        "stepped down, so the next step up to this rung waits longer"
379                    );
380                    return Some(target.clone());
381                }
382                Some(rungs[current_index].name.clone())
383            }
384            Ordering::Less => {
385                self.lower_since = None;
386                let cooling = self.last_downgrade.is_some_and(|at| {
387                    now.duration_since(at) < self.adaptation.post_downgrade_cooldown
388                });
389                let since = *self.higher_since.get_or_insert(now);
390                if !cooling && now.duration_since(since) >= self.upgrade_hold(target) {
391                    self.higher_since = None;
392                    self.trial = Some((target.clone(), None));
393                    return Some(target.clone());
394                }
395                Some(rungs[current_index].name.clone())
396            }
397        }
398    }
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    fn rung(name: &str, bitrate: u64) -> Rung {
406        Rung {
407            name: name.into(),
408            bitrate: Some(bitrate),
409            stalled: false,
410        }
411    }
412
413    fn ladder() -> Vec<Rung> {
414        vec![
415            rung("1080p", 4_000_000),
416            rung("720p", 2_000_000),
417            rung("360p", 500_000),
418        ]
419    }
420
421    fn estimate(bps: u64) -> NetworkSample {
422        NetworkSample {
423            loss: Some(0.0),
424            delivery: Some(bps),
425            ..NetworkSample::default()
426        }
427    }
428
429    fn loss(loss: f64) -> NetworkSample {
430        NetworkSample {
431            loss: Some(loss),
432            ..NetworkSample::default()
433        }
434    }
435
436    /// Decides once over `ranked` with no constraints.
437    fn step(
438        bound: &mut Bound,
439        ranked: &[Rung],
440        current: &str,
441        on_screen: &str,
442        reading: &NetworkSample,
443        now: Instant,
444    ) -> String {
445        bound
446            .decide(
447                ranked,
448                Some(current),
449                Some(on_screen),
450                &Constraints::default(),
451                reading,
452                now,
453            )
454            .expect("the ladder is not empty")
455    }
456
457    /// Decides once over the ladder from nothing, under `constraints`.
458    fn first(
459        bound: &mut Bound,
460        constraints: &Constraints,
461        reading: &NetworkSample,
462    ) -> Option<String> {
463        bound.decide(&ladder(), None, None, constraints, reading, Instant::now())
464    }
465
466    /// Runs `reading` every 100ms for `span`, feeding each decision back.
467    ///
468    /// Returns the rendition playing at the end, and the time.
469    fn run(
470        bound: &mut Bound,
471        current: &str,
472        reading: NetworkSample,
473        start: Instant,
474        span: Duration,
475    ) -> (String, Instant) {
476        let ranked = ladder();
477        let mut now = start;
478        let mut playing = current.to_string();
479        while now < start + span {
480            playing = step(bound, &ranked, &playing, &playing, &reading, now);
481            now += ms(100);
482        }
483        (playing, now)
484    }
485
486    #[test]
487    fn the_best_fitting_rung_is_chosen_from_nothing() {
488        let mut bound = Bound::default();
489        let chosen = first(&mut bound, &Constraints::default(), &estimate(3_000_000));
490        assert_eq!(chosen.as_deref(), Some("720p"));
491    }
492
493    #[test]
494    fn a_shortfall_steps_down_after_the_hold() {
495        let mut bound = Bound::default();
496        let start = Instant::now();
497        // Covers the fit ratio of 720p but not of 1080p.
498        let (playing, _) = run(&mut bound, "1080p", estimate(3_750_000), start, ms(400));
499        assert_eq!(playing, "1080p", "held for less than the downgrade hold");
500        let (playing, _) = run(&mut bound, "1080p", estimate(3_750_000), start, ms(700));
501        assert_eq!(playing, "720p");
502    }
503
504    /// An estimate that wanders just above the top rung's fit threshold steps up.
505    #[test]
506    fn an_application_limited_estimate_still_climbs_back() {
507        let ranked = vec![rung("high", 800_000), rung("low", 200_000)];
508        let mut bound = Bound::default();
509        let mut playing = "low".to_string();
510        let mut now = Instant::now();
511        // Readings just above the top rung's fit threshold of 1 Mbit/s.
512        let readings = [1_010_000, 1_075_000, 1_190_000, 1_020_000, 1_125_000];
513        for tick in 0..60 {
514            let reading = estimate(readings[tick % readings.len()]);
515            playing = step(&mut bound, &ranked, &playing, &playing, &reading, now);
516            now += ms(100);
517        }
518        assert_eq!(playing, "high");
519    }
520
521    #[test]
522    fn a_step_up_waits_out_the_upgrade_hold() {
523        let mut bound = Bound::default();
524        let start = Instant::now();
525        let (playing, _) = run(&mut bound, "360p", estimate(10_000_000), start, ms(3900));
526        assert_eq!(playing, "360p");
527        let (playing, _) = run(&mut bound, "360p", estimate(10_000_000), start, ms(4200));
528        assert_eq!(
529            playing, "1080p",
530            "the best fitting rung wins, not the next one"
531        );
532    }
533
534    #[test]
535    fn no_step_up_inside_the_cooldown_after_a_step_down() {
536        let mut bound = Bound::new(Adaptation {
537            post_downgrade_cooldown: Duration::from_secs(10),
538            ..Adaptation::default()
539        });
540        let start = Instant::now();
541        let (playing, now) = run(&mut bound, "1080p", estimate(3_750_000), start, ms(1000));
542        assert_eq!(playing, "720p");
543        let (playing, _) = run(&mut bound, &playing, estimate(10_000_000), now, ms(6000));
544        assert_eq!(playing, "720p", "inside the cooldown");
545    }
546
547    #[test]
548    fn a_single_low_reading_inside_the_window_is_not_a_shortfall() {
549        let mut bound = Bound::default();
550        let ranked = ladder();
551        let start = Instant::now();
552        let mut playing = "1080p".to_string();
553        for tick in 0..30u32 {
554            // Nine readings that fit, then one that does not.
555            let bps = match tick % 10 {
556                9 => 1_250_000,
557                _ => 7_500_000,
558            };
559            let now = start + ms(100) * tick;
560            playing = step(&mut bound, &ranked, &playing, &playing, &estimate(bps), now);
561        }
562        assert_eq!(playing, "1080p");
563    }
564
565    #[test]
566    fn emergency_loss_drops_to_the_bottom_at_once() {
567        let mut bound = Bound::default();
568        let chosen = step(
569            &mut bound,
570            &ladder(),
571            "1080p",
572            "1080p",
573            &loss(0.25),
574            Instant::now(),
575        );
576        assert_eq!(chosen, "360p");
577    }
578
579    #[test]
580    fn sustained_loss_steps_down_one_rung_per_hold_and_recovers() {
581        let mut bound = Bound::default();
582        let start = Instant::now();
583        let (playing, now) = run(&mut bound, "1080p", loss(0.12), start, ms(1100));
584        assert_eq!(playing, "720p");
585        let (playing, now) = run(&mut bound, &playing, loss(0.12), now, ms(1200));
586        assert_eq!(playing, "360p");
587
588        // Each rung stepped down from waits four times the usual hold before
589        // it is tried again, so the climb back takes two of those.
590        let (playing, _) = run(&mut bound, &playing, loss(0.0), now, ms(45_000));
591        assert_eq!(playing, "1080p", "clean loss lifts the ceiling again");
592    }
593
594    /// Without an estimate, only loss holds a rendition back.
595    #[test]
596    fn no_estimate_leaves_only_loss() {
597        let mut bound = Bound::default();
598        let (playing, _) = run(&mut bound, "1080p", loss(0.0), Instant::now(), ms(10_000));
599        assert_eq!(playing, "1080p");
600    }
601
602    /// A rendition ruled out while it plays is left at once, without a hold.
603    #[test]
604    fn an_excluded_rendition_is_left_at_once() {
605        let constraints = Constraints {
606            excluded: BTreeSet::from(["1080p".to_string()]),
607        };
608        let chosen = Bound::default().decide(
609            &ladder(),
610            Some("1080p"),
611            Some("1080p"),
612            &constraints,
613            &estimate(100_000_000),
614            Instant::now(),
615        );
616        assert_eq!(chosen.as_deref(), Some("720p"));
617    }
618
619    #[test]
620    fn a_stalled_rendition_is_avoided() {
621        let mut ranked = ladder();
622        ranked[0].stalled = true;
623        let chosen = Bound::default().decide(
624            &ranked,
625            None,
626            None,
627            &Constraints::default(),
628            &estimate(100_000_000),
629            Instant::now(),
630        );
631        assert_eq!(chosen.as_deref(), Some("720p"));
632    }
633
634    #[test]
635    fn with_everything_ruled_out_the_smallest_still_plays() {
636        let constraints = Constraints {
637            excluded: ladder().into_iter().map(|rung| rung.name).collect(),
638        };
639        let chosen = first(&mut Bound::default(), &constraints, &estimate(100_000_000));
640        assert_eq!(chosen.as_deref(), Some("360p"));
641    }
642
643    /// A new path drops the old path's estimates from the sliding maximum.
644    #[test]
645    fn a_new_path_forgets_the_old_one() {
646        let mut bound = Bound::default();
647        let start = Instant::now();
648        // Plenty on path 0.
649        let (playing, now) = run(&mut bound, "1080p", estimate(100_000_000), start, ms(2000));
650        assert_eq!(playing, "1080p");
651        // The path changes, and the new one only just carries 720p: the
652        // downgrade is due after one hold, not after the old maximum ages.
653        let fresh = NetworkSample {
654            path_generation: 1,
655            ..estimate(2_500_000)
656        };
657        let (playing, _) = run(&mut bound, "1080p", fresh, now, ms(600));
658        assert_eq!(playing, "720p", "the old path's estimate held the top rung");
659    }
660
661    /// A shortfall whose target wavers between two lower rungs steps down after one hold.
662    #[test]
663    fn a_wavering_lower_target_still_steps_down() {
664        // Each reading stands alone, so the sliding maximum does not smooth
665        // the waver away before the hold sees it.
666        let mut bound = Bound::new(Adaptation {
667            estimate_window: ms(1),
668            ..Adaptation::default()
669        });
670        let ranked = ladder();
671        let start = Instant::now();
672        let mut playing = "1080p".to_string();
673        for tick in 0..8u32 {
674            // Alternately fits 720p and only 360p: 3 and 1.5 Mbit/s.
675            let bps = if tick % 2 == 0 { 3_000_000 } else { 1_500_000 };
676            let now = start + ms(100) * tick;
677            playing = step(&mut bound, &ranked, &playing, &playing, &estimate(bps), now);
678        }
679        assert_ne!(playing, "1080p", "the hold restarted with every waver");
680    }
681
682    /// Sustained loss does not stack a second step while a switch is in flight.
683    ///
684    /// The next step comes one hold after the landing.
685    #[test]
686    fn loss_does_not_stack_steps_while_a_switch_is_in_flight() {
687        let mut bound = Bound::default();
688        let ranked = ladder();
689        let lossy = loss(0.12);
690        let start = Instant::now();
691        let mut asked = "1080p".to_string();
692        let mut now = start;
693        // The loss holds. The first step's replacement takes three seconds to
694        // land, and 1080p stays on screen meanwhile.
695        while now < start + ms(3500) {
696            asked = step(&mut bound, &ranked, &asked, "1080p", &lossy, now);
697            now += ms(100);
698        }
699        assert_eq!(asked, "720p", "a second step was stacked on the first");
700        // It lands, the loss goes on, and the next step comes after a hold.
701        let landed = now;
702        while now < landed + ms(400) {
703            asked = step(&mut bound, &ranked, &asked, "720p", &lossy, now);
704            now += ms(100);
705        }
706        assert_eq!(asked, "720p", "stepped again before a hold on the new rung");
707        while now < landed + ms(1200) {
708            asked = step(&mut bound, &ranked, &asked, "720p", &lossy, now);
709            now += ms(100);
710        }
711        assert_eq!(asked, "360p");
712    }
713
714    /// The cooldown after a step down runs from the landing.
715    #[test]
716    fn the_cooldown_runs_from_the_landing() {
717        let tuning = Adaptation::default();
718        let mut bound = Bound::new(tuning);
719        let ranked = ladder();
720        let mut asked = "1080p".to_string();
721        let mut now = Instant::now();
722        // A shortfall steps down after the hold.
723        while asked == "1080p" {
724            asked = step(
725                &mut bound,
726                &ranked,
727                &asked,
728                "1080p",
729                &estimate(3_750_000),
730                now,
731            );
732            now += ms(100);
733        }
734        assert_eq!(asked, "720p");
735        // The link recovers at once, but the switch takes five seconds to land.
736        let decided = now;
737        while now < decided + ms(5000) {
738            asked = step(
739                &mut bound,
740                &ranked,
741                &asked,
742                "1080p",
743                &estimate(100_000_000),
744                now,
745            );
746            now += ms(100);
747        }
748        assert_eq!(asked, "720p", "stepped back up before the step down landed");
749        let landed = now;
750        while now < landed + tuning.post_downgrade_cooldown - ms(200) {
751            asked = step(
752                &mut bound,
753                &ranked,
754                &asked,
755                "720p",
756                &estimate(100_000_000),
757                now,
758            );
759            now += ms(100);
760        }
761        assert_eq!(
762            asked, "720p",
763            "stepped up inside the cooldown after the landing"
764        );
765        // The step down counts against 1080p, so its next try waits longer
766        // than the usual hold.
767        let hold = bound.upgrade_hold("1080p");
768        assert!(hold > tuning.upgrade_hold);
769        while now < landed + tuning.post_downgrade_cooldown.max(hold) + ms(500) {
770            asked = step(
771                &mut bound,
772                &ranked,
773                &asked,
774                "720p",
775                &estimate(100_000_000),
776                now,
777            );
778            now += ms(100);
779        }
780        assert_eq!(asked, "1080p", "never came back up");
781    }
782
783    /// Each step down from a rung multiplies the hold before the next try at it.
784    ///
785    /// The link carries 720p but not 1080p, and the estimate read on 720p says
786    /// 1080p fits.
787    #[test]
788    fn failed_steps_up_back_off() {
789        let mut bound = Bound::default();
790        let ranked = ladder();
791        let start = Instant::now();
792        let mut playing = "720p".to_string();
793        let mut now = start;
794        let mut ups = Vec::new();
795        // Plenty is read while 720p plays. Once 1080p plays, the reading is short.
796        while now < start + Duration::from_secs(200) {
797            let reading = match playing.as_str() {
798                "1080p" => estimate(3_000_000),
799                _ => estimate(100_000_000),
800            };
801            let next = step(&mut bound, &ranked, &playing, &playing, &reading, now);
802            if next == "1080p" && playing != "1080p" {
803                ups.push(now.duration_since(start));
804            }
805            playing = next;
806            now += ms(100);
807        }
808        let gaps: Vec<Duration> = ups.windows(2).map(|pair| pair[1] - pair[0]).collect();
809        assert!(ups.len() >= 3, "tried {} times: {ups:?}", ups.len());
810        assert!(
811            gaps.windows(2).all(|pair| pair[1] > pair[0] * 3),
812            "the tries did not back off: {ups:?}"
813        );
814        assert!(
815            ups.len() <= 5,
816            "tried {} times in 200 s: {ups:?}",
817            ups.len()
818        );
819    }
820
821    /// A rung that holds through its trial gets the usual hold back.
822    #[test]
823    fn a_step_up_that_held_clears_its_failures() {
824        let mut bound = Bound::default();
825        bound.failed_tries.insert("1080p".into(), 3);
826        bound.trial = Some(("1080p".into(), None));
827        run(
828            &mut bound,
829            "1080p",
830            estimate(100_000_000),
831            Instant::now(),
832            ms(25_000),
833        );
834        assert!(bound.failed_tries.is_empty(), "{:?}", bound.failed_tries);
835        assert_eq!(
836            bound.upgrade_hold("1080p"),
837            Adaptation::default().upgrade_hold
838        );
839    }
840
841    /// The loss ceiling is part of what a path taught: it goes with it.
842    #[test]
843    fn a_new_path_lifts_the_loss_ceiling() {
844        let mut bound = Bound::default();
845        step(
846            &mut bound,
847            &ladder(),
848            "1080p",
849            "1080p",
850            &loss(0.25),
851            Instant::now(),
852        );
853        assert!(bound.loss_ceiling.is_some());
854        let fresh = NetworkSample {
855            path_generation: 1,
856            ..loss(0.0)
857        };
858        let chosen = first(&mut bound, &Constraints::default(), &fresh);
859        assert_eq!(chosen.as_deref(), Some("1080p"));
860    }
861
862    fn ms(millis: u64) -> Duration {
863        Duration::from_millis(millis)
864    }
865}