Skip to content

🎥 Make videos programmatically with React

33.5 KB
Raw Blame
import React, {
	createContext,
	forwardRef,
	useContext,
	useLayoutEffect,
	useMemo,
	useRef,
	useState,
} from 'react';
import {AbsoluteFillElement} from './AbsoluteFillElement.js';
import {
	withCommittedMetadata,
	type CommittedMetadata,
} from './committed-metadata.js';
import {getSingleChildComponent} from './component-identity.js';
import type {
	LoopDisplay,
	SequenceControls,
	SequenceRegistrationControls,
	TSequence,
} from './CompositionManager.js';
import {DefaultPremountContext} from './DefaultPremountContext.js';
import type {EffectDefinition} from './effects/effect-types.js';
import {getStackForControls} from './enable-sequence-stack-traces.js';
import {Freeze, useIsInsideNonPremountFreeze} from './freeze.js';
import {getSequenceBoundaryTolerance} from './get-sequence-boundary-tolerance.js';
import {
	sequenceSchema,
	sequenceSchemaWithoutFrom,
} from './interactivity-schema.js';
import {LoopContext, type LoopContextType} from './loop/loop-context.js';
import {
	resolveSequenceContentDuration,
	resolveSequenceDuration,
} from './resolve-sequence-duration.js';
import type {RuntimeValueStore} from './runtime-value-store.js';
import {
	SequenceActivityContext,
	SequenceActivityDormantContext,
	SequenceActivitySuspensionContext,
} from './sequence-activity-context.js';
import {
	getSequenceCropClipPath,
	resolveSequenceCrop,
	validateSequenceCrop,
} from './sequence-crop.js';
import {
	SequenceOutlineContext,
	SequenceOutlineInternals,
} from './sequence-outline.js';
import {
	SequenceActivityBoundary,
	SequenceActivityContent,
} from './SequenceActivityBoundary.js';
import {useSequenceActivityAdmission} from './SequenceActivityBudget.js';
import type {SequenceContextType} from './SequenceContext.js';
import {SequenceContext} from './SequenceContext.js';
import {SequenceRegistrationContext} from './SequenceManager.js';
import {IsInsideSeriesContext} from './series/is-inside-series.js';
import {useTimelinePosition} from './timeline-position-state.js';
import {
	TimelineTrackContext,
	type TimelineTrackItem,
} from './timeline-track-context.js';
import type {BasicMediaInTimelineReturnType} from './use-media-in-timeline.js';
import {usePremounting} from './use-premounting.js';
import {useRemotionEnvironment} from './use-remotion-environment.js';
import {useSequenceRegistration} from './use-sequence-registration.js';
import {useVideoConfig} from './use-video-config.js';
import {withInteractivitySchema} from './with-interactivity-schema.js';

const SeriesContentVisibilityContext = createContext(true);
const SequenceContextProvider = withCommittedMetadata(SequenceContext.Provider);

const EMPTY_EFFECTS: readonly EffectDefinition<unknown>[] = [];
type EffectDefinitionsWithRuntimeValues =
	readonly EffectDefinition<unknown>[] & {
		readonly runtimeValues: readonly RuntimeValueStore[];
	};

export type AbsoluteFillLayout = {
	layout?: 'absolute-fill';
	premountFor?: number;
	postmountFor?: number;
	style?: React.CSSProperties;
	styleWhilePremounted?: React.CSSProperties;
	styleWhilePostmounted?: React.CSSProperties;
	className?: string;
};

export type LayoutAndStyle =
	| AbsoluteFillLayout
	| {
			layout: 'none';
	  };

export type SequencePropsWithoutDuration = {
	readonly children?: React.ReactNode;
	readonly width?: number;
	readonly height?: number;
	readonly cropLeft?: number;
	readonly cropRight?: number;
	readonly cropTop?: number;
	readonly cropBottom?: number;
	readonly from?: number;
	readonly trimBefore?: number;
	readonly playbackRate?: number;
	readonly loop?: boolean;
	readonly freeze?: number | null;
	readonly name?: string;
	readonly showInTimeline?: boolean;
	readonly hidden?: boolean;
	readonly controls?: SequenceControls;
	readonly _remotionInternalEffects?: readonly EffectDefinition<unknown>[];
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalTimelineTrack?: Pick<
		TimelineTrackItem,
		'role' | 'seriesOffset'
	>;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalLoopDisplay?: LoopDisplay;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalPremountDisplay?: number | null;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalPostmountDisplay?: number | null;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalStack?: string;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalDocumentationLink?: string;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalSingleChildComponent?: unknown;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalIsPremounting?: boolean;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalIsPostmounting?: boolean;
	/**
	 * @deprecated For internal use only.
	 */
	readonly _remotionInternalIsMedia?:
		| {
				type: 'video' | 'audio';
				data: BasicMediaInTimelineReturnType;
		  }
		| {
				type: 'image';
				src: string;
		  };
	/**
	 * @deprecated This prop has no effect. Remotion Studio discovers selection outlines automatically.
	 */
	readonly outlineRef?: React.RefObject<Element | null> | null;
} & LayoutAndStyle;

