Skip to content

🎥 Make videos programmatically with React

refactor how codec is decided

Jonny Burger09960cba1756
diff --git a/packages/cli/src/compositions.ts b/packages/cli/src/compositions.ts
index 0c4f8262aa..668e7112ee 100644
--- a/packages/cli/src/compositions.ts
+++ b/packages/cli/src/compositions.ts
@@ -55,6 +55,7 @@ export const listCompositionsCommand = async (remotionRoot: string) => {
} = await getCliOptions({
isLambda: false,
type: 'get-compositions',
+ codec: 'h264',
});
const {urlOrBundle: bundled, cleanup: cleanupBundle} =
diff --git a/packages/cli/src/get-cli-options.ts b/packages/cli/src/get-cli-options.ts
index 5471e788bb..4e6630a5de 100644
--- a/packages/cli/src/get-cli-options.ts
+++ b/packages/cli/src/get-cli-options.ts
@@ -14,7 +14,7 @@ import {getFinalOutputCodec} from './get-final-output-codec';
import {getInputProps} from './get-input-props';
import {getImageFormat} from './image-formats';
import {Log} from './log';
-import {getUserPassedOutputLocation} from './user-passed-output-location';
+import {parsedCli} from './parse-command-line';
const getAndValidateFrameRange = () => {
const frameRange = ConfigInternals.getRange();
@@ -29,22 +29,12 @@ const getAndValidateFrameRange = () => {
return frameRange;
};
-const getFinalCodec = async (options: {isLambda: boolean}) => {
- const userCodec = ConfigInternals.getOutputCodecOrUndefined();
-
- const codec = getFinalOutputCodec({
- codec: userCodec,
- fileExtension: RenderInternals.getExtensionOfFilename(
- getUserPassedOutputLocation()
- ),
- emitWarning: true,
- });
+export const validateFfmepgCanUseCodec = async (codec: Codec) => {
const ffmpegExecutable = ConfigInternals.getCustomFfmpegExecutable();
if (
codec === 'vp8' &&
!(await RenderInternals.ffmpegHasFeature({
feature: 'enable-libvpx',
- isLambda: options.isLambda,
ffmpegExecutable,
}))
) {
@@ -60,7 +50,6 @@ const getFinalCodec = async (options: {isLambda: boolean}) => {
codec === 'h265' &&
!(await RenderInternals.ffmpegHasFeature({
feature: 'enable-gpl',
- isLambda: options.isLambda,
ffmpegExecutable,
}))
) {
@@ -76,7 +65,6 @@ const getFinalCodec = async (options: {isLambda: boolean}) => {
codec === 'h265' &&
!(await RenderInternals.ffmpegHasFeature({
feature: 'enable-libx265',
- isLambda: options.isLambda,
ffmpegExecutable,
}))
) {
@@ -87,8 +75,20 @@ const getFinalCodec = async (options: {isLambda: boolean}) => {
'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,
+ });
- return codec;
+ return {codec, reason};
};
const getBrowser = () =>
@@ -200,15 +200,10 @@ const getAndValidateBrowser = async (browserExecutable: BrowserExecutable) => {
export const getCliOptions = async (options: {
isLambda: boolean;
type: 'still' | 'series' | 'get-compositions';
+ codec: Codec;
}) => {
const frameRange = getAndValidateFrameRange();
- const codec: Codec =
- options.type === 'get-compositions'
- ? 'h264'
- : await getFinalCodec({
- isLambda: options.isLambda,
- });
const shouldOutputImageSequence =
options.type === 'still'
? true
@@ -220,14 +215,14 @@ export const getCliOptions = async (options: {
const overwrite = ConfigInternals.getShouldOverwrite({
defaultValue: !options.isLambda,
});
- const crf = getAndValidateCrf(shouldOutputImageSequence, codec);
- const pixelFormat = getAndValidatePixelFormat(codec);
+ const crf = getAndValidateCrf(shouldOutputImageSequence, options.codec);
+ const pixelFormat = getAndValidatePixelFormat(options.codec);
const imageFormat = getAndValidateImageFormat({
shouldOutputImageSequence,
- codec,
+ codec: options.codec,
pixelFormat,
});
- const proResProfile = getAndValidateProResProfile(codec);
+ const proResProfile = getAndValidateProResProfile(options.codec);
const browserExecutable = ConfigInternals.getBrowserExecutable();
const ffmpegExecutable = ConfigInternals.getCustomFfmpegExecutable();
const ffprobeExecutable = ConfigInternals.getCustomFfprobeExecutable();
@@ -242,9 +237,12 @@ export const getCliOptions = async (options: {
ConfigInternals.getChromiumOpenGlRenderer() ??
RenderInternals.DEFAULT_OPENGL_RENDERER,
};
- const everyNthFrame = ConfigInternals.getAndValidateEveryNthFrame(codec);
- const numberOfGifLoops =
- ConfigInternals.getAndValidateNumberOfGifLoops(codec);
+ const everyNthFrame = ConfigInternals.getAndValidateEveryNthFrame(
+ options.codec
+ );
+ const numberOfGifLoops = ConfigInternals.getAndValidateNumberOfGifLoops(
+ options.codec
+ );
const concurrency = ConfigInternals.getConcurrency();
@@ -255,7 +253,6 @@ export const getCliOptions = async (options: {
concurrency,
frameRange,
shouldOutputImageSequence,
- codec,
inputProps: getInputProps(() => undefined),
envVariables: await getEnvironmentVariables(),
quality: ConfigInternals.getQuality(),
diff --git a/packages/cli/src/get-final-output-codec.ts b/packages/cli/src/get-final-output-codec.ts
index a13e15ea8c..06a715d702 100644
--- a/packages/cli/src/get-final-output-codec.ts
+++ b/packages/cli/src/get-final-output-codec.ts
@@ -1,93 +1,93 @@
import type {Codec, CodecOrUndefined} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
-import {Log} from './log';
-export const getFinalOutputCodec = ({
- codec: inputCodec,
- fileExtension,
- emitWarning,
-}: {
- codec: CodecOrUndefined;
- fileExtension: string | null;
- emitWarning: boolean;
-}): Codec => {
- if (inputCodec === undefined && fileExtension === 'webm') {
- if (emitWarning) {
- Log.info(
- 'You have specified a .webm extension, using the VP8 encoder. Use --codec=vp9 to use the Vp9 encoder.'
- );
- }
-
- return 'vp8';
- }
-
- if (inputCodec === undefined && fileExtension === 'hevc') {
- if (emitWarning) {
- Log.info('You have specified a .hevc extension, using the H265 encoder.');
- }
+const fileExtensions: Record<string, Codec> = {
+ webm: 'vp8',
+ hevc: 'h265',
+ mp3: 'mp3',
+ mov: 'prores',
+ wav: 'wav',
+ aac: 'aac',
+ mkv: 'h264-mkv',
+ gif: 'gif',
+ mp4: 'h264',
+ m4a: 'aac',
+};
- return 'h265';
+const deriveExtensionFromFilename = (extension: string | null) => {
+ if (extension === null) {
+ return null;
}
- if (inputCodec === undefined && fileExtension === 'mp3') {
- if (emitWarning) {
- Log.info('You have specified a .mp3 extension, using the MP3 encoder.');
- }
+ return fileExtensions[extension] ?? null;
+};
- return 'mp3';
+export const getFinalOutputCodec = ({
+ cliFlag,
+ configFile,
+ downloadName,
+ outName,
+}: {
+ cliFlag: CodecOrUndefined;
+ outName: string | null;
+ downloadName: string | null;
+ configFile: Codec | null;
+}): {codec: Codec; reason: string} => {
+ const downloadNameExtension =
+ RenderInternals.getExtensionOfFilename(downloadName);
+ const outNameExtension = RenderInternals.getExtensionOfFilename(outName);
+
+ const derivedDownloadCodec = deriveExtensionFromFilename(
+ downloadNameExtension
+ );
+ const derivedOutNameCodec = deriveExtensionFromFilename(outNameExtension);
+
+ if (
+ derivedDownloadCodec &&
+ derivedOutNameCodec &&
+ derivedDownloadCodec !== derivedOutNameCodec
+ ) {
+ throw new TypeError(
+ `The download name is ${downloadName} but the output name is ${outName}. The file extensions must match`
+ );
}
- if (inputCodec === undefined && fileExtension === 'mov') {
- if (emitWarning) {
- Log.info(
- 'You have specified a .mov extension, using the Apple ProRes encoder.'
+ if (derivedDownloadCodec) {
+ if (cliFlag && derivedDownloadCodec !== cliFlag) {
+ throw new TypeError(
+ `The download name is ${downloadName} but --codec=${cliFlag} was passed. The download name implies a codec of ${derivedDownloadCodec} which does not align with the --codec flag.`
);
}
- return 'prores';
+ return {
+ codec: derivedDownloadCodec,
+ reason: 'derived from download name',
+ };
}
- if (inputCodec === undefined && fileExtension === 'wav') {
- if (emitWarning) {
- Log.info('You have specified a .wav extension, using the WAV encoder.');
- }
-
- return 'wav';
- }
-
- if (inputCodec === undefined && fileExtension === 'aac') {
- if (emitWarning) {
- Log.info('You have specified a .aac extension, using the AAC encoder.');
- }
-
- return 'aac';
- }
-
- if (inputCodec === undefined && fileExtension === 'm4a') {
- if (emitWarning) {
- Log.info('You have specified a .m4a extension, using the AAC encoder.');
- }
-
- return 'aac';
- }
-
- if (inputCodec === undefined && fileExtension === 'mkv') {
- if (emitWarning) {
- Log.info(
- 'You have specified a .mkv extension, using the H264 encoder and WAV audio format.'
+ if (derivedOutNameCodec) {
+ if (cliFlag && derivedOutNameCodec !== cliFlag) {
+ throw new TypeError(
+ `The out name is ${outName} but --codec=${cliFlag} was passed. The out name implies a codec of ${derivedOutNameCodec} which does not align with the --codec flag.`
);
}
- return 'h264-mkv';
+ return {
+ codec: derivedOutNameCodec,
+ reason: 'derived from out name',
+ };
}
- if (inputCodec === undefined && fileExtension === 'gif') {
- if (emitWarning) {
- Log.info('You have specified a .gif extension, rendering a GIF');
- }
+ if (cliFlag) {
+ return {codec: cliFlag, reason: 'from --codec flag'};
+ }
- return 'gif';
+ if (configFile) {
+ return {
+ codec: configFile,
+ reason: 'Config file',
+ };
}
- return inputCodec ?? RenderInternals.DEFAULT_CODEC;
+ return {codec: RenderInternals.DEFAULT_CODEC, reason: 'default'};
};
diff --git a/packages/cli/src/index.tsx b/packages/cli/src/index.tsx
index 7b40d1c097..77191a3d48 100644
--- a/packages/cli/src/index.tsx
+++ b/packages/cli/src/index.tsx
@@ -6,7 +6,7 @@ import {overrideRemotion} from './config/index';
import {getFileSizeDownloadBar} from './download-progress';
import {findRemotionRoot} from './find-closest-package-json';
import {formatBytes} from './format-bytes';
-import {getCliOptions} from './get-cli-options';
+import {getCliOptions, getFinalCodec} from './get-cli-options';
import {loadConfig} from './get-config-file-name';
import {handleCommonError} from './handle-common-errors';
import {initializeCli} from './initialize-cli';
@@ -108,4 +108,5 @@ export const CliInternals = {
formatBytes,
getFileSizeDownloadBar,
findRemotionRoot,
+ getFinalCodec,
};
diff --git a/packages/cli/src/parse-command-line.ts b/packages/cli/src/parse-command-line.ts
index 40339b8246..59fb7c4148 100644
--- a/packages/cli/src/parse-command-line.ts
+++ b/packages/cli/src/parse-command-line.ts
@@ -171,10 +171,6 @@ export const parseCommandLine = () => {
Config.Output.setCrf(parsedCli.crf);
}
- if (parsedCli.codec) {
- Config.Output.setCodec(parsedCli.codec);
- }
-
if (parsedCli['every-nth-frame']) {
Config.Rendering.setEveryNthFrame(parsedCli['every-nth-frame']);
}
diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsx
index b4883da402..33ae2ef6cd 100644
--- a/packages/cli/src/render.tsx
+++ b/packages/cli/src/render.tsx
@@ -16,6 +16,8 @@ import {ConfigInternals} from './config';
import {
getAndValidateAbsoluteOutputFile,
getCliOptions,
+ getFinalCodec,
+ validateFfmepgCanUseCodec,
} from './get-cli-options';
import {getCompositionId} from './get-composition-id';
import {getOutputFilename} from './get-filename';
@@ -28,6 +30,7 @@ import {
} from './progress-bar';
import {bundleOnCliOrTakeServeUrl} from './setup-cache';
import type {RenderStep} from './step';
+import {getUserPassedOutputLocation} from './user-passed-output-location';
import {checkAndValidateFfmpegVersion} from './validate-ffmpeg-version';
export const render = async (remotionRoot: string) => {
@@ -57,8 +60,14 @@ export const render = async (remotionRoot: string) => {
Log.verbose('Asset dirs', downloadMap.assetDir);
+ const {codec, reason: codecReason} = getFinalCodec({
+ downloadName: null,
+ outName: getUserPassedOutputLocation(),
+ });
+
+ validateFfmepgCanUseCodec(codec);
+
const {
- codec,
proResProfile,
concurrency,
frameRange,
@@ -87,6 +96,7 @@ export const render = async (remotionRoot: string) => {
} = await getCliOptions({
isLambda: false,
type: 'series',
+ codec,
});
const relativeOutputLocation = getOutputFilename({
@@ -105,7 +115,7 @@ export const render = async (remotionRoot: string) => {
Log.info(
chalk.gray(
- `Composition = ${compositionId}, Codec = ${codec}, Output = ${relativeOutputLocation}`
+ `Composition = ${compositionId}, Codec = ${codec} (${codecReason}), Output = ${relativeOutputLocation}`
)
);
diff --git a/packages/cli/src/still.ts b/packages/cli/src/still.ts
index a23ca553d3..6556823b67 100644
--- a/packages/cli/src/still.ts
+++ b/packages/cli/src/still.ts
@@ -81,6 +81,7 @@ export const still = async (remotionRoot: string) => {
} = await getCliOptions({
isLambda: false,
type: 'still',
+ codec: 'h264',
});
Log.verbose('Browser executable: ', browserExecutable);
diff --git a/packages/cli/src/test/final-output-codec.test.ts b/packages/cli/src/test/final-output-codec.test.ts
index 07a564d32f..b333b87546 100644
--- a/packages/cli/src/test/final-output-codec.test.ts
+++ b/packages/cli/src/test/final-output-codec.test.ts
@@ -17,11 +17,15 @@ describe('Codec tests valid codec input', () => {
test(`codec ${entry}`, () =>
expect(
getFinalOutputCodec({
- codec: entry,
- emitWarning: false,
- fileExtension: '',
+ cliFlag: entry,
+ outName: 'out',
+ configFile: null,
+ downloadName: null,
})
- ).toEqual(entry))
+ ).toEqual({
+ codec: entry,
+ reason: 'from --codec flag',
+ }))
);
});
@@ -34,36 +38,38 @@ describe('Codec tests undefined codec input with known extension', () => {
['aac', 'aac'],
['aac', 'm4a'],
];
- const inputCodecs: CodecOrUndefined[] = ['h264', undefined];
- inputCodecs.forEach((codec) =>
- codecExtensionCombination.forEach((entry) =>
- test(
- codec
- ? `should not look for extension ${entry[1]}`
- : `${entry[1]} should be recognized as ${entry[0]}`,
- () =>
- expect(
- getFinalOutputCodec({
- codec,
- emitWarning: false,
- fileExtension: entry[1],
- })
- ).toEqual(codec ?? entry[0])
- )
- )
- );
-});
-
-describe('Codec tests undefined codec input with unknown extension', () => {
- const unknownExtensions = ['', 'abc'];
- unknownExtensions.forEach((entry) =>
- test(`testing with "${entry}" as extension`, () =>
- expect(
+ codecExtensionCombination.forEach((entry) =>
+ test(`${entry[1]} should be recognized as ${entry[0]}`, () => {
+ return expect(
getFinalOutputCodec({
- codec: undefined,
- emitWarning: false,
- fileExtension: entry,
+ cliFlag: undefined,
+ configFile: null,
+ downloadName: null,
+ outName: 'hi.' + entry[1],
})
- ).toEqual('h264'))
+ ).toEqual({
+ codec: entry[0],
+ reason: 'derived from out name',
+ });
+ })
);
});
+
+test('Codec tests undefined codec input with unknown extension', () => {
+ expect(
+ getFinalOutputCodec({
+ cliFlag: undefined,
+ outName: 'hi.',
+ configFile: null,
+ downloadName: null,
+ })
+ ).toEqual({codec: 'h264', reason: 'default'});
+ expect(
+ getFinalOutputCodec({
+ cliFlag: undefined,
+ outName: 'hi.abc',
+ configFile: null,
+ downloadName: null,
+ })
+ ).toEqual({codec: 'h264', reason: 'default'});
+});
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index ad98858f3f..ae2f7b7066 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -47,11 +47,16 @@ export const renderCommand = async (args: string[]) => {
quit(1);
}
- const outName = args[2] ?? null;
+ const outName = parsedLambdaCli['out-name'];
+ const downloadName = args[2] ?? null;
+
+ const {codec, reason} = CliInternals.getFinalCodec({
+ downloadName,
+ outName: outName ?? null,
+ });
const {
chromiumOptions,
- codec,
crf,
envVariables,
frameRange,
@@ -70,6 +75,7 @@ export const renderCommand = async (args: string[]) => {
} = await CliInternals.getCliOptions({
type: 'series',
isLambda: true,
+ codec,
});
const functionName = await findFunctionName();
@@ -113,7 +119,7 @@ export const renderCommand = async (args: string[]) => {
overwrite,
});
- const totalSteps = outName ? 5 : 4;
+ const totalSteps = downloadName ? 5 : 4;
const progressBar = CliInternals.createOverwriteableCliOutput(
CliInternals.quietFlagProvided()
@@ -121,7 +127,12 @@ export const renderCommand = async (args: string[]) => {
Log.info(
CliInternals.chalk.gray(
- `Bucket = ${res.bucketName}, renderId = ${res.renderId}, functionName = ${functionName}`
+ `bucket = ${res.bucketName}, function = ${functionName}`
+ )
+ );
+ Log.info(
+ CliInternals.chalk.gray(
+ `renderId = ${res.renderId}, codec = ${codec} (${reason})`
)
);
Log.verbose(`CloudWatch logs (if enabled): ${res.cloudWatchLogs}`);
@@ -169,11 +180,11 @@ export const renderCommand = async (args: string[]) => {
retriesInfo: newStatus.retriesInfo,
})
);
- if (outName) {
+ if (downloadName) {
const downloadStart = Date.now();
const {outputPath, sizeInBytes} = await downloadMedia({
bucketName: res.bucketName,
- outPath: outName,
+ outPath: downloadName,
region: getAwsRegion(),
renderId: res.renderId,
onProgress: ({downloaded, totalSize}) => {
diff --git a/packages/lambda/src/cli/commands/still.ts b/packages/lambda/src/cli/commands/still.ts
index 10f931ca60..8c10544621 100644
--- a/packages/lambda/src/cli/commands/still.ts
+++ b/packages/lambda/src/cli/commands/still.ts
@@ -138,6 +138,7 @@ export const stillCommand = async (args: string[]) => {
} = await CliInternals.getCliOptions({
type: 'still',
isLambda: true,
+ codec: 'h264',
});
const functionName = await findFunctionName();
diff --git a/packages/renderer/src/ffmpeg-flags.ts b/packages/renderer/src/ffmpeg-flags.ts
index 1ee0f9a916..dc4ffbefe3 100644
--- a/packages/renderer/src/ffmpeg-flags.ts
+++ b/packages/renderer/src/ffmpeg-flags.ts
@@ -26,17 +26,10 @@ export const getFfmpegBuildInfo = async (options: {
export const ffmpegHasFeature = async ({
ffmpegExecutable,
feature,
- isLambda,
}: {
ffmpegExecutable: string | null;
feature: 'enable-gpl' | 'enable-libx265' | 'enable-libvpx';
- isLambda: boolean;
}) => {
- if (isLambda) {
- // When rendering in the cloud, we don't need a local binary
- return true;
- }
-
if (!(await binaryExists('ffmpeg', ffmpegExecutable))) {
return false;
}