🎥 Make videos programmatically with React
`@remotion/renderer`: Extract Fast Start finalization
JonnyBurger480f32b5ac0f
diff --git a/packages/renderer/src/finalize-fast-start.ts b/packages/renderer/src/finalize-fast-start.tsnew file mode 100644index 0000000000..c47dfe1213--- /dev/null+++ b/packages/renderer/src/finalize-fast-start.ts@@ -0,0 +1,96 @@+import {randomUUID} from 'node:crypto';+import {promises} from 'node:fs';+import path from 'node:path';+import {callFf} from './call-ffmpeg';+import type {LogLevel} from './log-level';+import {Log} from './logger';+import type {CancelSignal} from './make-cancel-signal';++export type FastStartMuxer = 'mov' | 'mp4';++export const finalizeFastStart = async ({+ input,+ output,+ muxer,+ force,+ indent,+ logLevel,+ binariesDirectory,+ cancelSignal,+}: {+ input: string;+ output: string;+ muxer: FastStartMuxer;+ force: boolean;+ indent: boolean;+ logLevel: LogLevel;+ binariesDirectory: string | null;+ cancelSignal: CancelSignal | null;+}) => {+ let fastStartFile: string | null = null;++ for (let attempt = 0; attempt < 3; attempt++) {+ const candidate = path.join(+ path.dirname(output),+ `${path.basename(output)}.${randomUUID()}.remotion-in-progress`,+ );+ const task = callFf({+ bin: 'ffmpeg',+ args: [+ '-hide_banner',+ '-i',+ input,+ '-c',+ 'copy',+ '-movflags',+ 'faststart',+ '-y',+ '-f',+ muxer,+ candidate,+ ],+ indent,+ logLevel,+ binariesDirectory,+ cancelSignal: cancelSignal ?? undefined,+ });+ let stderr = '';+ task.stderr?.on('data', (data: Buffer) => {+ stderr += data.toString();+ });++ try {+ await task;+ fastStartFile = candidate;+ break;+ } catch (error) {+ await promises.rm(candidate, {force: true}).catch(() => undefined);+ const isReopenFailure =+ stderr.includes('Unable to re-open') &&+ stderr.includes('output file for shifting data');+ if (!isReopenFailure || attempt === 2) {+ throw error;+ }++ Log.verbose(+ {indent, logLevel, tag: 'stitchFramesToVideo()'},+ `Retrying Fast Start finalization (attempt ${attempt + 2} of 3)`,+ );+ }+ }++ if (fastStartFile === null) {+ throw new Error('Fast Start finalization did not produce an output file');+ }++ if (force) {+ await promises.rename(fastStartFile, output);+ return;+ }++ try {+ await promises.link(fastStartFile, output);+ } finally {+ await promises.rm(fastStartFile, {force: true});+ }+};diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex efcada689b..2ac06ec33f 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -1,11 +1,10 @@-import {randomUUID} from 'node:crypto';import {cpSync, promises, rmSync} from 'node:fs';import path from 'node:path';import type {_InternalTypes} from 'remotion';import type {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';import type {RenderAssetInfo} from './assets/download-map';import {cleanDownloadMap} from './assets/download-map';-import {callFf, callFfNative} from './call-ffmpeg';+import {callFfNative} from './call-ffmpeg';import type {Codec} from './codec';import {DEFAULT_CODEC} from './codec';import {codecSupportsMedia} from './codec-supports-media';@@ -15,6 +14,7 @@ import {validateQualitySettings} from './crf';import {deleteDirectory} from './delete-directory';import {generateFfmpegArgs} from './ffmpeg-args';import type {FfmpegOverrideFn} from './ffmpeg-override';+import {finalizeFastStart, type FastStartMuxer} from './finalize-fast-start';import {findRemotionRoot} from './find-closest-package-json';import {getFileExtensionFromCodec} from './get-extension-from-codec';import {getExtensionOfFilename} from './get-extension-of-filename';@@ -112,6 +112,24 @@ export type StitchFramesToVideoOptions = {type ReturnType = Promise<Buffer | null>;+const getFastStartMuxer = ({+ codec,+ outputExtension,+}: {+ codec: Codec;+ outputExtension: string;+}): FastStartMuxer | null => {+ if (codec !== 'h264') {+ return null;+ }++ if (outputExtension === 'mp4' || outputExtension === 'mov') {+ return outputExtension;+ }++ return null;+};+const innerStitchFramesToVideo = async ({assetsInfo,@@ -218,12 +236,7 @@ const innerStitchFramesToVideo = async (getExtensionOfFilename(outputLocation) ??getFileExtensionFromCodec(codec, resolvedAudioCodec)).toLowerCase();- const fastStartMuxer =- codec === 'h264' && outputExtension === 'mp4'- ? 'mp4'- : codec === 'h264' && outputExtension === 'mov'- ? 'mov'- : null;+ const fastStartMuxer = getFastStartMuxer({codec, outputExtension});// Fast Start reopens its output for an in-place second pass. Keep that work// away from the public output path so Windows file observers cannot lock it.const fastStartIntermediate =@@ -509,78 +522,22 @@ const innerStitchFramesToVideo = async (});});- if (fastStartIntermediate) {+ if (fastStartIntermediate && fastStartMuxer) {const destination = outputLocation ?? tempFile;if (destination === null) {throw new Error('Expected a Fast Start output destination');}- const finalDestination = path.resolve(remotionRoot, destination);- let fastStartFile: string | null = null;-- for (let attempt = 0; attempt < 3; attempt++) {- const candidate = path.join(- path.dirname(finalDestination),- `${path.basename(finalDestination)}.${randomUUID()}.remotion-in-progress`,- );- const fastStartTask = callFf({- bin: 'ffmpeg',- args: [- '-hide_banner',- '-i',- fastStartIntermediate,- '-c',- 'copy',- '-movflags',- 'faststart',- '-y',- '-f',- fastStartMuxer,- candidate,- ],- indent,- logLevel,- binariesDirectory,- cancelSignal: cancelSignal ?? undefined,- });- let fastStartStderr = '';- fastStartTask.stderr?.on('data', (data: Buffer) => {- fastStartStderr += data.toString();- });-- try {- await fastStartTask;- fastStartFile = candidate;- break;- } catch (error) {- await promises.rm(candidate, {force: true}).catch(() => undefined);- const isReopenFailure =- fastStartStderr.includes('Unable to re-open') &&- fastStartStderr.includes('output file for shifting data');- if (!isReopenFailure || attempt === 2) {- throw error;- }-- Log.verbose(- {indent, logLevel, tag: 'stitchFramesToVideo()'},- `Retrying Fast Start finalization (attempt ${attempt + 2} of 3)`,- );- }- }-- if (fastStartFile === null) {- throw new Error('Fast Start finalization did not produce an output file');- }-- if (force) {- await promises.rename(fastStartFile, finalDestination);- } else {- try {- await promises.link(fastStartFile, finalDestination);- } finally {- await promises.rm(fastStartFile, {force: true});- }- }+ await finalizeFastStart({+ input: fastStartIntermediate,+ output: path.resolve(remotionRoot, destination),+ muxer: fastStartMuxer,+ force,+ indent,+ logLevel,+ binariesDirectory,+ cancelSignal,+ });}const result = tempFile === null ? null : await promises.readFile(tempFile);