🎥 Make videos programmatically with React
nice
JonnyBurger502df856a9f6
diff --git a/bun.lock b/bun.lockindex ec07921d88..75fdcbb7af 100644--- a/bun.lock+++ b/bun.lock@@ -1353,6 +1353,7 @@"@remotion/cli": "workspace:*","@remotion/google-fonts": "workspace:*","@remotion/layout-utils": "workspace:*",+ "@remotion/media": "workspace:*","@remotion/zod-types": "workspace:*","react": "19.0.0","react-dom": "19.0.0",diff --git a/packages/template-ai-video/README.md b/packages/template-ai-video/README.mdindex 6a60a8a60a..6d105b0247 100644--- a/packages/template-ai-video/README.md+++ b/packages/template-ai-video/README.md@@ -9,14 +9,16 @@Using this template you can create high quality **AI videos for TikTok or Instagram**.-It includes a CLI that will generate story script, images and voiceover using OpenAI and ElevenLabs.+It includes a CLI that will generate a story script, images and voiceover using OpenAI and ElevenLabs.-## Getting started with demo video+## Getting started++Set up the demo story:**Install Dependencies**```console-bun install+npm install```**Start Preview**@@ -25,9 +27,7 @@ bun installnpm run dev```-## How do I render my video?--Run this:+**Render video**```consolenpx remotion render@@ -35,11 +35,11 @@ npx remotion renderOr check out the [Remotion docs](/docs/render/). There are lots of ways to render.-## Creating your own videos+## Creating a new storyYou can easily create your own videos using provided CLI.-It will generate a script, images, voiceover and timeline based on your story title and topic. (topic can be e.g. history, eli5, fun facts, science, etc)+It will generate a script, images, voiceover and timeline based on your story title and topic. Topics that work well: history, ELI5, fun facts, science.**Configure environment variables**@@ -50,20 +50,20 @@ OPENAI_API_KEY=ELEVENLABS_API_KEY=```-If you did not create env file - you will be prompted for these variables when using CLI.+If you don't create an env file, you will be prompted for these variables when using CLI.**Select voice**-In **generateVoice()** function replace the voice id from ElevenLabs with the one you like. You can use their API for this. Alternatively, you can open any voice on their website and extract the Voice Id from the url (id comes after **voiceId=**)+In [`generateVoice()`](cli/service.ts) replace the voice id from ElevenLabs with the one you like. You can use their API for this. Alternatively, you can open any voice on their website and extract the Voice ID from the url (id comes after `voiceId=`).```consolehttps://elevenlabs.io/app/voice-library?voiceId=aTxZrSrp47xsP6Ot4Kgd```-**Generate srory timeline**+**Generate story timeline**```console-bun gen+npm run gen```You will be prompted to enter story title and topic.@@ -76,7 +76,7 @@ After you enter title and topic, CLI will generate text, images and audio with t## Technical overview-Remotion is rendering videos based on Timeline (timeline.json in project folder). This timeline is generated by CLI.+Remotion is rendering videos based on Timeline (timeline.json in project folder). The timeline is generated by CLI.It consists of three blocks - Elements, Text and Audio.@@ -84,22 +84,18 @@ Elements define slide backgrounds and include enter/exit transitions (e.g. blur)Text and audio are self explanatory. The only special thing about them is that they are synced.-You can customize the generation of the timeline in **createTimeLineFromStoryWithDetails()** function.+You can customize the generation of the timeline in [`createTimeLineFromStoryWithDetails()`](cli/timeline.ts) function.-## Deploying on a remove server+## Deploying on a remote server-Current project nees light modification if you want to deploy it as a remote service.+Current project needs light modification if you want to deploy it as a remote service.-Remotion renderer with template bundle shuold be deployed as per usual.+Remotion renderer with template bundle should be deployed as per usual.-Then you have to update Root.tsx to use timeline url that you will pass as a prop (instead of project name).+Then you have to update [`Root.tsx`](src/Root.tsx) to use timeline url that you will pass as a prop (instead of project name).The last thing - you have to upload generated resources (images and audio) to server and use urls to them instead of file names when generating a timeline.-## Optimisations--You can significantly speed up the story generation by generating audio and images in parallel.-## IssuesFound an issue with Remotion? Upgrade Remotion to receive fixes:diff --git a/packages/template-ai-video/cli/cli.ts b/packages/template-ai-video/cli/cli.tsindex 1f666ecdb8..c75d52bb97 100644--- a/packages/template-ai-video/cli/cli.ts+++ b/packages/template-ai-video/cli/cli.ts@@ -26,7 +26,7 @@ import * as fs from "fs";import * as path from "path";import { createTimeLineFromStoryWithDetails } from "./timeline";-dotenv.config();+dotenv.config({ quiet: true });interface GenerateOptions {apiKey?: string;@@ -196,11 +196,12 @@ async function generateStory(options: GenerateOptions) {const imagesSpinner = ora("Generating images and voice...").start();for (let i = 0; i < storyWithDetails.content.length; i++) {const storyItem = storyWithDetails.content[i];-+ imagesSpinner.text = `[${i * 2 + 1}/${storyWithDetails.content.length * 2}] Generating image for ${storyItem.text}`;await generateAiImage(storyItem.imageDescription,contentFs.getImagePath(storyItem.uid),);+ imagesSpinner.text = `[${i * 2 + 2}/${storyWithDetails.content.length * 2}] Generating voice for ${storyItem.text}`;const timings = await generateVoice(storyItem.text,elevenlabsApiKey!,diff --git a/packages/template-ai-video/cli/service.ts b/packages/template-ai-video/cli/service.tsindex bd9dbc9851..29da6cd666 100644--- a/packages/template-ai-video/cli/service.ts+++ b/packages/template-ai-video/cli/service.ts@@ -2,7 +2,7 @@ import z from "zod";import * as fs from "fs";import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";import { CharacterAlignmentResponseModel } from "@elevenlabs/elevenlabs-js/api";-import { ImageHeight, ImageWidth } from "../src/lib/constants";+import { IMAGE_HEIGHT, IMAGE_WIDTH } from "../src/lib/constants";import { zodToJsonSchema } from "zod-to-json-schema";let apiKey: string | null = null;@@ -71,7 +71,7 @@ export const generateAiImage = async (prompt: string, path: string) => {body: JSON.stringify({model: "dall-e-3",prompt,- size: `${ImageWidth}x${ImageHeight}`,+ size: `${IMAGE_WIDTH}x${IMAGE_HEIGHT}`,response_format: "b64_json",}),});diff --git a/packages/template-ai-video/package.json b/packages/template-ai-video/package.jsonindex 8d5b9144a7..1b75e8a6cd 100644--- a/packages/template-ai-video/package.json+++ b/packages/template-ai-video/package.json@@ -16,6 +16,7 @@"@remotion/cli": "workspace:*","@remotion/google-fonts": "workspace:*","@remotion/layout-utils": "workspace:*",+ "@remotion/media": "workspace:*","@remotion/zod-types": "workspace:*","react": "19.0.0","react-dom": "19.0.0",diff --git a/packages/template-ai-video/src/Root.tsx b/packages/template-ai-video/src/Root.tsxindex af7768c794..0eefd9783c 100644--- a/packages/template-ai-video/src/Root.tsx+++ b/packages/template-ai-video/src/Root.tsx@@ -1,57 +1,34 @@-import {- Composition,- continueRender,- delayRender,- getInputProps,-} from "remotion";+import { Composition } from "remotion";import { AIVideo, aiVideoSchema } from "./components/AIVideo";-import { useEffect, useMemo, useState } from "react";-import { FPS, WindowHeight, WindowWidth } from "./lib/constants";+import { FPS } from "./lib/constants";import { getTimelinePath, loadTimelineFromFile } from "./lib/utils";-interface InputProps extends Record<string, unknown> {- projectName?: string;-}-export const RemotionRoot: React.FC = () => {- const inputProps = getInputProps<InputProps>();- const [frameLength, setFrameLength] = useState(1);-- const resolvedProjectName = useMemo(- () => inputProps.projectName ?? "history_of_venus",- [inputProps],- );-- useEffect(() => {- const handle = delayRender("Calculating FPS duration...");-- const fetchConfig = async () => {- const { lengthFrames } = await loadTimelineFromFile(- getTimelinePath(resolvedProjectName),- );- setFrameLength(lengthFrames);- continueRender(handle);- };-- fetchConfig();-- return () => {- continueRender(handle);- };- }, [resolvedProjectName]);-return (<><Compositionid="AIVideo"component={AIVideo}- durationInFrames={frameLength}fps={FPS}- width={WindowWidth}- height={WindowHeight}+ width={1080}+ height={1920}schema={aiVideoSchema}defaultProps={{- projectName: resolvedProjectName,+ projectName: "history_of_venus",+ timeline: null,+ }}+ calculateMetadata={async ({ props }) => {+ const { lengthFrames, timeline } = await loadTimelineFromFile(+ getTimelinePath(props.projectName),+ );++ return {+ durationInFrames: lengthFrames,+ props: {+ ...props,+ timeline,+ },+ };}}/></>diff --git a/packages/template-ai-video/src/components/AIVideo.tsx b/packages/template-ai-video/src/components/AIVideo.tsxindex 4181ebab71..b62582caf1 100644--- a/packages/template-ai-video/src/components/AIVideo.tsx+++ b/packages/template-ai-video/src/components/AIVideo.tsx@@ -1,143 +1,116 @@-import {- AbsoluteFill,- Html5Audio,- Sequence,- staticFile,- useDelayRender,-} from "remotion";+import { AbsoluteFill, Sequence, staticFile } from "remotion";import { z } from "zod";-import { Timeline } from "../lib/types";-import { IntoFrameDuration } from "../lib/constants";+import { Audio } from "@remotion/media";+import { TimelineSchema } from "../lib/types";+import { FPS, INTRO_DURATION } from "../lib/constants";import { loadFont } from "@remotion/google-fonts/BreeSerif";import { Background } from "./Background";import Subtitle from "./Subtitle";-import { useEffect, useState } from "react";-import {- calculateFrameTiming,- getAudioPath,- getTimelinePath,- loadTimelineFromFile,-} from "../lib/utils";+import { calculateFrameTiming, getAudioPath } from "../lib/utils";export const aiVideoSchema = z.object({projectName: z.string().min(1),+ timeline: TimelineSchema.nullable(),});+const { fontFamily } = loadFont();+export const AIVideo: React.FC<z.infer<typeof aiVideoSchema>> = ({projectName,+ timeline,}) => {- const { fontFamily } = loadFont();- const [timeline, setTimeline] = useState<Timeline | null>();- const { delayRender, continueRender } = useDelayRender();-- useEffect(() => {- const handle = delayRender("Loading timeline...");-- const fetchConfig = async () => {- const { timeline } = await loadTimelineFromFile(- getTimelinePath(projectName),- );- setTimeline(timeline);- continueRender(handle);- };-- fetchConfig();-- return () => {- continueRender(handle);- };- }, [projectName]);+ if (!timeline) {+ throw new Error("Expected timeline to be fetched");+ }return (<AbsoluteFill style={{ backgroundColor: "white" }}>- {timeline && (- <>- <Sequence durationInFrames={IntoFrameDuration}>- <AbsoluteFill- style={{- justifyContent: "center",- alignItems: "center",- textAlign: "center",- display: "flex",- zIndex: 10,- }}- >- <div- style={{- fontSize: 120,- lineHeight: "122px",- width: "87%",- color: "black",- fontFamily,- textTransform: "uppercase",- backgroundColor: "yellow",- paddingTop: 20,- paddingBottom: 20,- border: "10px solid black",- }}- >- {timeline.shortTitle}- </div>- </AbsoluteFill>- </Sequence>+ <Sequence durationInFrames={INTRO_DURATION}>+ <AbsoluteFill+ style={{+ justifyContent: "center",+ alignItems: "center",+ textAlign: "center",+ display: "flex",+ zIndex: 10,+ }}+ >+ <div+ style={{+ fontSize: 120,+ lineHeight: "122px",+ width: "87%",+ color: "black",+ fontFamily,+ textTransform: "uppercase",+ backgroundColor: "yellow",+ paddingTop: 20,+ paddingBottom: 20,+ border: "10px solid black",+ }}+ >+ {timeline.shortTitle}+ </div>+ </AbsoluteFill>+ </Sequence>- {timeline.elements.map((element, index) => {- const { startFrame, duration } = calculateFrameTiming(- element.startMs,- element.endMs,- { includeIntro: index === 0 },- );+ {timeline.elements.map((element, index) => {+ const { startFrame, duration } = calculateFrameTiming(+ element.startMs,+ element.endMs,+ { includeIntro: index === 0 },+ );- return (- <Sequence- key={`element-${index}`}- from={startFrame}- durationInFrames={duration}- >- <Background project={projectName} item={element} />- </Sequence>- );- })}+ return (+ <Sequence+ key={`element-${index}`}+ from={startFrame}+ durationInFrames={duration}+ premountFor={3 * FPS}+ >+ <Background project={projectName} item={element} />+ </Sequence>+ );+ })}- {timeline.text.map((element, index) => {- const { startFrame, duration } = calculateFrameTiming(- element.startMs,- element.endMs,- { addIntroOffset: true },- );+ {timeline.text.map((element, index) => {+ const { startFrame, duration } = calculateFrameTiming(+ element.startMs,+ element.endMs,+ { addIntroOffset: true },+ );- return (- <Sequence- key={`element-${index}`}- from={startFrame}- durationInFrames={duration}- >- <Subtitle key={index} text={element.text} />- </Sequence>- );- })}+ return (+ <Sequence+ key={`element-${index}`}+ from={startFrame}+ durationInFrames={duration}+ >+ <Subtitle key={index} text={element.text} />+ </Sequence>+ );+ })}- {timeline.audio.map((element, index) => {- const { startFrame, duration } = calculateFrameTiming(- element.startMs,- element.endMs,- { addIntroOffset: true },- );+ {timeline.audio.map((element, index) => {+ const { startFrame, duration } = calculateFrameTiming(+ element.startMs,+ element.endMs,+ { addIntroOffset: true },+ );- return (- <Sequence- key={`element-${index}`}- from={startFrame}- durationInFrames={duration}- >- <Html5Audio- src={staticFile(getAudioPath(projectName, element.audioUrl))}- />- </Sequence>- );- })}- </>- )}+ return (+ <Sequence+ key={`element-${index}`}+ from={startFrame}+ durationInFrames={duration}+ premountFor={3 * FPS}+ >+ <Audio+ src={staticFile(getAudioPath(projectName, element.audioUrl))}+ />+ </Sequence>+ );+ })}</AbsoluteFill>);};diff --git a/packages/template-ai-video/src/components/Background.tsx b/packages/template-ai-video/src/components/Background.tsxindex 4c18879575..f41fab8b46 100644--- a/packages/template-ai-video/src/components/Background.tsx+++ b/packages/template-ai-video/src/components/Background.tsx@@ -1,11 +1,11 @@-import { AbsoluteFill, Img, staticFile, useCurrentFrame } from "remotion";import {- FPS,- ImageHeight,- ImageWidth,- WindowHeight,- WindowWidth,-} from "../lib/constants";+ AbsoluteFill,+ Img,+ staticFile,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";+import { FPS, IMAGE_HEIGHT, IMAGE_WIDTH } from "../lib/constants";import { BackgroundElement } from "../lib/types";import { calculateBlur, getImagePath } from "../lib/utils";@@ -17,11 +17,11 @@ export const Background: React.FC<{}> = ({ item, project }) => {const frame = useCurrentFrame();const localMs = (frame / FPS) * 1000;+ const { width, height } = useVideoConfig();- const viewSize = { width: WindowWidth, height: WindowHeight };- const imageRatio = ImageHeight / ImageWidth;+ const imageRatio = IMAGE_HEIGHT / IMAGE_WIDTH;- const imgWidth = viewSize.height;+ const imgWidth = height;const imgHeight = imgWidth * imageRatio;let animScale = 1 + EXTRA_SCALE;@@ -41,8 +41,8 @@ export const Background: React.FC<{}const imgScale = animScale;- const top = -(imgHeight * imgScale - viewSize.height) / 2;- const left = -(imgWidth * imgScale - viewSize.width) / 2;+ const top = -(imgHeight * imgScale - height) / 2;+ const left = -(imgWidth * imgScale - width) / 2;const blur = calculateBlur({ item, localMs });const maxBlur = 25;diff --git a/packages/template-ai-video/src/lib/constants.ts b/packages/template-ai-video/src/lib/constants.tsindex d7499af502..847c5a3697 100644--- a/packages/template-ai-video/src/lib/constants.ts+++ b/packages/template-ai-video/src/lib/constants.ts@@ -1,6 +1,4 @@export const FPS = 30;-export const WindowWidth = 1080;-export const WindowHeight = 1920;-export const IntoFrameDuration = 1;-export const ImageWidth = 1024;-export const ImageHeight = 1792;+export const INTRO_DURATION = 1 * FPS;+export const IMAGE_WIDTH = 1024;+export const IMAGE_HEIGHT = 1792;diff --git a/packages/template-ai-video/src/lib/utils.ts b/packages/template-ai-video/src/lib/utils.tsindex 5d012d0db0..f934710995 100644--- a/packages/template-ai-video/src/lib/utils.ts+++ b/packages/template-ai-video/src/lib/utils.ts@@ -1,6 +1,6 @@import { staticFile } from "remotion";import { BackgroundElement, Timeline } from "./types";-import { FPS, IntoFrameDuration } from "./constants";+import { FPS, INTRO_DURATION } from "./constants";export const loadTimelineFromFile = async (filename: string) => {const res = await fetch(staticFile(filename));@@ -25,9 +25,9 @@ export const calculateFrameTiming = (const { includeIntro = false, addIntroOffset = false } = options;const startFrame =- (startMs * FPS) / 1000 + (addIntroOffset ? IntoFrameDuration : 0);+ (startMs * FPS) / 1000 + (addIntroOffset ? INTRO_DURATION : 0);const duration =- ((endMs - startMs) * FPS) / 1000 + (includeIntro ? IntoFrameDuration : 0);+ ((endMs - startMs) * FPS) / 1000 + (includeIntro ? INTRO_DURATION : 0);return { startFrame, duration };};