export type SequenceProps = {
	readonly durationInFrames?: number;
} & SequencePropsWithoutDuration;

// Bind explicit arguments instead of capturing render variables. Extracted hooks
// can be inlined by minifiers and retain children through their shared scope.
const getSequenceRegistration = (sequence: TSequence): TSequence => {
	return sequence;
};

const getSequenceStack = (stack: string | null): string | null => {
	return stack;
};

const getSequenceCurrentFrame = (ref: React.RefObject<number>): number => {
	return ref.current;
};

const setSequenceWrapperRef = (
	ref: React.ForwardedRef<HTMLDivElement>,
	wrapperRef: React.RefObject<HTMLDivElement | null>,
	node: HTMLDivElement | null,
) => {
	wrapperRef.current = node;
	if (typeof ref === 'function') {
		ref(node);
	} else if (ref) {
		ref.current = node;
	}
};

const RegularSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
	HTMLDivElement,
	SequenceProps
> = (
	{
		from = 0,
		trimBefore = 0,
		playbackRate = 1,
		loop = false,
		freeze,
		durationInFrames,
		children,
		name,
		height,
		width,
		showInTimeline = true,
		hidden = false,
		controls,
		_remotionInternalEffects,
		_remotionInternalTimelineTrack: timelineTrackItem,
		_remotionInternalLoopDisplay: loopDisplay,
		_remotionInternalStack: stack,
		_remotionInternalSingleChildComponent: childComponentOverride,
		_remotionInternalDocumentationLink: documentationLink,
		_remotionInternalPremountDisplay: premountDisplay,
		_remotionInternalPostmountDisplay: postmountDisplay,
		_remotionInternalIsMedia: isMedia,
		cropLeft,
		cropRight,
		cropTop,
		cropBottom,
		...other
	},
	ref,
) => {
	const {layout = 'absolute-fill'} = other;

	const [id] = useState(() => String(Math.random()));
	const parentSequence = useContext(SequenceContext);
	const activityRequested = useContext(SequenceActivityContext);
	const parentDormant = useContext(SequenceActivityDormantContext);
	const activitySuspended = useContext(SequenceActivitySuspensionContext);
	const hadActivity = useRef(false);
	const env = useRemotionEnvironment();
	const activityEnabled = activityRequested && env.isStudio && !env.isRendering;
	const timelineTrack = useContext(TimelineTrackContext);
	const timelineTrackRole = timelineTrackItem?.role ?? 'clip';
	const seriesOffset = timelineTrackItem?.seriesOffset ?? null;
	const parentPlaybackRate = parentSequence?.playbackRate ?? 1;
	const cumulativePlaybackRate = parentPlaybackRate * playbackRate;
	const cumulatedFrom = parentSequence
		? parentSequence.cumulatedFrom + parentSequence.relativeFrom
		: 0;
	if (layout !== 'absolute-fill' && layout !== 'none') {
		throw new TypeError(
			`The layout prop of <Sequence /> expects either "absolute-fill" or "none", but you passed: ${layout}`,
		);
	}

	const cropProps = {cropLeft, cropRight, cropTop, cropBottom};
	const hasCropProp = Object.values(cropProps).some(
		(value) => value !== undefined,
	);

	if (layout === 'none' && hasCropProp) {
		throw new TypeError(
			'The cropLeft, cropRight, cropTop and cropBottom props of <Sequence /> are only supported with layout="absolute-fill".',
		);
	}

	validateSequenceCrop(cropProps);
	const {
		left: resolvedCropLeft,
		right: resolvedCropRight,
		top: resolvedCropTop,
		bottom: resolvedCropBottom,
	} = resolveSequenceCrop(cropProps);
	// @ts-expect-error
	if (layout === 'none' && typeof other.style !== 'undefined') {
		throw new TypeError(
			'If layout="none", you may not pass a style. Passed: ' +
				// @ts-expect-error
				JSON.stringify(other.style),
		);
	}

	const contentDurationInFrames = resolveSequenceContentDuration({
		durationInFrames,
	});

	if (typeof contentDurationInFrames !== 'number') {
		throw new TypeError(
			`You passed to durationInFrames an argument of type ${typeof contentDurationInFrames}, but it must be a number.`,
		);
	}

	if (contentDurationInFrames <= 0) {
		throw new TypeError(
			`durationInFrames must be positive, but got ${contentDurationInFrames}`,
		);
	}

	if (typeof from !== 'number') {
		throw new TypeError(
			`You passed to the "from" props of your <Sequence> an argument of type ${typeof from}, but it must be a number.`,
		);
	}

	if (!Number.isFinite(from)) {
		throw new TypeError(
			`The "from" prop of a sequence must be finite, but got ${from}.`,
		);
	}

	if (typeof trimBefore !== 'number') {
		throw new TypeError(
			`You passed to the "trimBefore" prop of your <Sequence> an argument of type ${typeof trimBefore}, but it must be a number.`,
		);
	}

	if (trimBefore < 0) {
		throw new TypeError(
			`The "trimBefore" prop of <Sequence /> must be greater than or equal to 0, but got ${trimBefore}.`,
		);
	}

	if (Number.isNaN(trimBefore)) {
		throw new TypeError(
			'The "trimBefore" prop of <Sequence /> must be a real number, but it is NaN.',
		);
	}

	if (!Number.isFinite(trimBefore)) {
		throw new TypeError(
			`The "trimBefore" prop of <Sequence /> must be finite, but it is ${trimBefore}.`,
		);
	}

	if (typeof loop !== 'boolean') {
		throw new TypeError(
			`The "loop" prop of <Sequence /> must be a boolean, but is of type ${typeof loop}.`,
		);
	}

	if (loop && !Number.isFinite(contentDurationInFrames)) {
		throw new Error(
			'The "loop" prop of <Sequence /> requires a finite "durationInFrames" prop, because a <Sequence /> has no intrinsic duration.',
		);
	}

	if (typeof freeze !== 'undefined' && freeze !== null) {
		if (typeof freeze !== 'number') {
			throw new TypeError(
				`The "freeze" prop of <Sequence /> must be a number, but is of type ${typeof freeze}.`,
			);
		}

		if (Number.isNaN(freeze)) {
			throw new TypeError(
				`The "freeze" prop of <Sequence /> must be a real number, but it is NaN.`,
			);
		}

		if (!Number.isFinite(freeze)) {
			throw new TypeError(
				`The "freeze" prop of <Sequence /> must be finite, but it is ${freeze}.`,
			);
		}
	}

	const absoluteFrame = useTimelinePosition();
	const lastPlaybackRate = useRef({playbackRate, frame: absoluteFrame});
	if (
		typeof playbackRate !== 'number' ||
		!Number.isFinite(playbackRate) ||
		playbackRate <= 0
	) {
		throw new TypeError(
			`The "playbackRate" prop of <Sequence /> must be a positive finite number, but got ${playbackRate}.`,
		);
	}

	if (
		lastPlaybackRate.current.frame !== absoluteFrame &&
		lastPlaybackRate.current.playbackRate !== playbackRate
	) {
		throw new Error(
			'The "playbackRate" prop of <Sequence /> must be constant. Animating playbackRate is not supported.',
		);
	}

	useLayoutEffect(() => {
		lastPlaybackRate.current = {playbackRate, frame: absoluteFrame};
	}, [absoluteFrame, playbackRate]);
	const videoConfig = useVideoConfig();
	const effectiveDurationInFrames = resolveSequenceDuration({
		durationInFrames,
		playbackRate,
		loop,
	});
	const windowRelativeFrom = from - trimBefore / playbackRate;

	const parentSequenceDuration = parentSequence
		? Math.min(
				parentSequence.durationInFrames - windowRelativeFrom,
				effectiveDurationInFrames,
			)
		: effectiveDurationInFrames;
	const actualDurationInFrames = Math.max(
		0,
		Math.min(videoConfig.durationInFrames - from, parentSequenceDuration),
	);

	// A looped sequence repeats the child range selected by `durationInFrames`. Each
	// iteration lasts `loopPeriod` parent frames and moves the clock origin,
	// while the visible window stays at [from, from + effectiveDurationInFrames).
	const frameInParent = (absoluteFrame - cumulatedFrom) * parentPlaybackRate;
	const loopPeriod =
		loop && Number.isFinite(contentDurationInFrames)
			? contentDurationInFrames / playbackRate
			: null;
	let loopIteration = 0;
	if (
		loopPeriod !== null &&
		(!activityEnabled ||
			(!parentDormant &&
				frameInParent >= from &&
				frameInParent < from + actualDurationInFrames))
	) {
		const loopsElapsed = (frameInParent - from) / loopPeriod;
		const nearestIteration = Math.round(loopsElapsed);
		// Fractional periods and nested playback rates can put an exact loop
		// boundary a few floating-point units before the next iteration.
		const isAtBoundary =
			Math.abs(loopsElapsed - nearestIteration) <=
			Number.EPSILON * Math.max(1, Math.abs(loopsElapsed)) * 4;
		const lastIteration = Math.ceil(actualDurationInFrames / loopPeriod) - 1;
		loopIteration = Math.max(
			0,
			Math.min(
				lastIteration,
				isAtBoundary ? nearestIteration : Math.floor(loopsElapsed),
			),
		);
	}

	const loopOffset = loopPeriod === null ? 0 : loopIteration * loopPeriod;
	const clockFrom = from + loopOffset;
	const effectiveRelativeFrom = clockFrom - trimBefore / playbackRate;
	const relativeFrom = effectiveRelativeFrom / parentPlaybackRate;
	const absoluteFrom = (parentSequence?.absoluteFrom ?? 0) + relativeFrom;
	// Inside a loop, the local clock ends after `durationInFrames`, except in a final
	// iteration that the parent cuts short.
	const localClockEnd =
		loopPeriod === null
			? actualDurationInFrames * playbackRate + trimBefore
			: Math.min(loopPeriod, actualDurationInFrames - loopOffset) *
					playbackRate +
				trimBefore;
	const sequenceRegistrationEnabled = useContext(SequenceRegistrationContext);
	const canvasOutlinesEnabled = useContext(SequenceOutlineContext);
	const shouldDiscoverOutline = env.isStudio || canvasOutlinesEnabled;
	const automaticOutlineRef = useMemo(
		() =>
			shouldDiscoverOutline && layout === 'none'
				? SequenceOutlineInternals.createRef()
				: null,
		[shouldDiscoverOutline, layout],
	);
	const wrapperRefForOutline = useRef<HTMLDivElement | null>(null);
	const refForOutline =
		layout === 'none' ? automaticOutlineRef : wrapperRefForOutline;

	const premounting = useMemo(() => {
		// || is intentional, ?? would not trigger on `false`
		return (
			parentSequence?.premounting ||
			Boolean(other._remotionInternalIsPremounting)
		);
	}, [other._remotionInternalIsPremounting, parentSequence?.premounting]);

	const postmounting = useMemo(() => {
		// || is intentional, ?? would not trigger on `false`
		return (
			parentSequence?.postmounting ||
			Boolean(other._remotionInternalIsPostmounting)
		);
	}, [other._remotionInternalIsPostmounting, parentSequence?.postmounting]);

	// `cumulatedNegativeFrom` answers: "How many frames of this media have
	// already elapsed before the first visible frame of this sequence?"
	//
	// This is intentionally based on the effective sequence start, not on adding
	// all negative `from` values. See the asset-calculation tests for:
	// - "Should calculate startFrom correctly with negative offset (Html5Audio)"
	// - "same as above, but with <Sequence from={0}> inbetween"
	// - "same as above, but a positive child offset cancels part of the negative parent offset"
	//
	// In particular, <Sequence from={-20}><Sequence from={10}> should have a
	// 10-frame pre-roll, because the positive child offset cancels part of the
	// negative parent offset. But <Sequence from={10}><Sequence from={-5}>
	// should still trim 5 frames from the media once the parent starts.
	const currentSequenceStart = cumulatedFrom + relativeFrom;
	const parentSequenceStart = parentSequence
		? parentSequence.cumulatedFrom + parentSequence.relativeFrom
		: 0;
	const parentFirstFrame = parentSequence
		? parentSequenceStart -
			parentSequence.cumulatedNegativeFrom / parentPlaybackRate
		: 0;
	const firstFrame = Math.max(
		0,
		parentFirstFrame,
		cumulatedFrom + clockFrom / parentPlaybackRate,
	);
	const cumulatedNegativeFrom =
		(currentSequenceStart - firstFrame) * cumulativePlaybackRate;

	const contextValue = useMemo((): SequenceContextType => {
		return {
			playbackRate: cumulativePlaybackRate,
			absoluteFrom,
			cumulatedFrom,
			relativeFrom,
			cumulatedNegativeFrom,
			durationInFrames: localClockEnd,
			parentFrom: parentSequence?.relativeFrom ?? 0,
			id,
			height: height ?? parentSequence?.height ?? null,
			width: width ?? parentSequence?.width ?? null,
			premounting,
			postmounting,
			premountDisplay: premountDisplay ?? null,
			postmountDisplay: postmountDisplay ?? null,
		};
	}, [
		cumulatedFrom,
		absoluteFrom,
		relativeFrom,
		cumulativePlaybackRate,
		localClockEnd,
		parentSequence,
		id,
		height,
		width,
		premounting,
		postmounting,
		premountDisplay,
		postmountDisplay,
		cumulatedNegativeFrom,
	]);

	const loopContextValue = useMemo((): LoopContextType | null => {
		if (loopPeriod === null) {
			return null;
		}

		return {
			iteration: loopIteration,
			durationInFrames: contentDurationInFrames,
		};
	}, [contentDurationInFrames, loopIteration, loopPeriod]);

	const resolvedLoopDisplay = useMemo((): LoopDisplay | undefined => {
		if (loopDisplay || loopPeriod === null) {
			return loopDisplay;
		}

		return {
			numberOfTimes: actualDurationInFrames / loopPeriod,
			startOffset: 0,
			durationInFrames: loopPeriod,
		};
	}, [actualDurationInFrames, loopDisplay, loopPeriod]);

	const timelineClipName = useMemo(() => {
		return name ?? '';
	}, [name]);

	const resolvedDocumentationLink =
		documentationLink ?? 'https://www.remotion.dev/docs/sequence';

	const isInsideSeries = useContext(IsInsideSeriesContext);

	const singleChildComponent = useMemo(
		() =>
			childComponentOverride === undefined
				? getSingleChildComponent(children)
				: childComponentOverride,
		[children, childComponentOverride],
	);
	const registrationStack = controls
		? (getStackForControls(controls) ?? stack ?? null)
		: (stack ?? null);
	const getStack = useMemo(
		() => getSequenceStack.bind(null, registrationStack),
		[registrationStack],
	);
	const registeredFrozenFrame = typeof freeze === 'number' ? freeze : null;
	const currentFrame =
		registeredFrozenFrame ??
		(absoluteFrame - currentSequenceStart) * cumulativePlaybackRate;
	const currentFrameRef = useRef(currentFrame);
	useLayoutEffect(() => {
		currentFrameRef.current = currentFrame;
	}, [currentFrame]);
	const getCurrentFrame = useMemo(
		() => getSequenceCurrentFrame.bind(null, currentFrameRef),
		[currentFrameRef],
	);
	const registeredTrimBefore = trimBefore === 0 ? null : trimBefore;
	const parentCumulatedNegativeFrom =
		parentSequence?.cumulatedNegativeFrom ?? 0;
	const startMediaFrom =
		isMedia && isMedia.type !== 'image'
			? isMedia.data.startMediaFrom +
				parentCumulatedNegativeFrom -
				cumulatedNegativeFrom
			: null;
	const mediaFrameAtSequenceZero =
		isMedia && isMedia.type !== 'image'
			? isMedia.data.startMediaFrom + parentCumulatedNegativeFrom
			: null;
	const frozenMediaFrame =
		isMedia && isMedia.type !== 'image' && mediaFrameAtSequenceZero !== null
			? registeredFrozenFrame === null
				? null
				: mediaFrameAtSequenceZero +
					(resolvedLoopDisplay
						? registeredFrozenFrame % resolvedLoopDisplay.durationInFrames
						: registeredFrozenFrame) *
						isMedia.data.playbackRate
			: null;
	const controlsSchema = controls?.schema;
	const controlsRuntimeValues = controls?.runtimeValues;
	const controlsOverrideId = controls?.overrideId;
	const controlsSupportsEffects = controls?.supportsEffects;
	const controlsComponentIdentity = controls?.componentIdentity;
	const controlsComponentName = controls?.componentName;
	const controlsVideoConfigValues = controls?.videoConfigValues;
	const isInsideNonPremountFreeze = useIsInsideNonPremountFreeze();
	const canInferDuration =
		(controlsComponentIdentity === 'dev.remotion.remotion.Series' ||
			controlsComponentIdentity ===
				'dev.remotion.transitions.TransitionSeries') &&
		!loop &&
		registeredFrozenFrame === null &&
		!isInsideNonPremountFreeze &&
		!hidden;
	const autoDuration = canInferDuration && durationInFrames === undefined;
	const isSeriesChild =
		controlsComponentIdentity === 'dev.remotion.remotion.Series.Sequence' ||
		controlsComponentIdentity ===
			'dev.remotion.transitions.TransitionSeries.Sequence' ||
		controlsComponentIdentity ===
			'dev.remotion.transitions.TransitionSeries.Transition' ||
		controlsComponentIdentity ===
			'dev.remotion.transitions.TransitionSeries.Overlay';
	const seriesContentVisible = useContext(SeriesContentVisibilityContext);
	const effectRuntimeValues = useMemo(
		() =>
			(
				_remotionInternalEffects as
					| EffectDefinitionsWithRuntimeValues
					| undefined
			)?.runtimeValues ?? null,
		[_remotionInternalEffects],
	);
	const registrationControls =
		useMemo((): SequenceRegistrationControls | null => {
			if (
				controlsSchema === undefined ||
				controlsRuntimeValues === undefined ||
				controlsOverrideId === undefined ||
				controlsSupportsEffects === undefined ||
				controlsComponentIdentity === undefined ||
				controlsComponentName === undefined ||
				controlsVideoConfigValues === undefined
			) {
				return null;
			}

			return {
				schema: controlsSchema,
				runtimeValues: controlsRuntimeValues,
				overrideId: controlsOverrideId,
				supportsEffects: controlsSupportsEffects,
				componentIdentity: controlsComponentIdentity,
				componentName: controlsComponentName,
				videoConfigValues: controlsVideoConfigValues,
			};
		}, [
			controlsComponentIdentity,
			controlsComponentName,
			controlsVideoConfigValues,
			controlsOverrideId,
			controlsRuntimeValues,
			controlsSchema,
			controlsSupportsEffects,
		]);

	const sequenceForRegistration = useMemo((): TSequence => {
		const trackRegistration = timelineTrack
			? {
					timelineTrack: {
						...timelineTrack,
						role: timelineTrackRole,
						seriesOffset,
					},
				}
			: {};
		if (isMedia) {
			if (isMedia.type === 'image') {
				return {
					...trackRegistration,
					sequencePlaybackRate: playbackRate,
					type: 'image',
					controls: registrationControls,
					effects: _remotionInternalEffects ?? EMPTY_EFFECTS,
					effectRuntimeValues,
					displayName: timelineClipName,
					documentationLink: resolvedDocumentationLink,
					duration: actualDurationInFrames,
					from,
					trimBefore: registeredTrimBefore,
					id,
					loopDisplay: resolvedLoopDisplay,
					parent: parentSequence?.id ?? null,
					postmountDisplay: postmountDisplay ?? null,
					premountDisplay: premountDisplay ?? null,
					showInTimeline,
					timelineOrder: null,
					src: isMedia.src,
					getStack,
					getCurrentFrame,
					refForOutline: refForOutline ?? null,
					isInsideSeries,
					frozenFrame: registeredFrozenFrame,
					singleChildComponent: singleChildComponent ?? null,
				};
			}

			return {
				...trackRegistration,
				type: isMedia.type,
				sequencePlaybackRate: playbackRate,
				controls: registrationControls,
				effects: _remotionInternalEffects ?? EMPTY_EFFECTS,
				effectRuntimeValues,
				displayName: timelineClipName,
				documentationLink: resolvedDocumentationLink,
				duration: actualDurationInFrames,
				from,
				trimBefore: registeredTrimBefore,
				id,
				loopDisplay: resolvedLoopDisplay,
				parent: parentSequence?.id ?? null,
				playbackRate: isMedia.data.playbackRate,
				postmountDisplay: postmountDisplay ?? null,
				premountDisplay: premountDisplay ?? null,
				showInTimeline,
				timelineOrder: null,
				src: isMedia.data.src,
				getStack,
				getCurrentFrame,
				startMediaFrom: startMediaFrom ?? isMedia.data.startMediaFrom,
				mediaFrameAtSequenceZero,
				muted: isMedia.data.muted,
				refForOutline: refForOutline ?? null,
				isInsideSeries,
				frozenFrame: registeredFrozenFrame,
				frozenMediaFrame,
				singleChildComponent: singleChildComponent ?? null,
			};
		}

		return {
			...trackRegistration,
			from,
			sequencePlaybackRate: playbackRate,
			trimBefore: registeredTrimBefore,
			duration: actualDurationInFrames,
			...(autoDuration ? {autoDuration: true} : {}),
			...(canInferDuration ? {canInferDuration: true} : {}),
			...(isSeriesChild ? {unclippedDuration: effectiveDurationInFrames} : {}),
			id,
			displayName: timelineClipName,
			documentationLink: resolvedDocumentationLink,
			parent: parentSequence?.id ?? null,
			type: 'sequence',
			showInTimeline,
			timelineOrder: null,
			loopDisplay: resolvedLoopDisplay,
			getStack,
			getCurrentFrame,
			premountDisplay: premountDisplay ?? null,
			postmountDisplay: postmountDisplay ?? null,
			controls: registrationControls,
			effects: _remotionInternalEffects ?? EMPTY_EFFECTS,
			effectRuntimeValues,
			refForOutline: refForOutline ?? null,
			isInsideSeries,
			frozenFrame: registeredFrozenFrame,
			singleChildComponent: singleChildComponent ?? null,
		};
	}, [
		id,
		timelineTrack,
		timelineTrackRole,
		seriesOffset,
		getCurrentFrame,
		getStack,
		timelineClipName,
		playbackRate,
		parentSequence?.id,
		actualDurationInFrames,
		autoDuration,
		canInferDuration,
		isSeriesChild,
		effectiveDurationInFrames,
		from,
		registeredTrimBefore,
		showInTimeline,
		resolvedLoopDisplay,
		premountDisplay,
		postmountDisplay,
		registrationControls,
		_remotionInternalEffects,
		effectRuntimeValues,
		isMedia,
		resolvedDocumentationLink,
		refForOutline,
		isInsideSeries,
		registeredFrozenFrame,
		startMediaFrom,
		mediaFrameAtSequenceZero,
		frozenMediaFrame,
		singleChildComponent,
	]);
	const getSequenceForRegistration = useMemo(
		() => getSequenceRegistration.bind(null, sequenceForRegistration),
		[sequenceForRegistration],
	);
	const registration = useSequenceRegistration({
		getSequence:
			env.isStudio || sequenceRegistrationEnabled
				? getSequenceForRegistration
				: null,
		id,
	});

	// Use an exclusive end so fractional clocks and frozen subframes remain visible.
	const endThreshold = from + effectiveDurationInFrames;
	const boundaryTolerance = getSequenceBoundaryTolerance({
		absoluteFrame,
		cumulatedFrom,
		from,
		parentPlaybackRate,
		durationInFrames: effectiveDurationInFrames,
	});
	const contentVisible =
		seriesContentVisible &&
		frameInParent - from >= -boundaryTolerance &&
		frameInParent - endThreshold < -boundaryTolerance;
	const activityDormant = parentDormant || !contentVisible;
	const admitted = useSequenceActivityAdmission(
		activityEnabled && !hidden
			? {
					id,
					parent: parentSequence?.id ?? null,
					compositionId: videoConfig.id,
					from: firstFrame,
					end:
						cumulatedFrom +
						(from + actualDurationInFrames) / parentPlaybackRate,
				}
			: null,
	);
	const renderActivity =
		activityEnabled &&
		(!activityDormant ||
			admitted ||
			(activitySuspended && hadActivity.current));
	// A scene visited during playback must keep its children and registrations
	// when it leaves the viewport, even if it was outside the discovery budget.
	const useCommitEffect = React.useInsertionEffect ?? useLayoutEffect;
	useCommitEffect(() => {
		hadActivity.current = renderActivity;
	}, [renderActivity]);
	const content = (activityEnabled ? renderActivity : contentVisible)
		? children
		: null;
	const frozenContent =
		content === null || typeof freeze === 'undefined' || freeze === null ? (
			content
		) : (
			<Freeze frame={freeze}>{content}</Freeze>
		);
	const loopedContent =
		frozenContent === null || loopContextValue === null ? (
			frozenContent
		) : (
			<LoopContext.Provider value={loopContextValue}>
				{frozenContent}
			</LoopContext.Provider>
		);

	const styleIfThere = other.layout === 'none' ? undefined : other.style;
	const cropClipPath = getSequenceCropClipPath({
		left: resolvedCropLeft,
		right: resolvedCropRight,
		top: resolvedCropTop,
		bottom: resolvedCropBottom,
		style: styleIfThere,
	});

	const sequenceRef = useMemo(
		() => setSequenceWrapperRef.bind(null, ref, wrapperRefForOutline),
		[ref, wrapperRefForOutline],
	);

	const defaultStyle: React.CSSProperties = useMemo(() => {
		return {
			flexDirection: undefined,
			...(width ? {width} : {}),
			...(height ? {height} : {}),
			...(styleIfThere ?? {}),
			...(cropClipPath
				? {
						clipPath: cropClipPath,
					}
				: {}),
		};
	}, [cropClipPath, height, styleIfThere, width]);

	if (ref !== null && layout === 'none') {
		throw new TypeError(
			'It is not supported to pass both a `ref` and `layout="none"` to <Sequence />.',
		);
	}

	const metadata = useMemo<CommittedMetadata | null>(
		() =>
			shouldDiscoverOutline || registration !== null
				? {
						type: 'sequence',
						id,
						value: registration,
						outlineChildrenRef: automaticOutlineRef,
					}
				: null,
		[automaticOutlineRef, id, registration, shouldDiscoverOutline],
	);

	if (hidden) {
		return shouldDiscoverOutline || registration !== null ? (
			<SequenceContextProvider
				value={contextValue}
				_remotionCommitMetadata={metadata}
			>
				{null}
			</SequenceContextProvider>
		) : null;
	}

	// Retain resolved scene registrations so Studio can recover the natural end
	// even when seeking past an explicit wrapper trim. Scene contents stay hidden.
	const retainSeriesRegistration = env.isStudio && canInferDuration;
	const contentForLayout = renderActivity ? (
		<SequenceActivityContent dormant={activityDormant}>
			{loopedContent}
		</SequenceActivityContent>
	) : (
		loopedContent
	);
	const renderedContent =
		loopedContent === null ? (
			retainSeriesRegistration ? (
				children
			) : null
		) : other.layout === 'none' ? (
			contentForLayout
		) : (
			<AbsoluteFillElement
				ref={sequenceRef}
				style={defaultStyle}
				className={other.className}
			>
				{contentForLayout}
			</AbsoluteFillElement>
		);
	const activityContent = renderActivity ? (
		<SequenceActivityBoundary dormant={activityDormant} frame={firstFrame}>
			{renderedContent}
		</SequenceActivityBoundary>
	) : (
		renderedContent
	);
	const sequenceContent = (
		<SequenceContextProvider
			value={contextValue}
			_remotionCommitMetadata={metadata}
		>
			{retainSeriesRegistration ? (
				<SeriesContentVisibilityContext.Provider
					value={renderActivity || contentVisible}
				>
					{activityContent}
				</SeriesContentVisibilityContext.Provider>
			) : (
				activityContent
			)}
		</SequenceContextProvider>
	);
	// Keep the provider mounted when track grouping changes so clip state survives.
	const sequence = (
		<TimelineTrackContext.Provider
			value={
				timelineTrackRole === 'track' ||
				(timelineTrackRole === 'clip' && !showInTimeline)
					? timelineTrack
					: null
			}
		>
			{sequenceContent}
		</TimelineTrackContext.Provider>
	);

	return sequence;
};

