🎥 Make videos programmatically with React
separate pre-pipeline and main pipeline
Jonny Burger8c9c36fdc5a9
diff --git a/packages/renderer/src/prespawn-ffmpeg.ts b/packages/renderer/src/prespawn-ffmpeg.tsnew file mode 100644index 0000000000..64edc95385--- /dev/null+++ b/packages/renderer/src/prespawn-ffmpeg.ts@@ -0,0 +1,146 @@+import execa from 'execa';+import {+ Codec,+ FfmpegExecutable,+ ImageFormat,+ Internals,+ PixelFormat,+ ProResProfile,+} from 'remotion';+import {getAudioCodecName} from './get-audio-codec-name';+import {getCodecName} from './get-codec-name';+import {getProResProfileName} from './get-prores-profile-name';+import {parseFfmpegProgress} from './parse-ffmpeg-progress';+import {DEFAULT_SAMPLE_RATE} from './sample-rate';+import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';+import {validateFfmpeg} from './validate-ffmpeg';++export type PreSticherOptions = {+ fps: number;+ width: number;+ height: number;+ outputLocation: string;+ pixelFormat: PixelFormat | undefined;+ codec: Codec | undefined;+ crf: number | null | undefined;+ onProgress: (progress: number) => void;+ proResProfile: ProResProfile | undefined;+ verbose: boolean;+ ffmpegExecutable: FfmpegExecutable | undefined;+ imageFormat: ImageFormat;+};++export const prespawnFfmpeg = async (options: PreSticherOptions) => {+ 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 encoderName = getCodecName(codec);+ const audioCodecName = getAudioCodecName(codec);+ const proResProfileName = getProResProfileName(codec, options.proResProfile);++ const isAudioOnly = encoderName === null;+ 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] audioCodec', audioCodecName);+ console.log('[verbose] pixelFormat', pixelFormat);+ if (supportsCrf) {+ console.log('[verbose] crf', crf);+ }++ console.log('[verbose] codec', codec);+ console.log('[verbose] isAudioOnly', isAudioOnly);+ console.log('[verbose] proResProfileName', proResProfileName);+ }++ Internals.validateSelectedCrfAndCodecCombination(crf, codec);+ Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);++ const ffmpegArgs = [+ ['-r', String(options.fps)],+ ...(isAudioOnly+ ? []+ : [+ ['-f', 'image2pipe'],+ ['-s', `${options.width}x${options.height}`],+ // If scale is very small (like 0.1), FFMPEG cannot figure out the image+ // format on it's own and we need to hint the format+ ['-vcodec', options.imageFormat === 'jpeg' ? 'mjpeg' : 'png'],+ ['-i', '-'],+ ]),+ encoderName+ ? // -c:v is the same as -vcodec as -codec:video+ // and specified the video codec.+ ['-c:v', encoderName]+ : // If only exporting audio, we drop the video explicitly+ ['-vn'],+ ...[+ proResProfileName ? ['-profile:v', proResProfileName] : null,+ supportsCrf ? ['-crf', String(crf)] : null,+ isAudioOnly ? null : ['-pix_fmt', pixelFormat],++ // Without explicitly disabling auto-alt-ref,+ // transparent WebM generation doesn't work+ pixelFormat === 'yuva420p' ? ['-auto-alt-ref', '0'] : null,+ isAudioOnly ? null : ['-b:v', '1M'],+ ],+ '-ar',+ String(DEFAULT_SAMPLE_RATE),+ // Stereo sound, even force mono to be stereo+ // Otherwise mixing mono + stereo ends up speeding up the audio+ '-ac',+ '2',+ audioCodecName ? ['-c:a', audioCodecName] : null,+ // Ignore audio from image sequence+ isAudioOnly ? null : ['-map', '0:v'],+ // Ignore metadata that may come from remote media+ isAudioOnly ? null : ['-map_metadata', '-1'],+ '-y',+ 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);+ let ffmpegOutput = '';+ task.stderr?.on('data', (data: Buffer) => {+ const str = data.toString();+ ffmpegOutput += str;+ if (options.onProgress) {+ const parsed = parseFfmpegProgress(str);+ if (parsed !== undefined) {+ options.onProgress(parsed);+ }+ }+ });+ return {task, getLogs: () => ffmpegOutput};+};diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex 30b0b23e5a..9691c12364 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -24,8 +24,9 @@ import {ServeUrlOrWebpackBundle,} from './legacy-webpack-config';import {ChromiumOptions} from './open-browser';+import {prespawnFfmpeg} from './prespawn-ffmpeg';import {renderFrames} from './render-frames';-import {spawnFfmpeg, stitchFramesToVideo} from './stitch-frames-to-video';+import {stitchFramesToVideo} from './stitch-frames-to-video';import {tmpDir} from './tmp-dir';import {OnStartData} from './types';import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';@@ -106,7 +107,7 @@ export const renderMedia = async ({let stitchStage: StitchingState = 'encoding';let stitcherFfmpeg: ExecaChildProcess<string> | undefined;- let preStitcher: Await<ReturnType<typeof spawnFfmpeg>> | null = null;+ let preStitcher: Await<ReturnType<typeof prespawnFfmpeg>> | null = null;let encodedFrames = 0;let renderedFrames = 0;let renderedDoneIn: number | null = null;@@ -146,12 +147,11 @@ export const renderMedia = async ({};if (preEncodedFileLocation) {- preStitcher = await spawnFfmpeg({+ preStitcher = await prespawnFfmpeg({width: composition.width * (scale ?? 1),height: composition.height * (scale ?? 1),fps: composition.fps,outputLocation: preEncodedFileLocation,- force: true,pixelFormat,codec,proResProfile,@@ -165,12 +165,7 @@ export const renderMedia = async ({'verbose'),ffmpegExecutable,- internalOptions: {- parallelEncoding,- preEncodedFileLocation: null,- imageFormat: actualImageFormat,- },- assetsInfo: null,+ imageFormat: actualImageFormat,});stitcherFfmpeg = preStitcher.task;}@@ -228,8 +223,6 @@ export const renderMedia = async ({await stitcherFfmpeg;} catch (err) {throw new Error(preStitcher?.getLogs());- } finally {- preStitcher?.cleanup?.();}}@@ -246,7 +239,6 @@ export const renderMedia = async ({fps: composition.fps,outputLocation,internalOptions: {- parallelEncoding: false,preEncodedFileLocation,imageFormat: actualImageFormat,},diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex de14be1023..9ba4173639 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -33,7 +33,7 @@ export type StitcherOptions = {height: number;outputLocation: string;force: boolean;- assetsInfo: RenderAssetInfo | null;+ assetsInfo: RenderAssetInfo;pixelFormat?: PixelFormat;codec?: Codec;crf?: number | null;@@ -45,7 +45,6 @@ export type StitcherOptions = {dir?: string;internalOptions?: {preEncodedFileLocation: string | null;- parallelEncoding: boolean;imageFormat: ImageFormat;};};@@ -54,17 +53,14 @@ const getAssetsData = async (options: StitcherOptions) => {const codec = options.codec ?? Internals.DEFAULT_CODEC;const encoderName = getCodecName(codec);const isAudioOnly = encoderName === null;- const fileUrlAssets = await (options.assetsInfo- ? convertAssetsToFileUrls({- assets: options.assetsInfo.assets,- downloadDir: options.assetsInfo.downloadDir,- onDownload: options.onDownload ?? (() => () => undefined),- })- : null);+ const fileUrlAssets = await convertAssetsToFileUrls({+ assets: options.assetsInfo.assets,+ downloadDir: options.assetsInfo.downloadDir,+ onDownload: options.onDownload ?? (() => () => undefined),+ });markAllAssetsAsDownloaded();- const assetPositions: Assets =- fileUrlAssets === null ? [] : calculateAssetPositions(fileUrlAssets);+ const assetPositions: Assets = calculateAssetPositions(fileUrlAssets);markAllAssetsAsDownloaded();@@ -145,13 +141,9 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {Internals.validateSelectedCrfAndCodecCombination(crf, codec);Internals.validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);- const {- complexFilterFlag = undefined,- cleanup = undefined,- assetPositions = undefined,- } = options.internalOptions?.parallelEncoding- ? {}- : await getAssetsData(options);+ const {complexFilterFlag, cleanup, assetPositions} = await getAssetsData(+ options+ );const ffmpegArgs = [['-r', String(options.fps)],@@ -160,39 +152,17 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {: isAudioOnly? []: [- [- '-f',- options.internalOptions?.parallelEncoding- ? ['image2pipe']- : 'image2',- ],+ ['-f', 'image2'],['-s', `${options.width}x${options.height}`],- options.assetsInfo- ? ['-start_number', String(options.assetsInfo.firstFrameIndex)]- : null,- options.assetsInfo- ? ['-i', options.assetsInfo.imageSequenceName]- : null,- // If scale is very small (like 0.1), FFMPEG cannot figure out the image- // format on it's own and we need to hint the format- options.internalOptions?.parallelEncoding- ? [- '-vcodec',- options.internalOptions.imageFormat === 'jpeg'- ? 'mjpeg'- : 'png',- ]- : null,- options.internalOptions?.parallelEncoding ? ['-i', '-'] : null,+ ['-start_number', String(options.assetsInfo.firstFrameIndex)],+ ['-i', options.assetsInfo.imageSequenceName],]),- ...(options.assetsInfo && assetPositions- ? assetsToFfmpegInputs({- assets: assetPositions.map((a) => a.src),- isAudioOnly,- fps: options.fps,- frameCount: options.assetsInfo.assets.length,- })- : []),+ ...assetsToFfmpegInputs({+ assets: assetPositions.map((a) => a.src),+ 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.@@ -235,7 +205,7 @@ export const spawnFfmpeg = async (options: StitcherOptions) => {const ffmpegString = ffmpegArgs.flat(2).filter(Boolean) as string[];const task = execa(options.ffmpegExecutable ?? 'ffmpeg', ffmpegString, {- cwd: options.internalOptions?.parallelEncoding ? undefined : options.dir,+ cwd: options.dir,});let ffmpegOutput = '';task.stderr?.on('data', (data: Buffer) => {