Skip to content

🎥 Make videos programmatically with React

remove gif.tsx and support cancel signal

Shankhadeep Dey5c2499fdf84d
diff --git a/packages/cli/src/gif.tsx b/packages/cli/src/gif.tsx
deleted file mode 100644
index a6cfeedba9..0000000000
--- a/packages/cli/src/gif.tsx
+++ /dev/null
@@ -1,251 +0,0 @@
-import {
- getCompositions,
- openBrowser,
- renderGif,
- RenderInternals,
- RenderMediaOnDownload,
- StitchingState,
-} from '@remotion/renderer';
-import chalk from 'chalk';
-import fs from 'fs';
-import os from 'os';
-import path from 'path';
-import {Internals} from 'remotion';
-import {getCliOptions} from './get-cli-options';
-import {getCompositionId} from './get-composition-id';
-import {initializeRenderCli} from './initialize-render-cli';
-import {Log} from './log';
-import {parsedCli, quietFlagProvided} from './parse-command-line';
-import {
- createOverwriteableCliOutput,
- DownloadProgress,
- makeRenderingAndStitchingProgress,
-} from './progress-bar';
-import {bundleOnCli} from './setup-cache';
-import {RenderStep} from './step';
-import {checkAndValidateFfmpegVersion} from './validate-ffmpeg-version';
-
-export const gif = async () => {
- const startTime = Date.now();
- const file = parsedCli._[1];
- if (!file) {
- Log.error('No entry point specified. Pass more arguments:');
- Log.error(
- ' npx remotion render [entry-point] [composition-name] [out-name]'
- );
- Log.error('Documentation: https://www.remotion.dev/docs/render');
- process.exit(1);
- }
-
- const fullPath = RenderInternals.isServeUrl(file)
- ? file
- : path.join(process.cwd(), file);
-
- await initializeRenderCli('sequence');
-
- const {
- codec,
- proResProfile,
- parallelism,
- frameRange,
- shouldOutputImageSequence,
- absoluteOutputFile,
- overwrite,
- inputProps,
- envVariables,
- quality,
- browser,
- crf,
- pixelFormat,
- imageFormat,
- browserExecutable,
- ffmpegExecutable,
- scale,
- chromiumOptions,
- port,
- skipNFrames,
- } = await getCliOptions({isLambda: false, type: 'series'});
-
- if (!absoluteOutputFile) {
- throw new Error(
- 'assertion error - expected absoluteOutputFile to not be null'
- );
- }
-
- Log.verbose('Browser executable: ', browserExecutable);
-
- await checkAndValidateFfmpegVersion({
- ffmpegExecutable,
- });
-
- const browserInstance = openBrowser(browser, {
- browserExecutable,
- shouldDumpIo: Internals.Logging.isEqualOrBelowLogLevel(
- Internals.Logging.getLogLevel(),
- 'verbose'
- ),
- chromiumOptions,
- forceDeviceScaleFactor: scale,
- });
-
- const steps: RenderStep[] = [
- RenderInternals.isServeUrl(fullPath) ? null : ('bundling' as const),
- 'rendering' as const,
- shouldOutputImageSequence ? null : ('stitching' as const),
- ].filter(Internals.truthy);
-
- const urlOrBundle = RenderInternals.isServeUrl(fullPath)
- ? fullPath
- : await bundleOnCli(fullPath, steps);
-
- const onDownload: RenderMediaOnDownload = (src) => {
- const id = Math.random();
- const download: DownloadProgress = {
- id,
- name: src,
- progress: 0,
- };
- downloads.push(download);
- updateRenderProgress();
-
- return ({percent}) => {
- download.progress = percent;
- updateRenderProgress();
- };
- };
-
- const puppeteerInstance = await browserInstance;
-
- const comps = await getCompositions(urlOrBundle, {
- inputProps,
- puppeteerInstance,
- envVariables,
- timeoutInMilliseconds: Internals.getCurrentPuppeteerTimeout(),
- chromiumOptions,
- browserExecutable,
- });
- const compositionId = getCompositionId(comps);
-
- const config = comps.find((c) => c.id === compositionId);
-
- if (!config) {
- throw new Error(`Cannot find composition with ID ${compositionId}`);
- }
-
- RenderInternals.validateEvenDimensionsWithCodec({
- width: config.width,
- height: config.height,
- codec,
- scale,
- });
-
- const outputDir = shouldOutputImageSequence
- ? absoluteOutputFile
- : await fs.promises.mkdtemp(path.join(os.tmpdir(), 'react-motion-render'));
-
- Log.verbose('Output dir', outputDir);
-
- const renderProgress = createOverwriteableCliOutput(quietFlagProvided());
- let totalFrames: number | null = RenderInternals.getDurationFromFrameRange(
- frameRange,
- config.durationInFrames
- );
- let encodedFrames = 0;
- let renderedFrames = 0;
- let encodedDoneIn: number | null = null;
- let renderedDoneIn: number | null = null;
- let stitchStage: StitchingState = 'encoding';
- const downloads: DownloadProgress[] = [];
-
- const updateRenderProgress = () => {
- if (totalFrames === null) {
- throw new Error('totalFrames should not be 0');
- }
-
- return renderProgress.update(
- makeRenderingAndStitchingProgress({
- rendering: {
- frames: renderedFrames,
- totalFrames,
- concurrency: RenderInternals.getActualConcurrency(parallelism),
- doneIn: renderedDoneIn,
- steps,
- },
- stitching: shouldOutputImageSequence
- ? null
- : {
- doneIn: encodedDoneIn,
- frames: encodedFrames,
- stage: stitchStage,
- steps,
- totalFrames,
- },
- downloads,
- })
- );
- };
-
- await renderGif({
- outputLocation: absoluteOutputFile,
- codec,
- composition: config,
- crf,
- envVariables,
- ffmpegExecutable,
- frameRange,
- imageFormat,
- skipNFrames,
- 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,
- });
-
- Log.info();
- Log.info();
- const seconds = Math.round((Date.now() - startTime) / 1000);
- Log.info(
- [
- '- Total render time:',
- seconds,
- seconds === 1 ? 'second' : 'seconds',
- ].join(' ')
- );
- Log.info('-', 'Output can be found at:');
- Log.info(chalk.cyan(`â–¶ ${absoluteOutputFile}`));
- Log.verbose('Cleaning up...');
-
- try {
- await RenderInternals.deleteDirectory(urlOrBundle);
- } catch (err) {
- Log.warn('Could not clean up directory.');
- Log.warn(err);
- Log.warn('Do you have minimum required Node.js version?');
- }
-
- Log.info(chalk.green(`\nYour gif is ready!`));
-};
diff --git a/packages/cli/src/index.tsx b/packages/cli/src/index.tsx
index 17350c3392..034e236aa1 100644
--- a/packages/cli/src/index.tsx
+++ b/packages/cli/src/index.tsx
@@ -3,7 +3,6 @@ import {checkNodeVersion} from './check-version';
import {listCompositionsCommand} from './compositions';
import {getCliOptions} from './get-cli-options';
import {loadConfig} from './get-config-file-name';
-import {gif} from './gif';
import {handleCommonError} from './handle-common-errors';
import {initializeRenderCli} from './initialize-render-cli';
import {lambdaCommand} from './lambda-command';
@@ -51,11 +50,11 @@ export const cli = async () => {
} else if (command === 'lambda') {
await lambdaCommand();
} else if (command === 'render') {
- await render();
+ await render({renderAsGif: false});
} else if (command === 'still') {
await still();
} else if (command === 'gif') {
- await 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.tsx
index 0ce0b7d306..de08513947 100644
--- a/packages/cli/src/render.tsx
+++ b/packages/cli/src/render.tsx
@@ -2,6 +2,7 @@ import {
getCompositions,
openBrowser,
renderFrames,
+ renderGif,
RenderInternals,
renderMedia,
RenderMediaOnDownload,
@@ -26,7 +27,7 @@ import {bundleOnCli} from './setup-cache';
import {RenderStep} from './step';
import {checkAndValidateFfmpegVersion} from './validate-ffmpeg-version';
-export const render = async () => {
+export const render = async ({renderAsGif}: {renderAsGif: boolean}) => {
const startTime = Date.now();
const file = parsedCli._[1];
if (!file) {
@@ -247,45 +248,86 @@ export const render = async () => {
return;
}
- await renderMedia({
- outputLocation: absoluteOutputFile,
- codec,
- composition: config,
- crf,
- envVariables,
- ffmpegExecutable,
- frameRange,
- imageFormat,
- skipNFrames,
- 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,
- });
+ if (renderAsGif) {
+ await renderGif({
+ outputLocation: absoluteOutputFile,
+ codec,
+ composition: config,
+ crf,
+ envVariables,
+ ffmpegExecutable,
+ frameRange,
+ imageFormat,
+ skipNFrames,
+ 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,
+ frameRange,
+ imageFormat,
+ skipNFrames,
+ 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,
+ });
+ }
Log.info();
Log.info();
@@ -309,5 +351,5 @@ export const render = async () => {
Log.warn('Do you have minimum required Node.js version?');
}
- Log.info(chalk.green('\nYour video is ready!'));
+ Log.info(chalk.green(`\nYour ${renderAsGif ? 'gif' : 'video'} is ready!`));
};
diff --git a/packages/example/src/Video.tsx b/packages/example/src/Video.tsx
index e650679a0e..6ed9520564 100644
--- a/packages/example/src/Video.tsx
+++ b/packages/example/src/Video.tsx
@@ -96,7 +96,7 @@ export const Index: React.FC = () => {
component={Framer}
width={1080}
height={1080}
- fps={30}
+ fps={60}
durationInFrames={100}
/>
<Composition
diff --git a/packages/renderer/src/render-gif.ts b/packages/renderer/src/render-gif.ts
index f8709330c2..53679ff740 100644
--- a/packages/renderer/src/render-gif.ts
+++ b/packages/renderer/src/render-gif.ts
@@ -2,19 +2,7 @@ import {ExecaChildProcess} from 'execa';
import fs from 'fs';
import os from 'os';
import path from 'path';
-import type {Browser as PuppeteerBrowser} from 'puppeteer-core';
-import {
- BrowserExecutable,
- Codec,
- FfmpegExecutable,
- FrameRange,
- Internals,
- PixelFormat,
- ProResProfile,
- SmallTCompMetadata,
-} from 'remotion';
-import {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';
-import {BrowserLog} from './browser-log';
+import {Internals} from 'remotion';
import {canUseParallelEncoding} from './can-use-parallel-encoding';
import {ensureFramesInOrder} from './ensure-frames-in-order';
import {ensureOutputDirectory} from './ensure-output-directory';
@@ -22,61 +10,20 @@ 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,
- ServeUrlOrWebpackBundle,
-} from './legacy-webpack-config';
-import {ChromiumOptions} from './open-browser';
+import {getServeUrlWithFallback} from './legacy-webpack-config';
+import {makeCancelSignal} from './make-cancel-signal';
import {prespawnFfmpeg} from './prespawn-ffmpeg';
import {renderFrames} from './render-frames';
-import {StitchingState} from './render-media';
+import {RenderMediaOptions, StitchingState} from './render-media';
import {stitchFramesToGif} from './stitch-frames-to-gif';
import {tmpDir} from './tmp-dir';
-import {OnStartData} from './types';
import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';
import {validateOutputFilename} from './validate-output-filename';
import {validateScale} from './validate-scale';
-export type RenderMediaOnProgress = (progress: {
- renderedFrames: number;
- encodedFrames: number;
- encodedDoneIn: number | null;
- renderedDoneIn: number | null;
- stitchStage: StitchingState;
-}) => void;
-
-export type RenderMediaOptions = {
- outputLocation: string;
- codec: Codec;
- composition: SmallTCompMetadata;
- inputProps?: unknown;
- parallelism?: number | null;
- crf?: number | null;
- imageFormat?: 'png' | 'jpeg' | 'none';
- ffmpegExecutable?: FfmpegExecutable;
- pixelFormat?: PixelFormat;
- envVariables?: Record<string, string>;
- quality?: number;
- frameRange?: FrameRange | null;
- skipNFrames?: number | null;
- puppeteerInstance?: PuppeteerBrowser;
- overwrite?: boolean;
- onProgress?: RenderMediaOnProgress;
- onDownload?: RenderMediaOnDownload;
- proResProfile?: ProResProfile;
- dumpBrowserLogs?: boolean;
- onBrowserLog?: ((log: BrowserLog) => void) | undefined;
- onStart?: (data: OnStartData) => void;
- timeoutInMilliseconds?: number;
- chromiumOptions?: ChromiumOptions;
- scale?: number;
- port?: number | null;
- browserExecutable?: BrowserExecutable;
-} & ServeUrlOrWebpackBundle;
-
type Await<T> = T extends PromiseLike<infer U> ? U : T;
-export const renderGif = async ({
+export const renderGif = ({
parallelism,
proResProfile,
crf,
@@ -103,14 +50,15 @@ export const renderGif = async ({
scale,
browserExecutable,
port,
+ cancelSignal,
...options
-}: RenderMediaOptions) => {
+}: RenderMediaOptions): Promise<void> => {
Internals.validateQuality(quality);
if (typeof crf !== 'undefined' && crf !== null) {
Internals.validateSelectedCrfAndCodecCombination(crf, codec);
}
- validateOutputFilename('gif', getExtensionOfFilename(outputLocation));
+ validateOutputFilename(codec, getExtensionOfFilename(outputLocation));
validateScale(scale);
@@ -123,6 +71,8 @@ export const renderGif = async ({
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);
@@ -137,7 +87,7 @@ export const renderGif = async ({
const outputDir = parallelEncoding
? null
- : await fs.promises.mkdtemp(path.join(os.tmpdir(), 'react-motion-render'));
+ : fs.mkdtempSync(path.join(os.tmpdir(), 'react-motion-render'));
validateEvenDimensionsWithCodec({
codec,
@@ -146,17 +96,33 @@ export const renderGif = async ({
width: composition.width,
});
- try {
- const callUpdate = () => {
- onProgress?.({
- encodedDoneIn,
- encodedFrames,
- renderedDoneIn,
- renderedFrames,
- stitchStage,
- });
- };
+ 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 createPrestitcherIfNecessary = async () => {
if (preEncodedFileLocation) {
preStitcher = await prespawnFfmpeg({
width: composition.width * (scale ?? 1),
@@ -177,60 +143,13 @@ export const renderGif = async ({
),
ffmpegExecutable,
imageFormat: actualImageFormat,
+ signal: cancelPrestitcher.cancelSignal,
});
stitcherFfmpeg = preStitcher.task;
}
+ };
- const realFrameRange = getRealFrameRange(
- composition.durationInFrames,
- frameRange ?? null
- );
-
- const {
- waitForRightTimeOfFrameToBeInserted,
- setFrameToStitch,
- waitForFinish,
- } = ensureFramesInOrder(realFrameRange);
-
- const {assetsInfo} = await renderFrames({
- config: composition,
- onFrameUpdate: (frame: number) => {
- stitchStage = 'gif';
- renderedFrames = frame;
- callUpdate();
- },
- parallelism,
- outputDir,
- onStart: (data) => {
- renderedFrames = 0;
- callUpdate();
- onStart?.(data);
- },
- inputProps,
- envVariables,
- imageFormat: actualImageFormat,
- quality,
- frameRange: frameRange ?? null,
- puppeteerInstance,
- onFrameBuffer: parallelEncoding
- ? async (buffer, frame) => {
- await waitForRightTimeOfFrameToBeInserted(frame);
- stitcherFfmpeg?.stdin?.write(buffer);
-
- setFrameToStitch(frame + 1);
- }
- : undefined,
- serveUrl,
- dumpBrowserLogs,
- onBrowserLog,
- onDownload,
- timeoutInMilliseconds,
- chromiumOptions,
- scale,
- ffmpegExecutable,
- browserExecutable,
- port,
- });
+ const waitForPrestitcherIfNecessary = async () => {
if (stitcherFfmpeg) {
await waitForFinish();
stitcherFfmpeg?.stdin?.end();
@@ -240,53 +159,146 @@ export const renderGif = async ({
throw new Error(preStitcher?.getLogs());
}
}
+ };
- renderedDoneIn = Date.now() - renderStart;
- callUpdate();
+ const happyPath = createPrestitcherIfNecessary()
+ .then(() => {
+ const renderFramesProc = renderFrames({
+ config: composition,
+ onFrameUpdate: (frame: number) => {
+ stitchStage = 'gif';
+ renderedFrames = frame;
+ callUpdate();
+ },
+ parallelism,
+ outputDir,
+ 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);
- ensureOutputDirectory(outputLocation);
+ setFrameToStitch(frame + 1);
+ }
+ : undefined,
+ serveUrl,
+ dumpBrowserLogs,
+ onBrowserLog,
+ onDownload,
+ timeoutInMilliseconds,
+ chromiumOptions,
+ scale,
+ ffmpegExecutable,
+ browserExecutable,
+ port,
+ cancelSignal: cancelRenderFrames.cancelSignal,
+ });
- const stitchStart = Date.now();
+ return renderFramesProc;
+ })
+ .then((renderFramesReturn) => {
+ return Promise.all([renderFramesReturn, waitForPrestitcherIfNecessary()]);
+ })
+ .then(([{assetsInfo}]) => {
+ renderedDoneIn = Date.now() - renderStart;
+ callUpdate();
- await stitchFramesToGif({
- width: composition.width * (scale ?? 1),
- height: composition.height * (scale ?? 1),
- fps: composition.fps,
- outputLocation,
- internalOptions: {
- preEncodedFileLocation,
- imageFormat: actualImageFormat,
- },
- force: overwrite ?? Internals.DEFAULT_OVERWRITE,
- pixelFormat,
- codec,
- proResProfile,
- crf,
- assetsInfo,
- ffmpegExecutable,
- onProgress: (frame: number) => {
- stitchStage = 'gif';
- encodedFrames = frame;
- callUpdate();
- },
- verbose: Internals.Logging.isEqualOrBelowLogLevel(
- Internals.Logging.getLogLevel(),
- 'verbose'
- ),
- dir: outputDir ?? undefined,
+ ensureOutputDirectory(outputLocation);
+
+ const stitchStart = Date.now();
+ return Promise.all([
+ stitchFramesToGif({
+ width: composition.width * (scale ?? 1),
+ height: composition.height * (scale ?? 1),
+ fps: composition.fps,
+ outputLocation,
+ internalOptions: {
+ preEncodedFileLocation,
+ imageFormat: actualImageFormat,
+ },
+ force: overwrite ?? Internals.DEFAULT_OVERWRITE,
+ pixelFormat,
+ codec,
+ proResProfile,
+ crf,
+ 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
+ );
+ 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);
+ }
});
- encodedFrames = getDurationFromFrameRange(
- frameRange ?? null,
- composition.durationInFrames
- );
- encodedDoneIn = Date.now() - stitchStart;
- callUpdate();
- } 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/stitch-frames-to-gif.ts b/packages/renderer/src/stitch-frames-to-gif.ts
index e2e59cae16..f1ef3202f9 100644
--- a/packages/renderer/src/stitch-frames-to-gif.ts
+++ b/packages/renderer/src/stitch-frames-to-gif.ts
@@ -1,19 +1,12 @@
import execa from 'execa';
import fs from 'fs';
import path from 'path';
-import {
- Codec,
- FfmpegExecutable,
- ImageFormat,
- Internals,
- PixelFormat,
- ProResProfile,
- RenderAssetInfo,
-} from 'remotion';
+import {Internals} 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 {StitcherOptions} from './stitch-frames-to-video';
import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';
import {validateFfmpeg} from './validate-ffmpeg';
@@ -23,27 +16,6 @@ const packageJson = fs.existsSync(packageJsonPath)
? JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))
: null;
-export type StitcherOptions = {
- fps: number;
- width: number;
- height: number;
- outputLocation: string;
- force: boolean;
- assetsInfo: RenderAssetInfo;
- pixelFormat?: PixelFormat;
- codec?: Codec;
- crf?: number | null;
- onProgress?: (progress: number) => void;
- proResProfile?: ProResProfile;
- verbose?: boolean;
- ffmpegExecutable?: FfmpegExecutable;
- dir?: string;
- internalOptions?: {
- preEncodedFileLocation: string | null;
- imageFormat: ImageFormat;
- };
-};
-
type ReturnType = {
task: Promise<unknown>;
getLogs: () => string;
@@ -144,6 +116,9 @@ export const spawnFfmpeg = async (
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) => {