🎥 Make videos programmatically with React
Docs: How to play videos in sequence
Jonny Burgerc2e25eb6f5e6
diff --git a/packages/docs/docs/calculate-metadata.mdx b/packages/docs/docs/calculate-metadata.mdxindex e4d92f6176..014e60bbf6 100644--- a/packages/docs/docs/calculate-metadata.mdx+++ b/packages/docs/docs/calculate-metadata.mdx@@ -11,14 +11,11 @@ crumb: "API"Use it if you:-<Step>1</Step> need to make the duration, width, height, or fps <a href="/docs/dynamic-metadata">dynamic based on some data</a>-<br />-<Step>2</Step> want to transform the props passed to the composition, for example+<Step>1</Step> need to make the `durationInFrames`, `width`, `height`, or `fps` <a href="/docs/dynamic-metadata">dynamic based on some data</a>+<br/><Step>2</Step> want to transform the props passed to the composition, for exampleto do <a href="/docs/data-fetching">data fetching</a>-<br />-<Step>3</Step> want to add a per-composition default codec-<br />-<Step>4</Step> want to run code once, before the actual render starts.+<br/><Step>3</Step> want to add a per-composition default codec+<br/><Step>4</Step> want to run code once, before the actual render starts.The `calculateMetadata()` function is called a single time, independently from the concurrency of the render.It runs in a separate tab, as part of the render process calling [`selectComposition()`](/docs/renderer/select-composition).diff --git a/packages/docs/docs/miscellaneous/snippets/align-duration.mdx b/packages/docs/docs/miscellaneous/snippets/align-duration.mdxindex 6f8d22176f..79d7438945 100644--- a/packages/docs/docs/miscellaneous/snippets/align-duration.mdx+++ b/packages/docs/docs/miscellaneous/snippets/align-duration.mdx@@ -1,7 +1,7 @@---image: /generated/articles-docs-miscellaneous-snippets-align-duration.pngtitle: How do I make the composition the same duration as my video?-sidebar_label: Align timeline duration to video+sidebar_label: Make timeline duration the samecrumb: 'FAQ'---@@ -32,7 +32,7 @@ export const MyComp: React.FC<MyCompProps> = ({src}) => {```Then, define a [`calculateMetadata()`](/docs/calculate-metadata) function that calculates the duration of the composition based on the video.-[Install `@remotion/media-utils`](/docs/media-utils) if necessary.+[Install `@remotion/media-parser`](/docs/media-parser) if necessary.```tsx twoslash title="MyComp.tsx"type MyCompProps = {@@ -42,21 +42,38 @@ type MyCompProps = {// ---cut---import {CalculateMetadataFunction} from 'remotion';-import {getVideoMetadata} from '@remotion/media-utils';+import {parseMedia} from '@remotion/media-parser';export const calculateMetadata: CalculateMetadataFunction<MyCompProps> = async ({props}) => {- const data = await getVideoMetadata(props.src);+ const {durationInSeconds, dimensions} = await parseMedia({+ src: props.src,+ fields: {+ durationInSeconds: true,+ dimensions: true,+ },+ });++ if (durationInSeconds === null) {+ throw new Error('Could not get video duration');+ }+const fps = 30;return {- durationInFrames: Math.floor(data.durationInSeconds * fps),+ durationInFrames: Math.floor(durationInSeconds * fps),fps,+ width: dimensions.width,+ height: dimensions.height,};};```+:::note+If your asset is not CORS-enabled, you can use the [`getVideoMetadata`](/docs/get-video-metadata) function from [`@remotion/media-utils`](/docs/media-utils) instead of `parseMedia()`.+:::+Finally, pass the `calculateMetadata` function to the `Composition` component and define the previously hardcoded `src` as a default prop:```tsx twoslash title="Root.tsx"@@ -111,7 +128,7 @@ export const Root: React.FC = () => {## How do I make the composition the same duration as my audio?-Follow the same steps, but instead if [`getVideoMetadata()`](/docs/get-video-metadata), use [`getAudioDurationInSeconds()`](/docs/get-audio-duration-in-seconds) from `@remotion/media-utils` to calculate the duration of the composition based on the audio file.+Follow the same steps, but instead of [`parseMedia()`](/docs/media-parser), use [`getAudioDurationInSeconds()`](/docs/get-audio-duration-in-seconds) from `@remotion/media-utils` to calculate the duration of the composition based on the audio file.## See Alsodiff --git a/packages/docs/docs/player/premounting.mdx b/packages/docs/docs/player/premounting.mdxindex 0a7c716b45..a4ef62778a 100644--- a/packages/docs/docs/player/premounting.mdx+++ b/packages/docs/docs/player/premounting.mdx@@ -2,11 +2,11 @@image: /generated/articles-docs-player-premounting.pngtitle: Premountingslug: /player/premounting-crumb: "@remotion/player"+crumb: '@remotion/player'----import { NoPremounting } from "../../components/Premounting/NoPremounting";-import { Premounting } from "../../components/Premounting/Premounting";+import {NoPremounting} from '../../components/Premounting/NoPremounting';+import {Premounting} from '../../components/Premounting/Premounting';# Premounting<AvailableFrom v="4.0.140"/>@@ -14,37 +14,23 @@ Remotion only ever renders the current frame.This means when a video or another asset is about to come up, it is not loaded by default.<NoPremounting />-<br />-<p style={{ lineHeight: 1.2 }}>- <sub>- <em>- Even though the video is soon about to appear, it is not yet loaded- because Remotion only ever renders the current time.- </em>- </sub>-</p>++:::note+Even though the video is soon about to appear, it is not yet loaded+because Remotion only ever renders the current time.+:::## What is premounting?Premounting is the practice of mounting a component containing assets earlier to allow assets some time to load before they appear.<Premounting />-<br />-<p style={{ lineHeight: 1.2 }}>- <sub>- <em>- The video is mounted earlier to give it some time to load.- <br />- It carries the style <code>opacity: 0</code> to make it invisible.- <br />- It's time defined by{" "}- <a href="/docs/use-current-frame">- <code>useCurrentFrame()</code>- </a>{" "}- is frozen at <code>0</code>.- </em>- </sub>-</p>++:::note+The video is mounted earlier to give it some time to load.<br />+It carries the style <code>opacity: 0</code> to make it invisible.+It's time defined by{' '}<a href="/docs/use-current-frame"><code>useCurrentFrame()</code></a>{' '}is frozen at <code>0</code>.+:::## Preloading a `<Sequence>`@@ -54,13 +40,13 @@ Add the [`premountFor`](/docs/sequence#premountfor) prop to the [`<Sequence>`](/The number you pass is the number in frames you premount the component for.```tsx twoslash title="Premounted.tsx"-import { Sequence, staticFile, Video } from "remotion";+import {Sequence, staticFile, Video} from 'remotion';// ---cut---const MyComp: React.FC = () => {return (<Sequence premountFor={100}>- <Video src={staticFile("bigbuckbunny.mp4")}></Video>+ <Video src={staticFile('bigbuckbunny.mp4')}></Video></Sequence>);};@@ -87,14 +73,14 @@ Premounting can also be implemented yourself with the public Remotion APIs.Use the following component like you would `<Sequence>`:```tsx twoslash title="PremountedSequence.tsx"-import React, { forwardRef, useMemo } from "react";+import React, {forwardRef, useMemo} from 'react';import {Freeze,getRemotionEnvironment,Sequence,SequenceProps,useCurrentFrame,-} from "remotion";+} from 'remotion';export type PremountedSequenceProps = SequenceProps & {premountFor: number;@@ -105,14 +91,14 @@ const PremountedSequenceRefForwardingFunction: React.ForwardRefRenderFunction<{premountFor: number;} & SequenceProps-> = ({ premountFor, ...props }, ref) => {+> = ({premountFor, ...props}, ref) => {const frame = useCurrentFrame();- if (props.layout === "none") {+ if (props.layout === 'none') {throw new Error('`<Premount>` does not support layout="none"');}- const { style: passedStyle, from = 0, ...otherProps } = props;+ const {style: passedStyle, from = 0, ...otherProps} = props;const active =frame < from &&frame >= from - premountFor &&@@ -123,7 +109,7 @@ const PremountedSequenceRefForwardingFunction: React.ForwardRefRenderFunction<...passedStyle,opacity: active ? 0 : 1,// @ts-expect-error Only in the docs - it will not give a type error in a Remotion project- pointerEvents: active ? "none" : passedStyle?.pointerEvents ?? "auto",+ pointerEvents: active ? 'none' : (passedStyle?.pointerEvents ?? 'auto'),};}, [active, passedStyle]);diff --git a/packages/docs/docs/remotion.mdx b/packages/docs/docs/remotion.mdxindex 7c6b41e79f..299f34f80c 100644--- a/packages/docs/docs/remotion.mdx+++ b/packages/docs/docs/remotion.mdx@@ -1,7 +1,7 @@---image: /generated/articles-docs-remotion.png-title: "remotion"-crumb: "Core API Reference"+title: 'remotion'+crumb: 'Core API Reference'---import {TableOfContents} from '../components/TableOfContents/remotion';@@ -19,6 +19,7 @@ import TabItem from '@theme/TabItem';defaultValue="npm"values={[{ label: 'npm', value: 'npm', },+{ label: 'bun', value: 'bun', },{ label: 'pnpm', value: 'pnpm', },{ label: 'yarn', value: 'yarn', },]@@ -27,6 +28,13 @@ values={[```bashnpm i remotion+```++ </TabItem>+<TabItem value="bun">++```bash+bun i remotion```</TabItem>diff --git a/packages/docs/docs/videos/sequence.mdx b/packages/docs/docs/videos/sequence.mdxnew file mode 100644index 0000000000..a8023701da--- /dev/null+++ b/packages/docs/docs/videos/sequence.mdx@@ -0,0 +1,296 @@+---+title: Playing videos in sequence+sidebar_label: Playing videos in sequence+crumb: 'How To'+---++If you would like to play multiple videos in sequence, you can:++<Step>1</Step> Define a component that renders a [`<Series>`](/docs/series) of [`<OffthreadVideo>`](/docs/offthread-video) components.+<br/><Step>2</Step> Create a [`calculateMetadata()`](/docs/calculate-metadata) function that fetches the duration of each video.+<br/><Step>3</Step> Register a [`<Composition>`](/docs/composition) that specifies a list of videos.++## Basic example++Start off by creating a component that renders a list of videos using the [`<Series>`](/docs/series) and [`<OffthreadVideo>`](/docs/offthread-video) component:++```tsx twoslash title="VideosInSequence.tsx"+import React from 'react';+import {OffthreadVideo, Series} from 'remotion';++type VideoToEmbed = {+ src: string;+ durationInFrames: number | null;+};++type Props = {+ videos: VideoToEmbed[];+};++export const VideosInSequence: React.FC<Props> = ({videos}) => {+ return (+ <Series>+ {videos.map((vid) => {+ if (vid.durationInFrames === null) {+ throw new Error('Could not get video duration');+ }++ return (+ <Series.Sequence+ key={vid.src}+ durationInFrames={vid.durationInFrames}+ >+ <OffthreadVideo src={vid.src} />+ </Series.Sequence>+ );+ })}+ </Series>+ );+};+```++In the same file, create a function that calculates the metadata for the composition:++<Step>1</Step> Calls [`parseMedia()`](/docs/media-parser) to get the duration of+each video.+<div style={{marginTop: -14}} />+<Step>2</Step> Create a [`calculateMetadata()`](/docs/calculate-metadata)+function that fetches the duration of each video.+<div style={{marginTop: -14}} />+<Step>3</Step> Sums up all durations to get the total duration of the+composition.++```tsx twoslash title="VideosInSequence.tsx"+import React from 'react';+import {+ OffthreadVideo,+ staticFile,+ Series,+ CalculateMetadataFunction,+} from 'remotion';+import {parseMedia} from '@remotion/media-parser';++type VideoToEmbed = {+ src: string;+ durationInFrames: number | null;+};++type Props = {+ videos: VideoToEmbed[];+};++// ---cut---+export const calculateMetadata: CalculateMetadataFunction<Props> = async ({+ props,+}) => {+ const fps = 30;+ const videos = await Promise.all([+ ...props.videos.map(async (video): Promise<VideoToEmbed> => {+ const {durationInSeconds} = await parseMedia({+ src: video.src,+ fields: {+ durationInSeconds: true,+ },+ });++ if (durationInSeconds === null) {+ throw new Error(`Could not get video duration of ${durationInSeconds}`);+ }++ return {+ durationInFrames: Math.floor(durationInSeconds * fps),+ src: video.src,+ };+ }),+ ]);++ const totalDurationInFrames = videos.reduce(+ (acc, video) => acc + (video.durationInFrames ?? 0),+ 0,+ );++ return {+ props: {+ ...props,+ videos,+ },+ fps,+ durationInFrames: totalDurationInFrames,+ };+};+```++In your [root file](/docs/terminology/root-file), create a [`<Composition>`](/docs/composition) that uses the `VideosInSequence` component and the exported `calculateMetadata` function:++```tsx twoslash title="Root.tsx"+// @filename: VideosInSequence.tsx+import React from 'react';+import {+ OffthreadVideo,+ staticFile,+ Series,+ CalculateMetadataFunction,+} from 'remotion';+import {parseMedia} from '@remotion/media-parser';++type VideoToEmbed = {+ src: string;+ durationInFrames: number | null;+};++type Props = {+ videos: VideoToEmbed[];+};++export const calculateMetadata: CalculateMetadataFunction<Props> = async ({+ props,+}) => {+ const fps = 30;+ const videos = await Promise.all([+ ...props.videos.map(async (video): Promise<VideoToEmbed> => {+ const {durationInSeconds} = await parseMedia({+ src: video.src,+ fields: {+ durationInSeconds: true,+ },+ });++ if (durationInSeconds === null) {+ throw new Error(`Could not get video duration of ${durationInSeconds}`);+ }++ return {+ durationInFrames: Math.floor(durationInSeconds * fps),+ src: video.src,+ };+ }),+ ]);++ const totalDurationInFrames = videos.reduce(+ (acc, video) => acc + video.durationInFrames!,+ 0,+ );++ return {+ props: {+ ...props,+ videos,+ },+ fps,+ durationInFrames: totalDurationInFrames,+ };+};++export const VideosInSequence: React.FC<Props> = ({videos}) => {+ return (+ <Series>+ {videos.map((vid) => {+ if (vid.durationInFrames === null) {+ throw new Error('Could not get video duration');+ }++ return (+ <Series.Sequence+ key={vid.src}+ durationInFrames={vid.durationInFrames}+ >+ <OffthreadVideo src={staticFile('video.mp4')} />+ </Series.Sequence>+ );+ })}+ </Series>+ );+};++// @filename: Root.tsx+// ---cut---++import React from 'react';+import {Composition, staticFile} from 'remotion';+import {VideosInSequence, calculateMetadata} from './VideosInSequence';++export const Root: React.FC = () => {+ return (+ <Composition+ id="VideosInSequence"+ component={VideosInSequence}+ width={1920}+ height={1080}+ defaultProps={{+ videos: [+ {+ durationInFrames: null,+ src: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',+ },+ {+ durationInFrames: null,+ src: staticFile('localvideo.mp4'),+ },+ ],+ }}+ calculateMetadata={calculateMetadata}+ />+ );+};+```++## Adding premounting++A video will only load when it is about to be played.+To create a smoother preview playback, we should do two things to all videos:++<Step>1</Step> Add a [`premountFor`](/docs/series#premountfor) prop to [`<Series.Sequence>`](/docs/series). This will+invisibly mount the video tag before it is played, giving it some time to load.{' '}+<div style={{marginTop: -14}} />+<Step>2</Step> Add the [`pauseWhenBuffering`](/docs/series#premount) prop. This will transition the Player into a [buffering state](/docs/player/buffer-state), should the video still need to load.++```tsx twoslash title="VideosInSequence.tsx" {14, 17}+import React from 'react';+import {OffthreadVideo, Series, useVideoConfig} from 'remotion';++type VideoToEmbed = {+ src: string;+ durationInFrames: number | null;+};++type Props = {+ videos: VideoToEmbed[];+};++// ---cut---+export const VideosInSequence: React.FC<Props> = ({videos}) => {+ const {fps} = useVideoConfig();++ return (+ <Series>+ {videos.map((vid) => {+ if (vid.durationInFrames === null) {+ throw new Error('Could not get video duration');+ }++ return (+ <Series.Sequence+ key={vid.src}+ premountFor={4 * fps}+ durationInFrames={vid.durationInFrames}+ >+ <OffthreadVideo pauseWhenBuffering src={vid.src} />+ </Series.Sequence>+ );+ })}+ </Series>+ );+};+```++## See also++- [OffthreadVideo](/docs/offthreadvideo)+- [Series](/docs/series)+- [calculateMetadata()](/docs/calculate-metadata)+- [parseMedia()](/docs/media-parser)+- [Composition](/docs/composition)+- [Root file](/docs/terminology/root-file)+- [Player buffering state](/docs/player/buffer-state)+- [Avoiding flickering in the Player](/docs/troubleshooting/player-flicker)+- [Combatting autoplay issues](/docs/player/autoplay)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 4f061d5e30..7853d4f594 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -669,7 +669,7 @@ module.exports = {},{type: 'category',- label: 'Designing videos',+ label: 'Designing visuals',items: ['transforms','assets',@@ -689,8 +689,9 @@ module.exports = {label: 'Embedding videos',items: ['videos/index',- 'videos/transparency','miscellaneous/snippets/align-duration',+ 'videos/sequence',+ 'videos/transparency','video-manipulation','miscellaneous/snippets/accelerated-video','miscellaneous/snippets/jumpcuts',