🎥 Make videos programmatically with React
Player: Keep the playback clock across effect re-runs when video config changes
Chirag Jangirb1bae20a49f6
diff --git a/packages/player/src/test/playback-survives-config-change.test.tsx b/packages/player/src/test/playback-survives-config-change.test.tsxnew file mode 100644index 0000000000..a59c439ed1--- /dev/null+++ b/packages/player/src/test/playback-survives-config-change.test.tsx@@ -0,0 +1,83 @@+import {expect, spyOn, test} from 'bun:test';+import {createRef} from 'react';+import {useCurrentFrame} from 'remotion';+import type {PlayerRef} from '../player-methods.js';+import {Player} from '../Player.js';+import {act, cleanup, render} from './test-utils.js';++test('Playback clock survives a durationInFrames change while playing', () => {+ let now = 0;+ let nextRaf = 0;+ const rafs = new Map<number, FrameRequestCallback>();+ const clock = spyOn(performance, 'now').mockImplementation(() => now);+ const raf = spyOn(globalThis, 'requestAnimationFrame').mockImplementation(+ (callback) => {+ const id = ++nextRaf;+ rafs.set(id, callback);+ return id;+ },+ );+ const cancel = spyOn(globalThis, 'cancelAnimationFrame').mockImplementation(+ (id) => {+ rafs.delete(id);+ },+ );+ const Composition = () => {+ const frame = useCurrentFrame();+ return <output>Frame {frame}</output>;+ };++ const tick = (time: number) => {+ now = time;+ const pending = [...rafs.values()];+ rafs.clear();+ for (const callback of pending) {+ callback(time);+ }+ };++ const props = (durationInFrames: number) => ({+ component: Composition,+ durationInFrames,+ compositionWidth: 320,+ compositionHeight: 180,+ fps: 30,+ initiallyMuted: true,+ numberOfSharedAudioTags: 0,+ });++ try {+ const player = createRef<PlayerRef>();+ const view = render(<Player ref={player} {...props(1000)} />);++ act(() => player.current!.play());+ expect(view.getByText('Frame 0')).toBeTruthy();++ // 50ms => 1 frame of 30fps should have been advanced.+ act(() => tick(50));+ expect(view.getByText('Frame 1')).toBeTruthy();++ // While playing, the composition length changes (e.g. a voiceover+ // finished loading), which re-runs the playback effect.+ // The clock should keep running instead of restarting from the+ // current frame.+ act(() => {+ tick(51);+ view.rerender(<Player ref={player} {...props(1001)} />);+ });++ // If the clock restarted at 51ms, 100ms here would only yield+ // 1000/fps * (1/33) frame advancements and the playback would fall+ // behind (“Frame 2” instead of “Frame 3”).+ act(() => tick(100));+ expect(view.getByText('Frame 3')).toBeTruthy();++ act(() => tick(200));+ expect(view.getByText('Frame 6')).toBeTruthy();+ } finally {+ cleanup();+ clock.mockRestore();+ raf.mockRestore();+ cancel.mockRestore();+ }+});diff --git a/packages/player/src/use-playback.ts b/packages/player/src/use-playback.tsindex 67100741ed..17594824a7 100644--- a/packages/player/src/use-playback.ts+++ b/packages/player/src/use-playback.ts@@ -29,6 +29,20 @@ const shouldForceAnchorChange = (newState: RemotionAudioContextState) => {);};+// The start timestamp and the frames already advanced within the current+// frame are kept across re-runs of the playback effect, so that a re-run+// (e.g. because durationInFrames changed, see issue #12279) does not+// restart the clock from the current frame and lose the already elapsed+// portion of the frame.+// A fresh clock is created only where a restart is correct: when starting+// playback, or when the fps or playback rate changed mid-playback.+type PlaybackClock = {+ startedTime: number;+ framesAdvanced: number;+ fps: number;+ playbackRate: number;+};+export const usePlayback = ({loop,playbackRate,@@ -67,6 +81,7 @@ export const usePlayback = ({const isBackgroundedRef = useIsBackgrounded();const lastTimeUpdateTimestamp = useRef<number>(0);+ const playbackClockRef = useRef<PlaybackClock | null>(null);useBrowserMediaSession({browserMediaControlsBehavior,@@ -158,10 +173,26 @@ export const usePlayback = ({}if (!playing) {+ playbackClockRef.current = null;sharedAudioContext?.suspend?.();return;}+ // Either carry over the previous clock or start a fresh one.+ const previousClock = playbackClockRef.current;+ const clock: PlaybackClock =+ previousClock !== null &&+ previousClock.fps === config.fps &&+ previousClock.playbackRate === playbackRate+ ? previousClock+ : {+ startedTime: performance.now(),+ framesAdvanced: 0,+ fps: config.fps,+ playbackRate,+ };+ playbackClockRef.current = clock;+if (sharedAudioContext?._experimentalKeepAudioContextAlive &&sharedAudioContext.audioContext &&@@ -200,8 +231,6 @@ export const usePlayback = ({id: Timer;}| null = null;- let startedTime = performance.now();- let framesAdvanced = 0;let playbackFrame = getCurrentFrame();let lastSeekRevision = seek?.revision.current ?? null;@@ -234,7 +263,7 @@ export const usePlayback = ({sharedAudioContext?.resume?.();}- const time = performance.now() - startedTime;+ const time = performance.now() - clock.startedTime;const actualLastFrame = outFrame ?? config.durationInFrames - 1;const actualFirstFrame = inFrame ?? 0;@@ -253,11 +282,11 @@ export const usePlayback = ({fps: config.fps,actualFirstFrame,actualLastFrame,- framesAdvanced,+ framesAdvanced: clock.framesAdvanced,shouldLoop: loop,});- framesAdvanced += framesToAdvance;+ clock.framesAdvanced += framesToAdvance;// A late callback can skip the endpoint. Hold that exact frame on end.const frameToDisplay =@@ -302,8 +331,9 @@ export const usePlayback = ({setPlayerMuted(true);}- startedTime = performance.now();- framesAdvanced = 0;+ // The audio context is being re-established; start a fresh clock.+ clock.startedTime = performance.now();+ clock.framesAdvanced = 0;queueNextFrame();});@@ -329,10 +359,12 @@ export const usePlayback = ({sharedAudioContext.resume();}- startedTime = performance.now();- framesAdvanced = 0;+ // Buffered media became reachable; start a fresh clock.+ clock.startedTime = performance.now();+ clock.framesAdvanced = 0;queueNextFrame();});+return;}