const RegularSequence = forwardRef(RegularSequenceRefForwardingFunction);

const PremountedPostmountedSequenceRefForwardingFunction: React.ForwardRefRenderFunction<
	HTMLDivElement,
	SequenceProps
> = (props, ref) => {
	if (props.layout === 'none') {
		throw new Error(
			'`<Sequence>` with `premountFor` and `postmountFor` props does not support layout="none"',
		);
	}

	const {
		style: passedStyle,
		from = 0,
		durationInFrames,
		premountFor = 0,
		postmountFor = 0,
		styleWhilePremounted,
		styleWhilePostmounted,
		...otherProps
	} = props;

	const {
		freezeFrame,
		isPremountingOrPostmounting,
		postmountingActive,
		premountingActive,
		premountingStyle,
	} = usePremounting({
		from,
		durationInFrames: resolveSequenceDuration({
			durationInFrames,
			playbackRate: otherProps.playbackRate,
			loop: otherProps.loop,
		}),
		premountFor,
		postmountFor,
		style: passedStyle ?? null,
		styleWhilePremounted: styleWhilePremounted ?? null,
		styleWhilePostmounted: styleWhilePostmounted ?? null,
		hideWhilePremounted: 'opacity',
	});

	return (
		<Freeze
			frame={freezeFrame}
			active={isPremountingOrPostmounting}
			_remotionInternalIsPremounting={premountingActive}
		>
			<RegularSequence
				ref={ref}
				from={from}
				durationInFrames={durationInFrames}
				style={premountingStyle ?? undefined}
				_remotionInternalPremountDisplay={premountFor}
				_remotionInternalPostmountDisplay={postmountFor}
				_remotionInternalIsPremounting={premountingActive}
				_remotionInternalIsPostmounting={postmountingActive}
				{...otherProps}
			/>
		</Freeze>
	);
};

