1use model::Comp;
2use std::time::{Duration, Instant};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
5pub enum SyncMode {
6 /// Wall/audio clock master: skips frames to hold real-time FPS.
7 RealtimeDrop,
8 /// Steps exactly +1 integer frame, throttled so it never runs faster than `comp.fps`.
9 EveryFrame,
10}
11
12/// Outcome of advancing [`PlaybackClock::tick_synced`].
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub struct TickResult {
15 pub playing: bool,
16 pub frame_changed: bool,
17 pub looped: bool,
18}
19
20/// Shared timeline & playback clock shared across all open viewers (Viewer 1, Viewer 2, Spline).
21pub struct PlaybackClock {
22 pub current_frame: f64,
23 pub playing: bool,
24 pub sync_mode: SyncMode,
25 /// Optional user-defined preview/export `[in, out]` frame markers (inclusive).
26 pub in_out_range: [Option<i64>; 2],
27 anchor_time: Instant,
28 anchor_frame: f64,
29 last_every_step: Instant,
30}
31
32impl Default for PlaybackClock {
33 fn default() -> Self {
34 Self::new()
35 }
36}
37
38impl PlaybackClock {
39 pub fn new() -> Self {
40 let now = Instant::now();
41 Self {
42 current_frame: 0.0,
43 playing: false,
44 sync_mode: SyncMode::RealtimeDrop,
45 in_out_range: [None, None],
46 anchor_time: now,
47 anchor_frame: 0.0,
48 last_every_step: now,
49 }
50 }
51
52 pub fn init_from_comp(&mut self, comp: &Comp) {
53 let cur = comp.current_time.round();
54 let r0 = comp.render_range[0] as f64;
55 let r1 = comp.render_range[1] as f64;
56 self.current_frame = if cur >= r0 && cur <= r1 { cur } else { r0 };
57 self.in_out_range = [None, None];
58 self.anchor_frame = self.current_frame;
59 self.anchor_time = Instant::now();
60 self.last_every_step = self.anchor_time;
61 }
62
63 /// Returns the active inclusive preview/export range `[in.unwrap_or(r0), out.unwrap_or(r1)]`,
64 /// clamped to `comp.render_range` and sorted ascending.
65 pub fn effective_preview_range(&self, comp: &Comp) -> [i64; 2] {
66 let r0 = comp.render_range[0];
67 let r1 = comp.render_range[1].max(r0);
68 let a = self.in_out_range[0].unwrap_or(r0).clamp(r0, r1);
69 let b = self.in_out_range[1].unwrap_or(r1).clamp(r0, r1);
70 if a <= b { [a, b] } else { [b, a] }
71 }
72
73 pub fn set_in_point(&mut self, comp: &Comp) {
74 let r0 = comp.render_range[0];
75 let r1 = comp.render_range[1].max(r0);
76 let f = (self.current_frame.round() as i64).clamp(r0, r1);
77 self.in_out_range[0] = Some(f);
78 if self.playing {
79 let [p0, p1] = self.effective_preview_range(comp);
80 if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 {
81 self.current_frame = p0 as f64;
82 }
83 let now = Instant::now();
84 self.anchor_time = now;
85 self.anchor_frame = self.current_frame;
86 self.last_every_step = now;
87 }
88 }
89
90 pub fn set_out_point(&mut self, comp: &Comp) {
91 let r0 = comp.render_range[0];
92 let r1 = comp.render_range[1].max(r0);
93 let f = (self.current_frame.round() as i64).clamp(r0, r1);
94 self.in_out_range[1] = Some(f);
95 if self.playing {
96 let [p0, p1] = self.effective_preview_range(comp);
97 if self.current_frame < p0 as f64 || self.current_frame > p1 as f64 {
98 self.current_frame = p0 as f64;
99 }
100 let now = Instant::now();
101 self.anchor_time = now;
102 self.anchor_frame = self.current_frame;
103 self.last_every_step = now;
104 }
105 }
106
107 pub fn clear_in_out(&mut self) {
108 self.in_out_range = [None, None];
109 if self.playing {
110 let now = Instant::now();
111 self.anchor_time = now;
112 self.anchor_frame = self.current_frame;
113 self.last_every_step = now;
114 }
115 }
116
117 /// Exact audio track timestamp (in seconds) for `frame` under `comp.fps` and `comp.audio_offset`.
118 pub fn audio_time_for_frame(comp: &Comp, frame: f64) -> f64 {
119 let f = if frame.is_finite() { frame } else { 0.0 };
120 let offset = if comp.audio_offset.is_finite() { comp.audio_offset } else { 0.0 };
121 (f - offset) / safe_fps(comp.fps)
122 }
123
124 /// Exact audio track timestamp (in seconds) for the current playhead frame.
125 pub fn audio_target_secs(&self, comp: &Comp) -> f64 {
126 Self::audio_time_for_frame(comp, self.current_frame)
127 }
128
129 /// Expected live audio playback timestamp (in seconds) at wall-clock `now`.
130 ///
131 /// In `RealtimeDrop`, tracks continuous wall-clock frame progress across the preview range.
132 /// In `EveryFrame`, bounds sub-frame progress to `[0, 1/fps]` so slow frame renders do not
133 /// let the audio stream drift ahead of the displayed frame.
134 pub fn expected_audio_secs(&self, comp: &Comp, now: Instant) -> f64 {
135 let fps = safe_fps(comp.fps);
136 if !self.playing {
137 return Self::audio_time_for_frame(comp, self.current_frame);
138 }
139 match self.sync_mode {
140 SyncMode::RealtimeDrop => {
141 let [p0, p1] = self.effective_preview_range(comp);
142 let r0 = p0 as f64;
143 let r1 = p1.max(p0) as f64;
144 let span = (r1 - r0 + 1.0).max(1.0);
145 if span <= 1.0 {
146 return Self::audio_time_for_frame(comp, r0);
147 }
148 let base = if !self.anchor_frame.is_finite() || self.anchor_frame < r0 || self.anchor_frame > r1 {
149 r0
150 } else {
151 self.anchor_frame
152 };
153 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();
154 let continuous = r0 + (base - r0 + elapsed * fps).rem_euclid(span);
155 Self::audio_time_for_frame(comp, continuous)
156 }
157 SyncMode::EveryFrame => {
158 let frame_dur = 1.0 / fps;
159 let sub = now
160 .saturating_duration_since(self.last_every_step)
161 .as_secs_f64()
162 .clamp(0.0, frame_dur);
163 Self::audio_time_for_frame(comp, self.current_frame) + sub
164 }
165 }
166 }
167
168 pub fn set_frame(&mut self, comp: &Comp, frame: f64, now: Instant) -> bool {
169 if !frame.is_finite() {
170 return false;
171 }
172 let [g0, g1] = safe_range(comp.global_range);
173 let clamped = frame.round().clamp(g0 as f64, g1 as f64);
174 let changed = (clamped - self.current_frame).abs() > 1e-6;
175 self.current_frame = clamped;
176 if self.playing {
177 self.anchor_time = now;
178 self.anchor_frame = self.current_frame;
179 self.last_every_step = now;
180 }
181 changed
182 }
183
184 pub fn toggle_play(&mut self, now: Instant) {
185 self.playing = !self.playing;
186 self.anchor_time = now;
187 self.anchor_frame = self.current_frame;
188 self.last_every_step = now;
189 }
190
191 /// Toggles playback and, when starting, snaps playhead into `effective_preview_range(comp)`
192 /// if it was outside so video and audio start locked on the same frame.
193 pub fn toggle_play_with_comp(&mut self, comp: &Comp, now: Instant) {
194 self.playing = !self.playing;
195 if self.playing {
196 let [p0, p1] = self.effective_preview_range(comp);
197 let r0 = p0 as f64;
198 let r1 = p1.max(p0) as f64;
199 if self.current_frame < r0 || self.current_frame > r1 {
200 self.current_frame = r0;
201 }
202 }
203 self.anchor_time = now;
204 self.anchor_frame = self.current_frame;
205 self.last_every_step = now;
206 }
207
208 /// Advances the playback clock; returns `(still_playing, frame_changed)`.
209 /// In `EveryFrame` mode, throttles to `<= comp.fps` so it never runs faster than realtime!
210 pub fn tick(&mut self, comp: &Comp, now: Instant) -> (bool, bool) {
211 let res = self.tick_synced(comp, now);
212 (res.playing, res.frame_changed)
213 }
214
215 /// Advances the playback clock and reports frame change plus exact loop wraparound.
216 pub fn tick_synced(&mut self, comp: &Comp, now: Instant) -> TickResult {
217 if !self.playing {
218 return TickResult {
219 playing: false,
220 frame_changed: false,
221 looped: false,
222 };
223 }
224 let [p0, p1] = self.effective_preview_range(comp);
225 let r0 = p0 as f64;
226 let r1 = p1.max(p0) as f64;
227 let span = (r1 - r0 + 1.0).max(1.0);
228 let fps = safe_fps(comp.fps);
229 let frame_dur = Duration::from_secs_f64(1.0 / fps);
230 if !self.current_frame.is_finite() {
231 self.current_frame = r0;
232 }
233 if !self.anchor_frame.is_finite() {
234 self.anchor_frame = r0;
235 }
236
237 let mut changed = false;
238 let mut looped = false;
239 match self.sync_mode {
240 SyncMode::RealtimeDrop => {
241 if span <= 1.0 {
242 if (self.current_frame - r0).abs() >= 1.0 {
243 self.current_frame = r0;
244 changed = true;
245 }
246 self.anchor_frame = r0;
247 self.anchor_time = now;
248 } else {
249 if self.anchor_frame < r0 || self.anchor_frame > r1 {
250 self.anchor_frame = r0;
251 self.anchor_time = now;
252 if (self.current_frame - r0).abs() >= 1.0 {
253 self.current_frame = r0;
254 changed = true;
255 looped = true;
256 }
257 }
258 let elapsed = now.saturating_duration_since(self.anchor_time).as_secs_f64();
259 let adv = (elapsed * fps).floor();
260 let raw = (self.anchor_frame - r0) + adv;
261 let wrapped = raw >= span;
262 let next = r0 + raw.rem_euclid(span);
263 if wrapped {
264 // Keep the sub-frame overshoot so looping never drifts behind the wall clock.
265 let raw_sub = (elapsed * fps - adv) / fps;
266 let sub = if raw_sub.is_finite() { raw_sub.clamp(0.0, 1.0) } else { 0.0 };
267 let overshoot = Duration::from_secs_f64(sub);
268 self.anchor_frame = next;
269 self.anchor_time = now.checked_sub(overshoot).unwrap_or(now);
270 looped = true;
271 }
272 if (next - self.current_frame).abs() >= 1.0 {
273 self.current_frame = next;
274 changed = true;
275 }
276 }
277 }
278 SyncMode::EveryFrame => {
279 let elapsed = now.saturating_duration_since(self.last_every_step);
280 if elapsed >= frame_dur {
281 let out_or_end = self.current_frame + 1.0 > r1 || self.current_frame < r0;
282 let next = if out_or_end {
283 if span > 1.0 {
284 looped = true;
285 }
286 r0
287 } else {
288 self.current_frame + 1.0
289 };
290 if (next - self.current_frame).abs() >= 1.0 {
291 changed = true;
292 }
293 self.current_frame = next;
294 // Preserve exact cadence under minor timer jitter while avoiding catch-up bursts after stalls.
295 if elapsed < frame_dur.mul_f64(2.0) {
296 self.last_every_step += frame_dur;
297 } else {
298 self.last_every_step = now;
299 }
300 }
301 }
302 }
303 TickResult {
304 playing: true,
305 frame_changed: changed,
306 looped,
307 }
308 }
309
310 pub fn next_wake(&self, comp: &Comp) -> Duration {
311 let fps = safe_fps(comp.fps);
312 Duration::from_secs_f64((0.5 / fps).min(0.016))
313 }
314}
315
316fn safe_fps(fps: f64) -> f64 {
317 if fps.is_finite() { fps.clamp(1.0, 10_000.0) } else { 1.0 }
318}
319
320fn safe_range(range: [i64; 2]) -> [i64; 2] {
321 [range[0], range[1].max(range[0])]
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use crate::tests::test_comp;
328
329 #[test]
330 fn effective_preview_range_sorts_and_clamps() {
331 let comp = test_comp();
332 let mut clock = PlaybackClock::new();
333 clock.init_from_comp(&comp);
334 assert_eq!(clock.effective_preview_range(&comp), [10, 50]);
335
336 clock.in_out_range = [Some(20), None];
337 assert_eq!(clock.effective_preview_range(&comp), [20, 50]);
338
339 clock.in_out_range = [None, Some(30)];
340 assert_eq!(clock.effective_preview_range(&comp), [10, 30]);
341
342 // Reversed and out-of-bounds points get clamped and sorted cleanly
343 clock.in_out_range = [Some(99), Some(2)];
344 assert_eq!(clock.effective_preview_range(&comp), [10, 50]);
345
346 clock.in_out_range = [Some(35), Some(18)];
347 assert_eq!(clock.effective_preview_range(&comp), [18, 35]);
348 }
349
350 #[test]
351 fn playback_clock_in_out_wraparound_realtime_and_every_frame() {
352 let comp = test_comp(); // fps = 30, render_range = [10, 50]
353 let t0 = Instant::now();
354
355 // RealtimeDrop: starting outside [20, 24] snaps cleanly to 20, then wraps 24 -> 20
356 let mut rt = PlaybackClock::new();
357 rt.init_from_comp(&comp);
358 rt.in_out_range = [Some(20), Some(24)];
359 rt.set_frame(&comp, 12.0, t0); // outside In/Out range
360 rt.toggle_play_with_comp(&comp, t0);
361 assert_eq!(rt.current_frame, 20.0);
362
363 let step = Duration::from_secs_f64(1.0 / 30.0);
364 // Advance 4 frames -> frame 24 (last frame in [20..=24])
365 let r4 = rt.tick_synced(&comp, t0 + step * 4 + Duration::from_millis(2));
366 assert!(r4.playing);
367 assert!(r4.frame_changed);
368 assert!(!r4.looped);
369 assert_eq!(rt.current_frame, 24.0);
370
371 // Advance 5th frame -> wraps cleanly back to 20 and reports looped = true
372 let r5 = rt.tick_synced(&comp, t0 + step * 5 + Duration::from_millis(2));
373 assert!(r5.playing);
374 assert!(r5.frame_changed);
375 assert!(r5.looped);
376 assert_eq!(rt.current_frame, 20.0);
377
378 // Next frame after wrap advances from 20 -> 21 without double-looping
379 let r6 = rt.tick_synced(&comp, t0 + step * 6 + Duration::from_millis(4));
380 assert!(r6.frame_changed);
381 assert!(!r6.looped);
382 assert_eq!(rt.current_frame, 21.0);
383
384 // EveryFrame: steps +1 per >=1/fps, preserves cadence across minor jitter, wraps 22 -> 20
385 let mut ef = PlaybackClock::new();
386 ef.init_from_comp(&comp);
387 ef.sync_mode = SyncMode::EveryFrame;
388 ef.in_out_range = [Some(20), Some(22)];
389 ef.set_frame(&comp, 20.0, t0);
390 ef.toggle_play_with_comp(&comp, t0);
391
392 // Minor 4ms jitter on step 1
393 let e1 = ef.tick_synced(&comp, t0 + step + Duration::from_millis(4));
394 assert_eq!((e1.frame_changed, e1.looped, ef.current_frame), (true, false, 21.0));
395 // Step 2 fires at t0 + 2*step (doesn't lose the 4ms jitter!)
396 let e2 = ef.tick_synced(&comp, t0 + step * 2 + Duration::from_millis(1));
397 assert_eq!((e2.frame_changed, e2.looped, ef.current_frame), (true, false, 22.0));
398 // Step 3 wraps 22 -> 20 with looped = true
399 let e3 = ef.tick_synced(&comp, t0 + step * 3 + Duration::from_millis(1));
400 assert_eq!((e3.frame_changed, e3.looped, ef.current_frame), (true, true, 20.0));
401 }
402
403 #[test]
404 fn audio_sync_target_time_computation() {
405 let mut comp = test_comp();
406 comp.fps = 24.0;
407 comp.audio_offset = 12.0;
408
409 let t0 = Instant::now();
410 let mut clock = PlaybackClock::new();
411 clock.init_from_comp(&comp);
412 clock.in_out_range = [Some(12), Some(36)];
413 clock.set_frame(&comp, 0.0, t0);
414 assert!((clock.audio_target_secs(&comp) - (-0.5)).abs() < 1e-9);
415
416 clock.set_frame(&comp, 12.0, t0);
417 assert!((clock.audio_target_secs(&comp) - 0.0).abs() < 1e-9);
418
419 clock.set_frame(&comp, 36.0, t0);
420 assert!((clock.audio_target_secs(&comp) - 1.0).abs() < 1e-9);
421
422 // RealtimeDrop expected_audio_secs tracks continuous sub-frame progress & wraparound
423 clock.set_frame(&comp, 24.0, t0);
424 clock.toggle_play_with_comp(&comp, t0);
425 let half_sec = Duration::from_millis(500);
426 let exp_rt = clock.expected_audio_secs(&comp, t0 + half_sec);
427 assert!((exp_rt - 1.0).abs() < 1e-6, "expected 1.0s at frame 36, got {exp_rt}");
428
429 // EveryFrame expected_audio_secs caps sub-frame progress at 1/fps when a frame stalls
430 clock.sync_mode = SyncMode::EveryFrame;
431 clock.set_frame(&comp, 24.0, t0); // expected base = (24 - 12) / 24 = 0.5s
432 let exp_stalled = clock.expected_audio_secs(&comp, t0 + Duration::from_millis(400));
433 let max_expected = 0.5 + (1.0 / 24.0);
434 assert!(
435 (exp_stalled - max_expected).abs() < 1e-6,
436 "EveryFrame stalled expected_audio_secs should cap at {max_expected}, got {exp_stalled}"
437 );
438 }
439
440 #[test]
441 fn loop_wraparound_keeps_the_sub_frame_overshoot() {
442 let comp = test_comp(); // 30 fps
443 let t0 = Instant::now();
444 let step = Duration::from_secs_f64(1.0 / 30.0);
445 let mut clock = PlaybackClock::new();
446 clock.init_from_comp(&comp);
447 clock.in_out_range = [Some(20), Some(24)];
448 clock.set_frame(&comp, 20.0, t0);
449 clock.toggle_play_with_comp(&comp, t0);
450
451 // Wrap with half a frame of overshoot...
452 let wrap = clock.tick_synced(&comp, t0 + step.mul_f64(5.5));
453 assert!(wrap.looped);
454 assert_eq!(clock.current_frame, 20.0);
455 // ...so 0.6 frames later a whole frame has elapsed on the original timeline.
456 let next = clock.tick_synced(&comp, t0 + step.mul_f64(6.1));
457 assert!(!next.looped);
458 assert_eq!(clock.current_frame, 21.0);
459 }
460
461 #[test]
462 fn playback_clock_handles_degenerate_fps_dt_ranges_and_nan() {
463 let mut comp = test_comp();
464 comp.global_range = [50, 10]; // inverted
465 comp.render_range = [40, 20]; // inverted
466 let t0 = Instant::now();
467 let mut clock = PlaybackClock::new();
468 clock.init_from_comp(&comp);
469
470 // NaN frame must not poison current_frame, and inverted global_range must not panic.
471 assert!(!clock.set_frame(&comp, f64::NAN, t0));
472 assert!(clock.current_frame.is_finite());
473
474 clock.current_frame = f64::NAN;
475 clock.toggle_play(t0);
476 for fps in [0.0, -24.0, f64::NAN, f64::INFINITY] {
477 comp.fps = fps;
478 let res = clock.tick_synced(&comp, t0 + Duration::from_secs(1_000_000_000));
479 assert!(res.playing);
480 assert!(clock.current_frame.is_finite());
481 assert!(clock.expected_audio_secs(&comp, t0 + Duration::from_secs(10)).is_finite());
482 let _ = clock.next_wake(&comp);
483 }
484
485 clock.sync_mode = SyncMode::EveryFrame;
486 clock.current_frame = f64::NAN;
487 let _ = clock.tick_synced(&comp, t0 + Duration::from_secs(1_000_000_000));
488 assert!(clock.current_frame.is_finite());
489 }
490}