forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcda6d0eTahinli3 months ago476 commits

clock.rs311 lines, 10.3 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/// Monotonic-while-playing playback position, in seconds. `Send`, with no
32/// threads or I/O of its own: every state change is an explicit call.
33pub struct PlaybackClock {
34 source: ClockSource,
35 playing: bool,
36 /// Timeline position of the current anchor. While paused this *is* `now()`.
37 base: f64,
38 /// Wall anchor; only meaningful while playing in [`ClockSource::Wall`].
39 anchor: Instant,
40 /// Audio position at the anchor, `None` until the first report after a
41 /// re-anchor. Reports are relative to this, so a stream that restarts its
42 /// sample counter after a seek re-syncs instead of jumping.
43 audio_ref: Option<f64>,
44 /// Last accepted report, to clamp a position that runs backwards.
45 audio_last: f64,
46}
47
48impl PlaybackClock {
49 /// A paused clock at t=0.
50 pub fn new(source: ClockSource) -> Self {
51 Self {
52 source,
53 playing: false,
54 base: 0.0,
55 anchor: Instant::now(),
56 audio_ref: None,
57 audio_last: 0.0,
58 }
59 }
60
61 pub fn source(&self) -> ClockSource {
62 self.source
63 }
64
65 pub fn is_playing(&self) -> bool {
66 self.playing
67 }
68
69 /// Current timeline position in seconds. Frozen exactly while paused, never
70 /// decreasing while playing.
71 pub fn now(&self) -> f64 {
72 if !self.playing {
73 return self.base;
74 }
75 match self.source {
76 ClockSource::Wall => self.base + self.anchor.elapsed().as_secs_f64(),
77 ClockSource::Audio => match self.audio_ref {
78 Some(r) => self.base + (self.audio_last - r),
79 None => self.base,
80 },
81 }
82 }
83
84 /// Resumes from wherever `now()` was frozen. No-op if already playing.
85 pub fn play(&mut self) {
86 if !self.playing {
87 self.playing = true;
88 self.reanchor(self.base);
89 }
90 }
91
92 pub fn pause(&mut self) {
93 if self.playing {
94 self.base = self.now();
95 self.playing = false;
96 }
97 }
98
99 /// Repositions the timeline to `secs`, playing or paused.
100 pub fn seek_to(&mut self, secs: f64) {
101 self.reanchor(secs);
102 }
103
104 /// Audio EOF: keeps the clock running off wall time from the current
105 /// position, so `now()` is continuous across the switch.
106 pub fn switch_to_wall(&mut self) {
107 self.reanchor(self.now());
108 self.source = ClockSource::Wall;
109 }
110
111 /// Hands the clock back to audio from the current position. The next
112 /// reported sample position becomes the new reference whatever its value.
113 pub fn switch_to_audio(&mut self) {
114 self.reanchor(self.now());
115 self.source = ClockSource::Audio;
116 }
117
118 /// The app's audio position poll. Ignored in wall mode, and ignored when it
119 /// runs backwards (a device reset restarts the counter) so playback time
120 /// never rewinds under the renderer; the app re-syncs with `seek_to` or
121 /// `switch_to_wall`.
122 pub fn set_audio_position(&mut self, samples_played: u64, sample_rate: u32) {
123 if sample_rate == 0 {
124 return;
125 }
126 let secs = samples_played as f64 / sample_rate as f64;
127 match self.audio_ref {
128 None => {
129 self.audio_ref = Some(secs);
130 self.audio_last = secs;
131 }
132 Some(_) if secs > self.audio_last => self.audio_last = secs,
133 Some(_) => {}
134 }
135 }
136
137 /// Makes `base` the current position and drops both source references, so
138 /// the next wall tick or audio report continues from there.
139 fn reanchor(&mut self, secs: f64) {
140 self.base = secs;
141 self.anchor = Instant::now();
142 self.audio_ref = None;
143 self.audio_last = 0.0;
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use std::thread::sleep;
151 use std::time::Duration;
152
153 const RATE: u32 = 48_000;
154
155 /// The app moves the clock between threads/closures.
156 fn _assert_send<T: Send>() {}
157 const _: fn() = || _assert_send::<PlaybackClock>();
158
159 fn audio_playing() -> PlaybackClock {
160 let mut c = PlaybackClock::new(ClockSource::Audio);
161 c.play();
162 c
163 }
164
165 #[test]
166 fn audio_follows_reports_exactly() {
167 let mut c = audio_playing();
168 assert_eq!(c.now(), 0.0);
169 c.set_audio_position(0, RATE); // first report sets the reference
170 assert_eq!(c.now(), 0.0);
171 c.set_audio_position(48_000, RATE);
172 assert_eq!(c.now(), 1.0);
173 c.set_audio_position(72_000, RATE);
174 assert_eq!(c.now(), 1.5);
175 }
176
177 #[test]
178 fn audio_reference_is_relative_not_absolute() {
179 // A stream already 10 s in still starts this clock's timeline at 0.
180 let mut c = audio_playing();
181 c.set_audio_position(480_000, RATE);
182 assert_eq!(c.now(), 0.0);
183 c.set_audio_position(504_000, RATE);
184 assert_eq!(c.now(), 0.5);
185 }
186
187 #[test]
188 fn audio_regression_clamps() {
189 let mut c = audio_playing();
190 c.set_audio_position(0, RATE);
191 c.set_audio_position(96_000, RATE);
192 assert_eq!(c.now(), 2.0);
193 c.set_audio_position(24_000, RATE); // device reset
194 assert_eq!(c.now(), 2.0, "clock must not rewind");
195 c.set_audio_position(0, RATE);
196 assert_eq!(c.now(), 2.0);
197 c.set_audio_position(120_000, RATE); // recovered, forward again
198 assert_eq!(c.now(), 2.5);
199 }
200
201 #[test]
202 fn zero_sample_rate_ignored() {
203 let mut c = audio_playing();
204 c.set_audio_position(1_000, 0);
205 assert_eq!(c.now(), 0.0);
206 }
207
208 #[test]
209 fn pause_freezes_and_play_resumes() {
210 let mut c = audio_playing();
211 c.set_audio_position(0, RATE);
212 c.set_audio_position(48_000, RATE);
213 c.pause();
214 assert!(!c.is_playing());
215 assert_eq!(c.now(), 1.0);
216 // Audio keeps running for a moment after a pause request; ignored.
217 c.set_audio_position(60_000, RATE);
218 assert_eq!(c.now(), 1.0);
219 c.play();
220 assert_eq!(c.now(), 1.0, "no time gained across the pause");
221 c.set_audio_position(72_000, RATE); // stream restarted mid-buffer
222 assert_eq!(c.now(), 1.0);
223 c.set_audio_position(96_000, RATE);
224 assert_eq!(c.now(), 1.5);
225 }
226
227 #[test]
228 fn wall_advances_with_real_time() {
229 let mut c = PlaybackClock::new(ClockSource::Wall);
230 c.play();
231 sleep(Duration::from_millis(120));
232 let t = c.now();
233 assert!((0.05..0.60).contains(&t), "wall clock at {t}");
234 c.pause();
235 let frozen = c.now();
236 sleep(Duration::from_millis(120));
237 assert_eq!(c.now(), frozen, "paused wall clock must not move");
238 c.play();
239 assert!(c.now() - frozen < 0.05);
240 sleep(Duration::from_millis(120));
241 assert!(c.now() > frozen + 0.05);
242 }
243
244 #[test]
245 fn switch_to_wall_is_continuous() {
246 let mut c = audio_playing();
247 c.set_audio_position(0, RATE);
248 c.set_audio_position(96_000, RATE);
249 let x = c.now();
250 c.switch_to_wall();
251 assert_eq!(c.source(), ClockSource::Wall);
252 assert!((c.now() - x).abs() < 0.01, "jumped from {x} to {}", c.now());
253 sleep(Duration::from_millis(120));
254 assert!(c.now() > x + 0.05, "wall clock did not take over");
255 }
256
257 #[test]
258 fn switch_to_audio_is_continuous() {
259 let mut c = PlaybackClock::new(ClockSource::Wall);
260 c.play();
261 sleep(Duration::from_millis(50));
262 let before = c.now();
263 c.switch_to_audio();
264 let x = c.now();
265 assert!((x - before).abs() < 0.01, "jumped from {before} to {x}");
266 assert_eq!(c.now(), x, "audio mode holds until the first report");
267 c.set_audio_position(240_000, RATE);
268 assert_eq!(c.now(), x);
269 c.set_audio_position(264_000, RATE);
270 assert_eq!(c.now(), x + 0.5);
271 }
272
273 #[test]
274 fn seek_while_paused() {
275 let mut c = PlaybackClock::new(ClockSource::Wall);
276 c.seek_to(12.0);
277 assert_eq!(c.now(), 12.0);
278 sleep(Duration::from_millis(50));
279 assert_eq!(c.now(), 12.0, "seek must not start the clock");
280 c.play();
281 sleep(Duration::from_millis(120));
282 let t = c.now();
283 assert!((12.05..12.60).contains(&t), "resumed at {t}");
284 }
285
286 #[test]
287 fn seek_while_playing_audio() {
288 let mut c = audio_playing();
289 c.set_audio_position(0, RATE);
290 c.set_audio_position(48_000, RATE);
291 c.seek_to(30.0);
292 assert_eq!(c.now(), 30.0);
293 // The app restarts the stream, so the counter comes back from zero.
294 c.set_audio_position(0, RATE);
295 assert_eq!(c.now(), 30.0);
296 c.set_audio_position(24_000, RATE);
297 assert_eq!(c.now(), 30.5);
298 assert!(c.is_playing());
299 }
300
301 #[test]
302 fn seek_while_playing_wall() {
303 let mut c = PlaybackClock::new(ClockSource::Wall);
304 c.play();
305 sleep(Duration::from_millis(50));
306 c.seek_to(5.0);
307 assert!((c.now() - 5.0).abs() < 0.01);
308 sleep(Duration::from_millis(120));
309 assert!(c.now() > 5.05);
310 }
311}