Skip to content

🎥 Make videos programmatically with React

7.3 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-use-before-define */
import React, {forwardRef, useCallback, useContext, useMemo} from 'react';
import {getAbsoluteSrc} from '../absolute-src.js';
import {
	calculateMediaDuration,
	getMediaTrimAfter,
} from '../calculate-media-duration.js';
import {cancelRender} from '../cancel-render.js';
import {addSequenceStackTraces} from '../enable-sequence-stack-traces.js';
import {Loop} from '../loop/index.js';
import {usePreload} from '../prefetch.js';
import {Sequence} from '../Sequence.js';
import {useRemotionEnvironment} from '../use-remotion-environment.js';
import {useVideoConfig} from '../use-video-config.js';
import {resolveV5Default} from '../v5-flag.js';
import {validateMediaProps} from '../validate-media-props.js';
import {
	resolveTrimProps,
	validateMediaTrimProps,
} from '../validate-start-from-props.js';
import {validateDurationInFrames} from '../validation/validate-duration-in-frames.js';
import {DurationsContext, onMediaDuration} from '../video/duration-state.js';
import {AudioForPreview} from './AudioForPreview.js';
import {AudioForRendering} from './AudioForRendering.js';
import type {RemotionAudioProps, RemotionMainAudioProps} from './props.js';
import {SharedAudioTagsContext} from './shared-audio-tags.js';
import {Html5MediaTrimContext} from './use-audio-frame.js';

const AudioRefForwardingFunction: React.ForwardRefRenderFunction<
	HTMLAudioElement,
	RemotionAudioProps &
		RemotionMainAudioProps & {
			/**
			 * @deprecated For internal use only
			 */
			readonly _remotionInternalStack?: string;
		}
