Skip to main content

moq_ext_adaptive/
switch.rs

1//! The decode supervisor's state machine.
2//!
3//! It tracks one incumbent and at most one replacement. A rendition switch or a
4//! decoder change opens a replacement decoder beside the one playing, and hands
5//! the picture over once the replacement has caught up. The transitions work on
6//! plain data, so a test can drive them step by step without real decoders or
7//! a clock.
8//!
9//! The rules:
10//!
11//! - There is at most one replacement. A new request supersedes it whole, open
12//!   task and warm decoder alike, so a switch to C while B is warming never
13//!   lands on B first.
14//! - A replacement has a target, a generation, and a deadline from its request
15//!   until it takes over. The deadline covers both the open and the first
16//!   picture.
17//! - A replacement takes over once its playhead is within [`CATCH_UP_SLACK`] of
18//!   the incumbent's, so the picture does not step backwards, or at the latest
19//!   [`CATCH_UP_PATIENCE`] after its first picture.
20//! - A replacement takes over on a picture it decoded, never on opening alone.
21//!   A decoder that opens and stays silent runs out its deadline. With nothing
22//!   playing, including after the incumbent ended, its first picture is enough.
23//! - A replacement that is given up is reported as given up, even with nothing
24//!   playing, so the caller can tell a failed first open from the end of the
25//!   video.
26
27use std::time::{Duration, Instant};
28
29use tracing::info;
30
31/// How far a replacement may trail the incumbent's playhead when it takes over.
32///
33/// The same slack `@moq/watch` uses. It absorbs scheduling noise, and it is the
34/// largest step backwards a switch can show.
35pub const CATCH_UP_SLACK: Duration = Duration::from_millis(100);
36
37/// How long a replacement waits to catch up after its first picture.
38///
39/// That is enough on a link with room, where a replacement catches up within a
40/// group. It is short against the switch deadline because on a saturated link
41/// the two tracks starve each other while they overlap.
42pub const CATCH_UP_PATIENCE: Duration = Duration::from_secs(1);
43
44/// What a decoder is built for: a rendition, under one decoder configuration.
45///
46/// The configuration is a generation number. A decoder change for the playing
47/// rendition is then a different target, while asking for the playing
48/// rendition again is not.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct Target {
51    /// The rendition's track name.
52    pub rendition: String,
53    /// The decoder settings generation, bumped on every change.
54    pub config: u64,
55}
56
57impl Target {
58    /// Creates a target for `rendition` under decoder configuration `config`.
59    #[must_use]
60    pub fn new(rendition: impl Into<String>, config: u64) -> Self {
61        Self {
62            rendition: rendition.into(),
63            config,
64        }
65    }
66}
67
68/// Why a replacement did not take over.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum Abandoned<E> {
71    /// A newer request replaced it before it took over.
72    Superseded,
73    /// The request was withdrawn: the rendition asked for is the one playing.
74    Withdrawn,
75    /// Its decoder did not open.
76    OpenFailed(E),
77    /// Its track ended before it produced a picture it could take over with.
78    Ended,
79    /// It did not take over within the deadline.
80    TimedOut,
81}
82
83/// What a transition did, for the caller to act on.
84///
85/// Dropping one unread loses a promotion or an abandoned switch the caller
86/// has to report.
87#[derive(Debug, PartialEq, Eq)]
88#[must_use]
89pub enum Outcome<E> {
90    /// Nothing the caller has to act on.
91    Idle,
92    /// A replacement took over, and the caller reports it as playing.
93    Promoted(Target),
94    /// A replacement was given up, and why.
95    Abandoned(Target, Abandoned<E>),
96    /// The incumbent ended with nothing on its way: the video has ended.
97    Ended,
98}
99
100/// What to do with a picture the replacement decoded.
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102pub enum Verdict {
103    /// Drop it: no replacement is warming, or it is still behind the playhead.
104    Discard,
105    /// Show it: the replacement has just taken over.
106    Promote,
107}
108
109/// A replacement's progress.
110#[derive(Debug)]
111enum Phase<R, O> {
112    /// Its decoder is opening, in the task `O`.
113    Opening(O),
114    /// Its decoder is open and decoding, but has not caught up yet.
115    Warming(R),
116}
117
118/// The decoder waiting to take over.
119#[derive(Debug)]
120struct Replacement<R, O> {
121    generation: u64,
122    target: Target,
123    deadline: Instant,
124    phase: Phase<R, O>,
125    /// When its first picture arrived, the start of its catch-up patience.
126    first_picture: Option<Instant>,
127}
128
129/// The decoder whose pictures are on screen.
130#[derive(Debug)]
131struct Playing<R> {
132    target: Target,
133    reader: R,
134    /// The presentation time of the last picture shown.
135    playhead: Option<Duration>,
136}
137
138/// One incumbent and at most one replacement.
139///
140/// `R` is a running decoder and `O` the task opening one, so tests can use
141/// stand-ins for both. Dropping a replacement drops its `O` and `R`, which
142/// cancels its work.
143#[derive(Debug)]
144pub struct Switcher<R, O> {
145    incumbent: Option<Playing<R>>,
146    replacement: Option<Replacement<R, O>>,
147    generations: u64,
148    patience: Duration,
149}
150
151impl<R, O> Switcher<R, O> {
152    /// Creates a switcher with nothing playing.
153    ///
154    /// `patience` is how long a replacement may take, from its request to
155    /// taking over, before it is given up.
156    #[must_use]
157    pub fn new(patience: Duration) -> Self {
158        Self {
159            incumbent: None,
160            replacement: None,
161            generations: 0,
162            patience,
163        }
164    }
165
166    /// Returns the target playing, if any.
167    #[must_use]
168    pub fn current(&self) -> Option<&Target> {
169        self.incumbent.as_ref().map(|playing| &playing.target)
170    }
171
172    /// Returns the target on its way in, if any.
173    #[must_use]
174    pub fn switching_to(&self) -> Option<&Target> {
175        self.replacement
176            .as_ref()
177            .map(|replacement| &replacement.target)
178    }
179
180    /// Returns the moment the replacement is given up, if there is one.
181    #[must_use]
182    pub fn deadline(&self) -> Option<Instant> {
183        self.replacement
184            .as_ref()
185            .map(|replacement| replacement.deadline)
186    }
187
188    /// Returns the generation of the replacement, if there is one.
189    #[must_use]
190    pub fn replacement_generation(&self) -> Option<u64> {
191        self.replacement
192            .as_ref()
193            .map(|replacement| replacement.generation)
194    }
195
196    /// Returns the running incumbent decoder.
197    #[must_use]
198    pub fn incumbent_mut(&mut self) -> Option<&mut R> {
199        self.incumbent.as_mut().map(|playing| &mut playing.reader)
200    }
201
202    /// Returns the open task of a replacement that is still opening.
203    #[must_use]
204    pub fn opening_mut(&mut self) -> Option<&mut O> {
205        match &mut self.replacement {
206            Some(Replacement {
207                phase: Phase::Opening(task),
208                ..
209            }) => Some(task),
210            _ => None,
211        }
212    }
213
214    /// Returns the decoder of a replacement that has opened.
215    #[must_use]
216    pub fn warming_mut(&mut self) -> Option<&mut R> {
217        match &mut self.replacement {
218            Some(Replacement {
219                phase: Phase::Warming(reader),
220                ..
221            }) => Some(reader),
222            _ => None,
223        }
224    }
225
226    /// Reports whether nothing is playing and nothing is on its way.
227    #[cfg(test)]
228    pub fn is_idle(&self) -> bool {
229        self.incumbent.is_none() && self.replacement.is_none()
230    }
231
232    /// Asks for `target`, starting at `now`.
233    ///
234    /// Asking for the playing target withdraws the replacement. Asking for the
235    /// replacement's target changes nothing. Anything else starts a new
236    /// replacement and supersedes the previous one. `open` gets the new
237    /// generation and target, and builds the task that opens the decoder.
238    ///
239    /// Returns the replacement this request withdrew or superseded, if any.
240    pub fn request<E>(
241        &mut self,
242        target: Target,
243        now: Instant,
244        open: impl FnOnce(u64, &Target) -> O,
245    ) -> Outcome<E> {
246        if self.current() == Some(&target) {
247            return match self.replacement.take() {
248                Some(replacement) => Outcome::Abandoned(replacement.target, Abandoned::Withdrawn),
249                None => Outcome::Idle,
250            };
251        }
252        if self.switching_to() == Some(&target) {
253            return Outcome::Idle;
254        }
255        self.generations += 1;
256        let generation = self.generations;
257        let task = open(generation, &target);
258        let previous = self.replacement.replace(Replacement {
259            generation,
260            target,
261            deadline: now + self.patience,
262            phase: Phase::Opening(task),
263            first_picture: None,
264        });
265        match previous {
266            Some(previous) => Outcome::Abandoned(previous.target, Abandoned::Superseded),
267            None => Outcome::Idle,
268        }
269    }
270
271    /// Records that the replacement of `generation` finished opening.
272    pub fn opened<E>(&mut self, generation: u64, result: Result<R, E>) -> Outcome<E> {
273        let Some(replacement) = self
274            .replacement
275            .as_mut()
276            .filter(|replacement| replacement.generation == generation)
277        else {
278            // A superseded open that finished anyway. Dropping its decoder is
279            // enough.
280            return Outcome::Idle;
281        };
282        match result {
283            Ok(reader) => {
284                replacement.phase = Phase::Warming(reader);
285                Outcome::Idle
286            }
287            Err(err) => {
288                let target = self.replacement.take().expect("matched above").target;
289                Outcome::Abandoned(target, Abandoned::OpenFailed(err))
290            }
291        }
292    }
293
294    /// Records that the incumbent decoded a picture at `pts`.
295    pub fn incumbent_frame(&mut self, pts: Duration) {
296        if let Some(playing) = &mut self.incumbent {
297            playing.playhead = Some(pts);
298        }
299    }
300
301    /// Decides what to do with a replacement picture at `pts`, arriving at `now`.
302    ///
303    /// Promotes the replacement once `pts` has caught up with the incumbent's
304    /// playhead, or once [`CATCH_UP_PATIENCE`] has passed since its first
305    /// picture. The caller then shows this picture and drops any pending
306    /// incumbent picture.
307    pub fn replacement_frame<E>(&mut self, pts: Duration, now: Instant) -> (Verdict, Outcome<E>) {
308        let Some(replacement) = &mut self.replacement else {
309            return (Verdict::Discard, Outcome::Idle);
310        };
311        if !matches!(replacement.phase, Phase::Warming(_)) {
312            return (Verdict::Discard, Outcome::Idle);
313        }
314        let first = *replacement.first_picture.get_or_insert(now);
315        let caught_up = match self.incumbent.as_ref().and_then(|playing| playing.playhead) {
316            Some(playhead) => pts + CATCH_UP_SLACK >= playhead,
317            None => true,
318        };
319        if !caught_up {
320            if now.duration_since(first) < CATCH_UP_PATIENCE {
321                return (Verdict::Discard, Outcome::Idle);
322            }
323            let behind = self
324                .incumbent
325                .as_ref()
326                .and_then(|playing| playing.playhead)
327                .map(|playhead| playhead.saturating_sub(pts));
328            info!(
329                rendition = %replacement.target.rendition,
330                ?behind,
331                "replacement did not catch up in time, taking over where it is"
332            );
333        }
334        let outcome = self.promote();
335        if let Some(playing) = &mut self.incumbent {
336            playing.playhead = Some(pts);
337        }
338        (Verdict::Promote, outcome)
339    }
340
341    /// Drops the incumbent, so the replacement takes over on its first picture.
342    ///
343    /// For a step down on a link that cannot carry the incumbent: while both
344    /// overlap they share the link, and the replacement's groups age out before
345    /// they arrive. The caller keeps its last picture up.
346    pub fn release_incumbent(&mut self) {
347        self.incumbent = None;
348    }
349
350    /// Records that the incumbent's track ended.
351    ///
352    /// Without a replacement on its way, the video has ended.
353    pub fn incumbent_ended<E>(&mut self) -> Outcome<E> {
354        self.incumbent = None;
355        match &self.replacement {
356            Some(_) => Outcome::Idle,
357            None => Outcome::Ended,
358        }
359    }
360
361    /// Records that the replacement's track ended before it took over.
362    pub fn replacement_ended<E>(&mut self) -> Outcome<E> {
363        match self.replacement.take() {
364            Some(replacement) => Outcome::Abandoned(replacement.target, Abandoned::Ended),
365            None => Outcome::Idle,
366        }
367    }
368
369    /// Gives the replacement up if its deadline has passed at `now`.
370    pub fn expire<E>(&mut self, now: Instant) -> Outcome<E> {
371        match &self.replacement {
372            Some(replacement) if replacement.deadline <= now => {
373                let target = self.replacement.take().expect("matched above").target;
374                Outcome::Abandoned(target, Abandoned::TimedOut)
375            }
376            _ => Outcome::Idle,
377        }
378    }
379
380    /// Makes the warm replacement the incumbent.
381    fn promote<E>(&mut self) -> Outcome<E> {
382        let Some(Replacement {
383            target,
384            phase: Phase::Warming(reader),
385            ..
386        }) = self.replacement.take()
387        else {
388            unreachable!("only a warm replacement is promoted");
389        };
390        self.incumbent = Some(Playing {
391            target: target.clone(),
392            reader,
393            playhead: None,
394        });
395        Outcome::Promoted(target)
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    //! The supervisor's transitions, driven one event at a time.
402    //!
403    //! A reader is its name and an open task is its generation, so a test can
404    //! see which ones the switcher kept.
405
406    use super::*;
407
408    const PATIENCE: Duration = Duration::from_secs(15);
409
410    type Test = Switcher<&'static str, u64>;
411
412    fn ms(millis: u64) -> Duration {
413        Duration::from_millis(millis)
414    }
415
416    fn target(rendition: &str) -> Target {
417        Target::new(rendition, 0)
418    }
419
420    /// Returns a switcher playing `high` with its playhead at `playhead`.
421    fn playing(playhead: Duration) -> (Test, Instant) {
422        let now = Instant::now();
423        let mut switcher = Test::new(PATIENCE);
424        let _: Outcome<()> = switcher.request(target("high"), now, |generation, _| generation);
425        let outcome: Outcome<()> = switcher.opened(1, Ok("high"));
426        assert_eq!(outcome, Outcome::Idle);
427        assert_eq!(
428            switcher.replacement_frame::<()>(playhead, Instant::now()),
429            (Verdict::Promote, Outcome::Promoted(target("high")))
430        );
431        (switcher, now)
432    }
433
434    /// Asks `switcher` for `rendition`.
435    fn ask(switcher: &mut Test, rendition: &str, now: Instant) -> Outcome<()> {
436        switcher.request(target(rendition), now, |generation, _| generation)
437    }
438
439    /// A first decoder takes over on its first picture, not when it opens.
440    #[test]
441    fn a_first_decoder_takes_over_on_its_first_picture() {
442        let now = Instant::now();
443        let mut switcher = Test::new(PATIENCE);
444        assert_eq!(ask(&mut switcher, "high", now), Outcome::Idle);
445        assert_eq!(switcher.opening_mut(), Some(&mut 1));
446        assert_eq!(switcher.opened::<()>(1, Ok("high")), Outcome::Idle);
447        assert_eq!(switcher.current(), None);
448        assert_eq!(switcher.deadline(), Some(now + PATIENCE));
449        assert_eq!(
450            switcher.replacement_frame::<()>(ms(0), Instant::now()),
451            (Verdict::Promote, Outcome::Promoted(target("high")))
452        );
453        assert_eq!(switcher.current(), Some(&target("high")));
454        assert_eq!(switcher.switching_to(), None);
455        assert_eq!(switcher.deadline(), None);
456    }
457
458    /// A first decoder that never decodes times out as a failed switch.
459    #[test]
460    fn a_silent_first_decoder_times_out() {
461        let now = Instant::now();
462        let mut switcher = Test::new(PATIENCE);
463        assert_eq!(ask(&mut switcher, "high", now), Outcome::Idle);
464        assert_eq!(switcher.opened::<()>(1, Ok("high")), Outcome::Idle);
465        assert_eq!(
466            switcher.expire::<()>(now + PATIENCE),
467            Outcome::Abandoned(target("high"), Abandoned::TimedOut)
468        );
469        assert!(switcher.is_idle());
470    }
471
472    /// A newer request drops an opening replacement with its open task.
473    ///
474    /// The superseded open's late result changes nothing.
475    #[test]
476    fn a_newer_request_supersedes_an_opening_replacement() {
477        let (mut switcher, now) = playing(ms(1000));
478        assert_eq!(ask(&mut switcher, "mid", now), Outcome::Idle);
479        let mid = switcher.replacement_generation().expect("mid is opening");
480
481        assert_eq!(
482            ask(&mut switcher, "low", now),
483            Outcome::Abandoned(target("mid"), Abandoned::Superseded)
484        );
485        let low = switcher.replacement_generation().expect("low is opening");
486        assert_ne!(mid, low);
487
488        // The superseded open finishes anyway.
489        assert_eq!(switcher.opened::<()>(mid, Ok("mid")), Outcome::Idle);
490        assert_eq!(switcher.switching_to(), Some(&target("low")));
491        assert!(switcher.warming_mut().is_none(), "mid must not warm up");
492    }
493
494    /// A newer request drops a warming replacement, decoder included.
495    #[test]
496    fn a_newer_request_supersedes_a_warming_replacement() {
497        let (mut switcher, now) = playing(ms(1000));
498        assert_eq!(ask(&mut switcher, "mid", now), Outcome::Idle);
499        assert_eq!(switcher.opened::<()>(2, Ok("mid")), Outcome::Idle);
500        assert_eq!(switcher.warming_mut(), Some(&mut "mid"));
501
502        assert_eq!(
503            ask(&mut switcher, "low", now),
504            Outcome::Abandoned(target("mid"), Abandoned::Superseded)
505        );
506        assert!(switcher.warming_mut().is_none());
507        assert_eq!(switcher.opening_mut(), Some(&mut 3));
508    }
509
510    #[test]
511    fn asking_for_the_replacement_again_changes_nothing() {
512        let (mut switcher, now) = playing(ms(1000));
513        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
514        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
515        assert_eq!(
516            switcher.opening_mut(),
517            Some(&mut 2),
518            "the open was restarted"
519        );
520    }
521
522    /// Asking for the playing rendition withdraws a pending switch.
523    #[test]
524    fn asking_for_the_playing_rendition_withdraws_the_replacement() {
525        let (mut switcher, now) = playing(ms(1000));
526        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
527        assert_eq!(
528            ask(&mut switcher, "high", now),
529            Outcome::Abandoned(target("low"), Abandoned::Withdrawn)
530        );
531        assert_eq!(switcher.switching_to(), None);
532        assert_eq!(switcher.current(), Some(&target("high")));
533    }
534
535    /// Pinning the playing rendition keeps a pending decoder change for it.
536    #[test]
537    fn a_decoder_change_survives_repinning_the_playing_rendition() {
538        let (mut switcher, now) = playing(ms(1000));
539        let rebuild = Target::new("high", 1);
540        let _: Outcome<()> = switcher.request(rebuild.clone(), now, |generation, _| generation);
541        assert_eq!(switcher.switching_to(), Some(&rebuild));
542
543        // The pin names the rendition under the configuration now asked for.
544        let _: Outcome<()> = switcher.request(rebuild.clone(), now, |generation, _| generation);
545        assert_eq!(switcher.switching_to(), Some(&rebuild));
546    }
547
548    /// A replacement behind the playhead decodes in silence until it catches up.
549    #[test]
550    fn a_replacement_behind_the_playhead_is_held_back() {
551        let (mut switcher, now) = playing(ms(10_000));
552        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
553        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
554
555        for behind in [ms(8000), ms(9000), ms(9899)] {
556            assert_eq!(
557                switcher.replacement_frame::<()>(behind, Instant::now()),
558                (Verdict::Discard, Outcome::Idle),
559                "a picture at {behind:?} would step back from 10s"
560            );
561        }
562        assert_eq!(switcher.current(), Some(&target("high")));
563
564        // Within the slack of the incumbent's playhead: close enough.
565        assert_eq!(
566            switcher.replacement_frame::<()>(ms(9900), Instant::now()),
567            (Verdict::Promote, Outcome::Promoted(target("low")))
568        );
569        assert_eq!(switcher.current(), Some(&target("low")));
570        assert_eq!(switcher.incumbent_mut(), Some(&mut "low"));
571    }
572
573    /// A replacement that cannot catch up takes over once its patience ends.
574    #[test]
575    fn a_replacement_that_cannot_catch_up_takes_over_after_its_patience() {
576        let (mut switcher, now) = playing(ms(10_000));
577        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
578        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
579        let first = now + ms(500);
580        assert_eq!(
581            switcher.replacement_frame::<()>(ms(8000), first).0,
582            Verdict::Discard
583        );
584        assert_eq!(
585            switcher
586                .replacement_frame::<()>(ms(8100), first + CATCH_UP_PATIENCE - ms(1))
587                .0,
588            Verdict::Discard
589        );
590        assert_eq!(
591            switcher.replacement_frame::<()>(ms(8200), first + CATCH_UP_PATIENCE),
592            (Verdict::Promote, Outcome::Promoted(target("low")))
593        );
594        assert_eq!(switcher.current(), Some(&target("low")));
595    }
596
597    /// A released incumbent lets the replacement take over on its first picture.
598    #[test]
599    fn a_released_incumbent_leaves_the_replacement_to_take_over() {
600        let (mut switcher, now) = playing(ms(10_000));
601        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
602        switcher.release_incumbent();
603        assert_eq!(switcher.current(), None);
604        assert_eq!(switcher.deadline(), Some(now + PATIENCE));
605        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
606        assert_eq!(
607            switcher.replacement_frame::<()>(ms(2000), now),
608            (Verdict::Promote, Outcome::Promoted(target("low")))
609        );
610    }
611
612    /// The playhead the replacement is held to moves with the incumbent.
613    #[test]
614    fn the_catch_up_bar_follows_the_incumbent() {
615        let (mut switcher, now) = playing(ms(1000));
616        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
617        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
618        switcher.incumbent_frame(ms(2000));
619        assert_eq!(
620            switcher.replacement_frame::<()>(ms(1500), Instant::now()).0,
621            Verdict::Discard
622        );
623        assert_eq!(
624            switcher.replacement_frame::<()>(ms(2000), Instant::now()).0,
625            Verdict::Promote
626        );
627    }
628
629    /// A replacement ahead of the incumbent takes over on its first picture.
630    #[test]
631    fn a_replacement_ahead_of_the_playhead_takes_over_at_once() {
632        let (mut switcher, now) = playing(ms(1000));
633        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
634        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
635        assert_eq!(
636            switcher.replacement_frame::<()>(ms(1200), Instant::now()),
637            (Verdict::Promote, Outcome::Promoted(target("low")))
638        );
639    }
640
641    /// Pictures without a warm replacement are discarded.
642    #[test]
643    fn only_a_warm_replacement_can_take_over() {
644        let (mut switcher, now) = playing(ms(1000));
645        assert_eq!(
646            switcher.replacement_frame::<()>(ms(5000), Instant::now()).0,
647            Verdict::Discard
648        );
649        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
650        assert_eq!(
651            switcher.replacement_frame::<()>(ms(5000), Instant::now()).0,
652            Verdict::Discard
653        );
654    }
655
656    /// After the incumbent ends, a warm replacement takes over on any picture.
657    #[test]
658    fn the_incumbent_ending_hands_over_on_the_next_picture() {
659        let (mut switcher, now) = playing(ms(10_000));
660        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
661        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
662        assert_eq!(switcher.incumbent_ended::<()>(), Outcome::Idle);
663        assert_eq!(switcher.current(), None);
664        assert_eq!(switcher.deadline(), Some(now + PATIENCE));
665        assert_eq!(
666            switcher.replacement_frame::<()>(ms(1000), Instant::now()),
667            (Verdict::Promote, Outcome::Promoted(target("low")))
668        );
669        assert_eq!(switcher.current(), Some(&target("low")));
670        assert_eq!(switcher.deadline(), None);
671    }
672
673    #[test]
674    fn the_incumbent_ending_keeps_an_opening_replacement_on_its_deadline() {
675        let (mut switcher, now) = playing(ms(1000));
676        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
677        assert_eq!(switcher.incumbent_ended::<()>(), Outcome::Idle);
678        assert_eq!(switcher.current(), None);
679        assert_eq!(switcher.deadline(), Some(now + PATIENCE));
680
681        // With nothing playing, the replacement takes over on its first
682        // picture.
683        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
684        assert_eq!(
685            switcher.replacement_frame::<()>(ms(0), Instant::now()).1,
686            Outcome::Promoted(target("low"))
687        );
688    }
689
690    #[test]
691    fn the_incumbent_ending_alone_ends_the_video() {
692        let (mut switcher, _) = playing(ms(1000));
693        assert_eq!(switcher.incumbent_ended::<()>(), Outcome::Ended);
694        assert!(switcher.is_idle());
695    }
696
697    /// The deadline runs from the request and covers the open.
698    #[test]
699    fn a_replacement_that_never_opens_times_out() {
700        let (mut switcher, now) = playing(ms(1000));
701        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
702        assert_eq!(switcher.expire::<()>(now + PATIENCE - ms(1)), Outcome::Idle);
703        assert_eq!(
704            switcher.expire::<()>(now + PATIENCE),
705            Outcome::Abandoned(target("low"), Abandoned::TimedOut)
706        );
707        assert_eq!(switcher.opening_mut(), None, "the open task was dropped");
708        assert_eq!(switcher.current(), Some(&target("high")));
709    }
710
711    /// The deadline also covers catching up.
712    #[test]
713    fn a_replacement_that_never_catches_up_times_out() {
714        let (mut switcher, now) = playing(ms(60_000));
715        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
716        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
717        assert_eq!(
718            switcher.replacement_frame::<()>(ms(1000), Instant::now()),
719            (Verdict::Discard, Outcome::Idle)
720        );
721        assert_eq!(
722            switcher.expire::<()>(now + PATIENCE),
723            Outcome::Abandoned(target("low"), Abandoned::TimedOut)
724        );
725        assert!(switcher.warming_mut().is_none());
726    }
727
728    /// A superseding request gets a fresh deadline.
729    #[test]
730    fn a_superseding_request_starts_its_own_deadline() {
731        let (mut switcher, now) = playing(ms(1000));
732        assert_eq!(ask(&mut switcher, "mid", now), Outcome::Idle);
733        let later = now + ms(10_000);
734        assert_eq!(
735            ask(&mut switcher, "low", later),
736            Outcome::Abandoned(target("mid"), Abandoned::Superseded)
737        );
738        assert_eq!(switcher.deadline(), Some(later + PATIENCE));
739    }
740
741    #[test]
742    fn a_failed_open_is_reported_and_leaves_the_incumbent_playing() {
743        let (mut switcher, now) = playing(ms(1000));
744        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
745        assert_eq!(
746            switcher.opened(2, Err("no such track")),
747            Outcome::Abandoned(target("low"), Abandoned::OpenFailed("no such track"))
748        );
749        assert_eq!(switcher.current(), Some(&target("high")));
750        assert_eq!(switcher.switching_to(), None);
751    }
752
753    #[test]
754    fn a_replacement_whose_track_ends_is_reported() {
755        let (mut switcher, now) = playing(ms(1000));
756        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
757        assert_eq!(switcher.opened::<()>(2, Ok("low")), Outcome::Idle);
758        assert_eq!(
759            switcher.replacement_ended::<()>(),
760            Outcome::Abandoned(target("low"), Abandoned::Ended)
761        );
762        assert_eq!(switcher.current(), Some(&target("high")));
763    }
764
765    /// A failure with nothing playing is a failed switch, not the end.
766    #[test]
767    fn a_failure_with_nothing_playing_is_a_failed_switch() {
768        let now = Instant::now();
769        let mut switcher = Test::new(PATIENCE);
770        assert_eq!(ask(&mut switcher, "high", now), Outcome::Idle);
771        assert_eq!(
772            switcher.opened(1, Err("no decoder")),
773            Outcome::Abandoned(target("high"), Abandoned::OpenFailed("no decoder"))
774        );
775        assert!(switcher.is_idle());
776
777        let (mut switcher, now) = playing(ms(1000));
778        assert_eq!(ask(&mut switcher, "low", now), Outcome::Idle);
779        assert_eq!(switcher.incumbent_ended::<()>(), Outcome::Idle);
780        assert_eq!(
781            switcher.opened(2, Err("no such track")),
782            Outcome::Abandoned(target("low"), Abandoned::OpenFailed("no such track"))
783        );
784        assert!(switcher.is_idle());
785    }
786}