🎥 Make videos programmatically with React
feat: parallelEncoding
辉宇6b4943400ecf
diff --git a/packages/cli/src/progress-bar.ts b/packages/cli/src/progress-bar.tsindex 7c92ad07f3..eb8f41ae37 100644--- a/packages/cli/src/progress-bar.ts+++ b/packages/cli/src/progress-bar.ts@@ -45,12 +45,14 @@ export const makeBundlingProgress = ({export const makeRenderingProgress = ({frames,totalFrames,+ encodedFrames,steps,concurrency,doneIn,}: {frames: number;totalFrames: number;+ encodedFrames?:number;steps: number;concurrency: number;doneIn: number | null;@@ -60,8 +62,8 @@ export const makeRenderingProgress = ({'🖼 ',`(2/${steps})`,makeProgressBar(progress),- `${doneIn ? 'Rendered' : 'Rendering'} frames (${concurrency}x)`,- doneIn === null ? `${frames}/${totalFrames}` : chalk.gray(`${doneIn}ms`),+ `${doneIn ? 'Rendered' : 'Rendering'}${encodedFrames===undefined?'':` and ${doneIn ? 'Encoded' : 'Encoding'}`} frames (${concurrency}x)`,+ doneIn === null ? `${encodedFrames===undefined?'':`${encodedFrames}/`}${frames}/${totalFrames}` : chalk.gray(`${doneIn}ms`),].join(' ');};diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsxindex 20fab91249..5896c15a8d 100644--- a/packages/cli/src/render.tsx+++ b/packages/cli/src/render.tsx@@ -25,6 +25,9 @@ import {import {bundleOnCli} from './setup-cache';import {checkAndValidateFfmpegVersion} from './validate-ffmpeg-version';import {getActualConcurrency} from "@remotion/renderer/dist/get-concurrency";+import {ChildProcess} from "child_process";+import {spawnFfmpeg} from "@remotion/renderer/dist/stitcher";+import { ExecaChildProcess } from 'execa';const onError = async (info: OnErrorInfo) => {Log.error();@@ -74,7 +77,7 @@ export const render = async () => {const actualParallelism = getActualConcurrency(parallelism ?? null);- const browserInstance = Promise.all(new Array(concurrentMode==='browser'?actualParallelism:1).fill(true).map(()=>RenderInternals.openBrowser(browser, {+ const browserInstance = Promise.all(new Array(concurrentMode === 'browser' ? actualParallelism : 1).fill(true).map(() => RenderInternals.openBrowser(browser, {browserExecutable,shouldDumpIo: Internals.Logging.isEqualOrBelowLogLevel('verbose'),})));@@ -84,7 +87,7 @@ export const render = async () => {});}- const steps = shouldOutputImageSequence ? 2 : 3;+ const steps = (shouldOutputImageSequence||parallelEncoding) ? 2 : 3;const bundled = await bundleOnCli(fullPath, steps);@@ -117,18 +120,56 @@ export const render = async () => {const renderProgress = createProgressBar();let totalFrames = 0;const renderStart = Date.now();- const {assetsInfo} = await renderFrames({++ let stitcherFfmpeg: ExecaChildProcess<string>;+ let preStitcher;+ let encodedFrames:number|undefined;+ let renderedFrames: number;+ const updateRenderProgress=()=>renderProgress.update(+ makeRenderingProgress({+ frames: renderedFrames||0,+ encodedFrames,+ totalFrames,+ concurrency: RenderInternals.getActualConcurrency(parallelism),+ doneIn: null,+ steps,+ })+ );+ if(parallelEncoding&&!shouldOutputImageSequence){+ if (typeof crf !== 'number') {+ throw new TypeError('CRF is unexpectedly not a number');+ }+++ preStitcher = await spawnFfmpeg({+ dir: outputDir,+ width: config.width,+ height: config.height,+ fps: config.fps,+ outputLocation: absoluteOutputFile,+ force: overwrite,+ imageFormat,+ pixelFormat,+ codec,+ proResProfile,+ crf,+ parallelism,+ onProgress: (frame: number) => {+ encodedFrames=frame;+ updateRenderProgress();+ },+ verbose: Internals.Logging.isEqualOrBelowLogLevel('verbose'),+ parallelEncoding,+ assetsInfo: {assets: [], bundleDir: bundled}+ });+ stitcherFfmpeg=preStitcher.task;+ }++ const renderer = renderFrames({config,onFrameUpdate: (frame: number) => {- renderProgress.update(- makeRenderingProgress({- frames: frame,- totalFrames,- concurrency: RenderInternals.getActualConcurrency(parallelism),- doneIn: null,- steps,- })- );+ renderedFrames=frame;+ updateRenderProgress();},parallelism,concurrentMode,@@ -137,16 +178,10 @@ export const render = async () => {outputDir,onError,onStart: ({frameCount: fc}: OnStartData) => {- renderProgress.update(- makeRenderingProgress({- frames: 0,- totalFrames: fc,- concurrency: RenderInternals.getActualConcurrency(parallelism),- doneIn: null,- steps,- })- );+ renderedFrames=0;+ if(parallelEncoding)encodedFrames=0;totalFrames = fc;+ updateRenderProgress();},inputProps,envVariables,@@ -157,12 +192,24 @@ export const render = async () => {frameRange: frameRange ?? null,dumpBrowserLogs: Internals.Logging.isEqualOrBelowLogLevel('verbose'),puppeteerInstance: openedBrowser,+ writeFrame: async buffer => {+ stitcherFfmpeg?.stdin?.write(buffer);+ }});+ const {assetsInfo}=await renderer;+ if(stitcherFfmpeg){+ // (await stitcherFfmpeg)?.stderr?.pipe(process.stderr);+ // (await stitcherFfmpeg)?.stdout?.pipe(process.stdout);+ stitcherFfmpeg?.stdin?.end();+ await stitcherFfmpeg;+ preStitcher?.cleanup?.();+ }const closeBrowserPromise = openedBrowser.map(o=>o.close());renderProgress.update(makeRenderingProgress({frames: totalFrames,+ encodedFrames: parallelEncoding?totalFrames:undefined,totalFrames,steps,concurrency: RenderInternals.getActualConcurrency(parallelism),@@ -180,54 +227,56 @@ export const render = async () => {throw new TypeError('CRF is unexpectedly not a number');}- const stitchingProgress = createProgressBar();+ if(!parallelEncoding){+ const stitchingProgress = createProgressBar();- stitchingProgress.update(- makeStitchingProgress({- doneIn: null,- frames: 0,- steps,- totalFrames,- })- );- const stitchStart = Date.now();- await stitchFramesToVideo({- dir: outputDir,- width: config.width,- height: config.height,- fps: config.fps,- outputLocation: absoluteOutputFile,- force: overwrite,- imageFormat,- pixelFormat,- codec,- proResProfile,- crf,- assetsInfo,- parallelism,- onProgress: (frame: number) => {- stitchingProgress.update(- makeStitchingProgress({- doneIn: null,- frames: frame,- steps,- totalFrames,- })- );- },- onDownload: (src: string) => {- Log.info('Downloading asset... ', src);- },- verbose: Internals.Logging.isEqualOrBelowLogLevel('verbose'),- });- stitchingProgress.update(- makeStitchingProgress({- doneIn: Date.now() - stitchStart,- frames: totalFrames,- steps,- totalFrames,- }) + '\n'- );+ stitchingProgress.update(+ makeStitchingProgress({+ doneIn: null,+ frames: 0,+ steps,+ totalFrames,+ })+ );+ const stitchStart = Date.now();+ await stitchFramesToVideo({+ dir: outputDir,+ width: config.width,+ height: config.height,+ fps: config.fps,+ outputLocation: absoluteOutputFile,+ force: overwrite,+ imageFormat,+ pixelFormat,+ codec,+ proResProfile,+ crf,+ assetsInfo,+ parallelism,+ onProgress: (frame: number) => {+ stitchingProgress.update(+ makeStitchingProgress({+ doneIn: null,+ frames: frame,+ steps,+ totalFrames,+ })+ );+ },+ onDownload: (src: string) => {+ Log.info('Downloading asset... ', src);+ },+ verbose: Internals.Logging.isEqualOrBelowLogLevel('verbose'),+ });+ stitchingProgress.update(+ makeStitchingProgress({+ doneIn: Date.now() - stitchStart,+ frames: totalFrames,+ steps,+ totalFrames,+ }) + '\n'+ );+ }Log.verbose('Cleaning up...');try {diff --git a/packages/example/remotion.config.ts b/packages/example/remotion.config.tsindex fc596e78b0..4b3b7a5c9a 100644--- a/packages/example/remotion.config.ts+++ b/packages/example/remotion.config.ts@@ -4,6 +4,8 @@ import {Config, WebpackOverrideFn} from 'remotion';Config.Output.setOverwriteOutput(true);Config.Rendering.setConcurrentMode('browser');+Config.Rendering.setParallelEncoding(true);+//Config.Log.setLevel('verbose');type Bundler = 'webpack' | 'esbuild';diff --git a/packages/renderer/src/provide-screenshot.ts b/packages/renderer/src/provide-screenshot.tsindex c7cae47c32..eda32122a8 100644--- a/packages/renderer/src/provide-screenshot.ts+++ b/packages/renderer/src/provide-screenshot.ts@@ -13,11 +13,11 @@ export const provideScreenshot = async ({quality: number | undefined;options: {frame: number;- output: string;+ output?: string;};-}): Promise<void> => {+}): Promise<Buffer> => {// console.log(options.output);- await screenshotDOMElement({+ return screenshotDOMElement({page,opts: {path: options.output,diff --git a/packages/renderer/src/render.ts b/packages/renderer/src/render.tsindex 1d1318215b..7aa93a2d6f 100644--- a/packages/renderer/src/render.ts+++ b/packages/renderer/src/render.ts@@ -42,6 +42,7 @@ export const renderFrames = async ({browserExecutable,concurrentMode,parallelEncoding,+ writeFrame,}: {config: VideoConfig;compositionId: string;@@ -62,6 +63,7 @@ export const renderFrames = async ({onError?: (info: OnErrorInfo) => void;concurrentMode?: ConcurrentMode;parallelEncoding?: boolean;+ writeFrame?: (buffer?: Buffer) => void;}): Promise<RenderFramesOutput> => {Internals.validateDimension(config.height,@@ -145,7 +147,7 @@ export const renderFrames = async ({browserInstance.map(initPage):new Array(actualParallelism).fill(true).map(()=>initPage(browserInstance[0]));- let stopCycling = () => {};+ let stopCycling;if(concurrentMode!=='browser')stopCycling=cycleBrowserTabs(browserInstance[0]).stopCycling;@@ -165,7 +167,7 @@ export const renderFrames = async ({onStart({frameCount,});- const assets = await Promise.all(+ const frameRenderTasks =new Array(frameCount).fill(Boolean).map((x, i) => i)@@ -199,8 +201,10 @@ export const renderFrames = async ({throw error;}+ let frameBuffer;+if (imageFormat !== 'none') {- await provideScreenshot({+ frameBuffer = await provideScreenshot({page: freePage,imageFormat,quality,@@ -221,13 +225,21 @@ export const renderFrames = async ({framesRendered++;onFrameUpdate(framesRendered);freePage.off('pageerror', errorCallback);- return collectedAssets;- })- );+ return {collectedAssets,frameBuffer};+ });++ if(parallelEncoding) {+ for (const i in frameRenderTasks) {+ const o = await frameRenderTasks[i];+ writeFrame?.(o.frameBuffer);+ }+ }++ const assets= (await Promise.all(frameRenderTasks)).map(o=>o.collectedAssets);close().catch((err) => {console.log('Unable to close web server', err);});- stopCycling();+ stopCycling?.();// If browser instance was passed in, we close all the pages// we opened.// If new browser was opened, then closing the browser as a cleanup.diff --git a/packages/renderer/src/screenshot-dom-element.ts b/packages/renderer/src/screenshot-dom-element.tsindex eef6806966..bec107930d 100644--- a/packages/renderer/src/screenshot-dom-element.ts+++ b/packages/renderer/src/screenshot-dom-element.ts@@ -16,11 +16,11 @@ export const screenshotDOMElement = async ({selector?: string;};}): Promise<Buffer> => {- const path = 'path' in opts ? opts.path : null;+ const path = 'path' in opts ? opts.path : undefined;const {selector} = opts;if (!selector) throw Error('Please provide a selector.');- if (!path) throw Error('Please provide a path.');+ // if (!path) throw Error('Please provide a path.');if (imageFormat === 'png') {await page.evaluate(() => {diff --git a/packages/renderer/src/stitcher.ts b/packages/renderer/src/stitcher.tsindex e70479f37e..4dac34d35b 100644--- a/packages/renderer/src/stitcher.ts+++ b/packages/renderer/src/stitcher.ts@@ -23,9 +23,9 @@ import {parseFfmpegProgress} from './parse-ffmpeg-progress';import {resolveAssetSrc} from './resolve-asset-src';import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';import {validateFfmpeg} from './validate-ffmpeg';+import {ChildProcess} from "child_process";-// eslint-disable-next-line complexity-export const stitchFramesToVideo = async (options: {+export type StitcherOptions= {dir: string;fps: number;width: number;@@ -44,7 +44,64 @@ export const stitchFramesToVideo = async (options: {onDownload?: (src: string) => void;proResProfile?: ProResProfile;verbose?: boolean;-}): Promise<void> => {+ parallelEncoding?: boolean;+}++const getAssetsData=async (options:StitcherOptions)=>{+ const codec = options.codec ?? Internals.DEFAULT_CODEC;+ const encoderName = getCodecName(codec);+ const isAudioOnly = encoderName === null;+ // eslint-disable-next-line @typescript-eslint/no-shadow+ const [frameInfo, fileUrlAssets] = await Promise.all([+ getFrameInfo({+ dir: options.dir,+ isAudioOnly,+ }),+ convertAssetsToFileUrls({+ assets: options.assetsInfo.assets,+ dir: options.assetsInfo.bundleDir,+ onDownload: options.onDownload ?? (() => undefined),+ }),+ ]);++ markAllAssetsAsDownloaded();+ const assetPositions = calculateAssetPositions(fileUrlAssets);++ // eslint-disable-next-line @typescript-eslint/no-shadow+ const assetPaths = assetPositions.map((asset) => resolveAssetSrc(asset.src));++ const assetAudioDetails = await getAssetAudioDetails({+ assetPaths,+ parallelism: options.parallelism,+ });++ const filters = calculateFfmpegFilters({+ assetAudioDetails,+ assetPositions,+ fps: options.fps,+ videoTrackCount: isAudioOnly ? 0 : 1,+ });+ if (options.verbose) {+ console.log('asset positions', assetPositions);+ }++ if (options.verbose) {+ console.log('filters', filters);+ }++ // eslint-disable-next-line @typescript-eslint/no-shadow+ const {complexFilterFlag, cleanup} = await createFfmpegComplexFilter(filters);++ return {+ complexFilterFlag,+ cleanup,+ frameInfo,+ assetPaths,+ }+}++// eslint-disable-next-line complexity+export const spawnFfmpeg = async (options: StitcherOptions) => {Internals.validateDimension(options.height,'height',@@ -95,63 +152,34 @@ export const stitchFramesToVideo = async (options: {);Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);- const [frameInfo, fileUrlAssets] = await Promise.all([- getFrameInfo({- dir: options.dir,- isAudioOnly,- }),- convertAssetsToFileUrls({- assets: options.assetsInfo.assets,- dir: options.assetsInfo.bundleDir,- onDownload: options.onDownload ?? (() => undefined),- }),- ]);-- markAllAssetsAsDownloaded();- const assetPositions = calculateAssetPositions(fileUrlAssets);-- const assetPaths = assetPositions.map((asset) => resolveAssetSrc(asset.src));-- const assetAudioDetails = await getAssetAudioDetails({+ const {+ complexFilterFlag,+ cleanup,+ frameInfo,assetPaths,- parallelism: options.parallelism,- });-- const filters = calculateFfmpegFilters({- assetAudioDetails,- assetPositions,- fps: options.fps,- videoTrackCount: isAudioOnly ? 0 : 1,- });- if (options.verbose) {- console.log('asset positions', assetPositions);- }-- if (options.verbose) {- console.log('filters', filters);- }+ } = options.parallelEncoding?{}:await getAssetsData(options);- const {complexFilterFlag, cleanup} = await createFfmpegComplexFilter(filters);const ffmpegArgs = [['-r', String(options.fps)],- isAudioOnly ? null : ['-f', 'image2'],+ isAudioOnly ? null : ['-f', options.parallelEncoding?'image2pipe':'image2'],isAudioOnly ? null : ['-s', `${options.width}x${options.height}`],frameInfo ? ['-start_number', String(frameInfo.startNumber)] : null,frameInfo? ['-i', `element-%0${frameInfo.numberLength}d.${imageFormat}`]: null,- ...assetsToFfmpegInputs({+ options.parallelEncoding?['-i','-']:null,+ ...assetPaths?assetsToFfmpegInputs({assets: assetPaths,isAudioOnly,fps: options.fps,frameCount: options.assetsInfo.assets.length,- }),+ }): [],encoderName? // -c:v is the same as -vcodec as -codec:video// and specified the video codec.- ['-c:v', encoderName]+ ['-c:v', encoderName]: // If only exporting audio, we drop the video explicitly- ['-vn'],+ ['-vn'],proResProfileName ? ['-profile:v', proResProfileName] : null,supportsCrf ? ['-crf', String(crf)] : null,isAudioOnly ? null : ['-pix_fmt', pixelFormat],@@ -180,8 +208,8 @@ export const stitchFramesToVideo = async (options: {.filter(Boolean) as string[];const task = execa('ffmpeg', ffmpegString, {cwd: options.dir});-task.stderr?.on('data', (data: Buffer) => {+ // console.log(data.toString());if (options.onProgress) {const parsed = parseFfmpegProgress(data.toString());if (parsed !== undefined) {@@ -189,6 +217,13 @@ export const stitchFramesToVideo = async (options: {}}});+ return {task,cleanup};+}++// eslint-disable-next-line complexity+export const stitchFramesToVideo = async (options: StitcherOptions): Promise<void> => {++ const {task,cleanup}=await spawnFfmpeg(options);await task;- cleanup();+ cleanup?.();};