const PremountedPostmountedSequence = forwardRef(
	PremountedPostmountedSequenceRefForwardingFunction,
);

const SequenceRefForwardingFunction: React.ForwardRefRenderFunction<
	HTMLDivElement,
	SequenceProps
> = (props, ref) => {
	const env = useRemotionEnvironment();
	const {fps} = useVideoConfig();
	const defaultPremountInSeconds = useContext(DefaultPremountContext);
	if (props.layout !== 'none' && !env.isRendering) {
		const effectivePremountFor =
			props.premountFor ?? Math.round(defaultPremountInSeconds * fps);
		if (effectivePremountFor || props.postmountFor) {
			return (
				<PremountedPostmountedSequence
					ref={ref}
					{...props}
					premountFor={effectivePremountFor}
				/>
			);
		}
	}

	return <RegularSequence {...props} ref={ref} />;
};

const SequenceInner = forwardRef(SequenceRefForwardingFunction);
export const SequenceWithoutSchema = SequenceInner;

/*
 * @description A component that time-shifts its children and wraps them in an absolutely positioned <div>.
 * @see [Documentation](https://www.remotion.dev/docs/sequence)
 */
export const Sequence = withInteractivitySchema({
	Component: SequenceInner,
	componentName: '<Sequence>',
	componentIdentity: 'dev.remotion.remotion.Sequence',
	schema: sequenceSchema,
	supportsEffects: false,
});

export const SequenceWithoutFrom = withInteractivitySchema({
	Component: SequenceInner,
	componentName: '<Sequence>',
	componentIdentity: null,
	schema: sequenceSchemaWithoutFrom,
	supportsEffects: false,
});