Skip to content

Write HTML. Render video. Built for agents.

perf(studio): playback no longer relayouts the timecode and playhead every frame (#4593)

Miguel Ángel471e90c057f7
diff --git a/packages/studio/src/player/components/PlayerControls.test.tsx b/packages/studio/src/player/components/PlayerControls.test.tsx
new file mode 100644
index 0000000000..f62d097082
--- /dev/null
+++ b/packages/studio/src/player/components/PlayerControls.test.tsx
@@ -0,0 +1,52 @@
+// @vitest-environment happy-dom
+
+import React, { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { liveTime, usePlayerStore } from "../store/playerStore";
+import { PlayerControls } from "./PlayerControls";
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+
+let host: HTMLDivElement;
+let root: Root;
+
+beforeEach(async () => {
+ usePlayerStore.setState({
+ isPlaying: true,
+ currentTime: 2,
+ duration: 30,
+ timeDisplayMode: "time",
+ });
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () =>
+ root.render(React.createElement(PlayerControls, { onTogglePlay: () => {}, onSeek: () => {} })),
+ );
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ host.remove();
+});
+
+describe("PlayerControls timecode", () => {
+ it("rewrites the timecode only when the shown text changes", async () => {
+ const timecode = host.querySelector("button.font-mono > span");
+ expect(timecode?.textContent).toBe("00:02");
+ const writes: MutationRecord[] = [];
+ const observer = new MutationObserver((records) => writes.push(...records));
+ observer.observe(timecode as Node, { childList: true, characterData: true, subtree: true });
+
+ for (let frame = 1; frame <= 30; frame++) liveTime.notify(2 + frame / 120);
+ await Promise.resolve();
+ expect(writes).toHaveLength(0);
+
+ liveTime.notify(3.01);
+ await Promise.resolve();
+ expect(timecode?.textContent).toBe("00:03");
+ expect(writes.length).toBeGreaterThan(0);
+ observer.disconnect();
+ });
+});
diff --git a/packages/studio/src/player/components/PlayerControls.tsx b/packages/studio/src/player/components/PlayerControls.tsx
index cc53e96762..de6e01a94b 100644
--- a/packages/studio/src/player/components/PlayerControls.tsx
+++ b/packages/studio/src/player/components/PlayerControls.tsx
@@ -213,10 +213,11 @@ export const PlayerControls = memo(function PlayerControls({
currentTimeRef.current = time;
if (!timeDisplayRef.current) return;
const currentDuration = durationRef.current;
- timeDisplayRef.current.textContent =
+ const text =
timeDisplayModeRef.current === "frame"
? formatFrameTime(time, currentDuration)
: formatTime(time);
+ if (timeDisplayRef.current.textContent !== text) timeDisplayRef.current.textContent = text;
};
const unsubscribe = liveTime.subscribe(updateTime);
updateTime(usePlayerStore.getState().currentTime);
diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts
index eebbe565c0..3311b5b4db 100644
--- a/packages/studio/src/player/components/Timeline.test.ts
+++ b/packages/studio/src/player/components/Timeline.test.ts
@@ -39,7 +39,7 @@ import {
} from "./timelineLayout";
import { AUTOMATION_LANE_H } from "./automationLaneHeight";
import { formatTime } from "../lib/time";
-import { usePlayerStore } from "../store/playerStore";
+import { liveTime, usePlayerStore } from "../store/playerStore";
import { TimelineEditProvider } from "../../contexts/TimelineEditContext";
vi.mock("./timelineRowVirtualizationFlag", () => ({
@@ -153,6 +153,27 @@ function renderSharedAutomationTimeline(selectedElementId?: string) {
return { host, root };
}
+describe("Timeline playhead motion", () => {
+ it("moves by fractional pixels while playing and snaps to device pixels once paused", () => {
+ usePlayerStore.setState({
+ duration: 11,
+ timelineReady: true,
+ currentTime: 10,
+ isPlaying: true,
+ zoomMode: "manual",
+ manualZoomPercent: 100,
+ elements: [{ id: "clip-1", tag: "div", start: 10, duration: 1, track: 0 }],
+ });
+ const { root, playhead } = renderTimelineGeometry("clip-1");
+ const wrapperLeft = GUTTER + TRACKS_LEFT_PAD + 1000.3 - PLAYHEAD_HEAD_W / 2;
+ act(() => liveTime.notify(10.003));
+ expect(playhead.style.transform).toBe(`translateX(${wrapperLeft}px)`);
+ act(() => usePlayerStore.setState({ isPlaying: false }));
+ expect(playhead.style.transform).toBe(`translateX(${Math.round(wrapperLeft)}px)`);
+ act(() => root.unmount());
+ });
+});
+
describe("Timeline provider boundary", () => {
it("keeps all-collapsed horizontal positions at the gutter plus the pre-t=0 pad", () => {
usePlayerStore.setState({
@@ -173,7 +194,9 @@ describe("Timeline provider boundary", () => {
expect(clip.style.bottom).toBe(`${CLIP_Y}px`);
expect(rulerOrigin.style.width).toBe(`${GUTTER + TRACKS_LEFT_PAD}px`);
expect(rulerTick.style.left).toBe("999.5px");
- expect(playhead.style.left).toBe(`${GUTTER + TRACKS_LEFT_PAD + 1000 - PLAYHEAD_HEAD_W / 2}px`);
+ expect(playhead.style.transform).toBe(
+ `translateX(${Math.round(GUTTER + TRACKS_LEFT_PAD + 1000 - PLAYHEAD_HEAD_W / 2)}px)`,
+ );
expect(playhead.style.width).toBe(`${PLAYHEAD_HEAD_W}px`);
expect(
resolveTimelineAssetDrop(
@@ -283,7 +306,9 @@ describe("Timeline provider boundary", () => {
expect(semanticRows[2]?.hasAttribute("aria-expanded")).toBe(false);
expect(trackHeader.style.width).toBe(`${LABEL_COL_W}px`);
expect(rulerOrigin.style.width).toBe(`${LABEL_COL_W + GUTTER}px`);
- expect(playhead.style.left).toBe(`${LABEL_COL_W + GUTTER + 1000 - PLAYHEAD_HEAD_W / 2}px`);
+ expect(playhead.style.transform).toBe(
+ `translateX(${Math.round(LABEL_COL_W + GUTTER + 1000 - PLAYHEAD_HEAD_W / 2)}px)`,
+ );
expect(diamondX).toBe(rulerX);
expect(rulerX).toBe(LABEL_COL_W + GUTTER + 1000);
expect(collapsedHeader.textContent).toContain("Outro");
diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx
index 31cb23a33e..bae7783317 100644
--- a/packages/studio/src/player/components/TimelineCanvas.tsx
+++ b/packages/studio/src/player/components/TimelineCanvas.tsx
@@ -9,10 +9,10 @@ import {
TRACKS_BOTTOM_PAD,
TRACK_H,
PLAYHEAD_HEAD_W,
- getTimelinePlayheadLeft,
getTimelineRowTop,
getTimelineRowHeight,
} from "./timelineLayout";
+import { getTimelinePlayheadTransform } from "./timelinePlayheadTransform";
import { TimelineLanes } from "./TimelineLanes";
import { TimelineGestureOverlay } from "./TimelineGestureOverlay";
import { useTimelineContext } from "./TimelineProvider";
@@ -234,7 +234,7 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
{/* Playhead — hidden while dragging a beat so its guideline doesn't
track the scrub and clutter the beat being moved. Explicit width +
- the half-head offset baked into getTimelinePlayheadLeft keep the
+ the half-head offset baked into getTimelinePlayheadTransform keep the
inner 1px line's CENTER exactly on contentOrigin + t * pps (the ruler
ticks' center), instead of relying on shrink-wrap sizing. */}
<TimelinePlayheadLayer scrollRef={props.scrollRef} contentOrigin={props.contentOrigin}>
@@ -242,7 +242,9 @@ export const TimelineCanvas = memo(function TimelineCanvas() {
ref={props.playheadRef}
className="absolute top-0 bottom-0 pointer-events-none"
style={{
- left: `${getTimelinePlayheadLeft(0, 0, props.contentOrigin)}px`,
+ left: 0,
+ transform: getTimelinePlayheadTransform(0, 0, props.contentOrigin, true),
+ willChange: "transform",
width: PLAYHEAD_HEAD_W,
display: beatDragging ? "none" : undefined,
}}
diff --git a/packages/studio/src/player/components/timelinePlayheadTransform.test.ts b/packages/studio/src/player/components/timelinePlayheadTransform.test.ts
new file mode 100644
index 0000000000..106eabb755
--- /dev/null
+++ b/packages/studio/src/player/components/timelinePlayheadTransform.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { getTimelinePlayheadTransform } from "./timelinePlayheadTransform";
+
+const x = (transform: string) => Number(/translateX\(([-\d.e]+)px\)/.exec(transform)?.[1]);
+
+describe("getTimelinePlayheadTransform", () => {
+ it("keeps fractional pixels while playing, so slow motion does not stair-step", () => {
+ // Fit zoom on a two-minute film is about 13.3px a second: 120 frames of one second of playback.
+ const frames = Array.from({ length: 121 }, (_, i) => i / 120);
+ const playing = new Set(frames.map((t) => getTimelinePlayheadTransform(t, 13.3, 80, false, 1)));
+ const resting = new Set(frames.map((t) => getTimelinePlayheadTransform(t, 13.3, 80, true, 1)));
+ expect(playing.size).toBe(121);
+ expect(resting.size).toBeLessThan(20);
+ });
+
+ it("at rest puts the line on the device pixel layout gives its ruler tick", () => {
+ // The 1px line sits 4px into the 9px wrapper; the tick is laid out at t * pps - 0.5 and rounded by layout.
+ for (const dpr of [1, 1.5, 2]) {
+ for (let i = 0; i <= 400; i += 1) {
+ const t = i * 0.0137;
+ const wrapper = x(getTimelinePlayheadTransform(t, 13.3, 80, true, dpr));
+ const lineDevicePx = Math.round((wrapper + 4) * dpr);
+ const tickDevicePx = Math.round((80 + t * 13.3 - 0.5) * dpr);
+ expect(lineDevicePx, `t=${t} dpr=${dpr}`).toBe(tickDevicePx);
+ }
+ }
+ });
+
+ it("at time zero at 1x lands the line on the tick's column", () => {
+ expect(getTimelinePlayheadTransform(0, 100, 80, true, 1)).toBe("translateX(76px)");
+ expect(Math.round(80 - 0.5)).toBe(76 + 4);
+ });
+});
diff --git a/packages/studio/src/player/components/timelinePlayheadTransform.ts b/packages/studio/src/player/components/timelinePlayheadTransform.ts
new file mode 100644
index 0000000000..3cdc1346a4
--- /dev/null
+++ b/packages/studio/src/player/components/timelinePlayheadTransform.ts
@@ -0,0 +1,17 @@
+import { getTimelinePlayheadLeft } from "./timelineLayout";
+
+/**
+ * Moves the playhead by transform, with no relayout. Playing, it keeps fractional pixels so slow motion stays
+ * smooth; at rest it rounds to device pixels the way layout rounds the ruler ticks, so the line sits on its tick.
+ */
+export function getTimelinePlayheadTransform(
+ time: number,
+ pixelsPerSecond: number,
+ contentOrigin: number,
+ atRest: boolean,
+ devicePixelRatio = globalThis.devicePixelRatio || 1,
+): string {
+ const left = getTimelinePlayheadLeft(time, pixelsPerSecond, contentOrigin);
+ if (!atRest) return `translateX(${left}px)`;
+ return `translateX(${Math.round(left * devicePixelRatio) / devicePixelRatio}px)`;
+}
diff --git a/packages/studio/src/player/components/useTimelinePlayhead.ts b/packages/studio/src/player/components/useTimelinePlayhead.ts
index 163a25e217..7f61430fe3 100644
--- a/packages/studio/src/player/components/useTimelinePlayhead.ts
+++ b/packages/studio/src/player/components/useTimelinePlayhead.ts
@@ -4,12 +4,12 @@ import { useMountEffect } from "../../hooks/useMountEffect";
import { getPinchTimelineZoomPercent } from "./timelineZoom";
import {
getTimelinePlaybackFollowScrollLeft,
- getTimelinePlayheadLeft,
getTimelineScrubTime,
getTimelineScrollLeftForZoomTransition,
getTimelineScrollLeftForZoomAnchor,
shouldAutoScrollTimeline,
} from "./timelineLayout";
+import { getTimelinePlayheadTransform } from "./timelinePlayheadTransform";
import { applyTimelineHorizontalAutoScrollStep } from "./timelineEditing";
interface UseTimelinePlayheadInput {
@@ -92,7 +92,12 @@ export function useTimelinePlayhead({
const syncPlayheadPosition = useCallback(
(time: number) => {
if (!playheadRef.current || durationRef.current <= 0) return;
- playheadRef.current.style.left = `${getTimelinePlayheadLeft(time, ppsRef.current, contentOrigin)}px`;
+ playheadRef.current.style.transform = getTimelinePlayheadTransform(
+ time,
+ ppsRef.current,
+ contentOrigin,
+ !usePlayerStore.getState().isPlaying,
+ );
},
[playheadRef, durationRef, ppsRef, contentOrigin],
);
@@ -122,14 +127,24 @@ export function useTimelinePlayhead({
}, [zoomMode, scrollRef]);
useMountEffect(() => {
- const unsub = liveTime.subscribe((t) => {
- if (!playheadRef.current || durationRef.current <= 0) return;
- const playheadX = contentOriginRef.current + Math.max(0, t) * ppsRef.current;
- playheadRef.current.style.left = `${getTimelinePlayheadLeft(
+ let lastLiveTime = usePlayerStore.getState().currentTime;
+ const place = (t: number, atRest: boolean) => {
+ if (!playheadRef.current || durationRef.current <= 0) return false;
+ playheadRef.current.style.transform = getTimelinePlayheadTransform(
t,
ppsRef.current,
contentOriginRef.current,
- )}px`;
+ atRest,
+ );
+ return true;
+ };
+ const unsubPlaying = usePlayerStore.subscribe((state, prev) => {
+ if (prev.isPlaying && !state.isPlaying) place(lastLiveTime, true);
+ });
+ const unsub = liveTime.subscribe((t) => {
+ lastLiveTime = t;
+ if (!place(t, !usePlayerStore.getState().isPlaying)) return;
+ const playheadX = contentOriginRef.current + Math.max(0, t) * ppsRef.current;
const scroll = scrollRef.current;
if (
!scroll ||
@@ -150,7 +165,10 @@ export function useTimelinePlayhead({
scroll.scrollLeft = nextScrollLeft;
}
});
- return unsub;
+ return () => {
+ unsub();
+ unsubPlaying();
+ };
});
const seekFromX = useCallback(