//! One playout clock shared by a broadcast's tracks. //! //! Each [`Track`] folds its arrivals into the clock with [`Track::received`], //! and [`Producer::due`] says when media is due. The clock's reference is the earliest //! arrival any live track has seen, measured against its timestamp, so it sits //! on the wall clock and follows the live edge, moving later only after a lasting //! step in path delay (see `doc/concept/audio-jitter.md`). Every track presents against //! it, which holds them together in the steady state. One that falls behind, //! such as audio stalled by congestion, only arrives late: it never holds or //! moves the others. Audio converges on the clock by stretching toward its //! [`due`](Producer::due) time rather than owning it. //! //! Playback trails the reference by the largest target a live track holds //! ([`Track::set_target`]), or by the delay passed to [`Producer::new`] while //! none holds one. Give a [`Consumer`] to a presenter: [`Consumer::present`] //! selects the newest due picture without waiting, so a canvas can repeat its //! previous picture. A presenter that sleeps until its next picture is due //! reads the [`Schedule`] it sleeps on and wakes when //! [`Consumer::poll_changed`] reports that it moved. //! //! Timestamps keep moving forward across a declared end, so the clock has no //! notion of one: media after it lands on the same schedule. A track whose //! timeline breaks, such as at lost media or a later group after a declared end, //! calls [`Track::reset`] so its arrivals stop holding the clock until the next //! one, as `@moq/watch`'s `Sync` does. Keep one active track per [`Kind`]. use kio::clock::Instant; use std::time::Duration; use moq_net::Timestamp; use std::{ sync::{Arc, Mutex}, task::Poll, }; use crate::container::Kind; /// One slot per [`Kind`]. const KINDS: usize = 3; /// How long a track's arrivals must all trail its anchor before the anchor /// follows them later: the estimator's window, so the clock and the target /// measure lateness against the same fastest frame. const FOLLOW: Duration = Duration::from_secs(2); struct Clock { state: Mutex, changed: kio::Shared<()>, } impl Clock { fn new(delay: Duration) -> Self { Self { state: Mutex::new(State::new(delay)), changed: Default::default(), } } fn wake(&self) { *self.changed.lock() = (); } } impl Part { /// Fold `arrival` into the open window, and once it closes move the anchor /// later to the window's earliest arrival if every arrival in it trailed the /// anchor by more than `half`, as after a lasting increase in path delay. fn follow(&mut self, arrival: Anchor, half: Duration) { let Some(mut window) = self.window else { self.window = Some(Window { start: arrival.at, least: arrival, }); return; }; if arrival.earlier(&window.least) { window.least = arrival; } // The arrival that closes a window counts in it and opens the next. if arrival.at.saturating_duration_since(window.start) < FOLLOW { self.window = Some(window); return; } self.window = Some(Window { start: arrival.at, least: arrival, }); let Some(anchor) = self.anchor else { return }; let Some(at) = anchor.at.checked_add(half) else { return }; let bound = Anchor { at, ..anchor }; if bound.earlier(&window.least) { self.anchor = Some(window.least); } } } /// A schedule pinning media time to the wall clock: `media` arrived at `at`. #[derive(Clone, Copy, Debug)] struct Anchor { at: Instant, media: Duration, } impl Anchor { /// When `media` lands on this schedule, before any delay. A time before the /// platform clock can express lands on the anchor, which is already past. fn at(&self, media: Duration) -> Option { match media.checked_sub(self.media) { Some(ahead) => self.at.checked_add(ahead), None => Some(self.at.checked_sub(self.media - media).unwrap_or(self.at)), } } /// Whether this schedule runs ahead of `other`, so its media lands earlier. fn earlier(&self, other: &Self) -> bool { match other.media.checked_sub(self.media) { Some(ahead) => self.at.checked_add(ahead).is_some_and(|at| at < other.at), None => other .at .checked_add(self.media - other.media) .is_none_or(|at| self.at < at), } } } /// Whether two optional schedules differ. fn moved(before: Option, after: Option) -> bool { match (before, after) { (Some(before), Some(after)) => before.earlier(&after) || after.earlier(&before), (before, after) => before.is_some() != after.is_some(), } } /// One track's hold on the clock. #[derive(Clone, Copy, Default)] struct Part { /// The earliest arrival on this track's current timeline, or the earliest /// of the last window once a whole window trailed it. anchor: Option, /// The delay this track asks playback to hold. target: Option, /// The window of arrivals that decides whether the anchor follows a lasting step later. window: Option, } /// A window of one track's arrivals: when it opened and the earliest schedule among them. #[derive(Clone, Copy)] struct Window { start: Instant, least: Anchor, } /// The playout clock every track of one broadcast presents against. /// /// Each track keeps the earliest arrival on its own timeline, and the reference /// is the earliest of those. That is what pulls playback toward live: a frame /// arriving earlier than the reference predicted re-pins it, while a late /// frame only reports that it is late. A lasting step later in the path's /// delay moves a track's anchor later once a whole window of its arrivals /// trailed it by more than half the delay. A track that resets or goes away /// gives up its arrivals, so the reference falls back to the earliest track left. struct State { /// How far behind the reference playback runs while no track holds a target. delay: Duration, parts: [Part; KINDS], /// The schedule the last track to go left behind, which what it already /// queued still presents against until any track anchors again. left: Option, } impl State { fn new(delay: Duration) -> Self { Self { delay, parts: Default::default(), left: None, } } /// The earliest schedule any track holds. fn reference(&self) -> Option { self.parts .iter() .filter_map(|part| part.anchor) .reduce(|earliest, anchor| if anchor.earlier(&earliest) { anchor } else { earliest }) .or(self.left) } /// How far behind the reference playback runs. fn delay(&self) -> Duration { self.parts .iter() .filter_map(|part| part.target) .max() .unwrap_or(self.delay) } /// Fold an arrival into `kind`'s timeline, reporting whether that moved the schedule. fn received(&mut self, kind: Kind, timestamp: Timestamp, now: Instant) -> bool { // An unscaled key has no media time to anchor on. let Ok(media) = Duration::try_from(timestamp) else { return false; }; let arrival = Anchor { at: now, media }; let before = self.reference(); let half = self.delay() / 2; let part = &mut self.parts[kind as usize]; if part.anchor.is_none_or(|anchor| arrival.earlier(&anchor)) { part.anchor = Some(arrival); } part.follow(arrival, half); self.left = None; moved(before, self.reference()) } /// End `kind`'s timeline, reporting whether that moved the schedule. fn reset(&mut self, kind: Kind) -> bool { let before = self.reference(); let part = &mut self.parts[kind as usize]; part.anchor = None; part.window = None; moved(before, self.reference()) } /// Release `kind` as its track goes. fn release(&mut self, kind: Kind) { let part = std::mem::take(&mut self.parts[kind as usize]); if self.parts.iter().all(|part| part.anchor.is_none()) { self.left = part.anchor.or(self.left); } } /// Hold `target` for `kind`, reporting whether that moved the schedule. fn set_target(&mut self, kind: Kind, target: Duration) -> bool { let before = self.delay(); self.parts[kind as usize].target = Some(target); before != self.delay() } /// The media position the clock will reach at `at`. fn position(&self, at: Instant) -> Option { let reference = self.reference()?; let at = at.checked_sub(self.delay()).unwrap_or(Instant::ZERO); Some(if at >= reference.at { reference.media.saturating_add(at.duration_since(reference.at)) } else { reference.media.saturating_sub(reference.at.duration_since(at)) }) } /// When `timestamp` should be presented, or `None` before any frame has /// anchored the clock. `None` means as soon as possible: there is nothing /// left to wait for, as for an unscaled timestamp, which has no media time. fn due(&self, timestamp: Timestamp) -> Option { self.schedule().due(timestamp) } /// The reference and delay every due time derives from. fn schedule(&self) -> Schedule { Schedule { reference: self.reference(), delay: self.delay(), } } } /// The playout schedule at one moment: where the reference sits and how far /// playback trails it. /// /// Two schedules are equal when they place every timestamp at the same /// instant, so a reference re-pinned onto the same line compares equal. #[derive(Clone, Copy, Debug)] pub struct Schedule { reference: Option, delay: Duration, } impl Schedule { /// How far behind the reference playback runs. pub fn delay(&self) -> Duration { self.delay } /// When `timestamp` is due on this schedule, or `None` before the first anchor or for an /// unscaled timestamp, which has no media time. pub fn due(&self, timestamp: Timestamp) -> Option { let at = self.reference?.at(Duration::try_from(timestamp).ok()?)?; Some(at.checked_add(self.delay).unwrap_or(at)) } } impl PartialEq for Schedule { fn eq(&self, other: &Self) -> bool { self.delay == other.delay && !moved(self.reference, other.reference) } } /// One track's hold on the shared clock: its arrivals and target. /// /// Dropping it releases its arrivals and target. pub struct Track { clock: Arc, role: Kind, } impl Track { /// Fold a frame that arrived at `now` into the clock, reporting whether that /// moved the schedule. /// /// A frame arriving earlier than the schedule predicted pulls playback toward /// live; a late one leaves it alone. A move makes every queued frame due /// earlier, so a presenter has to recompute the deadline it is asleep on. /// An [unscaled](Timestamp::unscaled) timestamp has no media time, so it /// moves nothing. pub fn received(&self, timestamp: Timestamp, now: Instant) -> bool { let moved = self.clock.state.lock().unwrap().received(self.role, timestamp, now); if moved { self.clock.wake(); } moved } /// End this track's timeline at a discontinuity, such as lost media, a rewind, /// or a later group after a declared end: its arrivals stop holding the clock /// until the next one. pub fn reset(&self) { if self.clock.state.lock().unwrap().reset(self.role) { self.clock.wake(); } } /// Ask playback to trail the reference by at least `target`, reporting /// whether that moved the schedule. Playback holds the largest target any /// live track asks for. pub fn set_target(&self, target: Duration) -> bool { let moved = self.clock.state.lock().unwrap().set_target(self.role, target); if moved { self.clock.wake(); } moved } /// Wait until playback trails the reference by something other than `seen`, returning the new delay. #[cfg_attr(feature = "async", kio::wrapper)] pub fn poll_delay_changed(&self, waiter: &kio::Waiter, seen: Duration) -> Poll { let mut delay = seen; let _ = std::task::ready!(self.clock.changed.poll(waiter, |_| { delay = self.clock.state.lock().unwrap().delay(); if delay == seen { Poll::Pending } else { Poll::Ready(()) } })); Poll::Ready(delay) } } impl Drop for Track { fn drop(&mut self) { self.clock.state.lock().unwrap().release(self.role); self.clock.wake(); } } /// Owns one broadcast's playout clock and hands out its tracks. /// /// Clones capture this broadcast's clock; resetting a handle never changes the /// clock its previous clones or tracks update. #[derive(Clone)] pub struct Producer { clock: Arc, current: Arc>>, } /// Reads the current playout schedule without moving it. /// /// Keeps the final schedule readable after its tracks drop, and follows the /// replacement clock when a producer resets for another broadcast. #[derive(Clone)] pub struct Consumer { current: Arc>>, } impl Producer { /// Create a broadcast clock that trails the reference by `delay` while no track holds a target. pub fn new(delay: Duration) -> Self { let clock = Arc::new(Clock::new(delay)); Self { clock: clock.clone(), current: Arc::new(Mutex::new(clock)), } } /// Replace this producer with a new broadcast clock and switch readers to it. /// /// Previous clones and tracks retain their old broadcast's clock. #[must_use = "use the returned producer for the replacement broadcast"] pub fn reset(self, delay: Duration) -> Self { let clock = Arc::new(Clock::new(delay)); // Wake the clock readers followed, which is not this handle's own when a // stale clone resets, and only after the swap so they find the new one. let replaced = std::mem::replace(&mut *self.current.lock().unwrap(), clock.clone()); replaced.wake(); Self { clock, current: self.current, } } /// Return a reader that follows this handle's broadcast replacements. pub fn consume(&self) -> Consumer { Consumer { current: self.current.clone(), } } /// Return a track bound to this broadcast's clock. pub fn track(&self, kind: Kind) -> Track { Track { clock: self.clock.clone(), role: kind, } } /// When `timestamp` should be presented, or `None` before any frame has /// anchored the clock. `None` means as soon as possible: there is nothing /// left to wait for. pub fn due(&self, timestamp: Timestamp) -> Option { self.clock.state.lock().unwrap().due(timestamp) } } impl Consumer { /// How far behind the reference playback runs. pub fn delay(&self) -> Duration { self.current.lock().unwrap().state.lock().unwrap().delay() } /// When this timestamp is due, or `None` before the first anchor. pub fn due(&self, timestamp: Timestamp) -> Option { self.current.lock().unwrap().state.lock().unwrap().due(timestamp) } /// The media time the clock presents at `at`, or `None` before the first anchor. pub fn position(&self, at: Instant) -> Option { self.current.lock().unwrap().state.lock().unwrap().position(at) } /// The current schedule, to read due times from or to pass to /// [`poll_changed`](Self::poll_changed). pub fn schedule(&self) -> Schedule { self.current.lock().unwrap().state.lock().unwrap().schedule() } /// Wait until the schedule differs from `seen`, returning the new one. /// /// Resolves once any due time moved: a track re-pinned the reference, the /// delay changed, the last anchor went away, or the producer reset onto a /// clock that schedules differently. A change made before the call, even /// while no wait was pending, resolves it at once; changes that cancel out /// before the call do not. #[cfg_attr(feature = "async", kio::wrapper)] pub fn poll_changed(&self, waiter: &kio::Waiter, seen: Schedule) -> Poll { loop { let clock = self.current.lock().unwrap().clone(); let mut changed = None; // A reset swaps readers before waking the old clock, so checking the // swap under the old clock's signal never misses one. let _ = std::task::ready!(clock.changed.poll(waiter, |_| { if !Arc::ptr_eq(&self.current.lock().unwrap(), &clock) { return Poll::Ready(()); } let schedule = clock.state.lock().unwrap().schedule(); if schedule == seen { return Poll::Pending; } changed = Some(schedule); Poll::Ready(()) })); if let Some(schedule) = changed { return Poll::Ready(schedule); } } } /// The newest due picture's index in presentation order, or `None` to repeat the previous one. /// /// Pass queued timestamps in ascending order and discard entries through the /// returned index after showing that picture. This stores no frames and leaves /// their retention and backpressure to the caller. Query again after every /// schedule move, which [`poll_changed`](Self::poll_changed) reports; a cached /// deadline can become stale. pub fn present(&self, timestamps: impl IntoIterator, now: Instant) -> Option { let clock = self.current.lock().unwrap(); let state = clock.state.lock().unwrap(); timestamps .into_iter() .take_while(|timestamp| state.due(*timestamp).is_none_or(|at| at <= now)) .count() .checked_sub(1) } } #[cfg(test)] mod tests { use super::*; const DELAY: Duration = Duration::from_millis(100); fn ms(millis: u64) -> Timestamp { Timestamp::from_millis(millis).unwrap() } #[derive(serde::Deserialize)] struct Case { name: String, delay: u64, runs: Vec, } #[derive(serde::Deserialize)] struct Run { tracks: Vec, start: u64, every: u64, frames: u64, offsets: Vec, reference: u64, } /// Each case plays runs of arrivals and checks where the reference sits after each. #[test] fn the_reference_conforms_to_the_corpus() { // Media starts this far into the track, so it is never negative. const MEDIA: u64 = 100_000; let cases: Vec = serde_json::from_str(include_str!("../../../doc/concept/audio-jitter/clock/corpus.json")).unwrap(); let base = Instant::ZERO.saturating_add(Duration::from_secs(5)); for case in cases { let delay = Duration::from_millis(case.delay); let clock = Producer::new(delay); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); for (index, run) in case.runs.iter().enumerate() { for i in 0..run.frames { let arrival = run.start + i * run.every; let offset = run.offsets[(i as usize) % run.offsets.len()]; let track = match run.tracks[(i as usize) % run.tracks.len()].as_str() { "audio" => &audio, "video" => &video, other => panic!("unknown track {other}"), }; track.received( ms(MEDIA + arrival - offset), base.saturating_add(Duration::from_millis(arrival)), ); } // The reference's offset is when media `MEDIA` is due, less the delay, after `base`. let due = clock.due(ms(MEDIA)).unwrap().saturating_sub(delay); assert_eq!( due.duration_since(base), Duration::from_millis(run.reference), "{} run {index}", case.name ); } } } /// Earlier arrivals pull the reference forward so playback converges on the /// live edge without giving up the delay; late ones leave it alone. #[test] fn the_earliest_arrival_sets_the_schedule() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let video = clock.track(Kind::Video); assert_eq!(clock.due(ms(0)), None, "nothing anchors before the first frame"); assert!(video.received(ms(0), start), "the first anchor"); assert_eq!(clock.due(ms(0)), Some(start.saturating_add(DELAY))); // 40ms of media later, but only 20ms of wall clock: the first frame was // 20ms late, so the schedule moves onto this one. let now = start.saturating_add(Duration::from_millis(20)); assert!(video.received(ms(40), now), "an early frame left the schedule alone"); assert_eq!(clock.due(ms(40)), Some(now.saturating_add(DELAY))); // A frame that merely arrives late keeps its media instant. The delay is // the room it has to be late in. let late = now.saturating_add(Duration::from_millis(70)); assert!(!video.received(ms(80), late), "a late arrival moved the schedule"); assert_eq!(clock.due(ms(80)), Some(now.saturating_add(Duration::from_millis(140)))); } /// The required decoupling: audio stalled by congestion arrives late, which /// neither holds video back nor moves it, while both share one schedule in /// the steady state. #[test] fn stalled_audio_no_longer_holds_video() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); audio.received(ms(0), start); video.received(ms(0), start); let steady = clock.due(ms(1_000)); assert_eq!( steady, Some(start.saturating_add(DELAY).saturating_add(Duration::from_secs(1))) ); // Video keeps arriving on time while audio stalls for 500ms, then audio // lands in a late burst and resets its timeline on a fresh sink. for frame in 1..=25 { let at = start.saturating_add(Duration::from_millis(frame * 40)); assert!(!video.received(ms(frame * 40), at)); } let resumed = start.saturating_add(Duration::from_millis(1_000)); for frame in 0..25 { assert!(!audio.received(ms(500 + frame * 20), resumed), "late audio moved video"); } audio.reset(); assert!(!audio.received(ms(1_000), resumed.saturating_add(Duration::from_millis(100)))); assert_eq!(clock.due(ms(1_000)), steady, "stalled audio held video"); } /// A video tune-in burst is the live edge: nothing owns the schedule, so it /// moves every track onto it, audio included. #[test] fn a_video_burst_moves_audio_onto_the_live_edge() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); audio.received(ms(1_000), start); assert!(video.received(ms(4_000), start)); assert_eq!(clock.due(ms(4_000)), Some(start.saturating_add(DELAY))); } /// A track that resets gives up its arrivals: the schedule falls back to the /// earliest track left, and with none left the next frame anchors afresh. #[test] fn a_reset_hands_the_schedule_to_the_tracks_left() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); video.received(ms(0), start); // Audio runs 30ms ahead of video, so it holds the schedule. audio.received(ms(30), start); assert_eq!(clock.due(ms(30)), Some(start.saturating_add(DELAY))); audio.reset(); assert_eq!( clock.due(ms(30)), Some(start.saturating_add(DELAY).saturating_add(Duration::from_millis(30))) ); video.reset(); assert_eq!(clock.due(ms(30)), None); let now = start.saturating_add(Duration::from_secs(5)); audio.received(ms(500), now); assert_eq!(clock.due(ms(500)), Some(now.saturating_add(DELAY))); // The last track to go leaves its schedule for what it queued, until // another anchors afresh. drop(audio); assert_eq!(clock.due(ms(500)), Some(now.saturating_add(DELAY))); let later = now.saturating_add(Duration::from_secs(5)); video.received(ms(0), later); assert_eq!(clock.due(ms(0)), Some(later.saturating_add(DELAY))); } /// Playback holds the deepest target a live track asks for, and the default /// while none asks. #[test] fn the_delay_is_the_largest_target_held() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); video.received(ms(0), start); assert_eq!(reader.delay(), DELAY); assert!(audio.set_target(Duration::from_millis(60))); assert_eq!(reader.delay(), Duration::from_millis(60)); assert_eq!(clock.due(ms(0)), Some(start.saturating_add(Duration::from_millis(60)))); assert!(video.set_target(Duration::from_millis(80))); assert!( !audio.set_target(Duration::from_millis(70)), "a shallower target moved the delay" ); assert_eq!(reader.delay(), Duration::from_millis(80)); drop(video); assert_eq!(reader.delay(), Duration::from_millis(70)); drop(audio); assert_eq!(reader.delay(), DELAY); } #[test] fn presentation_selects_due_frames_on_the_current_schedule() { let clock = Producer::new(Duration::from_millis(40)); let reader = clock.consume(); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); video.received(ms(0), now); let frames = [ms(0), ms(20), ms(40)]; assert_eq!(reader.present(frames, now), None); assert_eq!( reader.present(frames, now.saturating_add(Duration::from_millis(60))), Some(1) ); // Audio arrives 40ms ahead; stale video deadlines no longer apply. audio.received(ms(40), now); assert_eq!(reader.present(frames, now), Some(0)); assert_eq!( reader.present(frames, now.saturating_add(Duration::from_millis(39))), Some(1) ); assert_eq!( reader.present(frames, now.saturating_add(Duration::from_millis(40))), Some(2) ); // Neither a stall nor a future-only queue invents a new picture. assert_eq!(reader.present([], now.saturating_add(Duration::from_secs(1))), None); assert_eq!( reader.present([ms(200)], now.saturating_add(Duration::from_millis(100))), None ); } #[test] fn replacing_a_broadcast_isolates_its_old_update_handles() { let now = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let previous = clock.clone(); let old = clock.track(Kind::Audio); let clock = clock.reset(DELAY); let audio = clock.track(Kind::Audio); audio.received(ms(0), now); // A JoinSet abort can leave these updates and drops until after the new track started. old.received(ms(10_000), now); drop(old); previous.track(Kind::Audio).received(ms(10_000), now); assert_eq!(reader.due(ms(0)), Some(now.saturating_add(DELAY))); } /// Counts the wakes a parked poll receives. struct Wakes(std::sync::atomic::AtomicUsize); impl std::task::Wake for Wakes { fn wake(self: Arc) { self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } } impl Wakes { fn waiter() -> (Arc, kio::Waiter) { let wakes = Arc::new(Self(Default::default())); let waiter = kio::Waiter::new(std::task::Waker::from(wakes.clone())); (wakes, waiter) } fn count(&self) -> usize { self.0.load(std::sync::atomic::Ordering::Relaxed) } } /// Parks a waiter on the current schedule, applies `change`, and checks that /// the waiter woke and resolved to the schedule the change left behind. fn wakes_on(reader: &Consumer, change: impl FnOnce()) -> Schedule { let seen = reader.schedule(); let (wakes, waiter) = Wakes::waiter(); assert!(reader.poll_changed(&waiter, seen).is_pending()); change(); assert!(wakes.count() > 0, "the change left the waiter asleep"); let Poll::Ready(moved) = reader.poll_changed(&waiter, seen) else { panic!("the change did not resolve the wait"); }; assert_ne!(moved, seen); assert_eq!(moved, reader.schedule()); moved } /// Every way a due time can move wakes a parked reader. #[test] fn the_change_waiter_wakes_on_every_schedule_move() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); let anchored = wakes_on(&reader, || assert!(video.received(ms(0), start))); assert_eq!(anchored.due(ms(0)), Some(start.saturating_add(DELAY))); // Audio arrives 20ms ahead of video's schedule and re-pins it. let pinned = wakes_on(&reader, || { assert!(audio.received(ms(40), start.saturating_add(Duration::from_millis(20)))) }); assert_eq!( pinned.due(ms(40)), Some(start.saturating_add(Duration::from_millis(20) + DELAY)) ); let deeper = wakes_on(&reader, || assert!(video.set_target(Duration::from_millis(300)))); assert_eq!(deeper.delay(), Duration::from_millis(300)); // Releasing the deepest target falls back to the default delay. let shallower = wakes_on(&reader, || drop(video)); assert_eq!(shallower.delay(), DELAY); // The only anchored track breaks its timeline: nothing is scheduled. let reset = wakes_on(&reader, || audio.reset()); assert_eq!(reset.due(ms(0)), None); // A producer reset onto a clock with another delay moves readers onto it. let replaced = wakes_on(&reader, || drop(clock.reset(Duration::from_millis(250)))); assert_eq!(replaced.delay(), Duration::from_millis(250)); } /// A wait resolves only when a due time moves, not on every signal the /// clock raises. #[test] fn the_change_waiter_ignores_what_leaves_the_schedule_alone() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let audio = clock.track(Kind::Audio); let video = clock.track(Kind::Video); video.received(ms(0), start); assert!(audio.set_target(Duration::from_millis(200))); let seen = reader.schedule(); let (wakes, waiter) = Wakes::waiter(); assert!(reader.poll_changed(&waiter, seen).is_pending()); // A late arrival and a shallower target raise no signal at all. assert!(!video.received(ms(40), start.saturating_add(Duration::from_millis(60)))); assert!(!video.set_target(Duration::from_millis(150))); assert_eq!(wakes.count(), 0, "an unmoved schedule woke the waiter"); // A target that moves and moves back before the reader looks is no change. assert!(audio.set_target(Duration::from_millis(400))); assert!(audio.set_target(Duration::from_millis(200))); assert!(reader.poll_changed(&waiter, seen).is_pending()); // The reference passing to another anchor on the same line, as the track // holding it goes and then as the last one leaves its schedule behind, // moves no due time. let data = clock.track(Kind::Data); assert!(!data.received(ms(40), start.saturating_add(Duration::from_millis(40)))); drop(video); assert!(reader.poll_changed(&waiter, seen).is_pending()); drop(data); assert!(reader.poll_changed(&waiter, seen).is_pending()); } /// A producer reset onto a clock that schedules the same way leaves the /// reader waiting, now on the new clock. #[test] fn the_change_waiter_follows_a_producer_reset() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let reader = clock.consume(); let seen = reader.schedule(); let (wakes, waiter) = Wakes::waiter(); assert!(reader.poll_changed(&waiter, seen).is_pending()); let clock = clock.reset(DELAY); assert!(wakes.count() > 0, "the reset left the reader on the old clock"); assert!(reader.poll_changed(&waiter, seen).is_pending()); let woken = wakes.count(); let video = clock.track(Kind::Video); assert!(video.received(ms(0), start)); assert!(wakes.count() > woken, "the reader still waits on the old clock"); assert_eq!(reader.poll_changed(&waiter, seen), Poll::Ready(reader.schedule())); } /// A stale clone's reset replaces the clock readers follow, not its own, and /// wakes them on that one. #[test] fn the_change_waiter_follows_a_stale_clone_reset() { let clock = Producer::new(DELAY); let stale = clock.clone(); let reader = clock.consume(); let _current = clock.reset(DELAY); let seen = reader.schedule(); let (wakes, waiter) = Wakes::waiter(); assert!(reader.poll_changed(&waiter, seen).is_pending()); let replaced = stale.reset(Duration::from_millis(300)); assert!(wakes.count() > 0, "the reset left the reader on the clock it replaced"); let Poll::Ready(moved) = reader.poll_changed(&waiter, seen) else { panic!("the reset did not resolve the wait"); }; assert_eq!(moved.delay(), Duration::from_millis(300)); drop(replaced); } /// One move wakes every reader of the clock, clones and separate consumers alike. #[test] fn the_change_waiter_wakes_every_reader() { let start = Instant::ZERO.saturating_add(Duration::from_secs(1)); let clock = Producer::new(DELAY); let first = clock.consume(); let readers = [first.clone(), first, clock.consume()]; let video = clock.track(Kind::Video); let seen = readers[0].schedule(); let waiters: Vec<_> = readers .iter() .map(|reader| { let (wakes, waiter) = Wakes::waiter(); assert!(reader.poll_changed(&waiter, seen).is_pending()); (wakes, waiter) }) .collect(); video.received(ms(0), start); for (reader, (wakes, waiter)) in readers.iter().zip(&waiters) { assert!(wakes.count() > 0, "a reader slept through the move"); assert_eq!(reader.poll_changed(waiter, seen), Poll::Ready(reader.schedule())); } } /// Dropping a wait loses nothing: a move made while no wait is pending /// resolves the next one at once. #[kio::test] async fn a_dropped_change_wait_keeps_the_move() { let clock = Producer::new(DELAY); let reader = clock.consume(); let video = clock.track(Kind::Video); video.received(ms(0), kio::clock::now()); let seen = reader.schedule(); { let mut wait = std::pin::pin!(reader.changed(seen)); assert!(futures::poll!(wait.as_mut()).is_pending()); } assert!(video.set_target(Duration::from_millis(300))); let moved = reader.changed(seen).await; assert_eq!(moved.delay(), Duration::from_millis(300)); assert_eq!(moved, reader.schedule()); } /// A presenter asleep on a picture's due time wakes when the delay drops, /// and presents at the new due time instead of the one it slept on. #[kio::test] async fn a_presenter_reschedules_when_the_delay_moves() { use futures::future::{Either, select}; let clock = Producer::new(Duration::from_millis(500)); let reader = clock.consume(); let video = clock.track(Kind::Video); let start = kio::clock::now(); video.received(ms(0), start); let present = async { let mut schedule = reader.schedule(); loop { let due = schedule.due(ms(0)).expect("anchored"); let sleep = std::pin::pin!(kio::clock::sleep_until(due)); let moved = std::pin::pin!(reader.changed(schedule)); match select(sleep, moved).await { Either::Left(_) => return kio::clock::now(), Either::Right((moved, _)) => schedule = moved, } } }; let lower = async { kio::clock::sleep(Duration::from_millis(100)).await; assert!(video.set_target(Duration::from_millis(200))); }; let (presented, ()) = futures::join!(present, lower); assert_eq!(presented, start.saturating_add(Duration::from_millis(200))); } }