🎥 Make videos programmatically with React
Merge branch 'main' into pr/128
Jonny Burgerdc5771492385
diff --cc packages/cli/src/editor/components/TimelineElements.tsxindex d40cba7feb,8518815add..28c8647a88--- a/packages/cli/src/editor/components/TimelineElements.tsx+++ b/packages/cli/src/editor/components/TimelineElements.tsx@@@ -30,13 -26,13 +30,17 @@@ export const TimelineElements: React.Fif (!videoConfig) {return [];}- return calculateTimeline(sequences, videoConfig.durationInFrames);- }, [sequences, videoConfig]);+ return calculateTimeline({+ assets,+ sequences,+ sequenceDuration: videoConfig.durationInFrames,+ });+ }, [assets, sequences, videoConfig]);+ // If a composition is 100 frames long, the last frame is 99+ // and therefore frame 99 should be at the right+ const lastFrame = (videoConfig?.durationInFrames ?? 1) - 1;+return (<divstyle={{@@@ -60,16 -60,14 +68,16 @@@key={s.sequence.id}style={{background:- 'linear-gradient(to bottom, #3697e1, #348AC7 60%)',- border: '1px solid rgba(255, 255, 255, 0.2)',+ track.trackType === 'sequence'+ ? SEQUENCE_GRADIENT+ : AUDIO_GRADIENT,+ border: '1px solid rgba(255, 255, 255, 0.4)',borderRadius: 4,position: 'absolute',- height: 80,+ height: track.trackType === 'sequence' ? 80 : 60,marginTop: 1,marginLeft: `calc(${- (s.sequence.from / videoConfig.durationInFrames) * 100+ (s.sequence.from / lastFrame) * 100}%)`,width:s.sequence.duration === Infinitydiff --cc packages/cli/src/render.tsxindex cc8c06fff4,39675ee76f..c71deeb00f--- a/packages/cli/src/render.tsx+++ b/packages/cli/src/render.tsx@@@ -146,19 -185,19 +185,19 @@@ export const render = async () =>},cliProgress.Presets.shades_grey);- const assets = await renderFrames({- const rendered = await renderFrames({++ const {assetPositions, frameCount} = await renderFrames({config,onFrameUpdate: (frame) => renderProgress.update(frame),parallelism,compositionId,outputDir,- onStart: () => {- onStart: ({frameCount}) => {++ onStart: ({frameCount: fc}) => {process.stdout.write(`📼 (2/${steps}) Rendering frames (${getActualConcurrency(parallelism)}x concurrency)...\n`);- renderProgress.start(frames, 0);- renderProgress.start(frameCount, 0);++ renderProgress.start(fc, 0);},userProps,webpackBundle: bundled,@@@ -182,7 -223,7 +223,7 @@@},cliProgress.Presets.shades_grey);- stitchingProgress.start(frames, 0);- stitchingProgress.start(rendered.frameCount, 0);++ stitchingProgress.start(frameCount, 0);await stitchFramesToVideo({dir: outputDir,width: config.width,@@@ -194,8 -235,6 +235,8 @@@pixelFormat,codec,crf,- assets,++ assets: assetPositions,+ parallelism,onProgress: (frame) => {stitchingProgress.update(frame);},diff --cc packages/core/src/audio/AudioForDevelopment.tsxindex 4e55cbbab3,5c55a4c3e6..be38aec9f2--- a/packages/core/src/audio/AudioForDevelopment.tsx+++ b/packages/core/src/audio/AudioForDevelopment.tsx@@@ -1,8 -1,6 +1,8 @@@-import React, {useEffect, useRef} from 'react';+import React, {useContext, useEffect, useRef, useState} from 'react';+import {CompositionManager} from '../CompositionManager';+import {SequenceContext} from '../sequencing';import {usePlayingState} from '../timeline-position-state';- import {useCurrentFrame} from '../use-frame';+ import {useAbsoluteCurrentFrame, useCurrentFrame} from '../use-frame';import {useUnsafeVideoConfig} from '../use-unsafe-video-config';import {RemotionAudioProps} from './props';diff --cc packages/core/src/video/VideoForDevelopment.tsxindex 4f5edc0d62,3e026c6166..3fd38fb965--- a/packages/core/src/video/VideoForDevelopment.tsx+++ b/packages/core/src/video/VideoForDevelopment.tsx@@@ -25,10 -28,25 +28,25 @@@ export const VideoForDevelopment: Reactif (!videoConfig) {throw new Error('No video config found');}- if (!playing || currentFrame === 0) {- videoRef.current.currentTime = currentFrame / (1000 / videoConfig.fps);+ const currentTime = (() => {+ if (FEATURE_FLAG_V2_BREAKING_CHANGES) {+ // In Chrome, if 30fps, the first frame is still displayed at 0.033333+ // even though after that it increases by 0.033333333 each.+ // So frame = 0 in Remotion is like frame = 1 for the browser+ return (currentFrame + 1) / videoConfig.fps;+ }+ return currentFrame / (1000 / videoConfig.fps);+ })();++ if (!playing || absoluteFrame === 0) {+ videoRef.current.currentTime = currentTime;+ }++ if (videoRef.current.paused && !videoRef.current.ended && playing) {+ videoRef.current.currentTime = currentTime;+ videoRef.current.play();}- }, [currentFrame, playing, videoConfig]);+ }, [currentFrame, playing, videoConfig, absoluteFrame]);- return <video ref={videoRef} muted {...props} />;+ return <video ref={videoRef} {...props} />;};diff --cc packages/example/src/Video.tsxindex 377b184f82,262d96fe1d..a8abcbf254--- a/packages/example/src/Video.tsx+++ b/packages/example/src/Video.tsx@@@ -137,22 -140,30 +140,46 @@@ export const Index: React.FC = () =>fps={30}durationInFrames={10}/>+ <Composition+ id="audio-testing"+ lazyComponent={() => import('./AudioTesting')}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={300}+ />+ <Composition+ id="audio-testing-mute"+ lazyComponent={() => import('./AudioTestingMute')}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={300}+ />+ <Composition+ id="ten-frame-tester"+ component={TenFrameTester}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={10}+ />+ <Composition+ id="video-testing"+ component={VideoTesting}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={100}+ />+ <Composition+ id="framer"+ component={Framer}+ width={1080}+ height={1080}+ fps={30}+ durationInFrames={100}+ /></>);};diff --cc packages/renderer/package.jsonindex c7e6c729bc,82936aa044..407c1020ab--- a/packages/renderer/package.json+++ b/packages/renderer/package.json@@@ -17,14 -18,12 +18,13 @@@},"dependencies": {"@babel/preset-typescript": "^7.10.4",- "@remotion/bundler": "^1.4.0",- "@types/babel__core": "^7.1.12",- "@types/babel__template": "^7.4.0",+ "@remotion/bundler": "^1.5.2","execa": "^4.0.2",+ "p-limit": "^3.1.0",+ "node-static": "^0.7.11","prettier": "^2.0.5",- "puppeteer": "^7.1.0",- "remotion": "^1.4.0",+ "puppeteer-core": "^8.0.0",+ "remotion": "^1.5.0","typescript": "^4.1.2","webpack": "5.20.1","xns": "^2.0.7"diff --cc packages/renderer/src/render.tsindex 1917803155,eab405badc..1cd940e633--- a/packages/renderer/src/render.ts+++ b/packages/renderer/src/render.ts@@@ -1,10 -1,20 +1,22 @@@import path from 'path';- import {VideoConfig} from 'remotion';+ import {Browser, FrameRange, Internals, VideoConfig} from 'remotion';import {openBrowser, provideScreenshot} from '.';- import {calculateAssetsPosition} from './assets';++import {Assets, calculateAssetsPosition} from './assets';import {getActualConcurrency} from './get-concurrency';+ import {getFrameCount} from './get-frame-range';+ import {getFrameToRender} from './get-frame-to-render';import {DEFAULT_IMAGE_FORMAT, ImageFormat} from './image-format';import {Pool} from './pool';+ import {serveStatic} from './serve-static';++ export type RenderFramesOutput = {+ frameCount: number;++ assetPositions: Assets;+ };++ type OnStartData = {+ frameCount: number;+ };export const renderFrames = async ({config,@@@ -56,49 -73,45 +75,52 @@@const pool = new Pool(await Promise.all(pages));- const {durationInFrames: frames} = config;+ const frameCount = getFrameCount(config.durationInFrames, frameRange ?? null);// Substract one because 100 frames will be 00-99// --> 2 digits- const filePadLength = String(frames - 1).length;+ let filePadLength = 0;+ if (frameCount) {+ filePadLength = String(frameCount - 1).length;+ }let framesRendered = 0;- onStart();+++ onStart({+ frameCount,+ });- await Promise.all(+ const assetsFrames = await Promise.all(- new Array(frames)+ new Array(frameCount).fill(Boolean).map((x, i) => i)- .map(async (f) => {+ .map(async (index) => {+ const frame = getFrameToRender(frameRange ?? null, index);const freePage = await pool.acquire();- const paddedIndex = String(f).padStart(filePadLength, '0');- try {- await provideScreenshot({- page: freePage,- imageFormat,- quality,- options: {- frame: f,- output: path.join(- outputDir,- `element-${paddedIndex}.${imageFormat}`- ),- },- });+ const paddedIndex = String(frame).padStart(filePadLength, '0');- return await freePage.evaluate(() => {- return window.remotion_collectAssets();- });- } catch (err) {- console.log('Error taking screenshot', err);-- return [];- } finally {- pool.release(freePage);- framesRendered++;- onFrameUpdate(framesRendered);- }- await provideScreenshot({++ const screenshot = await provideScreenshot({+ page: freePage,+ imageFormat,+ quality,+ options: {+ frame,+ output: path.join(+ outputDir,+ `element-${paddedIndex}.${imageFormat}`+ ),+ },+ });+ pool.release(freePage);+ framesRendered++;+ onFrameUpdate(framesRendered);++ return await freePage.evaluate(() => {++ return window.remotion_collectAssets();++ });}));+ await Promise.all([browserInstance.close(), close()]);++ const assetPositions = calculateAssetsPosition(assetsFrames);+- await browser.close();-- return calculateAssetsPosition(assetsFrames);+ return {++ assetPositions,+ frameCount,+ };};diff --cc packages/renderer/src/stitcher.tsindex 2d0f471ac2,c0badab3aa..8db92e54ee--- a/packages/renderer/src/stitcher.ts+++ b/packages/renderer/src/stitcher.ts@@@ -62,68 -58,32 +62,71 @@@ export const stitchFramesToVideo = asyn);Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);+ const assetPaths = options.assets.map((asset) => resolveAssetSrc(asset.src));+ const assetAudioDetails = await getAssetAudioDetails({+ assetPaths,+ cwd: options.dir,+ parallelism: options.parallelism,+ });+const ffmpegArgs = [- '-r',- String(options.fps),- '-f',- 'image2',- '-s',- `${options.width}x${options.height}`,- '-start_number',- String(smallestNumber),- '-i',- `element-%0${numberLength}d.${imageFormat}`,- '-c:v',- encoderName,- '-crf',- crf,- '-b:v',- '1M',- options.force ? '-y' : null,- '-pix_fmt',- pixelFormat,+ ['-r', String(options.fps)],+ ['-f', 'image2'],+ ['-s', `${options.width}x${options.height}`],++ ['-start_number',++ String(smallestNumber)],+ ['-i', `element-%0${numberLength}d.${imageFormat}`],+ ...assetPaths.map((path) => ['-i', path]),+ ['-c:v', encoderName],+ ['-crf', String(crf)],+ ['-pix_fmt', pixelFormat],++// Without explicitly disabling auto-alt-ref,// transparent WebM generation doesn't work- pixelFormat === 'yuva420p' ? '-auto-alt-ref' : null,- pixelFormat === 'yuva420p' ? '0' : null,+ pixelFormat === 'yuva420p' ? ['-auto-alt-ref', '0'] : null,+ ['-b:v', '1M'],+ ['-c:a', 'aac'],+ !options.assets.length+ ? null+ : [+ '-filter_complex',+ [+ ...options.assets.map((asset, i) => {+ const duration = (asset.duration / options.fps).toFixed(3); // in seconds with milliseconds level precision+ const assetTrimLeft = (asset.sequenceFrame / options.fps).toFixed(+ 3+ );+ const assetTrimRight = (+ (asset.sequenceFrame + asset.duration) /+ options.fps+ ).toFixed(3);+ const startInVideo = (+ (asset.startInVideo / options.fps) *+ 1000+ ).toFixed(); // in milliseconds+ const audioDetails = assetAudioDetails.get(+ resolveAssetSrc(asset.src)+ );++ return [+ `[${i + 1}:a]`,+ duration ? `atrim=${assetTrimLeft}:${assetTrimRight},` : '',+ `adelay=${new Array(audioDetails!.channels).fill(startInVideo).join('|')}`,+ `[a${i + 1}]`,+ ].join('');+ }),+ `${options.assets.map((asset, i) => `[a${i + 1}]`).join('')}amix=${+ options.assets.length+ },dynaudnorm`,+ ].join(';'),+ ],+ '-shortest',+ ['-map', '0:v'],+ options.force ? '-y' : null,options.outputLocation,- ].filter(Boolean) as string[];+ ]+ .reduce<(string | null)[]>((acc, val) => acc.concat(val), [])+ .filter(Boolean) as string[];const task = execa('ffmpeg', ffmpegArgs, {cwd: options.dir});