1use std::{
22 cmp::Ordering,
23 collections::{BTreeMap, BTreeSet, VecDeque},
24 time::{Duration, Instant},
25};
26
27use tracing::debug;
28
29use crate::NetworkSample;
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct Rung {
34 pub name: String,
36 pub bitrate: Option<u64>,
38 pub stalled: bool,
40}
41
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct Constraints {
46 pub excluded: BTreeSet<String>,
48}
49
50impl Constraints {
51 #[must_use]
53 pub fn excluding(excluded: impl IntoIterator<Item = String>) -> Self {
54 Self {
55 excluded: excluded.into_iter().collect(),
56 }
57 }
58
59 #[must_use]
61 pub fn allows(&self, rung: &Rung) -> bool {
62 !rung.stalled && !self.excluded.contains(&rung.name)
63 }
64}
65
66#[derive(Debug, Clone, Copy)]
70#[non_exhaustive]
71pub struct Adaptation {
72 pub fit_ratio: f64,
78 pub estimate_window: Duration,
84 pub loss_step_down: f64,
88 pub loss_emergency: f64,
90 pub downgrade_hold: Duration,
92 pub upgrade_hold: Duration,
97 pub post_downgrade_cooldown: Duration,
99 pub trial: Duration,
107 pub upgrade_hold_max: Duration,
109 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#[derive(Debug, Default)]
132pub struct Bound {
133 adaptation: Adaptation,
134 path_generation: Option<u64>,
136 estimates: VecDeque<(Instant, u64)>,
138 loss_ceiling: Option<usize>,
140 lossy_since: Option<Instant>,
142 clean_since: Option<Instant>,
144 lower_since: Option<Instant>,
149 higher_since: Option<Instant>,
151 last_downgrade: Option<Instant>,
157 downgrading: bool,
159 in_flight: bool,
161 failed_tries: BTreeMap<String, u32>,
163 trial: Option<(String, Option<Instant>)>,
165}
166
167impl Bound {
168 #[must_use]
170 pub fn new(adaptation: Adaptation) -> Self {
171 Self {
172 adaptation,
173 ..Self::default()
174 }
175 }
176
177 fn upgrade_hold(&self, rung: &str) -> Duration {
179 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 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 fn is_emergency(&self, loss: Option<f64>) -> bool {
203 loss.is_some_and(|loss| loss >= self.adaptation.loss_emergency)
204 }
205
206 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 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 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 self.loss_ceiling = ceiling.checked_sub(1);
245 self.clean_since = Some(now);
246 }
247 }
248
249 #[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 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 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 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 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 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(¤t_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 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 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 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 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 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 #[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 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 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 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 #[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 #[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 #[test]
645 fn a_new_path_forgets_the_old_one() {
646 let mut bound = Bound::default();
647 let start = Instant::now();
648 let (playing, now) = run(&mut bound, "1080p", estimate(100_000_000), start, ms(2000));
650 assert_eq!(playing, "1080p");
651 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 #[test]
663 fn a_wavering_lower_target_still_steps_down() {
664 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 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 #[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 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 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 #[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 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 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 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 #[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 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 #[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 #[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}