Skip to content

πŸŽ₯ Make videos programmatically with React

write docs

Jonny Burger564488b279d7
diff --git a/packages/core/src/validate-media-props.ts b/packages/core/src/validate-media-props.ts
index fa658cb6ac..f83f2b877a 100644
--- a/packages/core/src/validate-media-props.ts
+++ b/packages/core/src/validate-media-props.ts
@@ -1,8 +1,9 @@
import {RemotionAudioProps} from './audio';
import {RemotionVideoProps} from './video';
+import {OffthreadVideoProps} from './video/props';
export const validateMediaProps = (
- props: RemotionVideoProps | RemotionAudioProps,
+ props: RemotionVideoProps | RemotionAudioProps | OffthreadVideoProps,
component: 'Video' | 'Audio'
) => {
if (
diff --git a/packages/core/src/video/OffthreadVideo.tsx b/packages/core/src/video/OffthreadVideo.tsx
index 5462c94d6e..85dc964ac9 100644
--- a/packages/core/src/video/OffthreadVideo.tsx
+++ b/packages/core/src/video/OffthreadVideo.tsx
@@ -1,117 +1,39 @@
-import React, {forwardRef, useContext, useEffect, useMemo} from 'react';
-import {getAbsoluteSrc} from '../absolute-src';
-import {
- useFrameForVolumeProp,
- useMediaStartsAt,
-} from '../audio/use-audio-frame';
-import {CompositionManager} from '../CompositionManager';
-import {Img} from '../Img';
-import {random} from '../random';
-import {SequenceContext} from '../sequencing';
-import {useAbsoluteCurrentFrame, useCurrentFrame} from '../use-frame';
-import {useUnsafeVideoConfig} from '../use-unsafe-video-config';
-import {evaluateVolume} from '../volume-prop';
-import {getExpectedMediaFrameUncorrected} from './get-current-time';
-import {RemotionOffthreadVideoProps} from './props';
-
-const OffthreadVideoForRenderingForwardFunction: React.ForwardRefRenderFunction<
- HTMLImageElement,
- RemotionOffthreadVideoProps
-> = (
- {onError, volume: volumeProp, playbackRate, src, ref: _ref, muted, ...props},
- ref
-) => {
- const absoluteFrame = useAbsoluteCurrentFrame();
-
- const frame = useCurrentFrame();
- const volumePropsFrame = useFrameForVolumeProp();
- const videoConfig = useUnsafeVideoConfig();
- const sequenceContext = useContext(SequenceContext);
- const mediaStartsAt = useMediaStartsAt();
-
- const {registerAsset, unregisterAsset} = useContext(CompositionManager);
-
- if (!src) {
- throw new TypeError('No `src` was passed to <OffthreadVideo>.');
+import React from 'react';
+import {getRemotionEnvironment} from '../get-environment';
+import {Sequence} from '../sequencing';
+import {validateMediaProps} from '../validate-media-props';
+import {validateStartFromProps} from '../validate-start-from-props';
+import {OffthreadVideoForRendering} from './OffthreadVideoForRendering';
+import {OffthreadVideoProps, RemotionMainVideoProps} from './props';
+import {VideoForDevelopment} from './VideoForDevelopment';
+
+export const OffthreadVideo: React.FC<
+ OffthreadVideoProps & RemotionMainVideoProps
+> = (props) => {
+ const {startFrom, endAt, ...otherProps} = props;
+
+ if (typeof startFrom !== 'undefined' || typeof endAt !== 'undefined') {
+ validateStartFromProps(startFrom, endAt);
+
+ const startFromFrameNo = startFrom ?? 0;
+ const endAtFrameNo = endAt ?? Infinity;
+ return (
+ <Sequence
+ layout="none"
+ from={0 - startFromFrameNo}
+ showInTimeline={false}
+ durationInFrames={endAtFrameNo}
+ >
+ <OffthreadVideo {...otherProps} />
+ </Sequence>
+ );
}
- // Generate a string that's as unique as possible for this asset
- // but at the same time the same on all threads
- const id = useMemo(
- () =>
- `video-${random(src ?? '')}-${sequenceContext?.cumulatedFrom}-${
- sequenceContext?.relativeFrom
- }-${sequenceContext?.durationInFrames}-muted:${muted}`,
- [
- src,
- muted,
- sequenceContext?.cumulatedFrom,
- sequenceContext?.relativeFrom,
- sequenceContext?.durationInFrames,
- ]
- );
+ validateMediaProps(props, 'Video');
- if (!videoConfig) {
- throw new Error('No video config found');
+ if (getRemotionEnvironment() === 'rendering') {
+ return <OffthreadVideoForRendering {...otherProps} />;
}
- const volume = evaluateVolume({
- volume: volumeProp,
- frame: volumePropsFrame,
- mediaVolume: 1,
- });
-
- useEffect(() => {
- if (!src) {
- throw new Error('No src passed');
- }
-
- if (muted) {
- return;
- }
-
- registerAsset({
- type: 'video',
- src: getAbsoluteSrc(src),
- id,
- frame: absoluteFrame,
- volume,
- mediaFrame: frame,
- playbackRate: playbackRate ?? 1,
- });
-
- return () => unregisterAsset(id);
- }, [
- muted,
- src,
- registerAsset,
- id,
- unregisterAsset,
- volume,
- frame,
- absoluteFrame,
- playbackRate,
- ]);
-
- const currentTime = useMemo(() => {
- return (
- getExpectedMediaFrameUncorrected({
- frame,
- playbackRate: playbackRate || 1,
- startFrom: -mediaStartsAt,
- }) / videoConfig.fps
- );
- }, [frame, mediaStartsAt, playbackRate, src, videoConfig.fps]);
-
- const actualSrc = useMemo(() => {
- return `http://localhost:9999/proxy?src=${encodeURIComponent(
- getAbsoluteSrc(src)
- )}&time=${encodeURIComponent(currentTime)}`;
- }, [currentTime, src]);
-
- return <Img src={actualSrc} {...props} onError={onError} />;
+ return <VideoForDevelopment {...otherProps} />;
};
-
-export const OffthreadVideo = forwardRef(
- OffthreadVideoForRenderingForwardFunction
-);
diff --git a/packages/core/src/video/OffthreadVideoForRendering.tsx b/packages/core/src/video/OffthreadVideoForRendering.tsx
new file mode 100644
index 0000000000..489e68b3f8
--- /dev/null
+++ b/packages/core/src/video/OffthreadVideoForRendering.tsx
@@ -0,0 +1,114 @@
+import React, {useContext, useEffect, useMemo} from 'react';
+import {getAbsoluteSrc} from '../absolute-src';
+import {
+ useFrameForVolumeProp,
+ useMediaStartsAt,
+} from '../audio/use-audio-frame';
+import {CompositionManager} from '../CompositionManager';
+import {Img} from '../Img';
+import {random} from '../random';
+import {SequenceContext} from '../sequencing';
+import {useAbsoluteCurrentFrame, useCurrentFrame} from '../use-frame';
+import {useUnsafeVideoConfig} from '../use-unsafe-video-config';
+import {evaluateVolume} from '../volume-prop';
+import {getExpectedMediaFrameUncorrected} from './get-current-time';
+import {OffthreadVideoProps} from './props';
+
+export const OffthreadVideoForRendering: React.FC<OffthreadVideoProps> = ({
+ onError,
+ volume: volumeProp,
+ playbackRate,
+ src,
+ muted,
+ ...props
+}) => {
+ const absoluteFrame = useAbsoluteCurrentFrame();
+
+ const frame = useCurrentFrame();
+ const volumePropsFrame = useFrameForVolumeProp();
+ const videoConfig = useUnsafeVideoConfig();
+ const sequenceContext = useContext(SequenceContext);
+ const mediaStartsAt = useMediaStartsAt();
+
+ const {registerAsset, unregisterAsset} = useContext(CompositionManager);
+
+ if (!src) {
+ throw new TypeError('No `src` was passed to <OffthreadVideo>.');
+ }
+
+ // Generate a string that's as unique as possible for this asset
+ // but at the same time the same on all threads
+ const id = useMemo(
+ () =>
+ `video-${random(src ?? '')}-${sequenceContext?.cumulatedFrom}-${
+ sequenceContext?.relativeFrom
+ }-${sequenceContext?.durationInFrames}-muted:${muted}`,
+ [
+ src,
+ muted,
+ sequenceContext?.cumulatedFrom,
+ sequenceContext?.relativeFrom,
+ sequenceContext?.durationInFrames,
+ ]
+ );
+
+ if (!videoConfig) {
+ throw new Error('No video config found');
+ }
+
+ const volume = evaluateVolume({
+ volume: volumeProp,
+ frame: volumePropsFrame,
+ mediaVolume: 1,
+ });
+
+ useEffect(() => {
+ if (!src) {
+ throw new Error('No src passed');
+ }
+
+ if (muted) {
+ return;
+ }
+
+ registerAsset({
+ type: 'video',
+ src: getAbsoluteSrc(src),
+ id,
+ frame: absoluteFrame,
+ volume,
+ mediaFrame: frame,
+ playbackRate: playbackRate ?? 1,
+ });
+
+ return () => unregisterAsset(id);
+ }, [
+ muted,
+ src,
+ registerAsset,
+ id,
+ unregisterAsset,
+ volume,
+ frame,
+ absoluteFrame,
+ playbackRate,
+ ]);
+
+ const currentTime = useMemo(() => {
+ return (
+ getExpectedMediaFrameUncorrected({
+ frame,
+ playbackRate: playbackRate || 1,
+ startFrom: -mediaStartsAt,
+ }) / videoConfig.fps
+ );
+ }, [frame, mediaStartsAt, playbackRate, videoConfig.fps]);
+
+ const actualSrc = useMemo(() => {
+ return `http://localhost:9999/proxy?src=${encodeURIComponent(
+ getAbsoluteSrc(src)
+ )}&time=${encodeURIComponent(currentTime)}`;
+ }, [currentTime, src]);
+
+ return <Img src={actualSrc} {...props} onError={onError} />;
+};
diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.ts
index 144456cfcf..4f7f5fdfc6 100644
--- a/packages/core/src/video/index.ts
+++ b/packages/core/src/video/index.ts
@@ -1,7 +1,7 @@
export {OffthreadVideo} from './OffthreadVideo';
export {
+ OffthreadVideoProps as RemotionOffthreadVideoProps,
RemotionMainVideoProps,
- RemotionOffthreadVideoProps,
RemotionVideoProps,
} from './props';
export {Video} from './Video';
diff --git a/packages/core/src/video/props.ts b/packages/core/src/video/props.ts
index 2d3e64ee10..a5040700aa 100644
--- a/packages/core/src/video/props.ts
+++ b/packages/core/src/video/props.ts
@@ -1,3 +1,4 @@
+import React from 'react';
import {VolumeProp} from '../volume-prop';
export type RemotionMainVideoProps = {
@@ -16,11 +17,12 @@ export type RemotionVideoProps = Omit<
playbackRate?: number;
};
-export type RemotionOffthreadVideoProps = React.DetailedHTMLProps<
- React.ImgHTMLAttributes<HTMLImageElement>,
- HTMLImageElement
-> & {
+export type OffthreadVideoProps = {
+ src: string;
+ className?: string;
+ style?: React.CSSProperties;
volume?: VolumeProp;
playbackRate?: number;
muted?: boolean;
+ onError?: React.ReactEventHandler<HTMLVideoElement | HTMLImageElement>;
};
diff --git a/packages/docs/docs/offthreadvideo.md b/packages/docs/docs/offthreadvideo.md
new file mode 100644
index 0000000000..3a4eda6bda
--- /dev/null
+++ b/packages/docs/docs/offthreadvideo.md
@@ -0,0 +1,41 @@
+---
+id: offthreadvideo
+title: "<OffthreadVideo />"
+---
+
+_Available from Remotion 3.0.11_
+
+This component imports and displays a video, similar to [`<Video/>`](/docs/video), but during rendering, extracts the exact frame from the video and displays it in a `<Img>` tag. This extraction process happens outside the browser using FFMPEG.
+
+This component was designed to combat limitations of the default `<Video>` element. See: [`<Video>` vs `<OffthreadVideo>`](/docs/video-vs-offthreadvideo).
+
+## Example
+
+```tsx twoslash
+import { AbsoluteFill, OffthreadVideo, staticFile } from "remotion";
+
+export const MyVideo = () => {
+ const video = staticFile("./video.webm");
+
+ return (
+ <AbsoluteFill>
+ <OffthreadVideo src={video} />
+ </AbsoluteFill>
+ );
+};
+```
+
+:::note
+You can also pass a URL as a `src` to load a video remotely.
+:::
+
+## API
+
+The props `volume`, `playbackRate` and `muted` are supported and work the same as in [`<Video>`](/docs/video).
+
+The props `onError`, `className` and `style` are supported and get passed to the underlying HTML element. Remember that during render, this is a `<img>` element, and during preview, this is a `<video>` element.
+
+## See also
+
+- [`<Video />`](/docs/video)
+- [`<Video>` vs `<OffthreadVideo>`](/docs/video-vs-offthreadvideo)
diff --git a/packages/docs/docs/video-vs-offthreadvideo.md b/packages/docs/docs/video-vs-offthreadvideo.md
new file mode 100644
index 0000000000..387cd211d1
--- /dev/null
+++ b/packages/docs/docs/video-vs-offthreadvideo.md
@@ -0,0 +1,42 @@
+---
+id: video-vs-offthreadvideo
+title: "<Video> vs. <OffthreadVideo>"
+---
+
+We offer two components for including other videos in your video: [`<Video />`](/docs/video) and [`<OffthreadVideo />`](/docs/offthreadvideo).
+This page offers a comparison to help you decide which tag to use.
+
+## [`<Video />`](/docs/video)
+
+Is based on the native HTML5 `<video>` element and therefore behaves similar to it.
+
+**Pros**
+
+βœ… &nbsp; Is based on the native HTML5 `<video>` element, so you can attach a ref and [draw the video to a canvas](/docs/video-manipulation).
+βœ… &nbsp; Can be rendered without having to be downloaded fully.
+βœ… &nbsp; Is usually faster to render.
+
+**Cons**
+
+β›” &nbsp; Chrome may throttle video tags if the page is heavy.
+β›” &nbsp; If too many video tags get rendered simultaneously, a timeout may occur.
+β›” &nbsp; If the input video framerate does not match with the output framerate, some duplicate frames may occur in the output.
+β›” &nbsp; A Google Chrome build with proprietary codecs is required.
+
+## [`<OffthreadVideo />`](/docs/offthreadvideo)
+
+A more sophisticated way of embedding a video, which:
+
+- renders a `<video>` tag during preview
+- displays the exact frame in an `<Img>` tag during rendering, that frame gets extracted using FFMPEG outside the browser
+
+**Pros**
+
+βœ… &nbsp; More videos can be displayed simulatenously as Chrome will not apply throttling
+βœ… &nbsp; No flickers or duplicate frames in the output video can occur.
+
+**Cons**
+
+β›” &nbsp; The video needs to be downloaded fully before a frame can be rendered.
+β›” &nbsp; No ref can be attached to this element, as it is `<video>` during preview but a `<img/>` during render.
+β›” &nbsp; The video cannot be drawn to a canvas.
diff --git a/packages/docs/docs/video.md b/packages/docs/docs/video.md
index 251c18fd44..bada56a971 100644
--- a/packages/docs/docs/video.md
+++ b/packages/docs/docs/video.md
@@ -34,11 +34,7 @@ import { AbsoluteFill, Video } from "remotion";
export const MyVideo = () => {
return (
<AbsoluteFill>
- <Video
- src={
- "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
- }
- />
+ <Video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" />
</AbsoluteFill>
);
};
@@ -144,7 +140,7 @@ You can use the `playbackRate` prop to control the speed of the video. `1` is th
While Remotion doesn't limit the range of possible playback speeds, in development mode the [`HTMLMediaElement.playbackRate`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playbackRate) API is used which throws errors on extreme values. At the time of writing, Google Chrome throws an exception if the playback rate is below `0.0625` or above `16`.
-```tsx twoslash title="Example of a fade in over 100 frames"
+```tsx twoslash title="Example of a video playing twice as fast"
import { AbsoluteFill, interpolate, Video } from "remotion";
import video from "./video.webm";
@@ -158,6 +154,12 @@ export const MyVideo = () => {
};
```
+## Alternative: `<OffthreadVideo>`
+
+[`<OffthreadVideo>`](/docs/offthreadvideo) is a drop-in alternative to `<Video>`. To decide which tag to use, see: [`<Video>` vs `<OffthreadVideo>`](/docs/video-vs-offthreadvideo)
+
## See also
- [`<Audio />`](/docs/audio)
+- [`<OffthreadVideo />`](/docs/offthreadvideo)
+- [`<Video>` vs `<OffthreadVideo>`](/docs/video-vs-offthreadvideo)
diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.js
index 1edc43a85a..5f9ca93a4b 100644
--- a/packages/docs/sidebars.js
+++ b/packages/docs/sidebars.js
@@ -134,6 +134,7 @@ module.exports = {
"sequence",
"loop",
"video",
+ "offthreadvideo",
"absolute-fill",
"img",
"iframe",
@@ -230,7 +231,14 @@ module.exports = {
type: "category",
label: "Miscellaneous",
collapsed: false,
- items: ["brownfield", "chromium-flags", "prereleases", "gpu", "react-18"],
+ items: [
+ "brownfield",
+ "chromium-flags",
+ "video-vs-offthreadvideo",
+ "prereleases",
+ "gpu",
+ "react-18",
+ ],
},
"3-0-migration",
"2-0-migration",
diff --git a/packages/eslint-config/src/auto-import-rules.ts b/packages/eslint-config/src/auto-import-rules.ts
index 2c08cf2e67..33d4ebb6fa 100644
--- a/packages/eslint-config/src/auto-import-rules.ts
+++ b/packages/eslint-config/src/auto-import-rules.ts
@@ -21,6 +21,7 @@ export const autoImports = {
Composition: "import {Composition} from 'remotion'",
Audio: "import {Audio} from 'remotion'",
Video: "import {Video} from 'remotion'",
+ OffthreadVideo: "import {OffthreadVideo} from 'remotion'",
Series: "import {Series} from 'remotion'",
Still: "import {Still} from 'remotion'",
Freeze: "import {Freeze} from 'remotion'",
diff --git a/packages/example/src/RemoteVideo/index.tsx b/packages/example/src/RemoteVideo/index.tsx
index 6ed00fd38a..1831df0c1b 100644
--- a/packages/example/src/RemoteVideo/index.tsx
+++ b/packages/example/src/RemoteVideo/index.tsx
@@ -1,8 +1,8 @@
-import {interpolate, Video} from 'remotion';
+import {interpolate, OffthreadVideo} from 'remotion';
const RemoteVideo: React.FC = () => {
return (
- <Video
+ <OffthreadVideo
volume={(f) =>
interpolate(f, [0, 500], [1, 0], {extrapolateRight: 'clamp'})
}