🎥 Make videos programmatically with React
refine
Jonny Burger4046a6263fde
diff --git a/packages/cli/src/get-filename.ts b/packages/cli/src/get-filename.tsindex d1c1e4ea28..8f2938ca7e 100644--- a/packages/cli/src/get-filename.ts+++ b/packages/cli/src/get-filename.ts@@ -10,6 +10,16 @@ export const getOutputFilename = (): string => {let filename = getUserPassedOutputLocation();let extension = getUserPassedFileExtension();+ if (imageSequence && extension !== null) {+ if (extension !== null) {+ console.error(+ 'The output directory of the image sequence cannot have an extension. Got: ' ++ extension+ );+ process.exit(1);+ }+ return filename;+ }if (extension === null && !imageSequence) {if (codec === 'h264' || codec === 'h265') {console.info('No file extension specified, adding .mp4 automatically.');@@ -40,9 +50,6 @@ export const getOutputFilename = (process.exit(1);}}- if (imageSequence && extension !== null) {- console.error('The output directory cannot have an extension.');- process.exit(1);- }+return filename;};diff --git a/packages/cli/src/parse-command-line.ts b/packages/cli/src/parse-command-line.tsindex f7449bd919..acbe1d092e 100644--- a/packages/cli/src/parse-command-line.ts+++ b/packages/cli/src/parse-command-line.ts@@ -12,6 +12,7 @@ export type CommandLineOptions = {force: boolean;codec: Codec;props: string;+ crf: number;};export const parsedCli = minimist<CommandLineOptions>(process.argv.slice(2));@@ -30,6 +31,9 @@ export const parseCommandLine = () => {if (parsedCli.sequence) {Config.Output.setImageSequence(true);}+ if (typeof parsedCli.crf !== 'undefined') {+ Config.Output.setCrf(parsedCli.crf);+ }if (parsedCli.codec) {Config.Output.setCodec(parsedCli.codec);}diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsxindex 1b296cf9f1..ddf1d8c213 100644--- a/packages/cli/src/render.tsx+++ b/packages/cli/src/render.tsx@@ -30,12 +30,23 @@ export const render = async () => {loadConfigFile(configFileName);parseCommandLine();const parallelism = Internals.getConcurrency();+ const shouldOutputImageSequence = Internals.getShouldOutputImageSequence();+ const userCodec = Internals.getOutputCodecOrUndefined();+ if (shouldOutputImageSequence && userCodec) {+ console.error(+ 'Detected both --codec and --sequence (formerly --png) flag.'+ );+ console.error(+ 'This is an error - no video codec can be used for image sequences.'+ );+ console.error('Remove one of the two flags and try again.');+ process.exit(1);+ }const codec = getFinalOutputCodec({- codec: Internals.getOutputCodecOrUndefined(),+ codec: userCodec,fileExtension: getUserPassedFileExtension(),emitWarning: true,});- const shouldOutputImageSequence = Internals.getShouldOutputImageSequence();const outputFile = getOutputFilename(codec, shouldOutputImageSequence);const overwrite = Internals.getShouldOverwrite();const userProps = getUserProps();@@ -48,14 +59,13 @@ export const render = async () => {);process.exit(1);}- if (- codec === 'h264' ||- codec === 'h265' ||- codec === 'vp8' ||- codec === 'vp9'- ) {+ if (shouldOutputImageSequence) {await validateFfmpeg();}+ const crf = shouldOutputImageSequence ? null : Internals.getActualCrf(codec);+ if (crf !== null) {+ Internals.validateSelectedCrf(crf, codec);+ }if (shouldOutputImageSequence) {fs.mkdirSync(absoluteOutputFile, {recursive: true,@@ -126,6 +136,9 @@ export const render = async () => {}if (!shouldOutputImageSequence) {process.stdout.write(`🧵 (3/${steps}) Stitching frames together...\n`);+ if (typeof crf !== 'number') {+ throw TypeError('CRF is unexpectedly not a number');+ }await stitchFramesToVideo({dir: outputDir,width: config.width,@@ -135,7 +148,8 @@ export const render = async () => {force: overwrite,imageFormat,pixelFormat: Internals.getPixelFormat(),- outputFormat: codec,+ codec,+ crf,});console.log('Cleaning up...');await fs.promises.rmdir(outputDir, {@@ -143,7 +157,7 @@ export const render = async () => {});console.log('\n▶️ Your video is ready - hit play!');} else {- console.log('\n▶️ Your PNG sequence is ready!');+ console.log('\n▶️ Your image sequence is ready!');}console.log(absoluteOutputFile);};diff --git a/packages/core/src/config/codec.ts b/packages/core/src/config/codec.tsindex 137e1ea1cd..1c46d4cc2a 100644--- a/packages/core/src/config/codec.ts+++ b/packages/core/src/config/codec.ts@@ -11,6 +11,8 @@ export const getOutputCodecOrUndefined = (): CodecOrUndefined => {return codec;};+export const DEFAULT_CODEC: Codec = 'h264';+export const getFinalOutputCodec = ({codec: inputCodec,fileExtension,@@ -36,7 +38,7 @@ export const getFinalOutputCodec = ({}return 'h265';}- return inputCodec ?? 'h264';+ return inputCodec ?? DEFAULT_CODEC;};export const setOutputFormat = (newLegacyFormat: LegacyFormat) => {diff --git a/packages/core/src/config/crf.ts b/packages/core/src/config/crf.tsindex 6f25f45313..b30a9de078 100644--- a/packages/core/src/config/crf.ts+++ b/packages/core/src/config/crf.ts@@ -1,11 +1,61 @@+import {Codec} from './codec';+type Crf = number | undefined;let currentCrf: Crf = undefined;export const setCrf = (newCrf: Crf) => {+ if (typeof newCrf !== 'number' && newCrf !== undefined) {+ throw new TypeError('The CRF must be a number or undefined.');+ }currentCrf = newCrf;};-export const getCrf = () => {+export const getCrfOrUndefined = () => {return currentCrf;};++export const getDefaultCrfForCodec = (codec: Codec): number => {+ if (codec === 'h264') {+ return 18; // FFMPEG default 23+ }+ if (codec === 'h265') {+ return 23; // FFMPEG default 28+ }+ if (codec === 'vp8') {+ return 9; // FFMPEG default 10+ }+ if (codec === 'vp9') {+ return 28; // FFMPEG recommendation 31+ }+ throw new TypeError(`Got unexpected codec "${codec}"`);+};++export const getValidCrfRanges = (codec: Codec): [number, number] => {+ if (codec === 'h264') {+ return [0, 51];+ }+ if (codec === 'h265') {+ return [0, 51];+ }+ if (codec === 'vp8') {+ return [4, 63];+ }+ if (codec === 'vp9') {+ return [0, 63];+ }+ throw new TypeError(`Got unexpected codec "${codec}"`);+};++export const validateSelectedCrf = (crf: number, codec: Codec) => {+ const range = getValidCrfRanges(codec);+ if (crf < range[0] && crf > range[1]) {+ throw new TypeError(+ `CRF must be between ${range[0]} and ${range[1]} for codec ${codec}. Passed: ${crf}`+ );+ }+};++export const getActualCrf = (codec: Codec) => {+ return getCrfOrUndefined() ?? getDefaultCrfForCodec(codec);+};diff --git a/packages/core/src/config/index.ts b/packages/core/src/config/index.tsindex c882bcd7f7..db257cb6e5 100644--- a/packages/core/src/config/index.ts+++ b/packages/core/src/config/index.ts@@ -1,5 +1,6 @@import {setCodec, setOutputFormat} from './codec';import {Concurrency, setConcurrency} from './concurrency';+import {setCrf} from './crf';import {setImageSequence} from './image-sequence';import {overrideWebpackConfig,@@ -55,6 +56,12 @@ export const Config = {* Can be `h264` (default), `h265`, `vp8` or `vp9`*/setCodec,+ /**+ * Set the Constant Rate Factor to pass to FFMPEG.+ * Lower values mean better quality, but be aware that the ranges of+ * possible values greatly differs between codecs.+ */+ setCrf,/*** Set to true if don't want a video but an image sequence as the output.*/@@ -62,5 +69,5 @@ export const Config = {},} as const;-export {Codec, getFinalOutputCodec} from './codec';+export type {Codec} from './codec';export type {PixelFormat, Concurrency, WebpackConfiguration, WebpackOverrideFn};diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex a7e0cc0de9..6f970cc223 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -4,8 +4,17 @@ import {TComposition,TSequence,} from './CompositionManager';-import {getOutputCodecOrUndefined} from './config/codec';+import {+ DEFAULT_CODEC,+ getFinalOutputCodec,+ getOutputCodecOrUndefined,+} from './config/codec';import {getConcurrency} from './config/concurrency';+import {+ getActualCrf,+ getDefaultCrfForCodec,+ validateSelectedCrf,+} from './config/crf';import {getShouldOutputImageSequence} from './config/image-sequence';import {getWebpackOverrideFn,@@ -40,6 +49,11 @@ export const Internals = {getWebpackOverrideFn,getQuality,getShouldOutputImageSequence,+ validateSelectedCrf,+ getFinalOutputCodec,+ DEFAULT_CODEC,+ getDefaultCrfForCodec,+ getActualCrf,};export type {diff --git a/packages/renderer/src/stitcher.ts b/packages/renderer/src/stitcher.tsindex 1b921a1c33..5c47dc3465 100644--- a/packages/renderer/src/stitcher.ts+++ b/packages/renderer/src/stitcher.ts@@ -1,6 +1,6 @@import execa from 'execa';import fs from 'fs';-import {Codec, PixelFormat} from 'remotion';+import {Codec, Internals, PixelFormat} from 'remotion';import {DEFAULT_IMAGE_FORMAT, ImageFormat} from './image-format';import {validateFfmpeg} from './validate-ffmpeg';@@ -29,9 +29,13 @@ export const stitchFramesToVideo = async (options: {force: boolean;imageFormat?: ImageFormat;pixelFormat?: PixelFormat;- outputFormat: Codec;+ codec?: Codec;+ crf?: number;}): Promise<void> => {+ const codec = options.codec ?? Internals.DEFAULT_CODEC;+ const crf = options.crf ?? Internals.getDefaultCrfForCodec(codec);const format = options.imageFormat ?? DEFAULT_IMAGE_FORMAT;+ Internals.validateSelectedCrf(crf, codec);await validateFfmpeg();const files = await fs.promises.readdir(options.dir);const biggestNumber = Math.max(@@ -44,6 +48,9 @@ export const stitchFramesToVideo = async (options: {);const numberLength = String(biggestNumber).length;+ const encoderName = getCodecName(codec);+ Internals.validateSelectedCrf(crf, codec);+await execa('ffmpeg',[@@ -56,9 +63,9 @@ export const stitchFramesToVideo = async (options: {'-i',`element-%0${numberLength}d.${format}`,'-c:v',- getCodecName(options.outputFormat),+ encoderName,'-crf',- '16',+ crf,'-b:v','1M',options.force ? '-y' : null,