Skip to content

🎥 Make videos programmatically with React

`remotion`: Expose `isPlaying()` on timeline context instead of `playbackStore`

Noah Lindner00120e9bb2ea
diff --git a/packages/core/src/TimelineContext.tsx b/packages/core/src/TimelineContext.tsx
index ac7d2f60c9..78a953aeac 100644
--- a/packages/core/src/TimelineContext.tsx
+++ b/packages/core/src/TimelineContext.tsx
@@ -6,10 +6,7 @@ import React, {
useRef,
useState,
} from 'react';
-import {
- createRuntimeValueStore,
- type RuntimeValueStoreController,
-} from './runtime-value-store.js';
+import {createPlayingController} from './playing-state.js';
import {
getInitialFrameState,
type PlayableMediaTag,
@@ -18,7 +15,7 @@ import {useDelayRender} from './use-delay-render';
export type TimelineContextValue = {
frame: Record<string, number>;
- playbackStore: RuntimeValueStoreController;
+ isPlaying: () => boolean;
audioAndVideoTags: RefObject<PlayableMediaTag[]>;
};
@@ -30,6 +27,7 @@ export type PlaybackRateContextValue = {
export type SetTimelineContextValue = {
setFrame: (u: React.SetStateAction<Record<string, number>>) => void;
setPlaying: (u: React.SetStateAction<boolean>) => void;
+ subscribePlaying: (listener: () => void) => () => void;
};
export const SetTimelineContext = createContext<SetTimelineContextValue>({
@@ -39,6 +37,9 @@ export const SetTimelineContext = createContext<SetTimelineContextValue>({
setPlaying: () => {
throw new Error('default');
},
+ subscribePlaying: () => {
+ throw new Error('default');
+ },
});
export const TimelineContext = createContext<TimelineContextValue | null>(null);
@@ -54,10 +55,7 @@ export const TimelineContextProvider: React.FC<{
readonly children: React.ReactNode;
readonly frameState: Record<string, number> | null;
}> = ({children, frameState}) => {
- const playbackStore = useMemo(
- () => createRuntimeValueStore({playing: false}),
- [],
- );
+ const playingController = useMemo(() => createPlayingController(false), []);
const [playbackRate, setPlaybackRate] = useState(1);
const audioAndVideoTags = useRef<PlayableMediaTag[]>([]);
@@ -109,10 +107,10 @@ export const TimelineContextProvider: React.FC<{
const timelineContextValue = useMemo((): TimelineContextValue => {
return {
frame,
- playbackStore,
+ isPlaying: playingController.isPlaying,
audioAndVideoTags,
};
- }, [frame, playbackStore]);
+ }, [frame, playingController.isPlaying, audioAndVideoTags]);
const playbackRateContextValue = useMemo((): PlaybackRateContextValue => {
return {
@@ -126,14 +124,14 @@ export const TimelineContextProvider: React.FC<{
setFrame,
setPlaying: (updater) => {
if (typeof updater === 'function') {
- const current = playbackStore.store.getSnapshot().playing as boolean;
- playbackStore.setSnapshot({playing: updater(current)});
+ playingController.setPlaying(updater(playingController.isPlaying()));
} else {
- playbackStore.setSnapshot({playing: updater});
+ playingController.setPlaying(updater);
}
},
+ subscribePlaying: playingController.subscribePlaying,
};
- }, [playbackStore]);
+ }, [playingController]);
return (
<AbsoluteTimeContext.Provider value={timelineContextValue}>
diff --git a/packages/core/src/freeze.tsx b/packages/core/src/freeze.tsx
index 48264e9b99..e358c121be 100644
--- a/packages/core/src/freeze.tsx
+++ b/packages/core/src/freeze.tsx
@@ -1,5 +1,4 @@
import React, {useContext, useMemo} from 'react';
-import {createRuntimeValueStore} from './runtime-value-store.js';
import type {SequenceContextType} from './SequenceContext.js';
import {SequenceContext} from './SequenceContext.js';
import {useTimelineContext} from './timeline-position-state.js';
@@ -70,11 +69,9 @@ export const Freeze: React.FC<FreezeProps> = ({
return timelineContext;
}
- const frozenStore = createRuntimeValueStore({playing: false});
-
return {
...timelineContext,
- playbackStore: frozenStore,
+ isPlaying: () => false,
frame: {
[videoConfig.id]: frameToFreeze + relativeFrom,
},
diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.ts
index eafd73f022..4af25d3111 100644
--- a/packages/core/src/internals.ts
+++ b/packages/core/src/internals.ts
@@ -131,6 +131,7 @@ import {
import type {NonceHistory} from './nonce.js';
import {NonceContext} from './nonce.js';
import {playbackLogging} from './playback-logging.js';
+import {createPlayingController} from './playing-state.js';
import {portalNode, setPortalNodeCurrentScale} from './portal-node.js';
import {PrefetchProvider} from './prefetch-state.js';
import {usePreload} from './prefetch.js';
@@ -310,6 +311,7 @@ export const Internals = {
makeRenderResourceManager,
RenderResourceManagerContext,
createRuntimeValueStore,
+ createPlayingController,
useUnsafeVideoConfig,
useFrameForVolumeProp,
useTimelinePosition: TimelinePosition.useTimelinePosition,
diff --git a/packages/core/src/playing-state.ts b/packages/core/src/playing-state.ts
new file mode 100644
index 0000000000..a010d15020
--- /dev/null
+++ b/packages/core/src/playing-state.ts
@@ -0,0 +1,32 @@
+export type PlayingController = {
+ readonly isPlaying: () => boolean;
+ readonly subscribePlaying: (listener: () => void) => () => void;
+ readonly setPlaying: (playing: boolean) => void;
+};
+
+export const createPlayingController = (
+ initialPlaying = false,
+): PlayingController => {
+ let playing = initialPlaying;
+ const listeners = new Set<() => void>();
+
+ return {
+ isPlaying: () => playing,
+ subscribePlaying: (listener) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+ setPlaying: (newPlaying) => {
+ if (playing === newPlaying) {
+ return;
+ }
+
+ playing = newPlaying;
+ for (const listener of listeners) {
+ listener();
+ }
+ },
+ };
+};
diff --git a/packages/core/src/test/nested-sequences.test.tsx b/packages/core/src/test/nested-sequences.test.tsx
index 32bc710194..00125e0578 100644
--- a/packages/core/src/test/nested-sequences.test.tsx
+++ b/packages/core/src/test/nested-sequences.test.tsx
@@ -3,7 +3,6 @@ import {cleanup, render} from '@testing-library/react';
import {useEffect} from 'react';
import {AbsoluteFill} from '../AbsoluteFill.js';
import {getTimelineDuration} from '../get-timeline-duration.js';
-import {createRuntimeValueStore} from '../runtime-value-store.js';
import {Sequence} from '../Sequence.js';
import {TimelineContext} from '../TimelineContext.js';
import {useCurrentFrame} from '../use-current-frame.js';
@@ -19,7 +18,7 @@ const getForFrame = (frame: number, content: React.ReactNode) => {
frame: {
'my-comp': frame,
},
- playbackStore: createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {
current: [],
},
@@ -256,7 +255,7 @@ test('Sequence freeze pins the child frame without remounting the sequence', ()
frame: {
'my-comp': 15,
},
- playbackStore: createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {
current: [],
},
@@ -277,7 +276,7 @@ test('Sequence freeze pins the child frame without remounting the sequence', ()
frame: {
'my-comp': 25,
},
- playbackStore: createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {
current: [],
},
diff --git a/packages/core/src/test/series.test.tsx b/packages/core/src/test/series.test.tsx
index 991896089a..fb98be908f 100644
--- a/packages/core/src/test/series.test.tsx
+++ b/packages/core/src/test/series.test.tsx
@@ -4,7 +4,6 @@ import {renderToString} from 'react-dom/server';
import {AbsoluteFill} from '../AbsoluteFill.js';
import {CanUseRemotionHooksProvider} from '../CanUseRemotionHooks.js';
import {Internals} from '../internals.js';
-import {createRuntimeValueStore} from '../runtime-value-store.js';
import {Sequence} from '../Sequence.js';
import {Series} from '../series/index.js';
import type {TimelineContextValue} from '../TimelineContext.js';
@@ -51,7 +50,7 @@ const renderForFrame = (frame: number, markup: React.ReactNode) => {
frame: {
'my-comp': frame,
},
- playbackStore: createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {current: []},
};
diff --git a/packages/core/src/test/wrap-sequence-context.tsx b/packages/core/src/test/wrap-sequence-context.tsx
index dd1480741c..7ae2b4f6e0 100644
--- a/packages/core/src/test/wrap-sequence-context.tsx
+++ b/packages/core/src/test/wrap-sequence-context.tsx
@@ -5,7 +5,6 @@ import type {CompositionManagerContext} from '../CompositionManagerContext.js';
import {CompositionManager} from '../CompositionManagerContext.js';
import type {LoggingContextValue} from '../log-level-context.js';
import {LogLevelContext} from '../log-level-context.js';
-import {createRuntimeValueStore} from '../runtime-value-store.js';
import {SequenceManagerProvider} from '../SequenceManager.js';
import type {
PlaybackRateContextValue,
@@ -116,7 +115,7 @@ export const WrapSequenceContext: React.FC<{
const timelineContext = useMemo<TimelineContextValue>(
() => ({
frame: {'my-comp': currentFrame},
- playbackStore: createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {current: []},
}),
[currentFrame],
diff --git a/packages/core/src/timeline-position-state.ts b/packages/core/src/timeline-position-state.ts
index c42d10b803..18344e9e69 100644
--- a/packages/core/src/timeline-position-state.ts
+++ b/packages/core/src/timeline-position-state.ts
@@ -126,7 +126,7 @@ type PlayingReturnType = readonly [
];
export const usePlayingState = (): PlayingReturnType => {
- const {playbackStore} = useTimelineContext();
+ const {isPlaying} = useTimelineContext();
const playing = usePlaying();
const {setPlaying} = useContext(SetTimelineContext);
@@ -136,14 +136,14 @@ export const usePlayingState = (): PlayingReturnType => {
setPlaying,
{
get current() {
- return playbackStore.store.getSnapshot().playing as boolean;
+ return isPlaying();
},
set current(val) {
- playbackStore.setSnapshot({playing: val});
+ setPlaying(val);
},
},
],
- [playbackStore, playing, setPlaying],
+ [isPlaying, playing, setPlaying],
);
};
diff --git a/packages/core/src/use-media-tag.ts b/packages/core/src/use-media-tag.ts
index 792335cafc..217e4a7d3c 100644
--- a/packages/core/src/use-media-tag.ts
+++ b/packages/core/src/use-media-tag.ts
@@ -21,7 +21,7 @@ export const useMediaTag = ({
isPremounting: boolean;
isPostmounting: boolean;
}) => {
- const {audioAndVideoTags, playbackStore} = useTimelineContext();
+ const {audioAndVideoTags, isPlaying} = useTimelineContext();
const logLevel = useLogLevel();
const mountTime = useMountTime();
const env = useRemotionEnvironment();
@@ -30,7 +30,7 @@ export const useMediaTag = ({
const tag: PlayableMediaTag = {
id,
play: (reason) => {
- if (!playbackStore.store.getSnapshot().playing) {
+ if (!isPlaying()) {
// Don't play if for example in a <Freeze> state.
return;
}
@@ -63,7 +63,7 @@ export const useMediaTag = ({
mediaRef,
mediaType,
onAutoPlayError,
- playbackStore,
+ isPlaying,
isPremounting,
isPostmounting,
logLevel,
diff --git a/packages/core/src/use-playing.ts b/packages/core/src/use-playing.ts
index b2573d4b27..f13c915300 100644
--- a/packages/core/src/use-playing.ts
+++ b/packages/core/src/use-playing.ts
@@ -1,11 +1,9 @@
-import {useSyncExternalStore} from 'react';
+import {useSyncExternalStore, useContext} from 'react';
import {useTimelineContext} from './timeline-position-state.js';
+import {SetTimelineContext} from './TimelineContext.js';
export const usePlaying = () => {
- const {playbackStore} = useTimelineContext();
- return useSyncExternalStore(
- playbackStore.store.subscribe,
- () => playbackStore.store.getSnapshot().playing as boolean,
- () => playbackStore.store.getSnapshot().playing as boolean,
- );
+ const {isPlaying} = useTimelineContext();
+ const {subscribePlaying} = useContext(SetTimelineContext);
+ return useSyncExternalStore(subscribePlaying, isPlaying, isPlaying);
};
diff --git a/packages/gif/src/test/Gif.test.tsx b/packages/gif/src/test/Gif.test.tsx
index 237216c1a4..148e794020 100644
--- a/packages/gif/src/test/Gif.test.tsx
+++ b/packages/gif/src/test/Gif.test.tsx
@@ -107,7 +107,7 @@ const compositionContext = {
const timelineContext = {
frame: {},
- playbackStore: Internals.createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {current: []},
} as React.ContextType<typeof Internals.TimelineContext>;
diff --git a/packages/mac-cursors/src/test/resolve-cursor.test.ts b/packages/mac-cursors/src/test/resolve-cursor.test.ts
index 2af3628a9d..d040dfa577 100644
--- a/packages/mac-cursors/src/test/resolve-cursor.test.ts
+++ b/packages/mac-cursors/src/test/resolve-cursor.test.ts
@@ -106,7 +106,7 @@ test('<MacOSCursor> renders the default cursor when the cursor prop is omitted',
} as React.ContextType<typeof Internals.CompositionManager>;
const timeline = {
frame: {comp: 0},
- playbackStore: Internals.createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {current: []},
} as React.ContextType<typeof Internals.TimelineContext>;
const markup = renderToString(
diff --git a/packages/player/src/Player.tsx b/packages/player/src/Player.tsx
index 7f70437416..6f1c2dad14 100644
--- a/packages/player/src/Player.tsx
+++ b/packages/player/src/Player.tsx
@@ -244,8 +244,8 @@ const PlayerFn = <
}));
const rootRef = useRef<PlayerRef>(null);
const audioAndVideoTags = useRef<PlayableMediaTag[]>([]);
- const playbackStore = useMemo(
- () => Internals.createRuntimeValueStore({playing: false}),
+ const playingController = useMemo(
+ () => Internals.createPlayingController(false),
[],
);
const [currentPlaybackRate, setCurrentPlaybackRate] = useState(playbackRate);
@@ -412,10 +412,10 @@ const PlayerFn = <
const timelineContextValue = useMemo((): TimelineContextValue => {
return {
frame,
- playbackStore,
+ isPlaying: playingController.isPlaying,
audioAndVideoTags,
};
- }, [frame, playbackStore]);
+ }, [frame, playingController.isPlaying, audioAndVideoTags]);
const playbackRateContextValue = useMemo((): PlaybackRateContextValue => {
return {
@@ -429,17 +429,14 @@ const PlayerFn = <
setFrame,
setPlaying: (updater) => {
if (typeof updater === 'function') {
- playbackStore.setSnapshot({
- playing: updater(
- playbackStore.store.getSnapshot().playing as boolean,
- ),
- });
+ playingController.setPlaying(updater(playingController.isPlaying()));
} else {
- playbackStore.setSnapshot({playing: updater});
+ playingController.setPlaying(updater);
}
},
+ subscribePlaying: playingController.subscribePlaying,
};
- }, [playbackStore, setFrame]);
+ }, [playingController, setFrame]);
if (typeof window !== 'undefined') {
// eslint-disable-next-line react-hooks/rules-of-hooks
diff --git a/packages/player/src/Thumbnail.tsx b/packages/player/src/Thumbnail.tsx
index 378e0656a8..8dfa6066b2 100644
--- a/packages/player/src/Thumbnail.tsx
+++ b/packages/player/src/Thumbnail.tsx
@@ -87,7 +87,7 @@ const ThumbnailFn = <
const timelineState: TimelineContextValue = useMemo(() => {
const value: TimelineContextValue = {
- playbackStore: Internals.createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
frame: {
[PLAYER_COMP_ID]: frameToDisplay,
},
diff --git a/packages/player/src/use-player-methods.ts b/packages/player/src/use-player-methods.ts
index 2accce5978..9795491318 100644
--- a/packages/player/src/use-player-methods.ts
+++ b/packages/player/src/use-player-methods.ts
@@ -22,6 +22,7 @@ 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 audioContext = useContext(Internals.SharedAudioContext);
const audioTagsContext = useContext(Internals.SharedAudioTagsContext);
const environment = useRemotionEnvironment();
@@ -48,6 +49,8 @@ export const usePlayerMethods = (): UsePlayerMethods => {
);
}
+ const {isPlaying: readIsPlaying} = timelineContext;
+
const getCurrentFrame = useCallback(() => {
if (!video) {
return (
@@ -103,7 +106,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
const play = useCallback(
(e?: SyntheticEvent | PointerEvent) => {
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
+ if (readIsPlaying()) {
return;
}
@@ -129,7 +132,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
tag.play('player play() was called and playing audio from a click'),
);
- timelineContext.playbackStore.setSnapshot({playing: true});
+ setPlaying(true);
playStart.current = getCurrentFrame();
emitter.dispatchPlay();
},
@@ -139,23 +142,25 @@ export const usePlayerMethods = (): UsePlayerMethods => {
config?.durationInFrames,
emitter,
getCurrentFrame,
+ readIsPlaying,
seek,
- timelineContext,
+ setPlaying,
+ timelineContext.audioAndVideoTags,
],
);
const pause = useCallback(() => {
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
- timelineContext.playbackStore.setSnapshot({playing: false});
+ if (readIsPlaying()) {
+ setPlaying(false);
emitter.dispatchPause();
audioContext?.suspend();
}
- }, [audioContext, emitter, timelineContext]);
+ }, [audioContext, emitter, readIsPlaying, setPlaying]);
const pauseAndReturnToPlayStart = useCallback(() => {
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
- timelineContext.playbackStore.setSnapshot({playing: false});
+ if (readIsPlaying()) {
+ setPlaying(false);
fallbackFrame.current = playStart.current;
if (config) {
timelineContext.frame = {
@@ -169,7 +174,14 @@ export const usePlayerMethods = (): UsePlayerMethods => {
emitter.dispatchPause();
}
}
- }, [config, emitter, setTimelinePosition, timelineContext]);
+ }, [
+ config,
+ emitter,
+ readIsPlaying,
+ setPlaying,
+ setTimelinePosition,
+ timelineContext,
+ ]);
const videoId = video?.id;
const lastFrame = (config?.durationInFrames ?? 1) - 1;
@@ -180,7 +192,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
return null;
}
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
+ if (readIsPlaying()) {
return;
}
@@ -201,7 +213,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
: {...currentFrames, [videoId]: newFrame},
);
},
- [setFrame, timelineContext, videoId],
+ [readIsPlaying, setFrame, timelineContext, videoId],
);
const frameForward = useCallback(
@@ -210,7 +222,7 @@ export const usePlayerMethods = (): UsePlayerMethods => {
return null;
}
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
+ if (readIsPlaying()) {
return;
}
@@ -231,23 +243,23 @@ export const usePlayerMethods = (): UsePlayerMethods => {
: {...currentFrames, [videoId]: newFrame},
);
},
- [lastFrame, setFrame, timelineContext, videoId],
+ [lastFrame, readIsPlaying, setFrame, timelineContext, videoId],
);
const toggle = useCallback(
(e?: SyntheticEvent | PointerEvent) => {
- if (timelineContext.playbackStore.store.getSnapshot().playing) {
+ if (readIsPlaying()) {
pause();
} else {
play(e);
}
},
- [pause, play, timelineContext],
+ [pause, play, readIsPlaying],
);
const isPlaying = useCallback(() => {
- return timelineContext.playbackStore.store.getSnapshot().playing as boolean;
- }, [timelineContext]);
+ return readIsPlaying();
+ }, [readIsPlaying]);
const isBuffering = useCallback(() => {
return bufferingContext.buffering.current;
diff --git a/packages/studio/src/components/WebMcp.tsx b/packages/studio/src/components/WebMcp.tsx
index 45debd3bea..91b662914e 100644
--- a/packages/studio/src/components/WebMcp.tsx
+++ b/packages/studio/src/components/WebMcp.tsx
@@ -129,7 +129,7 @@ export const WebMcp: FC = () => {
useContext(Internals.CompositionManager);
const {playbackRate: currentPlaybackRate, setPlaybackRate} =
Internals.usePlaybackRate();
- const {playbackStore} = Internals.Timeline.useTimelineContext();
+ const {isPlaying} = Internals.Timeline.useTimelineContext();
const {mediaVolume, playerMuted} = useContext(Internals.MediaVolumeContext);
const {setPlayerMuted} = useContext(Internals.SetMediaVolumeContext);
const {setZoom: setTimelineZoom, zoom: timelineZoomMap} =
@@ -688,7 +688,7 @@ export const WebMcp: FC = () => {
return Promise.resolve({
currentComposition: compositionId,
currentFrame: getCurrentFrame(),
- playing: playbackStore.store.getSnapshot().playing as boolean,
+ playing: isPlaying(),
muted: playerMutedRef.current,
volume: mediaVolumeRef.current,
playbackRate: playbackRateRef.current,
@@ -1218,7 +1218,7 @@ export const WebMcp: FC = () => {
};
}, [
clearSelection,
- playbackStore,
+ isPlaying,
selectComposition,
selectItems,
setEditorShowGuides,
diff --git a/packages/test-utils/src/timeline-context.ts b/packages/test-utils/src/timeline-context.ts
index 07624817b6..a1ddcdfe5a 100644
--- a/packages/test-utils/src/timeline-context.ts
+++ b/packages/test-utils/src/timeline-context.ts
@@ -1,5 +1,4 @@
import type {TimelineContextValue} from 'remotion';
-import {Internals} from 'remotion';
import {ID} from './id.js';
export const makeTimelineContext = (frame: number): TimelineContextValue => {
@@ -7,7 +6,7 @@ export const makeTimelineContext = (frame: number): TimelineContextValue => {
frame: {
[ID]: frame,
},
- playbackStore: Internals.createRuntimeValueStore({playing: false}),
+ isPlaying: () => false,
audioAndVideoTags: {current: []},
};
};