Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: follow playback in desktop timelines

Richie McIlroydf63d29ceb90
diff --git a/apps/desktop-gpui/src/editor_timeline.rs b/apps/desktop-gpui/src/editor_timeline.rs
index 91200041b..14ff44c47 100644
--- a/apps/desktop-gpui/src/editor_timeline.rs
+++ b/apps/desktop-gpui/src/editor_timeline.rs
@@ -33,6 +33,10 @@
use std::sync::Arc;
+mod playback_follow;
+
+pub use playback_follow::PlaybackFollow;
+
use cap_project::{
Camera3DSegment, CaptionTrackSegment, MaskKind, OverlayTrack, OverlayTrackKind,
ProjectConfiguration, SceneMode, TextLayout, TimelineConfiguration, ZoomMode,
diff --git a/apps/desktop-gpui/src/editor_timeline/playback_follow.rs b/apps/desktop-gpui/src/editor_timeline/playback_follow.rs
new file mode 100644
index 000000000..e587f6035
--- /dev/null
+++ b/apps/desktop-gpui/src/editor_timeline/playback_follow.rs
@@ -0,0 +1,209 @@
+use std::time::{Duration, Instant};
+
+use super::Transform;
+
+#[derive(Default)]
+pub struct PlaybackFollow {
+ previous: Option<Transform>,
+ resume_at: Option<Instant>,
+}
+
+impl PlaybackFollow {
+ pub fn reset(&mut self) {
+ self.previous = None;
+ self.resume_at = None;
+ }
+
+ pub fn update(
+ &mut self,
+ transform: &mut Transform,
+ playhead: f64,
+ duration: f64,
+ now: Instant,
+ interacting: bool,
+ ) {
+ if interacting || self.previous.is_some_and(|previous| previous != *transform) {
+ self.resume_at = Some(now + Duration::from_secs(1));
+ }
+ if self.resume_at.is_none_or(|resume_at| now >= resume_at)
+ && transform.position.is_finite()
+ && transform.zoom.is_finite()
+ && playhead.is_finite()
+ && duration.is_finite()
+ && transform.zoom > 0.
+ && duration > 0.
+ {
+ let position = if playhead < transform.position {
+ playhead - transform.zoom * 0.2
+ } else if playhead > transform.position + transform.zoom * 0.8 {
+ playhead - transform.zoom * 0.8
+ } else {
+ transform.position
+ };
+ transform.position = position.clamp(0., (duration - transform.zoom).max(0.));
+ }
+ self.previous = Some(*transform);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn playback_follow_stays_still_then_tracks_at_playback_speed() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let start = Instant::now();
+ for frame in 0..=1080 {
+ let time = f64::from(frame) / 60.;
+ follow.update(
+ &mut transform,
+ time,
+ 60.,
+ start + Duration::from_secs_f64(time),
+ false,
+ );
+ assert!((transform.position - (time - 8.).max(0.)).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn playback_follow_reveals_seeks_and_restarts() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ follow.update(&mut transform, 45., 60., now, false);
+ assert_eq!(transform.position, 37.);
+ follow.update(&mut transform, 20., 60., now, false);
+ assert_eq!(transform.position, 18.);
+ follow.reset();
+ follow.update(&mut transform, 0., 60., now, false);
+ assert_eq!(transform.position, 0.);
+ }
+
+ #[test]
+ fn playback_follow_stays_within_the_project() {
+ for (position, zoom, duration, expected) in
+ [(49., 10., 60., 50.), (0., 60., 60., 0.), (0., 3., 2., 0.)]
+ {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform { position, zoom };
+ follow.update(&mut transform, duration, duration, Instant::now(), false);
+ assert_eq!(transform.position, expected);
+ }
+ }
+
+ #[test]
+ fn playback_follow_gives_manual_pan_and_zoom_a_grace_period() {
+ for manual in [
+ Transform {
+ position: 30.,
+ zoom: 10.,
+ },
+ Transform {
+ position: 0.,
+ zoom: 5.,
+ },
+ ] {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ follow.update(&mut transform, 8., 60., now, false);
+ transform = manual;
+ follow.update(&mut transform, 9., 60., now, false);
+ assert_eq!(transform, manual);
+ follow.update(
+ &mut transform,
+ 10.,
+ 60.,
+ now + Duration::from_millis(999),
+ false,
+ );
+ assert_eq!(transform, manual);
+ follow.update(
+ &mut transform,
+ 10.,
+ 60.,
+ now + Duration::from_secs(1),
+ false,
+ );
+ assert_eq!(transform.position, if manual.zoom == 10. { 8. } else { 6. });
+ }
+ }
+
+ #[test]
+ fn playback_follow_waits_for_stationary_drags_to_finish() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 0.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ for seconds in 0..=3 {
+ follow.update(
+ &mut transform,
+ 20.,
+ 60.,
+ now + Duration::from_secs(seconds),
+ true,
+ );
+ assert_eq!(transform.position, 0.);
+ }
+ follow.update(
+ &mut transform,
+ 20.,
+ 60.,
+ now + Duration::from_millis(3999),
+ false,
+ );
+ assert_eq!(transform.position, 0.);
+ follow.update(
+ &mut transform,
+ 20.,
+ 60.,
+ now + Duration::from_secs(4),
+ false,
+ );
+ assert_eq!(transform.position, 12.);
+ }
+
+ #[test]
+ fn playback_follow_resets_manual_suspension_on_restart() {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform {
+ position: 30.,
+ zoom: 10.,
+ };
+ let now = Instant::now();
+ follow.update(&mut transform, 0., 60., now, true);
+ follow.reset();
+ follow.update(&mut transform, 0., 60., now, false);
+ assert_eq!(transform.position, 0.);
+ }
+
+ #[test]
+ fn playback_follow_ignores_invalid_geometry() {
+ for (zoom, playhead, duration) in [
+ (0., 10., 60.),
+ (10., 10., 0.),
+ (10., f64::NAN, 60.),
+ (f64::INFINITY, 10., 60.),
+ (10., 10., f64::NAN),
+ ] {
+ let mut follow = PlaybackFollow::default();
+ let mut transform = Transform { position: 5., zoom };
+ follow.update(&mut transform, playhead, duration, Instant::now(), false);
+ assert_eq!(transform.position, 5.);
+ }
+ }
+}
diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs
index ce61cf736..1c652b712 100644
--- a/apps/desktop-gpui/src/editor_window.rs
+++ b/apps/desktop-gpui/src/editor_window.rs
@@ -1427,6 +1427,7 @@ pub struct EditorWindow {
timeline: TimelineModel,
/// The viewport, the hover ghost and the hovered track.
view: TimelineView,
+ playback_follow: timeline::PlaybackFollow,
/// `onMount`'s `checkBounds` runs once, when the timeline first has a
/// width (`TL/index.tsx:689-703`). There is no mount hook here, so the
/// first render that knows both the width and the duration does it.
@@ -1839,6 +1840,7 @@ impl EditorWindow {
play_mark: None,
timeline: TimelineModel::default(),
view: TimelineView::default(),
+ playback_follow: timeline::PlaybackFollow::default(),
fitted: false,
zoom_slider_track: ui::SliderTrack::default(),
zoom_slider_drag: false,
@@ -2460,6 +2462,7 @@ impl EditorWindow {
/// effect, by prev/next, and by the clips sidebar's import path
/// (`ClipsSidebar.tsx:508-511`).
pub(crate) fn stop_playback(&mut self, cx: &mut Context<Self>) {
+ self.playback_follow.reset();
if let Some(transport) = &self.transport {
transport.pause();
}
@@ -2489,6 +2492,7 @@ impl EditorWindow {
let Some(transport) = &self.transport else {
return;
};
+ self.playback_follow.reset();
// `Math.floor(editorState.playbackTime * FPS)`.
let frame = (from.max(0.0) * EDITOR_PREVIEW_FPS as f64).floor() as u32;
transport.play_from(frame);
@@ -8724,7 +8728,7 @@ impl EditorWindow {
// -- Timeline ------------------------------------------------------------
fn render_timeline(
- &self,
+ &mut self,
viewport_width: f32,
_viewport_height: f32,
cx: &mut Context<Self>,
@@ -8737,7 +8741,7 @@ impl EditorWindow {
// since the last applied sample so the 60Hz ticker's redraws land
// between events instead of on them -- but only once this play epoch
// has actually produced a sample (`playhead_extrapolation`).
- let playhead_view = {
+ let mut playhead_view = {
let mut view = self.view;
let ahead = playhead_extrapolation(
self.playing,
@@ -8749,6 +8753,22 @@ impl EditorWindow {
}
view
};
+ if self.playing {
+ let interacting = self.scrub.is_some()
+ || self.drag.is_some()
+ || self.lane_reorder.is_some()
+ || self.minimap_drag.is_some()
+ || self.zoom_slider_drag;
+ let total = self.total_duration();
+ self.playback_follow.update(
+ &mut self.view.transform,
+ playhead_view.playhead,
+ total,
+ Instant::now(),
+ interacting,
+ );
+ playhead_view.transform = self.view.transform;
+ }
let playhead_x = timeline::playhead_offset(playhead_view, content_width);
let ghost_x = timeline::ghost_offset(self.view, content_width);
diff --git a/apps/desktop/src/routes/editor/Timeline/index.tsx b/apps/desktop/src/routes/editor/Timeline/index.tsx
index 34ee58fea..37ddb8ad2 100644
--- a/apps/desktop/src/routes/editor/Timeline/index.tsx
+++ b/apps/desktop/src/routes/editor/Timeline/index.tsx
@@ -17,6 +17,7 @@ import {
Index,
type JSX,
Match,
+ on,
onCleanup,
onMount,
Show,
@@ -69,6 +70,7 @@ import { TimelineContextProvider, useTimelineContext } from "./context";
import { type KeyboardSegmentDragState, KeyboardTrack } from "./KeyboardTrack";
import { type MaskSegmentDragState, MaskTrack } from "./MaskTrack";
import { Minimap } from "./Minimap";
+import { PlaybackFollow } from "./playback-follow";
import { type SceneSegmentDragState, SceneTrack } from "./SceneTrack";
import { type TextSegmentDragState, TextTrack } from "./TextTrack";
import { type ThreeDSegmentDragState, ThreeDTrack } from "./ThreeDTrack";
@@ -216,6 +218,65 @@ export function Timeline(props: {
const timelineBounds = createElementBounds(timelineRef);
const secsPerPixel = () => transform().zoom / (timelineBounds.width ?? 1);
+ const playbackFollow = new PlaybackFollow();
+ const playbackDuration = createMemo(totalDuration);
+ let followRafId: number | null = null;
+ let timelinePointerDown = false;
+
+ createEventListener(
+ window,
+ "mousedown",
+ (event) => {
+ if (event.button === 0 && event.target instanceof Node) {
+ timelinePointerDown =
+ timelineContainerRef()?.contains(event.target) ?? false;
+ }
+ },
+ { capture: true },
+ );
+ createEventListenerMap(window, {
+ mouseup: () => {
+ timelinePointerDown = false;
+ },
+ blur: () => {
+ timelinePointerDown = false;
+ },
+ });
+
+ function cancelPlaybackFollow() {
+ if (followRafId !== null) cancelAnimationFrame(followRafId);
+ followRafId = null;
+ playbackFollow.reset();
+ }
+
+ createEffect(
+ on(
+ [() => editorState.playing, () => editorState.playbackTime],
+ ([playing]) => {
+ if (!playing) {
+ cancelPlaybackFollow();
+ return;
+ }
+ if (followRafId !== null) return;
+ followRafId = requestAnimationFrame(() => {
+ followRafId = null;
+ if (!editorState.playing || !timelineBounds.width) return;
+ const viewport = transform();
+ const position = playbackFollow.update(
+ viewport,
+ editorState.playbackTime,
+ playbackDuration(),
+ performance.now(),
+ timelinePointerDown,
+ );
+ if (position !== viewport.position) {
+ setEditorState("timeline", "transform", "position", position);
+ }
+ });
+ },
+ ),
+ );
+ onCleanup(cancelPlaybackFollow);
const openAudioPicker = (laneIndex: number) => {
batch(() => {
diff --git a/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts b/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts
new file mode 100644
index 000000000..1b3fa282c
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/playback-follow.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+import { PlaybackFollow } from "./playback-follow";
+
+describe("timeline playback following", () => {
+ it("leaves the viewport still until the playhead reaches the follow point", () => {
+ const follow = new PlaybackFollow();
+ const viewport = { position: 0, zoom: 10 };
+ for (const time of [0, 1, 4, 8]) {
+ expect(follow.update(viewport, time, 60, time * 1000, false)).toBe(0);
+ }
+ });
+
+ it("scrolls at playback speed without mistaking its own movement for panning", () => {
+ const follow = new PlaybackFollow();
+ const viewport = { position: 0, zoom: 10 };
+ for (let frame = 0; frame <= 600; frame++) {
+ const time = 8 + frame / 60;
+ viewport.position = follow.update(viewport, time, 60, time * 1000, false);
+ expect(time - viewport.position).toBeCloseTo(8);
+ }
+ });
+
+ it("reveals offscreen seeks and restarts from the beginning", () => {
+ const follow = new PlaybackFollow();
+ expect(follow.update({ position: 0, zoom: 10 }, 45, 60, 0, false)).toBe(37);
+ follow.reset();
+ expect(follow.update({ position: 37, zoom: 10 }, 0, 60, 1, false)).toBe(0);
+ });
+
+ it("reveals a backward seek with room before the playhead", () => {
+ const follow = new PlaybackFollow();
+ expect(follow.update({ position: 30, zoom: 10 }, 20, 60, 0, false)).toBe(
+ 18,
+ );
+ });
+
+ it("stops scrolling at the project end without exposing extra empty space", () => {
+ const follow = new PlaybackFollow();
+ expect(follow.update({ position: 49, zoom: 10 }, 60, 60, 0, false)).toBe(
+ 50,
+ );
+ });
+
+ it("does not scroll a project that already fits, including short projects", () => {
+ for (const [duration, zoom] of [
+ [60, 60],
+ [2, 3],
+ ]) {
+ const follow = new PlaybackFollow();
+ expect(
+ follow.update({ position: 0, zoom }, duration, duration, 0, false),
+ ).toBe(0);
+ }
+ });
+
+ it("allows manual panning and resumes after a second", () => {
+ const follow = new PlaybackFollow();
+ follow.update({ position: 0, zoom: 10 }, 9, 60, 0, false);
+ const viewport = { position: 30, zoom: 10 };
+ expect(follow.update(viewport, 9.1, 60, 100, false)).toBe(30);
+ expect(follow.update(viewport, 10, 60, 1099, false)).toBe(30);
+ expect(follow.update(viewport, 10, 60, 1100, false)).toBe(8);
+ });
+
+ it("preserves a zoom anchor during the grace period", () => {
+ const follow = new PlaybackFollow();
+ follow.update({ position: 0, zoom: 10 }, 8, 60, 0, false);
+ const viewport = { position: 0, zoom: 5 };
+ expect(follow.update(viewport, 8, 60, 1, false)).toBe(0);
+ expect(follow.update(viewport, 9, 60, 1001, false)).toBe(5);
+ });
+
+ it("holds the viewport for the full drag, even when the pointer stops moving", () => {
+ const follow = new PlaybackFollow();
+ const viewport = { position: 0, zoom: 10 };
+ for (const now of [0, 1000, 2000, 3000]) {
+ expect(follow.update(viewport, 20, 60, now, true)).toBe(0);
+ }
+ expect(follow.update(viewport, 20, 60, 3999, false)).toBe(0);
+ expect(follow.update(viewport, 20, 60, 4000, false)).toBe(12);
+ });
+
+ it("clears manual suspension for a new playback session", () => {
+ const follow = new PlaybackFollow();
+ follow.update({ position: 30, zoom: 10 }, 0, 60, 0, true);
+ follow.reset();
+ expect(follow.update({ position: 30, zoom: 10 }, 0, 60, 1, false)).toBe(0);
+ });
+
+ it("ignores unavailable duration and invalid playback geometry", () => {
+ for (const [zoom, playhead, duration] of [
+ [0, 10, 60],
+ [10, 10, 0],
+ [10, Number.NaN, 60],
+ [Number.POSITIVE_INFINITY, 10, 60],
+ [10, 10, Number.NaN],
+ ]) {
+ const follow = new PlaybackFollow();
+ expect(
+ follow.update({ position: 5, zoom }, playhead, duration, 0, false),
+ ).toBe(5);
+ }
+ });
+});
diff --git a/apps/desktop/src/routes/editor/Timeline/playback-follow.ts b/apps/desktop/src/routes/editor/Timeline/playback-follow.ts
new file mode 100644
index 000000000..96e0e5a07
--- /dev/null
+++ b/apps/desktop/src/routes/editor/Timeline/playback-follow.ts
@@ -0,0 +1,50 @@
+type Viewport = {
+ position: number;
+ zoom: number;
+};
+
+export class PlaybackFollow {
+ private previous: Viewport | undefined;
+ private resumeAt = 0;
+
+ reset() {
+ this.previous = undefined;
+ this.resumeAt = 0;
+ }
+
+ update(
+ viewport: Viewport,
+ playhead: number,
+ duration: number,
+ now: number,
+ interacting: boolean,
+ ) {
+ const { position, zoom } = viewport;
+ if (
+ interacting ||
+ (this.previous &&
+ (this.previous.position !== position || this.previous.zoom !== zoom))
+ ) {
+ this.resumeAt = now + 1000;
+ }
+ let next = position;
+ if (
+ now >= this.resumeAt &&
+ Number.isFinite(position) &&
+ Number.isFinite(zoom) &&
+ Number.isFinite(playhead) &&
+ Number.isFinite(duration) &&
+ zoom > 0 &&
+ duration > 0
+ ) {
+ if (playhead < position) {
+ next = playhead - zoom * 0.2;
+ } else if (playhead > position + zoom * 0.8) {
+ next = playhead - zoom * 0.8;
+ }
+ next = Math.min(Math.max(next, 0), Math.max(duration - zoom, 0));
+ }
+ this.previous = { position: next, zoom };
+ return next;
+ }
+}