forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6a8d990Tahinli16 days ago1049 commits

clock.rs426 lines, 14.4 KiBHistoryRawDownload
1//! Playback master clock: the one answer to "what time is it in this timeline?".
2//!
3//! Audio owns the clock whenever it plays -- the app polls the audio plugin and
4//! feeds the sample position in with [`PlaybackClock::set_audio_position`]. With
5//! no audio (muted, video-only, past audio EOF) the clock is anchored to an
6//! [`Instant`] instead. Both modes are the same timeline, so switching mid-play
7//! re-anchors at the current time and never jumps.
8//!
9//! Granularity contract: in audio mode `now()` steps at the audio quantum, not
10//! smoothly. The reported position advances once per 256-1024 frame buffer
11//! (5-23 ms at 48 kHz) while the app polls per rendered frame (~16 ms), so two
12//! consecutive polls can return the same time and the next can jump by a whole
13//! quantum. That is below the app's drift threshold, so it costs nothing today.
14//! Smoothing (interpolating with the report's own timestamp) belongs on the
15//! audio-plugin side where that timestamp exists, not here.
16//!
17//! Drift policy -- whether a late frame is dropped or an early one held -- is the
18//! app's; this type only reports time.
19
20use std::time::Instant;
21
22/// What drives [`PlaybackClock::now`].
23#[derive(Clone, Copy, PartialEq, Eq, Debug)]
24pub enum ClockSource {
25 /// Externally reported audio sample position.
26 Audio,
27 /// Elapsed wall time since the last anchor.
28 Wall,
29}
30
31/// Playback position, in seconds. `Send`, with no threads or I/O of its own:
32/// every state change is an explicit call.
33///
34/// Forward at 1x it never decreases while playing. At any other rate it runs
35/// on wall time, scaled by [`rate`](Self::rate): forward at 2/4/8x, backward at
36/// -1/-2x. A backward clock stops at zero rather than going negative.
37pub struct PlaybackClock {
38 source: ClockSource,
39 playing: bool,
40 /// Signed speed of the wall clock; 1.0 is real time. Audio never runs at
41 /// any other rate (see [`set_rate`](Self::set_rate)), so the audio arm of
42 /// [`now`](Self::now) ignores it.
43 rate: f64,
44 /// Timeline position of the current anchor. While paused this *is* `now()`.
45 base: f64,
46 /// Wall anchor; only meaningful while playing in [`ClockSource::Wall`].
47 anchor: Instant,
48 /// Audio position at the anchor, `None` until the first report after a
49 /// re-anchor. Reports are relative to this, so a stream that restarts its
50 /// sample counter after a seek re-syncs instead of jumping.
51 audio_ref: Option<f64>,
52 /// Last accepted report, to clamp a position that runs backwards.
53 audio_last: f64,
54}
55
56impl PlaybackClock {
57 /// A paused clock at t=0.
58 pub fn new(source: ClockSource) -> Self {
59 Self {
60 source,
61 playing: false,
62 rate: 1.0,
63 base: 0.0,
64 anchor: Instant::now(),
65 audio_ref: None,
66 audio_last: 0.0,
67 }
68 }
69
70 pub fn source(&self) -> ClockSource {
71 self.source
72 }
73
74 pub fn is_playing(&self) -> bool {
75 self.playing
76 }
77
78 pub fn rate(&self) -> f64 {
79 self.rate
80 }
81
82 /// Current timeline position in seconds. Frozen exactly while paused. While
83 /// playing at 1x it never decreases; at another rate it moves at that rate
84 /// and stops at zero going backward.
85 pub fn now(&self) -> f64 {
86 if !self.playing {
87 return self.base;
88 }
89 match self.source {
90 ClockSource::Wall => {
91 (self.base + self.anchor.elapsed().as_secs_f64() * self.rate).max(0.0)
92 }
93 ClockSource::Audio => match self.audio_ref {
94 Some(r) => self.base + (self.audio_last - r),
95 None => self.base,
96 },
97 }
98 }
99
100 /// Resumes from wherever `now()` was frozen. No-op if already playing.
101 pub fn play(&mut self) {
102 if !self.playing {
103 self.playing = true;
104 self.reanchor(self.base);
105 }
106 }
107
108 pub fn pause(&mut self) {
109 if self.playing {
110 self.base = self.now();
111 self.playing = false;
112 }
113 }
114
115 /// Sets the speed. Any rate other than 1.0 switches to wall time and the
116 /// caller must keep audio silent: a clock on wall time never feeds
117 /// [`set_audio_position`](Self::set_audio_position) backward. The change
118 /// is continuous -- `now()` is read at the old rate first, then the anchor
119 /// moves to it. Going back to 1.0 leaves the source as it is; the caller
120 /// reopens audio with [`switch_to_audio`](Self::switch_to_audio) at the
121 /// current position.
122 pub fn set_rate(&mut self, rate: f64) {
123 if rate == self.rate {
124 return;
125 }
126 if rate != 1.0 {
127 self.switch_to_wall();
128 } else {
129 self.reanchor(self.now());
130 }
131 self.rate = rate;
132 }
133
134 /// Repositions the timeline to `secs`, playing or paused.
135 pub fn seek_to(&mut self, secs: f64) {
136 self.reanchor(secs);
137 }
138
139 /// Audio EOF: keeps the clock running off wall time from the current
140 /// position, so `now()` is continuous across the switch.
141 pub fn switch_to_wall(&mut self) {
142 self.reanchor(self.now());
143 self.source = ClockSource::Wall;
144 }
145
146 /// Hands the clock back to audio from the current position. The next
147 /// reported sample position becomes the new reference whatever its value.
148 /// Only valid at 1x: call [`set_rate`](Self::set_rate)`(1.0)` first.
149 pub fn switch_to_audio(&mut self) {
150 debug_assert_eq!(self.rate, 1.0, "audio clock runs only at 1x");
151 self.reanchor(self.now());
152 self.source = ClockSource::Audio;
153 }
154
155 /// The app's audio position poll. Ignored in wall mode, and ignored when it
156 /// runs backwards (a device reset restarts the counter) so playback time
157 /// never rewinds under the renderer; the app re-syncs with `seek_to` or
158 /// `switch_to_wall`.
159 pub fn set_audio_position(&mut self, samples_played: u64, sample_rate: u32) {
160 if sample_rate == 0 {
161 return;
162 }
163 let secs = samples_played as f64 / sample_rate as f64;
164 match self.audio_ref {
165 None => {
166 self.audio_ref = Some(secs);
167 self.audio_last = secs;
168 }
169 Some(_) if secs > self.audio_last => self.audio_last = secs,
170 Some(_) => {}
171 }
172 }
173
174 /// Makes `base` the current position and drops both source references, so
175 /// the next wall tick or audio report continues from there.
176 fn reanchor(&mut self, secs: f64) {
177 self.base = secs;
178 self.anchor = Instant::now();
179 self.audio_ref = None;
180 self.audio_last = 0.0;
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187 use std::thread::sleep;
188 use std::time::Duration;
189
190 const RATE: u32 = 48_000;
191
192 /// The app moves the clock between threads/closures.
193 fn _assert_send<T: Send>() {}
194 const _: fn() = || _assert_send::<PlaybackClock>();
195
196 fn audio_playing() -> PlaybackClock {
197 let mut c = PlaybackClock::new(ClockSource::Audio);
198 c.play();
199 c
200 }
201
202 #[test]
203 fn audio_follows_reports_exactly() {
204 let mut c = audio_playing();
205 assert_eq!(c.now(), 0.0);
206 c.set_audio_position(0, RATE); // first report sets the reference
207 assert_eq!(c.now(), 0.0);
208 c.set_audio_position(48_000, RATE);
209 assert_eq!(c.now(), 1.0);
210 c.set_audio_position(72_000, RATE);
211 assert_eq!(c.now(), 1.5);
212 }
213
214 #[test]
215 fn audio_reference_is_relative_not_absolute() {
216 // A stream already 10 s in still starts this clock's timeline at 0.
217 let mut c = audio_playing();
218 c.set_audio_position(480_000, RATE);
219 assert_eq!(c.now(), 0.0);
220 c.set_audio_position(504_000, RATE);
221 assert_eq!(c.now(), 0.5);
222 }
223
224 #[test]
225 fn audio_regression_clamps() {
226 let mut c = audio_playing();
227 c.set_audio_position(0, RATE);
228 c.set_audio_position(96_000, RATE);
229 assert_eq!(c.now(), 2.0);
230 c.set_audio_position(24_000, RATE); // device reset
231 assert_eq!(c.now(), 2.0, "clock must not rewind");
232 c.set_audio_position(0, RATE);
233 assert_eq!(c.now(), 2.0);
234 c.set_audio_position(120_000, RATE); // recovered, forward again
235 assert_eq!(c.now(), 2.5);
236 }
237
238 #[test]
239 fn zero_sample_rate_ignored() {
240 let mut c = audio_playing();
241 c.set_audio_position(1_000, 0);
242 assert_eq!(c.now(), 0.0);
243 }
244
245 #[test]
246 fn pause_freezes_and_play_resumes() {
247 let mut c = audio_playing();
248 c.set_audio_position(0, RATE);
249 c.set_audio_position(48_000, RATE);
250 c.pause();
251 assert!(!c.is_playing());
252 assert_eq!(c.now(), 1.0);
253 // Audio keeps running for a moment after a pause request; ignored.
254 c.set_audio_position(60_000, RATE);
255 assert_eq!(c.now(), 1.0);
256 c.play();
257 assert_eq!(c.now(), 1.0, "no time gained across the pause");
258 c.set_audio_position(72_000, RATE); // stream restarted mid-buffer
259 assert_eq!(c.now(), 1.0);
260 c.set_audio_position(96_000, RATE);
261 assert_eq!(c.now(), 1.5);
262 }
263
264 #[test]
265 fn wall_advances_with_real_time() {
266 let mut c = PlaybackClock::new(ClockSource::Wall);
267 c.play();
268 sleep(Duration::from_millis(120));
269 let t = c.now();
270 assert!((0.05..0.60).contains(&t), "wall clock at {t}");
271 c.pause();
272 let frozen = c.now();
273 sleep(Duration::from_millis(120));
274 assert_eq!(c.now(), frozen, "paused wall clock must not move");
275 c.play();
276 assert!(c.now() - frozen < 0.05);
277 sleep(Duration::from_millis(120));
278 assert!(c.now() > frozen + 0.05);
279 }
280
281 #[test]
282 fn switch_to_wall_is_continuous() {
283 let mut c = audio_playing();
284 c.set_audio_position(0, RATE);
285 c.set_audio_position(96_000, RATE);
286 let x = c.now();
287 c.switch_to_wall();
288 assert_eq!(c.source(), ClockSource::Wall);
289 assert!((c.now() - x).abs() < 0.01, "jumped from {x} to {}", c.now());
290 sleep(Duration::from_millis(120));
291 assert!(c.now() > x + 0.05, "wall clock did not take over");
292 }
293
294 #[test]
295 fn switch_to_audio_is_continuous() {
296 let mut c = PlaybackClock::new(ClockSource::Wall);
297 c.play();
298 sleep(Duration::from_millis(50));
299 let before = c.now();
300 c.switch_to_audio();
301 let x = c.now();
302 assert!((x - before).abs() < 0.01, "jumped from {before} to {x}");
303 assert_eq!(c.now(), x, "audio mode holds until the first report");
304 c.set_audio_position(240_000, RATE);
305 assert_eq!(c.now(), x);
306 c.set_audio_position(264_000, RATE);
307 assert_eq!(c.now(), x + 0.5);
308 }
309
310 #[test]
311 fn seek_while_paused() {
312 let mut c = PlaybackClock::new(ClockSource::Wall);
313 c.seek_to(12.0);
314 assert_eq!(c.now(), 12.0);
315 sleep(Duration::from_millis(50));
316 assert_eq!(c.now(), 12.0, "seek must not start the clock");
317 c.play();
318 sleep(Duration::from_millis(120));
319 let t = c.now();
320 assert!((12.05..12.60).contains(&t), "resumed at {t}");
321 }
322
323 #[test]
324 fn seek_while_playing_audio() {
325 let mut c = audio_playing();
326 c.set_audio_position(0, RATE);
327 c.set_audio_position(48_000, RATE);
328 c.seek_to(30.0);
329 assert_eq!(c.now(), 30.0);
330 // The app restarts the stream, so the counter comes back from zero.
331 c.set_audio_position(0, RATE);
332 assert_eq!(c.now(), 30.0);
333 c.set_audio_position(24_000, RATE);
334 assert_eq!(c.now(), 30.5);
335 assert!(c.is_playing());
336 }
337
338 #[test]
339 fn seek_while_playing_wall() {
340 let mut c = PlaybackClock::new(ClockSource::Wall);
341 c.play();
342 sleep(Duration::from_millis(50));
343 c.seek_to(5.0);
344 assert!((c.now() - 5.0).abs() < 0.01);
345 sleep(Duration::from_millis(120));
346 assert!(c.now() > 5.05);
347 }
348 #[test]
349 fn rate_defaults_to_real_time() {
350 let c = PlaybackClock::new(ClockSource::Wall);
351 assert_eq!(c.rate(), 1.0);
352 }
353
354 #[test]
355 fn set_rate_while_paused_moves_nothing() {
356 let mut c = PlaybackClock::new(ClockSource::Wall);
357 c.seek_to(7.0);
358 c.set_rate(4.0);
359 assert_eq!(c.rate(), 4.0);
360 assert_eq!(c.now(), 7.0);
361 sleep(Duration::from_millis(50));
362 assert_eq!(c.now(), 7.0, "paused clock must not run at any rate");
363 }
364
365 #[test]
366 fn faster_rate_advances_faster() {
367 let mut c = PlaybackClock::new(ClockSource::Wall);
368 c.set_rate(8.0);
369 c.play();
370 sleep(Duration::from_millis(100));
371 let t = c.now();
372 assert!((0.5..3.0).contains(&t), "8x after 100 ms at {t}");
373 }
374
375 #[test]
376 fn reverse_rate_runs_backward_and_stops_at_zero() {
377 let mut c = PlaybackClock::new(ClockSource::Wall);
378 c.seek_to(10.0);
379 c.set_rate(-2.0);
380 c.play();
381 sleep(Duration::from_millis(100));
382 let t = c.now();
383 assert!(t < 10.0 - 0.1 && t > 9.0, "-2x after 100 ms at {t}");
384 c.seek_to(0.05);
385 sleep(Duration::from_millis(100));
386 assert_eq!(c.now(), 0.0, "backward clock must clamp at zero");
387 }
388
389 #[test]
390 fn set_rate_is_continuous() {
391 let mut c = PlaybackClock::new(ClockSource::Wall);
392 c.play();
393 sleep(Duration::from_millis(30));
394 let before = c.now();
395 c.set_rate(2.0);
396 assert!((c.now() - before).abs() < 0.01, "jumped on rate change");
397 c.set_rate(1.0);
398 assert!((c.now() - before).abs() < 0.01, "jumped back to 1x");
399 }
400
401 #[test]
402 fn leaving_audio_for_a_rate_switches_to_wall_without_a_jump() {
403 let mut c = audio_playing();
404 c.set_audio_position(0, RATE);
405 c.set_audio_position(96_000, RATE);
406 let x = c.now();
407 c.set_rate(2.0);
408 assert_eq!(c.source(), ClockSource::Wall);
409 assert!((c.now() - x).abs() < 0.01, "jumped from {x} to {}", c.now());
410 // Audio reports arriving now are ignored: wall time owns the clock.
411 c.set_audio_position(480_000, RATE);
412 assert!((c.now() - x).abs() < 0.05, "audio report moved a wall clock");
413 }
414
415 #[test]
416 fn rate_changes_while_playing_do_not_rewind() {
417 let mut c = PlaybackClock::new(ClockSource::Wall);
418 c.seek_to(5.0);
419 c.play();
420 c.set_rate(-1.0);
421 let at = c.now();
422 c.set_rate(1.0);
423 assert!((c.now() - at).abs() < 0.01);
424 assert!(c.now() >= 4.99);
425 }
426}