🎥 Make videos programmatically with React
Merge branch 'v4' into render-button
Jonny Burger9bd1c13ada7c
diff --cc packages/cli/src/get-cli-options.tsindex 9b13362d11,1703724e5e..8a72d0752b--- a/packages/cli/src/get-cli-options.ts+++ b/packages/cli/src/get-cli-options.ts@@@ -1,7 -1,7 +1,6 @@@import type {BrowserExecutable,ChromiumOptions,-- Codec,FrameRange,} from '@remotion/renderer';import {RenderInternals} from '@remotion/renderer';@@@ -25,60 -27,20 +24,6 @@@ const getAndValidateFrameRange = () =>return frameRange;};- export const validateFfmpegCanUseCodec = async (- codec: Codec,- remotionRoot: string- ) => {- const ffmpegExecutable = ConfigInternals.getCustomFfmpegExecutable();- if (- codec === 'vp8' &&- !(await RenderInternals.ffmpegHasFeature({- feature: 'enable-libvpx',- ffmpegExecutable,- remotionRoot,- }))- ) {- Log.error(- "The Vp8 codec has been selected, but your FFMPEG binary wasn't compiled with the --enable-lipvpx flag."- );- Log.error(- 'This does not work, please switch out your FFMPEG binary or choose a different codec.'- );- }-- if (- codec === 'h265' &&- !(await RenderInternals.ffmpegHasFeature({- feature: 'enable-gpl',- ffmpegExecutable,- remotionRoot,- }))- ) {- Log.error(- "The H265 codec has been selected, but your FFMPEG binary wasn't compiled with the --enable-gpl flag."- );- Log.error(- 'This does not work, please recompile your FFMPEG binary with --enable-gpl --enable-libx265 or choose a different codec.'- );- }-export const getFinalCodec = (options: {- downloadName: string | null;- outName: string | null;-}): {codec: Codec; reason: string} => {- const {codec, reason} = getFinalOutputCodec({- cliFlag: parsedCli.codec,- configFile: ConfigInternals.getOutputCodecOrUndefined() ?? null,- downloadName: options.downloadName,- outName: options.outName,- });--- if (- codec === 'h265' &&- !(await RenderInternals.ffmpegHasFeature({- feature: 'enable-libx265',- ffmpegExecutable,- remotionRoot,- }))- ) {- Log.error(- "The H265 codec has been selected, but your FFMPEG binary wasn't compiled with the --enable-libx265 flag."- );- Log.error(- 'This does not work, please recompile your FFMPEG binary with --enable-gpl --enable-libx265 or choose a different codec.'- );- }- return {codec, reason};--};--const getBrowser = () =>ConfigInternals.getBrowser() ?? RenderInternals.DEFAULT_BROWSER;diff --cc packages/cli/src/index.tsxindex cf28bb2774,540c46055c..c6a2e8c70d--- a/packages/cli/src/index.tsx+++ b/packages/cli/src/index.tsx@@@ -8,10 -8,10 +8,11 @@@ import {overrideRemotion} from './confiimport {determineFinalImageFormat} from './determine-image-format';import {getFileSizeDownloadBar} from './download-progress';import {findEntryPoint} from './entry-point';+ import {ffmpegCommand, ffprobeCommand} from './ffmpeg';import {formatBytes} from './format-bytes';-import {getCliOptions, getFinalCodec} from './get-cli-options';+import {getCliOptions} from './get-cli-options';import {loadConfig} from './get-config-file-name';+import {getFinalOutputCodec} from './get-final-output-codec';import {handleCommonError} from './handle-common-errors';import {getImageFormat} from './image-formats';import {initializeCli} from './initialize-cli';diff --cc packages/cli/src/render.tsxindex 806291b6d1,20036a21cd..2cb3f14bba--- a/packages/cli/src/render.tsx+++ b/packages/cli/src/render.tsx@@@ -68,58 -88,295 +66,56 @@@ export const render = async (remotionRoremotionRoot,});- Log.verbose('Browser executable: ', browserExecutable);-- const browserInstance = openBrowser(browser, {- browserExecutable,- shouldDumpIo: RenderInternals.isEqualOrBelowLogLevel(- ConfigInternals.Logging.getLogLevel(),- 'verbose'- ),- chromiumOptions,- forceDeviceScaleFactor: scale,- });-- const steps: RenderStep[] = [- RenderInternals.isServeUrl(file) ? null : ('bundling' as const),- 'rendering' as const,- shouldOutputImageSequence ? null : ('stitching' as const),- ].filter(Internals.truthy);-- const {urlOrBundle, cleanup: cleanupBundle} = await bundleOnCliOrTakeServeUrl(- {- fullPath: file,+ const jobCleanups: (() => void)[] = [];+ try {+ await renderCompFlow({- ffmpegExecutable,- ffprobeExecutable,+ fullEntryPoint,remotionRoot,- steps,+ browserExecutable,+ indent: false,+ logLevel: ConfigInternals.Logging.getLogLevel(),+ browser,+ chromiumOptions,+ scale,+ shouldOutputImageSequence,publicDir,- }- );-- registerCleanupJob(() => cleanupBundle());-- const onDownload: RenderMediaOnDownload = (src) => {- const id = Math.random();- const download: DownloadProgress = {- id,- name: src,- progress: 0,- downloaded: 0,- totalBytes: null,- };- downloads.push(download);- updateRenderProgress();- return ({percent, downloaded, totalSize}) => {- download.progress = percent;- download.totalBytes = totalSize;- download.downloaded = downloaded;- updateRenderProgress();- };- };-- const puppeteerInstance = await browserInstance;-- const comps = await getCompositions(urlOrBundle, {- inputProps,- puppeteerInstance,- envVariables,- timeoutInMilliseconds: puppeteerTimeout,- chromiumOptions,- browserExecutable,- downloadMap,- port,- });-- const {compositionId, config, reason, argsAfterComposition} =- await getCompositionWithDimensionOverride({- validCompositions: comps,+ envVariables,+ inputProps,+ puppeteerTimeout,+ port,height,width,- args: remainingArgs,- });-- const {codec, reason: codecReason} = getFinalCodec({- downloadName: null,- outName: getUserPassedOutputLocation(argsAfterComposition),- });-- RenderInternals.validateEvenDimensionsWithCodec({- width: config.width,- height: config.height,- codec,- scale,- });-- const audioCodec = getResolvedAudioCodec();-- const relativeOutputLocation = getOutputFilename({- imageSequence: shouldOutputImageSequence,- compositionName: compositionId,- defaultExtension: RenderInternals.getFileExtensionFromCodec(- codec,- audioCodec- ),- args: argsAfterComposition,- });-- Log.info(- chalk.gray(- `Entry point = ${path.relative(- process.cwd(),- file- )} (${entryPointReason}), Composition = ${compositionId} (${reason}), Codec = ${codec} (${codecReason}), Output = ${relativeOutputLocation}`- )- );-- const absoluteOutputFile = getAndValidateAbsoluteOutputFile(- relativeOutputLocation,- overwrite- );-- const outputDir = shouldOutputImageSequence- ? {dir: absoluteOutputFile, cleanup: false}- : {- dir: await fs.promises.mkdtemp(- path.join(os.tmpdir(), 'react-motion-render')- ),- cleanup: true,- };-- if (outputDir.cleanup) {- registerCleanupJob(() => RenderInternals.deleteDirectory(outputDir.dir));- }-- Log.verbose('Output dir', outputDir.dir);-- const renderProgress = createOverwriteableCliOutput(quietFlagProvided());- const realFrameRange = RenderInternals.getRealFrameRange(- config.durationInFrames,- frameRange- );- const totalFrames: number[] = RenderInternals.getFramesToRender(- realFrameRange,- everyNthFrame- );- 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.length === 0) {- throw new Error('totalFrames should not be 0');- }-- return renderProgress.update(- makeRenderingAndStitchingProgress({- rendering: {- frames: renderedFrames,- totalFrames: totalFrames.length,- concurrency: RenderInternals.getActualConcurrency(concurrency),- doneIn: renderedDoneIn,- steps,- },- stitching: shouldOutputImageSequence- ? null- : {- doneIn: encodedDoneIn,- frames: encodedFrames,- stage: stitchStage,- steps,- totalFrames: totalFrames.length,- codec,- },- downloads,- })- );- };-- const imageFormat = getImageFormat(- shouldOutputImageSequence ? undefined : codec- );-- if (shouldOutputImageSequence) {- fs.mkdirSync(absoluteOutputFile, {- recursive: true,- });- if (imageFormat === 'none') {- Log.error(- 'Cannot render an image sequence with a codec that renders no images.'- );- Log.error(`codec = ${codec}, imageFormat = ${imageFormat}`);- process.exit(1);- }-- await renderFrames({- config,- imageFormat,- inputProps,- onFrameUpdate: (rendered) => {- renderedFrames = rendered;- updateRenderProgress();- },- onStart: () => undefined,- onDownload: (src: string) => {- if (src.startsWith('data:')) {- Log.info(- '\nWriting Data URL to file: ',- src.substring(0, 30) + '...'- );- } else {- Log.info('\nDownloading asset... ', src);- }- },- outputDir: outputDir.dir,- serveUrl: urlOrBundle,- dumpBrowserLogs: RenderInternals.isEqualOrBelowLogLevel(- ConfigInternals.Logging.getLogLevel(),- 'verbose'- ),+ remainingArgs,+ compositionIdFromUi: null,+ entryPointReason,+ overwrite,+ quiet: quietFlagProvided(),+ concurrency,everyNthFrame,- envVariables,frameRange,- concurrency,- puppeteerInstance,+ configFileImageFormat,quality,- timeoutInMilliseconds: puppeteerTimeout,- chromiumOptions,- scale,- browserExecutable,- port,- downloadMap,+ onProgress: () => undefined,+ addCleanupCallback: (c) => {+ jobCleanups.push(c);+ },+ outputLocationFromUI: null,+ uiCodec: null,+ uiImageFormat: null,+ cancelSignal: null,+ crf,+ ffmpegOverride,+ audioBitrate,+ muted,+ enforceAudioTrack,+ proResProfile,+ pixelFormat,+ videoBitrate,+ numberOfGifLoops,+ // TODO+ audioCodec: null,});- renderedDoneIn = Date.now() - startTime;-- updateRenderProgress();- Log.info();- Log.info();- Log.info(chalk.green('\nYour image sequence is ready!'));- Log.info(chalk.cyan(`▶ ${absoluteOutputFile}`));-- return;- }-- const options = await getRenderMediaOptions({- config,- outputLocation: absoluteOutputFile,- serveUrl: urlOrBundle,- codec,- remotionRoot,- });-- await renderMedia({- ...options,- onProgress: (update) => {- encodedDoneIn = update.encodedDoneIn;- encodedFrames = update.encodedFrames;- renderedDoneIn = update.renderedDoneIn;- stitchStage = update.stitchStage;- renderedFrames = update.renderedFrames;- updateRenderProgress();- },- puppeteerInstance,- onDownload,- internal: {- downloadMap,- onCtrlCExit: registerCleanupJob,- },- onSlowestFrames: (slowestFrames) => {- Log.verbose();- Log.verbose(`Slowest frames:`);- slowestFrames.forEach(({frame, time}) => {- Log.verbose(`Frame ${frame} (${time.toFixed(3)}ms)`);- });- },- });-- 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.info(- chalk.green(`\nYour ${codec === 'gif' ? 'GIF' : 'video'} is ready!`)- );-- if (- RenderInternals.isEqualOrBelowLogLevel(- ConfigInternals.Logging.getLogLevel(),- 'verbose'- )- ) {- RenderInternals.perf.logPerf();+ } finally {+ await Promise.all(jobCleanups.map((c) => c()));}};diff --cc packages/cli/src/still.tsindex be0e07d076,4732aa11c6..de4c2a571f--- a/packages/cli/src/still.ts+++ b/packages/cli/src/still.ts@@@ -31,66 -57,185 +31,64 @@@ export const still = async (remotionRoo}const {- inputProps,- envVariables,- quality,browser,- stillFrame,browserExecutable,chromiumOptions,- scale,+ envVariables,- ffmpegExecutable,- ffprobeExecutable,+ height,+ inputProps,overwrite,- puppeteerTimeout,port,publicDir,- height,+ puppeteerTimeout,+ quality,+ scale,+ stillFrame,width,+ configFileImageFormat,+ logLevel,} = await getCliOptions({isLambda: false,type: 'still',remotionRoot,});- Log.verbose('Browser executable: ', browserExecutable);-- const browserInstance = openBrowser(browser, {- browserExecutable,- chromiumOptions,- shouldDumpIo: RenderInternals.isEqualOrBelowLogLevel(- ConfigInternals.Logging.getLogLevel(),- 'verbose'- ),- forceDeviceScaleFactor: scale,- });-- const steps: RenderStep[] = [- RenderInternals.isServeUrl(file) ? null : ('bundling' as const),- 'rendering' as const,- ].filter(truthy);-- const {cleanup: cleanupBundle, urlOrBundle} = await bundleOnCliOrTakeServeUrl(- {fullPath: file, remotionRoot, steps, publicDir}- );-- registerCleanupJob(() => cleanupBundle());-- const puppeteerInstance = await browserInstance;-- const downloadMap = RenderInternals.makeDownloadMap();- registerCleanupJob(() => RenderInternals.cleanDownloadMap(downloadMap));-- const comps = await getCompositions(urlOrBundle, {- inputProps,- puppeteerInstance,- envVariables,- timeoutInMilliseconds: puppeteerTimeout,- chromiumOptions,- port,- browserExecutable,- downloadMap,- });-- const {compositionId, config, reason, argsAfterComposition} =- await getCompositionWithDimensionOverride({- validCompositions: comps,+ const jobCleanups: (() => void)[] = [];++ try {+ await renderStillFlow({+ remotionRoot,+ entryPointReason,+ fullEntryPoint,+ remainingArgs,+ browser,+ browserExecutable,+ chromiumOptions,+ envVariables,- ffmpegExecutable,- ffprobeExecutable,height,+ inputProps,+ overwrite,+ port,+ publicDir,+ puppeteerTimeout,+ quality,+ scale,+ stillFrame,width,- args: remainingArgs,+ compositionIdFromUi: null,+ imageFormatFromUi: null,+ configFileImageFormat,+ logLevel,+ onProgress: () => undefined,+ indentOutput: false,+ addCleanupCallback: (c) => {+ jobCleanups.push(c);+ },+ cancelSignal: null,});- const {format: imageFormat, source} = determineFinalImageFormat({- cliFlag: parsedCli['image-format'] ?? null,- configImageFormat: ConfigInternals.getUserPreferredImageFormat() ?? null,- downloadName: null,- outName: getUserPassedOutputLocation(argsAfterComposition),- isLambda: false,- });-- const relativeOutputLocation = getOutputLocation({- compositionId,- defaultExtension: imageFormat,- args: argsAfterComposition,- type: 'asset',- });-- const absoluteOutputLocation = getAndValidateAbsoluteOutputFile(- relativeOutputLocation,- overwrite- );-- mkdirSync(path.join(absoluteOutputLocation, '..'), {- recursive: true,- });-- Log.info(- chalk.gray(- `Entry point = ${file} (${entryPointReason}), Output = ${relativeOutputLocation}, Format = ${imageFormat} (${source}), Composition = ${compositionId} (${reason})`- )- );-- const renderProgress = createOverwriteableCliOutput(quietFlagProvided());- const renderStart = Date.now();-- const downloads: DownloadProgress[] = [];- let frames = 0;- const totalFrames = 1;-- const updateProgress = () => {- renderProgress.update(- makeRenderingAndStitchingProgress({- rendering: {- frames,- concurrency: 1,- doneIn: frames === totalFrames ? Date.now() - renderStart : null,- steps,- totalFrames,- },- downloads,- stitching: null,- })- );- };-- updateProgress();-- const onDownload: RenderMediaOnDownload = (src) => {- const id = Math.random();- const download: DownloadProgress = {- id,- name: src,- progress: 0,- downloaded: 0,- totalBytes: null,- };- downloads.push(download);- updateProgress();-- return ({percent}) => {- download.progress = percent;- updateProgress();- };- };-- await renderStill({- composition: config,- frame: stillFrame,- output: absoluteOutputLocation,- serveUrl: urlOrBundle,- quality,- dumpBrowserLogs: RenderInternals.isEqualOrBelowLogLevel(- ConfigInternals.Logging.getLogLevel(),- 'verbose'- ),- envVariables,- imageFormat,- inputProps,- chromiumOptions,- timeoutInMilliseconds: ConfigInternals.getCurrentPuppeteerTimeout(),- scale,- browserExecutable,- overwrite,- onDownload,- port,- downloadMap,- });-- frames = 1;- updateProgress();- Log.info();-- const closeBrowserPromise = puppeteerInstance.close(false);-- Log.info(chalk.green('\nYour still frame is ready!'));-- 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(`▶️ ${absoluteOutputLocation}`));- await closeBrowserPromise;+ } finally {++ // TODO: Check whether all temp files are cleaned up++ // after this change+ await Promise.all(jobCleanups.map((c) => c()));+ }};diff --cc packages/renderer/src/index.tsindex 1e879d1d86,15c0af347b..794dff85c2--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@@ -45,13 -42,8 +42,12 @@@ import {validateQuality} from './qualitimport {isPathInside} from './serve-handler/is-path-inside';import {serveStatic} from './serve-static';import {tmpDir} from './tmp-dir';-import {validateConcurrency} from './validate-concurrency';+import {+ getMaxConcurrency,+ getMinConcurrency,+ validateConcurrency,+} from './validate-concurrency';import {validateEvenDimensionsWithCodec} from './validate-even-dimensions-with-codec';- import {validateFfmpeg} from './validate-ffmpeg';import {DEFAULT_OPENGL_RENDERER,validateOpenGlRenderer,@@@ -162,12 -144,8 +149,10 @@@ export const RenderInternals =cleanDownloadMap,convertToPositiveFrameIndex,findRemotionRoot,- getExecutableBinary,validateBitrate,- getFfmpegVersion,combineVideos,+ getMinConcurrency,+ getMaxConcurrency,getDefaultAudioCodec,validAudioCodecs,defaultFileExtensionMap,