🎥 Make videos programmatically with React
new page about dynamic metadata
Jonny Burger9f8971ece0b6
diff --git a/packages/docs/docs/data-fetching.md b/packages/docs/docs/data-fetching.mdindex 5960ab4179..36d38d38be 100644--- a/packages/docs/docs/data-fetching.md+++ b/packages/docs/docs/data-fetching.md@@ -62,9 +62,10 @@ export const Root: React.FC = () => {};```-The `props` being passed to `calculateMetadata()` are the [input props merged together with the default props](/docs/props-resolution). If you only want to fetch based on the default props, use the `defaultProps` also available in the same object.+The `props` being passed to `calculateMetadata()` are the [input props merged together with the default props](/docs/props-resolution).+In addition to `props`, `defaultProps` can also be read from the same object.-The type of the untransformed input and the transformed output must be the same.+When transforming, the input and the output must be the same TypeScript type.Consider using a nullable type for your data and throw an error inside your component to deal with the `null` type:```tsx twoslash title="MyComp.tsx"@@ -227,6 +228,32 @@ export const Root = () => {By implementing this pattern, The `id` in the [props editor](/docs/visual-editing) can now be tweaked and Remotion will refetch the data whenever it changes.+### Setting the duration based on data++You may set the `durationInFrames`, `fps`, `width` and `height` by returning those keys in the callback function:++```tsx twoslash+import { CalculateMetadataFunction } from "remotion";++type MyCompProps = {+ durationInSeconds: number;+};++export const calculateMyCompMetadata: CalculateMetadataFunction<+ MyCompProps+> = async ({ props }) => {+ const fps = 30;+ const durationInSeconds = props.durationInSeconds;++ return {+ durationInFrames: durationInSeconds * fps,+ fps,+ };+};+```++Learn more about this feature in the [Variable metadata](/docs/variable-metadata) page.+### Aborting stale requestsThe props in the props editor may rapidly change for example by typing fast.diff --git a/packages/docs/docs/dynamic-metadata.md b/packages/docs/docs/dynamic-metadata.mdindex c4c0d13a2e..2ca244f53c 100644--- a/packages/docs/docs/dynamic-metadata.md+++ b/packages/docs/docs/dynamic-metadata.md@@ -1,81 +1,72 @@---image: /generated/articles-docs-dynamic-metadata.pngid: dynamic-metadata-title: Dynamic duration, FPS & dimensions+title: Variable metadatacrumb: "How To"----```twoslash include example-export const MyComponent: React.FC<{- duration: number;-}> = ({duration}) => {- return (- <div>props: {duration}</div>- );-}-// - MyComponent-export const VideoTesting: React.FC = () => <></>-// - VideoTesting-```+You may change the duration of the video based on some asynchronously determined data.+The same goes for the width, height and framerate of the video.-## Change metadata based on input props+## Using the `calculateMetadata()` function<AvailableFrom v="4.0.0"/>-_Available since v2.0._+Consider a scenario where a video is dynamically specified as a background and the duration of the composition should be aligned with the duration of the video.-Using [Input props](/docs/parametrized-rendering) you can customize the content of your videos while rendering. But what about if you want to change the duration, frame rate or the dimensions of your video based on input props or asynchronous operations?+Pass a [`calculateMetadata`](/docs/composition#calculatemetadata) callback function to a [`<Composition>`](/docs/composition). This function should take the [combined props](/docs/props-resolution) and calculate the metadata.-Use the `getInputProps()` method to retrieve the props that you have passed as an input.-For example if you have passed `--props='{"hello": "world"}'` as a command line flag, you can read the value in your Remotion project like this:--```tsx twoslash-// It's better to fake type here than to import any-const getInputProps = () => ({ hello: "world" } as const);-// ---cut----const { hello } = getInputProps();-console.log(hello); // "world"-```--You can use this technique to dynamically change the frame rate, dimensions or duration of our video as you render. For example, if you pass `--props={"duration": 100}` during rendering, the video will be 100 frames long if you define your composition as followed:+```tsx twoslash title="src/Root.tsx"+import { getVideoMetadata } from "@remotion/media-utils";+import { Composition, Video } from "remotion";-```tsx twoslash-// @include: example-MyComponent-// ---cut----import { Composition, getInputProps } from "remotion";+type MyCompProps = {+ src: string;+};-const inputProps = getInputProps();+const MyComp: React.FC<MyCompProps> = ({ src }) => {+ return <Video src={src} />;+};-export const Index = () => {+export const Root: React.FC = () => {return (- <>- <Composition- id="MyComposition"- component={MyComponent}- width={1920}- height={1080}- fps={30}- durationInFrames={inputProps?.duration ?? 20}- />- </>+ <Composition+ id="MyComp"+ component={MyComp}+ durationInFrames={300}+ fps={30}+ width={1920}+ height={1080}+ defaultProps={{+ src: "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",+ }}+ calculateMetadata={async ({ props }) => {+ const data = await getVideoMetadata(props.src);++ return {+ durationInFrames: Math.floor(data.durationInSeconds * 30),+ };+ }}+ />);};```-:::tip-In the example above, we specified fallback duration for use while you are previewing the video, but you can also pass `--props` during preview!-:::+The `props` defaults to the `defaultProps` specified, but may be overriden by [passing input props to the render](/props-resolution).++Return an object with `durationInFrames` to change the duration of the video.+In addition or instead, you may also return `fps`, `width` and `height` to update the video's resolution and framerate.-## Change metadata based on asynchronous information+It is also possible to transform the props [passed to the component by returning a `props` field](/docs/data-fetching) at the same time.-_Available since v1.5._+## With `useEffect()` and `getInputProps()`-Sometimes you need to calculate metadata programmatically in a non-synchronous manner. For example, you have a source video and you want your video to be just as long as the source video. You can use the [`delayRender()`/`continueRender()`](/docs/data-fetching) pattern for this as well!+In the following example, Remotion is instructed to wait for the [`getVideoMetadata()`](/docs/get-video-metadata) promise to resolve before evaluating the composition.-In this example, we fetch the duration of "Big Buck Bunny" and use it to make our video just that long:+By calling [`delayRender()`](/docs/delay-render), Remotion will be blocked from proceeding until [`continueRender()`](/docs/continue-render) is called.-```tsx twoslash-// @include: example-VideoTesting+```tsx twoslash title="src/Root.tsx"import { useEffect, useState } from "react";import { Composition, continueRender, delayRender } from "remotion";+const VideoTesting: React.FC = () => null;// ---cut---import { getVideoMetadata } from "@remotion/media-utils";@@ -97,53 +88,151 @@ export const Index: React.FC = () => {}, [handle]);return (- <>- <Composition- id="dynamic-duration"- component={VideoTesting}- width={1080}- height={1080}- fps={30}- durationInFrames={duration}- />- </>+ <Composition+ id="dynamic-duration"+ component={VideoTesting}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={duration}+ />);};```-## Change metadata in server-side rendering+To dynamically pass a video asset, you [may pass input props](/docs/props-resolution) when rendering and retrieve them inside your React code using [`getInputProps()`](/docs/get-input-props).-Both `getCompositions()` and `renderFrames()` functions accept an `inputProps` object as a parameter.+```tsx twoslash title="src/Root.tsx"+import { getInputProps } from "remotion";-```tsx twoslash-import { getCompositions } from "@remotion/renderer";-const bundled: string = "";-// ---cut----getCompositions(bundled, {- inputProps: {- custom: "data",- },-});+const inputProps = getInputProps();+const src = inputProps.src;```-```tsx twoslash-const renderFrames = (options: { inputProps: {} }) => {};+### Drawbacks++This technique is not recommended anymore since v4.0, because the `useEffect()` does not only get executed when Remotion is initially calculating the metadata of the video, but also when spawning a render worker.++Since a render process might be highly concurrent, this might lead to unnecessary API calls and rate limitations.++## Using together with dimension overrides++Override parameters such as [`--width`](/docs/cli/render#--width) will be given priority and override the variable dimensions you set using `calculateMetadata()`.++The [`--scale`](/docs/scaling) parameter has the highest priority and will be applied after override parameters and `calculateMetadata()`.++## Changing dimensions and FPS after the video was designed++If you designed your video with certain dimensions and then want to render a different resolution (e.g. 4K instead of Full HD), you can use [output scaling](/docs/scaling).++If you designed your video with certain FPS and then want to change the frame rate, you can use the [`<FpsConverter>`](/docs/miscellaneous/snippets/fps-converter) snippet.++## With the `<Player>`++The [`<Player>`](/docs/player) will react if the metadata being passed to it changes. There are two viable ways to do dynamically set the metadata of the Player:++<p><Step>1</Step> Perform data fetching using <code>useEffect()</code>:</p>++```tsx twoslash title="MyApp.tsx"+import { getVideoMetadata } from "@remotion/media-utils";+import { useEffect, useState } from "react";++const VideoTesting: React.FC = () => null;// ---cut----renderFrames({- // ...- inputProps: {- custom: "data",- },-});+import { Player } from "@remotion/player";++export const Index: React.FC = () => {+ const [duration, setDuration] = useState(1);++ useEffect(() => {+ getVideoMetadata(+ "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"+ )+ .then(({ durationInSeconds }) => {+ setDuration(Math.round(durationInSeconds * 30));+ })+ .catch((err) => {+ console.log(`Error fetching metadata: ${err}`);+ });+ }, []);++ return (+ <Player+ component={VideoTesting}+ compositionWidth={1080}+ compositionHeight={1080}+ fps={30}+ durationInFrames={duration}+ />+ );+};```-Make sure to pass the parameter to both of these functions, so the input props are available to `getInputProps` during the composition fetching and rendering stage.+<p><Step>2</Step> Call your own <code>calculateMetadata()</code> function reused from your Remotion project:</p>-## Changing dimensions and FPS after the video was designed+```tsx twoslash title="MyApp.tsx"+import { useEffect, useState } from "react";+import { CalculateMetadataFunction } from "remotion";-- If you designed your video with certain dimensions and now want to render a different resolution (e.g. 4K instead of Full HD), you can use [output scaling](/docs/scaling).-- If you designed your video with certain FPS and now want to change the frame rate, you can use the [`<FpsConverter>`](/docs/miscellaneous/snippets/fps-converter) snippet.+const VideoTesting: React.FC = () => null;++// ---cut---+import { Player } from "@remotion/player";++type Props = {};++const calculateMetadataFunction: CalculateMetadataFunction<+ Props+> = async () => {+ return {+ props: {},+ durationInFrames: 1,+ width: 100,+ height: 100,+ fps: 30,+ };+};++type Metadata = {+ durationInFrames: number;+ compositionWidth: number;+ compositionHeight: number;+ fps: number;+ props: Props;+};++export const Index: React.FC = () => {+ const [metadata, setMetadata] = useState<Metadata | null>(null);++ useEffect(() => {+ calculateMetadataFunction({+ defaultProps: {},+ props: {},+ abortSignal: new AbortController().signal,+ })+ .then(({ durationInFrames, props, width, height, fps }) => {+ setMetadata({+ durationInFrames: durationInFrames as number,+ compositionWidth: width as number,+ compositionHeight: height as number,+ fps: fps as number,+ props: props as Props,+ });+ })+ .catch((err) => {+ console.log(`Error fetching metadata: ${err}`);+ });+ }, []);++ if (!metadata) {+ return null;+ }++ return <Player component={VideoTesting} {...metadata} />;+};+```## See also-- [`getInputProps()`](/docs/get-input-props)+- [How props get resolved](/docs/props-resolution)+- [Data fetching](/docs/data-fetching)diff --git a/packages/docs/docs/lottie/getlottiemetadata.md b/packages/docs/docs/lottie/getlottiemetadata.mdindex 2cbb675140..a1f1d59760 100644--- a/packages/docs/docs/lottie/getlottiemetadata.md+++ b/packages/docs/docs/lottie/getlottiemetadata.md@@ -210,4 +210,4 @@ The natural framerate of the Lottie animation.## See also-- [Change Remotion composition metadata based on Lottie metadata](/docs/dynamic-metadata#change-metadata-based-on-asynchronous-information)+- [Change Remotion composition metadata based on Lottie metadata](/docs/dynamic-metadata)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 586d6a9f32..d7c62e921d 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -386,6 +386,7 @@ module.exports = {"schemas","visual-editing","data-fetching",+ "dynamic-metadata","props-resolution",],},@@ -395,7 +396,6 @@ module.exports = {items: ["encoding","transparent-videos",- "dynamic-metadata","ssr","webpack","tailwind",