🎥 Make videos programmatically with React
internalize stitchFramesToVideo
Jonny Burger91216d1a5986
diff --git a/packages/lambda/src/shared/validate-outname.ts b/packages/lambda/src/shared/validate-outname.tsindex 690e22ada6..aa9b3963a2 100644--- a/packages/lambda/src/shared/validate-outname.ts+++ b/packages/lambda/src/shared/validate-outname.ts@@ -35,7 +35,7 @@ export const validateOutname = (codec,audioCodec,extension: RenderInternals.getExtensionOfFilename(outName) as string,- preferLossless: false,+ preferLossless: true,});}diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex ba8c0baae3..00c33b872f 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -50,7 +50,7 @@ import {shouldUseParallelEncoding} from './prestitcher-memory-usage';import type {ProResProfile} from './prores-profile';import {validateSelectedCodecAndProResCombination} from './prores-profile';import {internalRenderFrames} from './render-frames';-import {stitchFramesToVideo} from './stitch-frames-to-video';+import {internalStitchFramesToVideo} from './stitch-frames-to-video';import type {OnStartData} from './types';import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';import {validateEveryNthFrame} from './validate-every-nth-frame';@@ -547,17 +547,14 @@ export const internalRenderMedia = ({const stitchStart = Date.now();return Promise.all([- stitchFramesToVideo({+ internalStitchFramesToVideo({width: composition.width * scale,height: composition.height * scale,fps,outputLocation: absoluteOutputLocation,- internalOptions: {- preEncodedFileLocation,- imageFormat,- preferLossless,- indent,- },+ preEncodedFileLocation,+ preferLossless,+ indent,force: overwrite,pixelFormat,codec,@@ -576,7 +573,7 @@ export const internalRenderMedia = ({cancelSignal: cancelStitcher.cancelSignal,muted: disableAudio,enforceAudioTrack,- ffmpegOverride,+ ffmpegOverride: ffmpegOverride ?? null,audioBitrate,videoBitrate,audioCodec,diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex a64445d58b..87808d80c1 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -26,7 +26,6 @@ import {findRemotionRoot} from './find-closest-package-json';import {getCodecName} from './get-codec-name';import {getFileExtensionFromCodec} from './get-extension-from-codec';import {getProResProfileName} from './get-prores-profile-name';-import type {VideoImageFormat} from './image-format';import {Log} from './logger';import type {CancelSignal} from './make-cancel-signal';import {cancelErrorMessages} from './make-cancel-signal';@@ -50,6 +49,34 @@ const packageJson = fs.existsSync(packageJsonPath)? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')): null;+type InternalStitchFramesToVideoOptions = {+ audioBitrate: string | null;+ videoBitrate: string | null;+ fps: number;+ width: number;+ height: number;+ outputLocation: string | null;+ force: boolean;+ assetsInfo: RenderAssetInfo;+ pixelFormat: PixelFormat;+ numberOfGifLoops: number | null;+ codec: Codec;+ audioCodec: AudioCodec | null;+ crf: number | null;+ onProgress?: null | ((progress: number) => void);+ onDownload: undefined | RenderMediaOnDownload;+ proResProfile: undefined | ProResProfile;+ verbose: boolean;+ dir: string;+ cancelSignal: CancelSignal | null;+ preEncodedFileLocation: string | null;+ preferLossless: boolean;+ indent: boolean;+ muted: boolean;+ enforceAudioTrack: boolean;+ ffmpegOverride: null | FfmpegOverrideFn;+};+export type StitchFramesToVideoOptions = {audioBitrate?: string | null;videoBitrate?: string | null;@@ -68,14 +95,8 @@ export type StitchFramesToVideoOptions = {onDownload?: RenderMediaOnDownload;proResProfile?: ProResProfile;verbose?: boolean;- dir?: string;+ dir: string;cancelSignal?: CancelSignal;- internalOptions?: {- preEncodedFileLocation: string | null;- imageFormat: VideoImageFormat;- preferLossless: boolean;- indent: boolean;- };muted?: boolean;enforceAudioTrack?: boolean;ffmpegOverride?: FfmpegOverrideFn;@@ -168,48 +189,71 @@ const getAssetsData = async ({return outName;};-const spawnFfmpeg = async (- options: StitchFramesToVideoOptions,+const innerStitchFramesToVideo = async (+ {+ assetsInfo,+ audioBitrate,+ audioCodec,+ cancelSignal,+ codec,+ crf,+ dir,+ enforceAudioTrack,+ ffmpegOverride,+ force,+ fps,+ height,+ indent,+ muted,+ onDownload,+ outputLocation,+ pixelFormat,+ preEncodedFileLocation,+ preferLossless,+ proResProfile,+ verbose,+ videoBitrate,+ width,+ numberOfGifLoops,+ onProgress,+ }: InternalStitchFramesToVideoOptions,remotionRoot: string): Promise<ReturnType> => {Internals.validateDimension(- options.height,+ height,'height','passed to `stitchFramesToVideo()`');Internals.validateDimension(- options.width,+ width,'width','passed to `stitchFramesToVideo()`');- const codec = options.codec ?? DEFAULT_CODEC;validateEvenDimensionsWithCodec({- width: options.width,- height: options.height,+ width,+ height,codec,scale: 1,});validateSelectedCodecAndProResCombination({codec,- proResProfile: options.proResProfile,+ proResProfile,});- validateBitrate(options.audioBitrate, 'audioBitrate');- validateBitrate(options.videoBitrate, 'videoBitrate');+ validateBitrate(audioBitrate, 'audioBitrate');+ validateBitrate(videoBitrate, 'videoBitrate');- Internals.validateFps(options.fps, 'in `stitchFramesToVideo()`', false);- const pixelFormat = options.pixelFormat ?? DEFAULT_PIXEL_FORMAT;+ Internals.validateFps(fps, 'in `stitchFramesToVideo()`', false);const encoderName = getCodecName(codec);- const proResProfileName = getProResProfileName(codec, options.proResProfile);+ const proResProfileName = getProResProfileName(codec, proResProfile);const mediaSupport = codecSupportsMedia(codec);const shouldRenderAudio =mediaSupport.audio &&- (options.assetsInfo.assets.flat(1).length > 0 ||- options.enforceAudioTrack) &&- !options.muted;+ (assetsInfo.assets.flat(1).length > 0 || enforceAudioTrack) &&+ !muted;const shouldRenderVideo = mediaSupport.video;@@ -220,22 +264,21 @@ const spawnFfmpeg = async (}// Explanation: https://github.com/remotion-dev/remotion/issues/1647- const resolvedAudioCodec = options.internalOptions?.preferLossless+ const resolvedAudioCodec = preferLossless? getDefaultAudioCodec({codec, preferLossless: true})- : options.audioCodec ??- getDefaultAudioCodec({codec, preferLossless: false});+ : audioCodec ?? getDefaultAudioCodec({codec, preferLossless: false});- const tempFile = options.outputLocation+ const tempFile = outputLocation? null: path.join(- options.assetsInfo.downloadMap.stitchFrames,+ assetsInfo.downloadMap.stitchFrames,`out.${getFileExtensionFromCodec(codec, resolvedAudioCodec)}`);Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'encoder',@@ -243,8 +286,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'audioCodec',@@ -252,8 +295,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'pixelFormat',@@ -261,8 +304,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'codec',@@ -270,8 +313,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'shouldRenderAudio',@@ -279,8 +322,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'shouldRenderVideo',@@ -288,8 +331,8 @@ const spawnFfmpeg = async ();Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'proResProfileName',@@ -297,31 +340,31 @@ const spawnFfmpeg = async ();validateQualitySettings({- crf: options.crf,+ crf,codec,- videoBitrate: options.videoBitrate,+ videoBitrate,});validateSelectedPixelFormatAndCodecCombination(pixelFormat, codec);- const expectedFrames = options.assetsInfo.assets.length;+ const expectedFrames = assetsInfo.assets.length;const updateProgress = (preStitchProgress: number, muxProgress: number) => {const totalFrameProgress =0.5 * preStitchProgress * expectedFrames + muxProgress * 0.5;- options.onProgress?.(Math.round(totalFrameProgress));+ onProgress?.(Math.round(totalFrameProgress));};const audio = shouldRenderAudio? await getAssetsData({- assets: options.assetsInfo.assets,- onDownload: options.onDownload,- fps: options.fps,+ assets: assetsInfo.assets,+ onDownload,+ fps,expectedFrames,- verbose: options.verbose ?? false,+ verbose,onProgress: (prog) => updateProgress(prog, 0),- downloadMap: options.assetsInfo.downloadMap,+ downloadMap: assetsInfo.downloadMap,remotionRoot,- indent: options.internalOptions?.indent ?? false,+ indent,}): null;@@ -341,17 +384,17 @@ const spawnFfmpeg = async (mapAudioCodecToFfmpegAudioCodecName(resolvedAudioCodec),// Set bitrate up to 320k, for aac it might effectively be lower'-b:a',- options.audioBitrate ?? '320k',- options.force ? '-y' : null,- options.outputLocation ?? tempFile,+ audioBitrate ?? '320k',+ force ? '-y' : null,+ outputLocation ?? tempFile,].filter(Internals.truthy));- options.cancelSignal?.(() => {+ cancelSignal?.(() => {ffmpegTask.kill();});await ffmpegTask;- options.onProgress?.(expectedFrames);+ onProgress?.(expectedFrames);if (audio) {deleteDirectory(path.dirname(audio));}@@ -368,7 +411,7 @@ const spawnFfmpeg = async (resolve(null);}});- deleteDirectory(options.assetsInfo.downloadMap.stitchFrames);+ deleteDirectory(assetsInfo.downloadMap.stitchFrames);return {getLogs: () => '',@@ -377,28 +420,23 @@ const spawnFfmpeg = async (}const ffmpegArgs = [- ...(options.internalOptions?.preEncodedFileLocation- ? [['-i', options.internalOptions?.preEncodedFileLocation]]+ ...(preEncodedFileLocation+ ? [['-i', preEncodedFileLocation]]: [- ['-r', String(options.fps)],+ ['-r', String(fps)],['-f', 'image2'],- ['-s', `${options.width}x${options.height}`],- ['-start_number', String(options.assetsInfo.firstFrameIndex)],- ['-i', options.assetsInfo.imageSequenceName],+ ['-s', `${width}x${height}`],+ ['-start_number', String(assetsInfo.firstFrameIndex)],+ ['-i', assetsInfo.imageSequenceName],]),audio ? ['-i', audio] : null,- (options.numberOfGifLoops ?? null) === null+ numberOfGifLoops === null? null- : [- '-loop',- convertNumberOfGifLoopsToFfmpegSyntax(- options.numberOfGifLoops ?? null- ),- ],+ : ['-loop', convertNumberOfGifLoopsToFfmpegSyntax(numberOfGifLoops)],// -c:v is the same as -vcodec as -codec:video// and specified the video codec.['-c:v', encoderName],- ...(options.internalOptions?.preEncodedFileLocation+ ...(preEncodedFileLocation? []: [proResProfileName ? ['-profile:v', proResProfileName] : null,@@ -408,8 +446,8 @@ const spawnFfmpeg = async (// transparent WebM generation doesn't workpixelFormat === 'yuva420p' ? ['-auto-alt-ref', '0'] : null,...validateQualitySettings({- crf: options.crf,- videoBitrate: options.videoBitrate,+ crf,+ videoBitrate,codec,}),]),@@ -418,7 +456,7 @@ const spawnFfmpeg = async (? ['-c:a', mapAudioCodecToFfmpegAudioCodecName(resolvedAudioCodec)]: null,// Set max bitrate up to 1024kbps, will choose lower if that's too much- resolvedAudioCodec ? ['-b:a', options.audioBitrate || '512K'] : null,+ resolvedAudioCodec ? ['-b:a', audioBitrate || '512K'] : null,// Ignore metadata that may come from remote media['-map_metadata', '-1'],[@@ -428,36 +466,36 @@ const spawnFfmpeg = async (' '),],- options.force ? '-y' : null,- options.outputLocation ?? tempFile,+ force ? '-y' : null,+ outputLocation ?? tempFile,];const ffmpegString = ffmpegArgs.flat(2).filter(Boolean) as string[];- const finalFfmpegString = options.ffmpegOverride- ? options.ffmpegOverride({type: 'stitcher', args: ffmpegString})+ const finalFfmpegString = ffmpegOverride+ ? ffmpegOverride({type: 'stitcher', args: ffmpegString}): ffmpegString;Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent: indent ?? false,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},'Generated final FFMPEG command:');Log.verboseAdvanced({- indent: options.internalOptions?.indent ?? false,- logLevel: options.verbose ? 'verbose' : 'info',+ indent,+ logLevel: verbose ? 'verbose' : 'info',tag: 'stitchFramesToVideo()',},finalFfmpegString.join(' '));const task = callFf('ffmpeg', finalFfmpegString, {- cwd: options.dir,+ cwd: dir,});- options.cancelSignal?.(() => {+ cancelSignal?.(() => {task.kill();});let ffmpegOutput = '';@@ -465,7 +503,7 @@ const spawnFfmpeg = async (task.stderr?.on('data', (data: Buffer) => {const str = data.toString();ffmpegOutput += str;- if (options.onProgress) {+ if (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)@@ -486,10 +524,10 @@ const spawnFfmpeg = async (return {task: task.then(() => {- deleteDirectory(options.assetsInfo.downloadMap.audioPreprocessing);+ deleteDirectory(assetsInfo.downloadMap.audioPreprocessing);if (tempFile === null) {- deleteDirectory(options.assetsInfo.downloadMap.stitchFrames);+ deleteDirectory(assetsInfo.downloadMap.stitchFrames);return null;}@@ -499,7 +537,7 @@ const spawnFfmpeg = async (return Promise.all([file,deleteDirectory(path.dirname(tempFile)),- deleteDirectory(options.assetsInfo.downloadMap.stitchFrames),+ deleteDirectory(assetsInfo.downloadMap.stitchFrames),]);}).then(([file]) => file);@@ -508,22 +546,17 @@ const spawnFfmpeg = async (};};-/**- * @description Takes a series of images and audio information generated by renderFrames() and encodes it to a video.- * @see [Documentation](https://www.remotion.dev/docs/renderer/stitch-frames-to-video)- */-export const stitchFramesToVideo = async (- options: StitchFramesToVideoOptions+export const internalStitchFramesToVideo = async (+ options: InternalStitchFramesToVideoOptions): Promise<Buffer | null> => {const remotionRoot = findRemotionRoot();- const {task, getLogs} = await spawnFfmpeg(options, remotionRoot);+ warnAboutM2Bug(options.codec, options.pixelFormat);+ const {task, getLogs} = await innerStitchFramesToVideo(options, remotionRoot);const happyPath = task.catch(() => {throw new Error(getLogs());});- warnAboutM2Bug(options.codec ?? null, options.pixelFormat ?? null);-return Promise.race([happyPath,new Promise<Buffer | null>((_resolve, reject) => {@@ -533,3 +566,60 @@ export const stitchFramesToVideo = async (}),]);};++/**+ * @description Takes a series of images and audio information generated by renderFrames() and encodes it to a video.+ * @see [Documentation](https://www.remotion.dev/docs/renderer/stitch-frames-to-video)+ */+export const stitchFramesToVideo = ({+ assetsInfo,+ force,+ fps,+ height,+ width,+ audioBitrate,+ audioCodec,+ cancelSignal,+ codec,+ crf,+ dir,+ enforceAudioTrack,+ ffmpegOverride,+ muted,+ numberOfGifLoops,+ onDownload,+ onProgress,+ outputLocation,+ pixelFormat,+ proResProfile,+ verbose,+ videoBitrate,+}: StitchFramesToVideoOptions): Promise<Buffer | null> => {+ return internalStitchFramesToVideo({+ assetsInfo,+ audioBitrate: audioBitrate ?? null,+ audioCodec: audioCodec ?? null,+ cancelSignal: cancelSignal ?? null,+ codec: codec ?? DEFAULT_CODEC,+ crf: crf ?? null,+ dir,+ enforceAudioTrack: enforceAudioTrack ?? false,+ ffmpegOverride: ffmpegOverride ?? null,+ force,+ fps,+ height,+ indent: false,+ muted: muted ?? false,+ numberOfGifLoops: numberOfGifLoops ?? null,+ onDownload: onDownload ?? undefined,+ onProgress,+ outputLocation: outputLocation ?? null,+ pixelFormat: pixelFormat ?? DEFAULT_PIXEL_FORMAT,+ proResProfile,+ verbose: verbose ?? false,+ videoBitrate: videoBitrate ?? null,+ width,+ preEncodedFileLocation: null,+ preferLossless: false,+ });+};