Skip to content

🎥 Make videos programmatically with React

`remotion`: Stabilize playing reads and fix imperative player re-renders

Noah Lindner7b6c26803b7a
diff --git a/packages/core/src/TimelineContext.tsx b/packages/core/src/TimelineContext.tsx
index a04d64497f..434e7d2f9f 100644
--- a/packages/core/src/TimelineContext.tsx
+++ b/packages/core/src/TimelineContext.tsx
@@ -1,6 +1,7 @@
import type {RefObject} from 'react';
import React, {
createContext,
+ useCallback,
useLayoutEffect,
useMemo,
useRef,
@@ -28,6 +29,9 @@ export type SetTimelineContextValue = {
setFrame: (u: React.SetStateAction<Record<string, number>>) => void;
setPlaying: (u: React.SetStateAction<boolean>) => void;
subscribePlaying: (listener: () => void) => () => void;
+ frameRef: RefObject<Record<string, number>>;
+ isPlaying: () => boolean;
+ audioAndVideoTags: RefObject<PlayableMediaTag[]>;
};
export const SetTimelineContext = createContext<SetTimelineContextValue>({
@@ -40,6 +44,11 @@ export const SetTimelineContext = createContext<SetTimelineContextValue>({
subscribePlaying: () => {
throw new Error('default');
},
+ frameRef: {current: {}},
+ isPlaying: () => {
+ throw new Error('default');
+ },
+ audioAndVideoTags: {current: []},
});
export const TimelineContext = createContext<TimelineContextValue | null>(null);
@@ -51,6 +60,8 @@ export const AbsoluteTimeContext = createContext<TimelineContextValue | null>(
null,
);
+const studioFrameRef: RefObject<Record<string, number>> = {current: {}};
+
export const TimelineContextProvider: React.FC<{
readonly children: React.ReactNode;
readonly frameState: Record<string, number> | null;
@@ -67,8 +78,11 @@ export const TimelineContextProvider: React.FC<{
);
const frame = frameState ?? _frame;
- const frameRef = useRef(frame);
- frameRef.current = frame;
+
+ const readIsPlaying = useCallback(
+ () => playingStore.store.getSnapshot().playing,
+ [playingStore],
+ );
const {delayRender, continueRender} = useDelayRender();
@@ -110,10 +124,10 @@ export const TimelineContextProvider: React.FC<{
const timelineContextValue = useMemo((): TimelineContextValue => {
return {
frame,
- isPlaying: () => playingStore.store.getSnapshot().playing as boolean,
+ isPlaying: readIsPlaying,
audioAndVideoTags,
};
- }, [frame, playingStore, audioAndVideoTags]);
+ }, [frame, readIsPlaying]);
const playbackRateContextValue = useMemo((): PlaybackRateContextValue => {
return {
@@ -127,15 +141,18 @@ export const TimelineContextProvider: React.FC<{
setFrame,
setPlaying: (updater) => {
if (typeof updater === 'function') {
- const current = playingStore.store.getSnapshot().playing as boolean;
+ const current = playingStore.store.getSnapshot().playing;
playingStore.setSnapshot({playing: updater(current)});
} else {
playingStore.setSnapshot({playing: updater});
}
},
subscribePlaying: playingStore.store.subscribe,
+ frameRef: studioFrameRef,
+ isPlaying: readIsPlaying,
+ audioAndVideoTags,
};
- }, [playingStore]);
+ }, [playingStore, readIsPlaying]);
return (
<AbsoluteTimeContext.Provider value={timelineContextValue}>
diff --git a/packages/core/src/runtime-value-store.ts b/packages/core/src/runtime-value-store.ts
index 25fb97cd27..f311258162 100644
--- a/packages/core/src/runtime-value-store.ts
+++ b/packages/core/src/runtime-value-store.ts
@@ -1,22 +1,26 @@
export type RuntimeValueSnapshot = Readonly<Record<string, unknown>>;
-export type RuntimeValueStore = {
- getSnapshot: () => RuntimeValueSnapshot;
+export type RuntimeValueStore<
+ TSnapshot extends RuntimeValueSnapshot = RuntimeValueSnapshot,
+> = {
+ getSnapshot: () => TSnapshot;
subscribe: (listener: () => void) => () => void;
};
-export type RuntimeValueStoreController = {
- store: RuntimeValueStore;
- setSnapshot: (newSnapshot: RuntimeValueSnapshot) => void;
+export type RuntimeValueStoreController<
+ TSnapshot extends RuntimeValueSnapshot = RuntimeValueSnapshot,
+> = {
+ store: RuntimeValueStore<TSnapshot>;
+ setSnapshot: (newSnapshot: TSnapshot) => void;
};
-export const createRuntimeValueStore = (
- initialSnapshot: RuntimeValueSnapshot,
-): RuntimeValueStoreController => {
+export const createRuntimeValueStore = <TSnapshot extends RuntimeValueSnapshot>(
+ initialSnapshot: TSnapshot,
+): RuntimeValueStoreController<TSnapshot> => {
let snapshot = initialSnapshot;
const listeners = new Set<() => void>();
- const store: RuntimeValueStore = {
+ const store: RuntimeValueStore<TSnapshot> = {
getSnapshot: () => snapshot,
subscribe: (listener) => {
listeners.add(listener);
diff --git a/packages/core/src/use-media-tag.ts b/packages/core/src/use-media-tag.ts
index 217e4a7d3c..9292871b3f 100644
--- a/packages/core/src/use-media-tag.ts
+++ b/packages/core/src/use-media-tag.ts
@@ -1,5 +1,5 @@
import type {RefObject} from 'react';
-import {useEffect} from 'react';
+import {useEffect, useRef} from 'react';
import {useLogLevel, useMountTime} from './log-level-context.js';
import {playAndHandleNotAllowedError} from './play-and-handle-not-allowed-error.js';
import type {PlayableMediaTag} from './timeline-position-state.js';
@@ -22,6 +22,8 @@ export const useMediaTag = ({
isPostmounting: boolean;
}) => {
const {audioAndVideoTags, isPlaying} = useTimelineContext();
+ const isPlayingRef = useRef(isPlaying);
+ isPlayingRef.current = isPlaying;
const logLevel = useLogLevel();
const mountTime = useMountTime();
const env = useRemotionEnvironment();
@@ -30,7 +32,7 @@ export const useMediaTag = ({
const tag: PlayableMediaTag = {
id,
play: (reason) => {
- if (!isPlaying()) {
+ if (!isPlayingRef.current()) {
// Don't play if for example in a <Freeze> state.
return;
}
@@ -63,7 +65,6 @@ export const useMediaTag = ({
mediaRef,
mediaType,
onAutoPlayError,
- isPlaying,
isPremounting,
isPostmounting,
logLevel,
diff --git a/packages/player/src/Player.tsx b/packages/player/src/Player.tsx
index 2683e4f2fc..100121b9e4 100644
--- a/packages/player/src/Player.tsx
+++ b/packages/player/src/Player.tsx
@@ -1,6 +1,7 @@
import type {ComponentType, LazyExoticComponent, RefObject} from 'react';
import React, {
forwardRef,
+ useCallback,
useEffect,
useImperativeHandle,
useLayoutEffect,
@@ -242,12 +243,18 @@ const PlayerFn = <
const [frame, setFrame] = useState<Record<string, number>>(() => ({
[PLAYER_COMP_ID]: initialFrame ?? 0,
}));
+ const frameRef = useRef(frame);
+ frameRef.current = frame;
const rootRef = useRef<PlayerRef>(null);
const audioAndVideoTags = useRef<PlayableMediaTag[]>([]);
const playingStore = useMemo(
() => Internals.createRuntimeValueStore({playing: false}),
[],
);
+ const readIsPlaying = useCallback(
+ () => playingStore.store.getSnapshot().playing,
+ [playingStore],
+ );
const [currentPlaybackRate, setCurrentPlaybackRate] = useState(playbackRate);
if (typeof compositionHeight !== 'number') {
@@ -412,10 +419,10 @@ const PlayerFn = <
const timelineContextValue = useMemo((): TimelineContextValue => {
return {
frame,
- isPlaying: () => playingStore.store.getSnapshot().playing as boolean,
+ isPlaying: readIsPlaying,
audioAndVideoTags,
};
- }, [frame, playingStore, audioAndVideoTags]);
+ }, [frame, readIsPlaying]);
const playbackRateContextValue = useMemo((): PlaybackRateContextValue => {
return {
@@ -429,15 +436,18 @@ const PlayerFn = <
setFrame,
setPlaying: (updater) => {
if (typeof updater === 'function') {
- const current = playingStore.store.getSnapshot().playing as boolean;
+ const current = playingStore.store.getSnapshot().playing;
playingStore.setSnapshot({playing: updater(current)});
} else {
playingStore.setSnapshot({playing: updater});
}
},
subscribePlaying: playingStore.store.subscribe,
+ frameRef,
+ isPlaying: readIsPlaying,
+ audioAndVideoTags,
};
- }, [playingStore, setFrame]);
+ }, [playingStore, setFrame, frameRef, readIsPlaying]);
if (typeof window !== 'undefined') {
// eslint-disable-next-line react-hooks/rules-of-hooks
diff --git a/packages/player/src/SharedPlayerContext.tsx b/packages/player/src/SharedPlayerContext.tsx
index a759fdc0db..891337b26e 100644
--- a/packages/player/src/SharedPlayerContext.tsx
+++ b/packages/player/src/SharedPlayerContext.tsx
@@ -158,9 +158,6 @@ export const SharedPlayerContexts: React.FC<{
};
}, []);
- const frameRef = useRef(timelineContext.frame);
- frameRef.current = timelineContext.frame;
-
return (
<Internals.RemotionEnvironmentContext.Provider value={env}>
<Internals.LogLevelContext.Provider value={logLevelContext}>
diff --git a/packages/player/src/use-player-methods.ts b/packages/player/src/use-player-methods.ts
index 9795491318..1d3abf30e7 100644
--- a/packages/player/src/use-player-methods.ts
+++ b/packages/player/src/use-player-methods.ts
@@ -21,8 +21,12 @@ export type UsePlayerMethods = {
export const usePlayerMethods = (): UsePlayerMethods => {
const setFrame = Internals.Timeline.useTimelineSetFrame();
const setTimelinePosition = Internals.Timeline.useTimelineSetFrame();
- const timelineContext = useContext(Internals.TimelineContext);
- const {setPlaying} = useContext(Internals.SetTimelineContext);
+ const {
+ setPlaying,
+ frameRef,
+ isPlaying: readIsPlaying,
+ audioAndVideoTags,
+ } = useContext(Internals.SetTimelineContext);
const audioContext = useContext(Internals.SharedAudioContext);
const audioTagsContext = useContext(Internals.SharedAudioTagsContext);
const environment = useRemotionEnvironment();
@@ -32,12 +36,6 @@ export const usePlayerMethods = (): UsePlayerMethods => {
const playStart = useRef(0);
const fallbackFrame = useRef<number | null>(null);
- if (!timelineContext) {
- throw new Error(
- 'Timeline context is not available. This hook must be used inside a <Player> or the Remotion Studio.',
- );
- }
-
if (!emitter) {
throw new TypeError('Expected Player event emitter context');
}
@@ -49,8 +47,6 @@ export const usePlayerMethods = (): UsePlayerMethods => {
);
}
- const {isPlaying: readIsPlaying} = timelineContext;
-
const getCurrentFrame = useCallback(() => {
if (!video) {
return (
@@ -62,7 +58,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
}
const unclamped =
- timelineContext.frame[video.id] ??
+ frameRef.current[video.id] ??
(environment.isPlayer
? 0
: Internals.Timeline.getFrameForComposition(video.id));
@@ -71,7 +67,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
unclamped,
video.durationInFrames,
);
- }, [environment.isPlayer, timelineContext, video]);
+ }, [environment.isPlayer, frameRef, video]);
const seek = useCallback(
(newFrame: number) => {
@@ -85,9 +81,9 @@ export const usePlayerMethods = (): UsePlayerMethods => {
fallbackFrame.current = frameToSeekTo;
if (video?.id) {
- if (timelineContext.frame[video.id] !== frameToSeekTo) {
- timelineContext.frame = {
- ...timelineContext.frame,
+ if (frameRef.current[video.id] !== frameToSeekTo) {
+ frameRef.current = {
+ ...frameRef.current,
[video.id]: frameToSeekTo,
};
}
@@ -101,7 +97,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
emitter.dispatchSeek(frameToSeekTo);
},
- [config, emitter, setTimelinePosition, timelineContext, video?.id],
+ [config, emitter, frameRef, setTimelinePosition, video?.id],
);
const play = useCallback(
@@ -128,7 +124,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
* Play audios and videos directly here so they can benefit from
* being triggered by a click
*/
- timelineContext.audioAndVideoTags.current.forEach((tag) =>
+ audioAndVideoTags.current.forEach((tag) =>
tag.play('player play() was called and playing audio from a click'),
);
@@ -137,6 +133,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
emitter.dispatchPlay();
},
[
+ audioAndVideoTags,
audioContext,
audioTagsContext,
config?.durationInFrames,
@@ -145,7 +142,6 @@ export const usePlayerMethods = (): UsePlayerMethods => {
readIsPlaying,
seek,
setPlaying,
- timelineContext.audioAndVideoTags,
],
);
@@ -163,8 +159,8 @@ export const usePlayerMethods = (): UsePlayerMethods => {
setPlaying(false);
fallbackFrame.current = playStart.current;
if (config) {
- timelineContext.frame = {
- ...timelineContext.frame,
+ frameRef.current = {
+ ...frameRef.current,
[config.id]: playStart.current,
};
setTimelinePosition((currentFrames) => ({
@@ -177,10 +173,10 @@ export const usePlayerMethods = (): UsePlayerMethods => {
}, [
config,
emitter,
+ frameRef,
readIsPlaying,
setPlaying,
setTimelinePosition,
- timelineContext,
]);
const videoId = video?.id;
@@ -197,14 +193,14 @@ export const usePlayerMethods = (): UsePlayerMethods => {
}
const previousFrame =
- timelineContext.frame[videoId] ?? window.remotion_initialFrame ?? 0;
+ frameRef.current[videoId] ?? window.remotion_initialFrame ?? 0;
const newFrame = Math.max(0, previousFrame - frames);
if (previousFrame === newFrame) {
return;
}
- timelineContext.frame = {
- ...timelineContext.frame,
+ frameRef.current = {
+ ...frameRef.current,
[videoId]: newFrame,
};
setFrame((currentFrames) =>
@@ -213,7 +209,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
: {...currentFrames, [videoId]: newFrame},
);
},
- [readIsPlaying, setFrame, timelineContext, videoId],
+ [frameRef, readIsPlaying, setFrame, videoId],
);
const frameForward = useCallback(
@@ -227,14 +223,14 @@ export const usePlayerMethods = (): UsePlayerMethods => {
}
const previousFrame =
- timelineContext.frame[videoId] ?? window.remotion_initialFrame ?? 0;
+ frameRef.current[videoId] ?? window.remotion_initialFrame ?? 0;
const newFrame = Math.min(lastFrame, previousFrame + frames);
if (previousFrame === newFrame) {
return;
}
- timelineContext.frame = {
- ...timelineContext.frame,
+ frameRef.current = {
+ ...frameRef.current,
[videoId]: newFrame,
};
setFrame((currentFrames) =>
@@ -243,7 +239,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
: {...currentFrames, [videoId]: newFrame},
);
},
- [lastFrame, readIsPlaying, setFrame, timelineContext, videoId],
+ [frameRef, lastFrame, readIsPlaying, setFrame, videoId],
);
const toggle = useCallback(