🎥 Make videos programmatically with React
eliminate redundancy
Jonny Burgere9e65bf77dab
diff --git a/packages/cli/src/index.tsx b/packages/cli/src/index.tsxindex 034e236aa1..eaf6b0ac13 100644--- a/packages/cli/src/index.tsx+++ b/packages/cli/src/index.tsx@@ -50,11 +50,9 @@ export const cli = async () => {} else if (command === 'lambda') {await lambdaCommand();} else if (command === 'render') {- await render({renderAsGif: false});+ await render();} else if (command === 'still') {await still();- } else if (command === 'gif') {- await render({renderAsGif: true});} else if (command === 'upgrade') {await upgrade();} else if (command === VERSIONS_COMMAND) {diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsxindex 5fd36605a4..ec92d179c1 100644--- a/packages/cli/src/render.tsx+++ b/packages/cli/src/render.tsx@@ -2,7 +2,6 @@ import {getCompositions,openBrowser,renderFrames,- renderGif,RenderInternals,renderMedia,RenderMediaOnDownload,@@ -27,7 +26,7 @@ import {bundleOnCli} from './setup-cache';import {RenderStep} from './step';import {checkAndValidateFfmpegVersion} from './validate-ffmpeg-version';-export const render = async ({renderAsGif}: {renderAsGif: boolean}) => {+export const render = async () => {const startTime = Date.now();const file = parsedCli._[1];if (!file) {@@ -253,89 +252,47 @@ export const render = async ({renderAsGif}: {renderAsGif: boolean}) => {return;}- if (renderAsGif || codec === 'gif') {- await renderGif({- outputLocation: absoluteOutputFile,- codec,- composition: config,- crf,- envVariables,- ffmpegExecutable,- frameRange,- imageFormat,- skipNFrames,- loop,- inputProps,- onProgress: (update) => {- encodedDoneIn = update.encodedDoneIn;- encodedFrames = update.encodedFrames;- renderedDoneIn = update.renderedDoneIn;- stitchStage = update.stitchStage;- renderedFrames = update.renderedFrames;- updateRenderProgress();- },- puppeteerInstance,- overwrite,- parallelism,- pixelFormat,- proResProfile,- quality,- serveUrl: urlOrBundle,- dumpBrowserLogs: Internals.Logging.isEqualOrBelowLogLevel(- Internals.Logging.getLogLevel(),- 'verbose'- ),- onStart: ({frameCount}) => {- totalFrames = frameCount;- },- chromiumOptions,- timeoutInMilliseconds: Internals.getCurrentPuppeteerTimeout(),- scale,- port,- });- } else {- await renderMedia({- outputLocation: absoluteOutputFile,- codec,- composition: config,- crf,- envVariables,- ffmpegExecutable,- ffprobeExecutable,- frameRange,- imageFormat,- inputProps,- onProgress: (update) => {- encodedDoneIn = update.encodedDoneIn;- encodedFrames = update.encodedFrames;- renderedDoneIn = update.renderedDoneIn;- stitchStage = update.stitchStage;- renderedFrames = update.renderedFrames;- updateRenderProgress();- },- puppeteerInstance,- overwrite,- parallelism,- pixelFormat,- proResProfile,- quality,- serveUrl: urlOrBundle,- onDownload,- dumpBrowserLogs: Internals.Logging.isEqualOrBelowLogLevel(- Internals.Logging.getLogLevel(),- 'verbose'- ),- onStart: ({frameCount}) => {- totalFrames = frameCount;- },- chromiumOptions,- timeoutInMilliseconds: Internals.getCurrentPuppeteerTimeout(),- scale,- port,- loop,- skipNFrames,- });- }+ await renderMedia({+ outputLocation: absoluteOutputFile,+ codec,+ composition: config,+ crf,+ envVariables,+ ffmpegExecutable,+ ffprobeExecutable,+ frameRange,+ imageFormat,+ inputProps,+ onProgress: (update) => {+ encodedDoneIn = update.encodedDoneIn;+ encodedFrames = update.encodedFrames;+ renderedDoneIn = update.renderedDoneIn;+ stitchStage = update.stitchStage;+ renderedFrames = update.renderedFrames;+ updateRenderProgress();+ },+ puppeteerInstance,+ overwrite,+ parallelism,+ pixelFormat,+ proResProfile,+ quality,+ serveUrl: urlOrBundle,+ onDownload,+ dumpBrowserLogs: Internals.Logging.isEqualOrBelowLogLevel(+ Internals.Logging.getLogLevel(),+ 'verbose'+ ),+ onStart: ({frameCount}) => {+ totalFrames = frameCount;+ },+ chromiumOptions,+ timeoutInMilliseconds: Internals.getCurrentPuppeteerTimeout(),+ scale,+ port,+ loop,+ skipNFrames,+ });Log.info();Log.info();@@ -359,7 +316,7 @@ export const render = async ({renderAsGif}: {renderAsGif: boolean}) => {Log.warn('Do you have minimum required Node.js version?');}- Log.info(chalk.green(`\nYour ${renderAsGif ? 'gif' : 'video'} is ready!`));+ Log.info(chalk.green(`\nYour video is ready!`));if (Internals.Logging.isEqualOrBelowLogLevel(diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex 376208dd08..6a88025836 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -36,7 +36,6 @@ export {CancelSignal, makeCancelSignal} from './make-cancel-signal';export {openBrowser} from './open-browser';export type {ChromiumOptions} from './open-browser';export {renderFrames} from './render-frames';-export {renderGif} from './render-gif';export {renderMedia,RenderMediaOnProgress,diff --git a/packages/renderer/src/render-gif.ts b/packages/renderer/src/render-gif.tsdeleted file mode 100644index caea8f8618..0000000000--- a/packages/renderer/src/render-gif.ts+++ /dev/null@@ -1,308 +0,0 @@-import {ExecaChildProcess} from 'execa';-import fs from 'fs';-import os from 'os';-import path from 'path';-import {Internals} from 'remotion';-import {canUseParallelEncoding} from './can-use-parallel-encoding';-import {ensureFramesInOrder} from './ensure-frames-in-order';-import {ensureOutputDirectory} from './ensure-output-directory';-import {getDurationFromFrameRange} from './get-duration-from-frame-range';-import {getFileExtensionFromCodec} from './get-extension-from-codec';-import {getExtensionOfFilename} from './get-extension-of-filename';-import {getRealFrameRange} from './get-frame-to-render';-import {getServeUrlWithFallback} from './legacy-webpack-config';-import {makeCancelSignal} from './make-cancel-signal';-import {prespawnFfmpeg} from './prespawn-ffmpeg';-import {renderFrames} from './render-frames';-import {RenderMediaOptions, StitchingState} from './render-media';-import {stitchFramesToGif} from './stitch-frames-to-gif';-import {tmpDir} from './tmp-dir';-import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';-import {validateOutputFilename} from './validate-output-filename';-import {validateScale} from './validate-scale';--type Await<T> = T extends PromiseLike<infer U> ? U : T;--export const renderGif = ({- parallelism,- proResProfile,- crf,- composition,- imageFormat,- ffmpegExecutable,- inputProps,- pixelFormat,- codec,- envVariables,- quality,- frameRange,- puppeteerInstance,- outputLocation,- onProgress,- overwrite,- onDownload,- loop,- skipNFrames,- dumpBrowserLogs,- onBrowserLog,- onStart,- timeoutInMilliseconds,- chromiumOptions,- scale,- browserExecutable,- port,- cancelSignal,- ...options-}: RenderMediaOptions): Promise<void> => {- Internals.validateQuality(quality);- if (typeof crf !== 'undefined' && crf !== null) {- Internals.validateSelectedCrfAndCodecCombination(crf, codec);- }-- validateOutputFilename(codec, getExtensionOfFilename(outputLocation));-- validateScale(scale);-- const serveUrl = getServeUrlWithFallback(options);-- let stitchStage: StitchingState = 'encoding';- let stitcherFfmpeg: ExecaChildProcess<string> | undefined;- let preStitcher: Await<ReturnType<typeof prespawnFfmpeg>> | null = null;- let encodedFrames = 0;- let renderedFrames = 0;- let renderedDoneIn: number | null = null;- let encodedDoneIn: number | null = null;- let cancelled = false;-- const renderStart = Date.now();- const tmpdir = tmpDir('pre-encode');- const parallelEncoding = canUseParallelEncoding(codec);- const actualImageFormat = imageFormat ?? 'jpeg';-- const preEncodedFileLocation = parallelEncoding- ? path.join(- tmpdir,- 'pre-encode.' + getFileExtensionFromCodec(codec, 'chunk')- )- : null;-- const outputDir = parallelEncoding- ? null- : fs.mkdtempSync(path.join(os.tmpdir(), 'react-motion-render'));-- validateEvenDimensionsWithCodec({- codec,- height: composition.height,- scale: scale ?? 1,- width: composition.width,- });-- const callUpdate = () => {- onProgress?.({- encodedDoneIn,- encodedFrames,- renderedDoneIn,- renderedFrames,- stitchStage,- });- };-- const realFrameRange = getRealFrameRange(- composition.durationInFrames,- frameRange ?? null- );-- const cancelRenderFrames = makeCancelSignal();- const cancelPrestitcher = makeCancelSignal();- const cancelStitcher = makeCancelSignal();-- cancelSignal?.(() => {- cancelRenderFrames.cancel();- });-- const {waitForRightTimeOfFrameToBeInserted, setFrameToStitch, waitForFinish} =- ensureFramesInOrder(realFrameRange);- const actualGifFps = Math.floor(composition.fps / (skipNFrames + 1));- const createPrestitcherIfNecessary = async () => {- if (preEncodedFileLocation) {- preStitcher = await prespawnFfmpeg({- width: composition.width * (scale ?? 1),- height: composition.height * (scale ?? 1),- fps: actualGifFps,- outputLocation: preEncodedFileLocation,- pixelFormat,- codec,- proResProfile,- crf,- onProgress: (frame: number) => {- encodedFrames = frame;- callUpdate();- },- verbose: Internals.Logging.isEqualOrBelowLogLevel(- Internals.Logging.getLogLevel(),- 'verbose'- ),- ffmpegExecutable,- imageFormat: actualImageFormat,- signal: cancelPrestitcher.cancelSignal,- });- stitcherFfmpeg = preStitcher.task;- }- };-- const waitForPrestitcherIfNecessary = async () => {- if (stitcherFfmpeg) {- await waitForFinish();- stitcherFfmpeg?.stdin?.end();- try {- await stitcherFfmpeg;- } catch (err) {- throw new Error(preStitcher?.getLogs());- }- }- };-- const happyPath = createPrestitcherIfNecessary()- .then(() => {- const renderFramesProc = renderFrames({- config: composition,- onFrameUpdate: (frame: number) => {- stitchStage = 'gif';- renderedFrames = frame;- callUpdate();- },- parallelism,- outputDir,- skipNFrames,- onStart: (data) => {- renderedFrames = 0;- callUpdate();- onStart?.(data);- },- inputProps,- envVariables,- imageFormat: actualImageFormat,- quality,- frameRange: frameRange ?? null,- puppeteerInstance,- onFrameBuffer: parallelEncoding- ? async (buffer, frame) => {- await waitForRightTimeOfFrameToBeInserted(frame);- if (cancelled) {- return;- }-- stitcherFfmpeg?.stdin?.write(buffer);-- setFrameToStitch(frame + 1);- }- : undefined,- serveUrl,- dumpBrowserLogs,- onBrowserLog,- onDownload,- timeoutInMilliseconds,- chromiumOptions,- scale,- ffmpegExecutable,- browserExecutable,- port,- cancelSignal: cancelRenderFrames.cancelSignal,- });-- return renderFramesProc;- })- .then((renderFramesReturn) => {- return Promise.all([renderFramesReturn, waitForPrestitcherIfNecessary()]);- })- .then(([{assetsInfo}]) => {- renderedDoneIn = Date.now() - renderStart;- callUpdate();-- ensureOutputDirectory(outputLocation);-- const stitchStart = Date.now();- return Promise.all([- stitchFramesToGif({- width: composition.width * (scale ?? 1),- height: composition.height * (scale ?? 1),- fps: actualGifFps,- outputLocation,- internalOptions: {- preEncodedFileLocation,- imageFormat: actualImageFormat,- },- force: overwrite ?? Internals.DEFAULT_OVERWRITE,- pixelFormat,- codec,- proResProfile,- crf,- loop,- assetsInfo,- ffmpegExecutable,- onProgress: (frame: number) => {- stitchStage = 'gif';- encodedFrames = frame;- callUpdate();- },- verbose: Internals.Logging.isEqualOrBelowLogLevel(- Internals.Logging.getLogLevel(),- 'verbose'- ),- dir: outputDir ?? undefined,- cancelSignal: cancelStitcher.cancelSignal,- }),- stitchStart,- ]);- })- .then(([, stitchStart]) => {- encodedFrames = getDurationFromFrameRange(- frameRange ?? null,- composition.durationInFrames,- skipNFrames- );- encodedDoneIn = Date.now() - stitchStart;- callUpdate();- })- .catch((err) => {- /**- * When an error is thrown in renderFrames(...) (e.g., when delayRender() is used incorrectly), fs.unlinkSync(...) throws an error that the file is locked because ffmpeg is still running, and renderMedia returns it.- * Therefore we first kill the FFMPEG process before deleting the file- */- cancelled = true;- cancelRenderFrames.cancel();- cancelStitcher.cancel();- cancelPrestitcher.cancel();- if (stitcherFfmpeg !== undefined && stitcherFfmpeg.exitCode === null) {- const promise = new Promise<void>((resolve) => {- setTimeout(() => {- resolve();- }, 2000);- (stitcherFfmpeg as ExecaChildProcess<string>).on('close', resolve);- });- stitcherFfmpeg.kill();- return promise.then(() => {- throw err;- });- }-- throw err;- })- .finally(() => {- if (- preEncodedFileLocation !== null &&- fs.existsSync(preEncodedFileLocation)- ) {- fs.unlinkSync(preEncodedFileLocation);- }- });-- return Promise.race([- happyPath,- new Promise<void>((_resolve, reject) => {- cancelSignal?.(() => {- reject(new Error('renderMedia() got cancelled'));- });- }),- ]);-};diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex 8d66cda3e7..11e6d11b61 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -181,12 +181,14 @@ export const renderMedia = ({const {waitForRightTimeOfFrameToBeInserted, setFrameToStitch, waitForFinish} =ensureFramesInOrder(realFrameRange);+ const actualGifFps = Math.floor(composition.fps / (skipNFrames + 1));+const createPrestitcherIfNecessary = async () => {if (preEncodedFileLocation) {preStitcher = await prespawnFfmpeg({width: composition.width * (scale ?? 1),height: composition.height * (scale ?? 1),- fps: composition.fps,+ fps: actualGifFps,outputLocation: preEncodedFileLocation,pixelFormat,codec,@@ -286,7 +288,7 @@ export const renderMedia = ({stitchFramesToVideo({width: composition.width * (scale ?? 1),height: composition.height * (scale ?? 1),- fps: composition.fps,+ fps: actualGifFps,outputLocation,internalOptions: {preEncodedFileLocation,diff --git a/packages/renderer/src/stitch-frames-to-gif.ts b/packages/renderer/src/stitch-frames-to-gif.tsdeleted file mode 100644index 325b8e01d7..0000000000--- a/packages/renderer/src/stitch-frames-to-gif.ts+++ /dev/null@@ -1,155 +0,0 @@-import execa from 'execa';-import fs from 'fs';-import path from 'path';-import {Internals} from 'remotion';-import {getCodecName} from './get-codec-name';-import {getProResProfileName} from './get-prores-profile-name';-import {parseFfmpegProgress} from './parse-ffmpeg-progress';-import {StitcherOptions} from './stitch-frames-to-video';-import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';-import {validateFfmpeg} from './validate-ffmpeg';--const packageJsonPath = path.join(__dirname, '..', 'package.json');--const packageJson = fs.existsSync(packageJsonPath)- ? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))- : null;--type ReturnType = {- task: Promise<unknown>;- getLogs: () => string;-};--export const spawnFfmpeg = async (- options: StitcherOptions-): Promise<ReturnType> => {- Internals.validateDimension(- options.height,- 'height',- 'passed to `stitchFramesToVideo()`'- );- Internals.validateDimension(- options.width,- 'width',- 'passed to `stitchFramesToVideo()`'- );- Internals.validateFps(options.fps, 'passed to `stitchFramesToVideo()`');- const codec = options.codec ?? Internals.DEFAULT_CODEC;- validateEvenDimensionsWithCodec({- width: options.width,- height: options.height,- codec,- scale: 1,- });- const crf = options.crf ?? Internals.getDefaultCrfForCodec(codec);- const pixelFormat = options.pixelFormat ?? Internals.DEFAULT_PIXEL_FORMAT;- await validateFfmpeg(options.ffmpegExecutable ?? null);- const loop = options.loop ?? Internals.getLoop();-- const encoderName = getCodecName(codec);- const proResProfileName = getProResProfileName(codec, options.proResProfile);-- const supportsCrf = encoderName && codec !== 'prores';-- if (options.verbose) {- console.log(- '[verbose] ffmpeg',- options.ffmpegExecutable ?? 'ffmpeg in PATH'- );- console.log('[verbose] encoder', encoderName);- console.log('[verbose] pixelFormat', pixelFormat);- if (supportsCrf) {- console.log('[verbose] crf', crf);- }-- console.log('[verbose] codec', codec);- console.log('[verbose] proResProfileName', proResProfileName);- }-- Internals.validateSelectedCrfAndCodecCombination(crf, codec);- Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);-- const expectedFrames = options.assetsInfo.assets.length;-- const updateProgress = (preStitchProgress: number, muxProgress: number) => {- const totalFrameProgress =- 0.5 * preStitchProgress * expectedFrames + muxProgress * 0.5;- options.onProgress?.(Math.round(totalFrameProgress));- };-- const ffmpegArgs = [- ['-r', String(options.fps)],- ...(options.internalOptions?.preEncodedFileLocation- ? [['-i', options.internalOptions?.preEncodedFileLocation]]- : [- ['-f', 'image2'],- ['-s', `${options.width}x${options.height}`],- ['-start_number', String(options.assetsInfo.firstFrameIndex)],- ['-i', options.assetsInfo.imageSequenceName],- ]),- // -c:v is the same as -vcodec as -codec:video- // and specified the video codec.- // eslint-disable-next-line no-negated-condition- loop === null ? null : ['-loop', typeof loop !== 'number' ? '-1' : loop],- // Ignore metadata that may come from remote media- ['-map_metadata', '-1'],- [- '-metadata',- `comment=` +- [`Made with Remotion`, packageJson ? packageJson.version : null].join(- ' '- ),- ],- options.force ? '-y' : null,- options.outputLocation,- ];-- if (options.verbose) {- console.log('Generated FFMPEG command:');- console.log(ffmpegArgs);- }-- const ffmpegString = ffmpegArgs.flat(2).filter(Boolean) as string[];-- const task = execa(options.ffmpegExecutable ?? 'ffmpeg', ffmpegString, {- cwd: options.dir,- });- options.cancelSignal?.(() => {- task.kill();- });- let ffmpegOutput = '';- let isFinished = false;- task.stderr?.on('data', (data: Buffer) => {- const str = data.toString();- ffmpegOutput += str;- if (options.onProgress) {- const parsed = parseFfmpegProgress(str);- // FFMPEG bug: In some cases, FFMPEG does hang after it is finished with it's job- // Example repo: https://github.com/JonnyBurger/ffmpeg-repro (access can be given upon request)- if (parsed !== undefined) {- // If two times in a row the finishing frame is logged, we quit the render- if (parsed === expectedFrames) {- if (isFinished) {- task.stdin?.write('q');- } else {- isFinished = true;- }- }-- updateProgress(1, parsed);- }- }- });- return {task, getLogs: () => ffmpegOutput};-};--export const stitchFramesToGif = async (- options: StitcherOptions-): Promise<void> => {- const {task, getLogs} = await spawnFfmpeg(options);- try {- await task;- } catch (err) {- throw new Error(getLogs());- }-};diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex 8a9229de5b..c09216fe64 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -262,6 +262,10 @@ export const spawnFfmpeg = async (['-i', options.assetsInfo.imageSequenceName],]),['-i', audio],+ // TODO: Infinite loop+ options.loop === null+ ? null+ : ['-loop', typeof options.loop === 'number' ? options.loop : '-1'],// -c:v is the same as -vcodec as -codec:video// and specified the video codec.['-c:v', encoderName],