> = (props, ref) => {
	const audioTagsContext = useContext(SharedAudioTagsContext);
	const propsWithFreeze = props as typeof props & {readonly freeze?: unknown};
	const {
		startFrom,
		endAt,
		trimBefore,
		trimAfter,
		durationInFrames,
		name,
		_remotionInternalStack,
		pauseWhenBuffering,
		showInTimeline,
		onError: onRemotionError,
		freeze,
		...otherProps
	} = propsWithFreeze;
	const {loop, freeze: _freeze, ...propsOtherThanLoop} = propsWithFreeze;
	const {fps} = useVideoConfig();
	const environment = useRemotionEnvironment();
	const shouldPauseWhenBuffering = resolveV5Default(pauseWhenBuffering);

	if (environment.isClientSideRendering) {
		throw new Error(
			'<Html5Audio> is not supported in @remotion/web-renderer. Use <Audio> from @remotion/media instead. See https://remotion.dev/docs/client-side-rendering/limitations',
		);
	}

	if (typeof freeze !== 'undefined') {
		throw new TypeError(
			'The "freeze" prop is not supported on <Html5Audio />. Use <Sequence freeze={...}> to freeze media playback.',
		);
	}

	const {durations, setDurations} = useContext(DurationsContext);
	if (typeof props.src !== 'string') {
		throw new TypeError(
			`The \`<Html5Audio>\` tag requires a string for \`src\`, but got ${JSON.stringify(
				props.src,
			)} instead.`,
		);
	}

	const preloadedSrc = usePreload(props.src);

	const onError: React.ReactEventHandler<HTMLAudioElement> = useCallback(
		(e) => {
			// eslint-disable-next-line no-console
			console.log(e.currentTarget.error);

			// If there is no `loop` property, we don't need to get the duration
			// and this does not need to be a fatal error
			const errMessage = `Could not play audio with src ${preloadedSrc}: ${e.currentTarget.error}. See https://remotion.dev/docs/media-playback-error for help.`;

			if (loop) {
				if (onRemotionError) {
					onRemotionError(new Error(errMessage));
					return;
				}

				cancelRender(new Error(errMessage));
			} else {
				onRemotionError?.(new Error(errMessage));
				// eslint-disable-next-line no-console
				console.warn(errMessage);
			}
		},
		[loop, onRemotionError, preloadedSrc],
	);

	const onDuration = useMemo(
		() => onMediaDuration.bind(null, setDurations),
		[setDurations],
	);

	const durationFetched =
		durations[getAbsoluteSrc(preloadedSrc)] ??
		durations[getAbsoluteSrc(props.src)];

	validateMediaTrimProps({startFrom, endAt, trimBefore, trimAfter});
	if (durationInFrames !== undefined) {
		validateDurationInFrames(durationInFrames, {
			component: 'of the <Html5Audio /> component',
			allowFloats: true,
		});
	}

	const {trimBeforeValue, trimAfterValue} = resolveTrimProps({
		startFrom,
		endAt,
		trimBefore,
		trimAfter,
	});
	const effectiveTrimAfter = getMediaTrimAfter({
		durationInFrames,
		trimAfter: trimAfterValue,
		trimBefore: trimBeforeValue,
	});

	// An explicit trim end defines the loop before metadata has loaded. Waiting
	// for metadata would leave the media unmounted when seeking into later loops.
	const loopDuration =
		effectiveTrimAfter ??
		(durationFetched === undefined ? undefined : durationFetched * fps);
	if (loop && loopDuration !== undefined) {
		if (!Number.isFinite(loopDuration)) {
			return (
				<Html5Audio
					{...propsOtherThanLoop}
					ref={ref}
					_remotionInternalNativeLoopPassed
				/>
			);
		}

		return (
			<Loop
				layout="none"
				durationInFrames={calculateMediaDuration({
					trimAfter: effectiveTrimAfter,
					mediaDurationInFrames: loopDuration,
					playbackRate: props.playbackRate ?? 1,
					trimBefore: trimBeforeValue,
				})}
			>
				<Html5Audio
					{...propsOtherThanLoop}
					ref={ref}
					_remotionInternalNativeLoopPassed
				/>
			</Loop>
		);
	}

	if (
		typeof trimBeforeValue !== 'undefined' ||
		typeof effectiveTrimAfter !== 'undefined'
	) {
		return (
			<Html5MediaTrimContext.Provider value={trimBeforeValue ?? 0}>
				<Sequence
					layout="none"
					from={0 - (trimBeforeValue ?? 0)}
					showInTimeline={false}
					durationInFrames={
						effectiveTrimAfter === undefined
							? undefined
							: (trimBeforeValue ?? 0) +
								(effectiveTrimAfter - (trimBeforeValue ?? 0)) /
									(props.playbackRate ?? 1)
					}
					name={name}
				>
					<Html5Audio
						_remotionInternalNeedsDurationCalculation={Boolean(loop)}
						pauseWhenBuffering={shouldPauseWhenBuffering}
						{...otherProps}
						ref={ref}
					/>
				</Sequence>
			</Html5MediaTrimContext.Provider>
		);
	}

	validateMediaProps(
		{
			playbackRate: props.playbackRate,
			preservePitch: props.preservePitch,
			volume: props.volume,
		},
		'Html5Audio',
	);

	if (environment.isRendering) {
		return (
			<AudioForRendering
				onDuration={onDuration}
				{...props}
				ref={ref}
				onNativeError={onError}
				_remotionInternalNeedsDurationCalculation={Boolean(loop)}
			/>
		);
	}

	return (
		<AudioForPreview
			_remotionInternalNativeLoopPassed={
				props._remotionInternalNativeLoopPassed ?? false
			}
			_remotionInternalStack={_remotionInternalStack ?? null}
			shouldPreMountAudioTags={
				audioTagsContext !== null && audioTagsContext.numberOfAudioTags > 0
			}
			{...props}
			ref={ref}
			onNativeError={onError}
			onDuration={onDuration}
			pauseWhenBuffering={shouldPauseWhenBuffering}
			_remotionInternalNeedsDurationCalculation={Boolean(loop)}
			showInTimeline={showInTimeline ?? true}
		/>
	);
};

/**
 * @description With this component, you can add audio to your video. All audio formats which are supported by Chromium are supported by the component.
 * @see [Documentation](https://remotion.dev/docs/html5-audio)
 */
export const Html5Audio = forwardRef(AudioRefForwardingFunction);
addSequenceStackTraces(Html5Audio);

/**
 * @deprecated This component has been renamed to `Html5Audio`.
 * @see [Documentation](https://remotion.dev/docs/mediabunny/new-video)
 */
export const Audio = Html5Audio;