Skip to content

🎥 Make videos programmatically with React

5.0 KB
Raw Blame
import {createContext, useContext} from 'react';
import {
	SequenceActivityAbsoluteTimeContext,
	SequenceActivityDormantContext,
	SequenceActivityTimelineContext,
} from './sequence-activity-context.js';
import {
	AbsoluteTimeContext,
	PlaybackRateContext,
	SetTimelineContext,
	TimelineContext,
	type PlaybackRateContextValue,
	type TimelineContextValue,
} from './TimelineContext.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
import {useVideo} from './use-video.js';

export type PlayableMediaTag = {
	play: (reason: string) => void;
	id: string;
};

type CurrentTimePerComposition = Record<string, number>;

// Reading TimelineContext and ignoring its value would still schedule frame
// updates. Inactive subscribers must read a separate, never-changing context.
const UnsubscribedTimelineContext = createContext<TimelineContextValue | null>(
	null,
);

const makeKey = () => {
	return `remotion.time-all`;
};

export const persistCurrentFrame = (time: CurrentTimePerComposition) => {
	localStorage.setItem(makeKey(), JSON.stringify(time));
};

export const getInitialFrameState = () => {
	const item = localStorage.getItem(makeKey()) ?? '{}';
	const obj: CurrentTimePerComposition = JSON.parse(item);
	return obj;
};

export const getFrameForComposition = (composition: string) => {
	const item = localStorage.getItem(makeKey()) ?? '{}';
	const obj: CurrentTimePerComposition = JSON.parse(item);

	if (obj[composition] !== undefined) {
		return Number(obj[composition]);
	}

	if (typeof window === 'undefined') {
		return 0;
	}

	return window.remotion_initialFrame ?? 0;
};

export const clampFrameToCompositionRange = (
	frame: number,
	durationInFrames: number,
) => {
	return Math.max(0, Math.min(Math.max(0, durationInFrames - 1), frame));
};

const useTimelinePositionFromContext = (
	state: TimelineContextValue | null,
): number => {
	const videoConfig = useVideo();
	const env = useRemotionEnvironment();
	const dormant = useContext(SequenceActivityDormantContext);

	if (state === null) {
		return 0;
	}

	if (!videoConfig) {
		return typeof window === 'undefined'
			? 0
			: (window.remotion_initialFrame ?? 0);
	}

	const unclamped =
		state.frame[videoConfig.id] ??
		(env.isPlayer ? 0 : getFrameForComposition(videoConfig.id));

	// A discovery clock can be beyond the composition end, for example when a
	// nested scene is trimmed by its parent. Keep its initial local frame intact.
	return dormant
		? unclamped
		: clampFrameToCompositionRange(unclamped, videoConfig.durationInFrames);
};

export const useTimelineContext = (): TimelineContextValue => {
	const dormant = useContext(SequenceActivityDormantContext);
	const state = useContext(
		dormant ? SequenceActivityTimelineContext : TimelineContext,
	);
	if (state === null) {
		throw new Error(
			'TimelineContext is not available. This hook must be used inside a <Player> or the Remotion Studio.',
		);
	}

	return state;
};

export const usePlaybackRate = (): PlaybackRateContextValue => {
	const state = useContext(PlaybackRateContext);
	if (state === null) {
		throw new Error(
			'PlaybackRateContext is not available. This hook must be used inside a <Player> or the Remotion Studio.',
		);
	}

	return state;
};

export const useTimelinePosition = (): number => {
	const state = useTimelineContext();
	return useTimelinePositionFromContext(state);
};

export const useTimelinePositionWithOptionalSubscription = (
	subscribe: boolean,
): number => {
	const dormant = useContext(SequenceActivityDormantContext);
	const state = useContext(
		subscribe
			? dormant
				? SequenceActivityTimelineContext
				: TimelineContext
			: UnsubscribedTimelineContext,
	);
	const frame = useTimelinePositionFromContext(state);
	if (subscribe && state === null) {
		throw new Error(
			'TimelineContext is not available. This hook must be used inside a <Player> or the Remotion Studio.',
		);
	}

	return frame;
};

export const useIsInsideFreeze = (): boolean => {
	return useTimelineContext().isInsideFreeze;
};

export const useAbsoluteTimelinePosition = (): number => {
	const dormant = useContext(SequenceActivityDormantContext);
	const state = useContext(
		dormant ? SequenceActivityAbsoluteTimeContext : AbsoluteTimeContext,
	);
	if (state === null) {
		throw new Error(
			'AbsoluteTimeContext is not available. This hook must be used inside a <Player> or the Remotion Studio.',
		);
	}

	return useTimelinePositionFromContext(state);
};

// Playback and frame persistence only. Navigation must use useTimelineSeekFrame.
export const useTimelineSetFrameWithoutSeek = (): ((
	u: React.SetStateAction<Record<string, number>>,
) => void) => {
	const {setFrameWithoutSeek} = useContext(SetTimelineContext);
	return setFrameWithoutSeek;
};

// Explicit navigation only. Rendering and thumbnails have no seek revision.
export const useTimelineSeekFrame = () => {
	const {seek, setFrameWithoutSeek} = useContext(SetTimelineContext);
	return seek?.seekFrame ?? setFrameWithoutSeek;
};

export {usePlaying} from './use-playing.js';
export {useBuffering} from './use-buffering.js';