🎥 Make videos programmatically with React
separate
Jonny Burger457ac31b7c4b
diff --git a/packages/cli/src/benchmark.ts b/packages/cli/src/benchmark.tsindex 4f8abb6eba..6a3682dc6e 100644--- a/packages/cli/src/benchmark.ts+++ b/packages/cli/src/benchmark.ts@@ -460,6 +460,7 @@ export const benchmarkCommand = async (commandLine: parsedCli,}).value,finishRenderProgress: () => undefined,+ separateAudioTo: null,},(run, progress) => {benchmarkProgress.update(diff --git a/packages/cli/src/render-flows/render.ts b/packages/cli/src/render-flows/render.tsindex 2d884d1132..5714f6bba2 100644--- a/packages/cli/src/render-flows/render.ts+++ b/packages/cli/src/render-flows/render.ts@@ -518,6 +518,7 @@ export const renderVideoFlow = async ({updateRenderProgress({newline: true, printToConsole: true});},binariesDirectory,+ separateAudioTo: null,});Log.info(diff --git a/packages/cloudrun/src/functions/render-media-single-thread.ts b/packages/cloudrun/src/functions/render-media-single-thread.tsindex 39c27592e7..76fecdf750 100644--- a/packages/cloudrun/src/functions/render-media-single-thread.ts+++ b/packages/cloudrun/src/functions/render-media-single-thread.ts@@ -121,6 +121,7 @@ export const renderMediaSingleThread = async (repro: false,finishRenderProgress: () => undefined,binariesDirectory: null,+ separateAudioTo: null,});const storage = new Storage();diff --git a/packages/it-tests/src/rendering/base64-audio.test.ts b/packages/it-tests/src/rendering/base64-audio.test.tsindex 4a179222ca..0173a4dbc1 100644--- a/packages/it-tests/src/rendering/base64-audio.test.ts+++ b/packages/it-tests/src/rendering/base64-audio.test.ts@@ -31,6 +31,7 @@ test("Should be able to render a MP3 audio file", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("mp3");diff --git a/packages/it-tests/src/rendering/frame-accuracy-gif.test.ts b/packages/it-tests/src/rendering/frame-accuracy-gif.test.tsindex b59de3f254..174dd04225 100644--- a/packages/it-tests/src/rendering/frame-accuracy-gif.test.ts+++ b/packages/it-tests/src/rendering/frame-accuracy-gif.test.ts@@ -48,6 +48,7 @@ const getMissedFramesforCodec = async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});let missedFrames = 0;diff --git a/packages/it-tests/src/rendering/render-scale.test.ts b/packages/it-tests/src/rendering/render-scale.test.tsindex 37b0324df3..7fca84cab1 100644--- a/packages/it-tests/src/rendering/render-scale.test.ts+++ b/packages/it-tests/src/rendering/render-scale.test.ts@@ -44,6 +44,7 @@ test("Should be able to render video with scale 2", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: h264");@@ -84,6 +85,7 @@ test("Should be able to render video with scale 0.1", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: h264");diff --git a/packages/it-tests/src/rendering/rendering.test.ts b/packages/it-tests/src/rendering/rendering.test.tsindex ac13495eb7..d948bfaaa9 100644--- a/packages/it-tests/src/rendering/rendering.test.ts+++ b/packages/it-tests/src/rendering/rendering.test.ts@@ -41,6 +41,7 @@ test("Should be able to render video with custom port", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: h264");@@ -148,6 +149,7 @@ test("Should render a ProRes video", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data.includes("prores (4444)") || data.includes("prores (ap4h")).toBe(@@ -176,6 +178,7 @@ test("Should render a still image if single frame specified", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: png");@@ -204,6 +207,7 @@ test("Should be able to render a WAV audio file", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("pcm_s16le");@@ -235,6 +239,7 @@ test("Should be able to render a MP3 audio file", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("mp3");@@ -266,6 +271,7 @@ test("Should be able to render a AAC audio file", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("aac");@@ -294,6 +300,7 @@ test("Should render a video with GIFs", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: h264");@@ -322,6 +329,7 @@ test("Should render a video with Offline Audio-context", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Stream #0:0: Audio: mp3");@@ -345,6 +353,7 @@ test("Should succeed to render an audio file that doesn't have any audio inputs"indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Duration: 00:00:00.36");@@ -406,6 +415,7 @@ test("Dynamic duration should work, and render from inside src/", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});const data = info.stderr;expect(data).toContain("Video: h264");diff --git a/packages/it-tests/src/ssr/render-frames.test.ts b/packages/it-tests/src/ssr/render-frames.test.tsindex 9e282c02e7..b35feb9d8c 100644--- a/packages/it-tests/src/ssr/render-frames.test.ts+++ b/packages/it-tests/src/ssr/render-frames.test.ts@@ -62,6 +62,7 @@ test("Legacy SSR way of rendering videos should still work", async () => {indent: false,logLevel: "info",binariesDirectory: null,+ cancelSignal: undefined,});expect(probe.stderr).toMatch(/Video: h264/);diff --git a/packages/lambda/src/cli/commands/render/progress.ts b/packages/lambda/src/cli/commands/render/progress.tsindex 3d05b51776..00fe17cd3e 100644--- a/packages/lambda/src/cli/commands/render/progress.ts+++ b/packages/lambda/src/cli/commands/render/progress.ts@@ -184,12 +184,13 @@ export const makeMultiProgressFromStatus = (totalChunks: status.renderMetadata?.totalChunks ?? null,doneIn: status.timeToFinishChunks,framesRendered: status.framesRendered,- totalFrames: status.renderMetadata- ? RenderInternals.getFramesToRender(- status.renderMetadata.frameRange,- status.renderMetadata.everyNthFrame,- ).length- : null,+ totalFrames:+ status.renderMetadata && status.renderMetadata.type === 'video'+ ? RenderInternals.getFramesToRender(+ status.renderMetadata.frameRange,+ status.renderMetadata.everyNthFrame,+ ).length+ : null,},encodingProgress: {framesEncoded: status.encodingStatus?.framesEncoded ?? 0,diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.tsindex 8dfc742ee2..2320f5679b 100644--- a/packages/lambda/src/cli/commands/render/render.ts+++ b/packages/lambda/src/cli/commands/render/render.ts@@ -32,7 +32,7 @@ import {makeMultiProgressFromStatus, makeProgressString} from './progress';export const RENDER_COMMAND = 'render';function getTotalFrames(status: RenderProgress): number | null {- return status.renderMetadata+ return status.renderMetadata && status.renderMetadata.type === 'video'? RenderInternals.getFramesToRender(status.renderMetadata.frameRange,status.renderMetadata.everyNthFrame,diff --git a/packages/lambda/src/functions/helpers/create-post-render-data.ts b/packages/lambda/src/functions/helpers/create-post-render-data.tsindex 17468a7b69..7f6f243b5c 100644--- a/packages/lambda/src/functions/helpers/create-post-render-data.ts+++ b/packages/lambda/src/functions/helpers/create-post-render-data.ts@@ -16,6 +16,7 @@ import type {OutputFileMetadata} from './find-output-file-in-bucket';import {getFilesToDelete} from './get-files-to-delete';import {getRetryStats} from './get-retry-stats';import {getTimeToFinish} from './get-time-to-finish';+import {lambdaRenderHasAudioVideo} from './render-has-audio-video';import type {EnhancedErrorInfo} from './write-lambda-error';export const createPostRenderData = ({@@ -86,6 +87,8 @@ export const createPostRenderData = ({renderId,});+ const {hasAudio, hasVideo} = lambdaRenderHasAudioVideo(renderMetadata);+return {cost: {currency: 'USD',@@ -108,6 +111,8 @@ export const createPostRenderData = ({filesCleanedUp: getFilesToDelete({chunkCount: renderMetadata.totalChunks,renderId,+ hasAudio,+ hasVideo,}).length,timeToEncode,timeToCleanUp: timeToDelete,@@ -117,12 +122,15 @@ export const createPostRenderData = ({type: 'absolute-time',}),retriesInfo,- mostExpensiveFrameRanges: getMostExpensiveChunks(- parsedTimings,- renderMetadata.framesPerLambda,- renderMetadata.frameRange[0],- renderMetadata.frameRange[1],- ),+ mostExpensiveFrameRanges:+ renderMetadata.type === 'still'+ ? []+ : getMostExpensiveChunks(+ parsedTimings,+ renderMetadata.framesPerLambda,+ renderMetadata.frameRange[0],+ renderMetadata.frameRange[1],+ ),deleteAfter: renderMetadata.deleteAfter,estimatedBillingDurationInMilliseconds,};diff --git a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts b/packages/lambda/src/functions/helpers/get-cleanup-progress.tsindex d65c912ddf..e1efe3104c 100644--- a/packages/lambda/src/functions/helpers/get-cleanup-progress.ts+++ b/packages/lambda/src/functions/helpers/get-cleanup-progress.ts@@ -7,11 +7,15 @@ export const getCleanupProgress = ({output,chunkCount,renderId,+ hasAudio,+ hasVideo,}: {contents: _Object[];output: string | null;chunkCount: number;renderId: string;+ hasAudio: boolean;+ hasVideo: boolean;}): null | CleanupInfo => {if (output === null) {return null;@@ -20,6 +24,8 @@ export const getCleanupProgress = ({const filesToDelete = getFilesToDelete({chunkCount,renderId,+ hasAudio,+ hasVideo,});const filesStillThere = contents.filter((c) => {return filesToDelete.find((f) => {diff --git a/packages/lambda/src/functions/helpers/get-files-to-delete.ts b/packages/lambda/src/functions/helpers/get-files-to-delete.tsindex cc3e1a8c5d..c1f9046c14 100644--- a/packages/lambda/src/functions/helpers/get-files-to-delete.ts+++ b/packages/lambda/src/functions/helpers/get-files-to-delete.ts@@ -13,16 +13,33 @@ export type CleanupJob = {export const getFilesToDelete = ({chunkCount,renderId,+ hasVideo,+ hasAudio,}: {chunkCount: number;renderId: string;+ hasVideo: boolean;+ hasAudio: boolean;}): CleanupJob[] => {- const chunks = new Array(chunkCount).fill(true).map((_x, i) =>- chunkKeyForIndex({- index: i,- renderId,- }),- );+ const videoChunks = hasVideo+ ? new Array(chunkCount).fill(true).map((_x, i) =>+ chunkKeyForIndex({+ index: i,+ renderId,+ type: 'video',+ }),+ )+ : [];+ const audioChunks = hasAudio+ ? new Array(chunkCount).fill(true).map((_x, i) =>+ chunkKeyForIndex({+ index: i,+ renderId,+ type: 'audio',+ }),+ )+ : [];+const lambdaTimings = new Array(chunkCount).fill(true).map((_x, i) => lambdaTimingsPrefixForChunk(renderId, i));@@ -31,7 +48,13 @@ export const getFilesToDelete = ({name: lambdaChunkInitializedPrefix(renderId),type: 'prefix' as const,},- ...chunks.map((i) => {+ ...videoChunks.map((i) => {+ return {+ name: i,+ type: 'exact' as const,+ };+ }),+ ...audioChunks.map((i) => {return {name: i,type: 'exact' as const,diff --git a/packages/lambda/src/functions/helpers/get-progress.ts b/packages/lambda/src/functions/helpers/get-progress.tsindex 5ac7ccf0ec..b5afb22441 100644--- a/packages/lambda/src/functions/helpers/get-progress.ts+++ b/packages/lambda/src/functions/helpers/get-progress.ts@@ -31,6 +31,7 @@ import {getTimeToFinish} from './get-time-to-finish';import {inspectErrors} from './inspect-errors';import {lambdaLs} from './io';import {makeTimeoutError} from './make-timeout-error';+import {lambdaRenderHasAudioVideo} from './render-has-audio-video';import type {EnhancedErrorInfo} from './write-lambda-error';export const getProgress = async ({@@ -64,10 +65,13 @@ export const getProgress = async ({customCredentials,);- const totalFrameCount = RenderInternals.getFramesToRender(- postRenderData.renderMetadata.frameRange,- postRenderData.renderMetadata.everyNthFrame,- ).length;+ const totalFrameCount =+ postRenderData.renderMetadata.type === 'still'+ ? 1+ : RenderInternals.getFramesToRender(+ postRenderData.renderMetadata.frameRange,+ postRenderData.renderMetadata.everyNthFrame,+ ).length;return {framesRendered: totalFrameCount,@@ -173,11 +177,17 @@ export const getProgress = async ({diskSizeInMb: MAX_EPHEMERAL_STORAGE_IN_MB,});+ const {hasAudio, hasVideo} = renderMetadata+ ? lambdaRenderHasAudioVideo(renderMetadata)+ : {hasAudio: false, hasVideo: false};+const cleanup = getCleanupProgress({chunkCount: renderMetadata?.totalChunks ?? 0,contents,output: outputFile?.url ?? null,renderId,+ hasAudio,+ hasVideo,});const timeToFinish = getTimeToFinish({diff --git a/packages/lambda/src/functions/helpers/make-timeout-message.ts b/packages/lambda/src/functions/helpers/make-timeout-message.tsindex 204b52cf99..b5e52e0454 100644--- a/packages/lambda/src/functions/helpers/make-timeout-message.ts+++ b/packages/lambda/src/functions/helpers/make-timeout-message.ts@@ -29,9 +29,12 @@ const makeChunkMissingMessage = ({.map((ch) => {const isLastChunk = ch === renderMetadata.totalChunks - 1;const start = ch * renderMetadata.framesPerLambda;- const end = isLastChunk- ? renderMetadata.frameRange[1]- : (ch + 1) * renderMetadata.framesPerLambda - 1;+ const end =+ renderMetadata.type === 'still'+ ? 0+ : isLastChunk+ ? renderMetadata.frameRange[1]+ : (ch + 1) * renderMetadata.framesPerLambda - 1;const msg = `Chunk ${ch} (Frames ${start} - ${end})`;diff --git a/packages/lambda/src/functions/helpers/merge-chunks.ts b/packages/lambda/src/functions/helpers/merge-chunks.tsindex 32c41b8851..83c0e1f20b 100644--- a/packages/lambda/src/functions/helpers/merge-chunks.ts+++ b/packages/lambda/src/functions/helpers/merge-chunks.ts@@ -31,6 +31,7 @@ import {getFilesToDelete} from './get-files-to-delete';import {getOutputUrlFromMetadata} from './get-output-url-from-metadata';import {inspectErrors} from './inspect-errors';import {lambdaDeleteFile, lambdaLs, lambdaWriteFile} from './io';+import {lambdaRenderHasAudioVideo} from './render-has-audio-video';import type {EnhancedErrorInfo} from './write-lambda-error';import {writeLambdaError} from './write-lambda-error';import {writePostRenderData} from './write-post-render-data';@@ -216,9 +217,15 @@ export const mergeChunksAndFinishRender = async (options: {expectedBucketOwner: options.expectedBucketOwner,});+ const {hasAudio, hasVideo} = lambdaRenderHasAudioVideo(+ options.renderMetadata,+ );+const jobs = getFilesToDelete({chunkCount: options.chunkCount,renderId: options.renderId,+ hasAudio,+ hasVideo,});const deletProm =diff --git a/packages/lambda/src/functions/helpers/render-has-audio-video.ts b/packages/lambda/src/functions/helpers/render-has-audio-video.tsnew file mode 100644index 0000000000..1ec6fc9237--- /dev/null+++ b/packages/lambda/src/functions/helpers/render-has-audio-video.ts@@ -0,0 +1,23 @@+import {RenderInternals} from '@remotion/renderer';+import type {RenderMetadata} from '../../defaults';++export const lambdaRenderHasAudioVideo = (+ renderMetadata: RenderMetadata,+): {+ hasAudio: boolean;+ hasVideo: boolean;+} => {+ if (renderMetadata.type === 'still') {+ throw new Error('Cannot merge stills');+ }++ const hasVideo = renderMetadata+ ? !RenderInternals.isAudioCodec(renderMetadata.codec)+ : false;+ const hasAudio = renderMetadata ? renderMetadata.muted : false;++ return {+ hasAudio,+ hasVideo,+ };+};diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex 87ef24a9bd..1d78b7fcc5 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -322,6 +322,7 @@ const innerLaunchHandler = async ({numberOfGifLoops: params.numberOfGifLoops,downloadBehavior: params.downloadBehavior,audioBitrate: params.audioBitrate,+ muted: params.muted,};const {key, renderBucketName, customCredentials} = getExpectedOutName(diff --git a/packages/lambda/src/functions/merge.ts b/packages/lambda/src/functions/merge.tsindex 2699b3f8d8..74366bd6a0 100644--- a/packages/lambda/src/functions/merge.ts+++ b/packages/lambda/src/functions/merge.ts@@ -38,6 +38,10 @@ export const mergeHandler = async (throw new Error('expected codec');}+ if (renderMetadata.type === 'still') {+ throw new Error('Cannot merge stills');+ }+const {key, renderBucketName, customCredentials} = getExpectedOutName(renderMetadata,params.bucketName,diff --git a/packages/lambda/src/functions/renderer.ts b/packages/lambda/src/functions/renderer.tsindex 04480fbf72..d36c378cf4 100644--- a/packages/lambda/src/functions/renderer.ts+++ b/packages/lambda/src/functions/renderer.ts@@ -14,6 +14,7 @@ import {RENDERER_PATH_TOKEN,} from '../shared/constants';import {isFlakyError} from '../shared/is-flaky-error';+import {truthy} from '../shared/truthy';import {enableNodeIntrospection} from '../shared/why-is-node-running';import type {ChunkTimingData,@@ -102,20 +103,24 @@ const renderHandler = async (const outdir = RenderInternals.tmpDir(RENDERER_PATH_TOKEN);const chunkCodec: Codec = params.codec === 'gif' ? 'h264-mkv' : params.codec;+ const chunk = `localchunk-${String(params.chunk).padStart(8, '0')}`;+ const defaultAudioCodec = RenderInternals.getDefaultAudioCodec({+ codec: params.codec,+ preferLossless: params.preferLossless,+ });- const outputLocation = path.join(- outdir,- `localchunk-${String(params.chunk).padStart(- 8,- '0',- )}.${RenderInternals.getFileExtensionFromCodec(- chunkCodec,- RenderInternals.getDefaultAudioCodec({- codec: params.codec,- preferLossless: params.preferLossless,- }),- )}`,+ const videoExtension = RenderInternals.getFileExtensionFromCodec(+ chunkCodec,+ defaultAudioCodec,);+ const audioExtension = defaultAudioCodec+ ? RenderInternals.getExtensionFromAudioCodec(defaultAudioCodec)+ : null;++ const videoOutputLocation = path.join(outdir, `${chunk}.${videoExtension}`);+ const audioOutputLocation = audioExtension+ ? path.join(outdir, `${chunk}.${audioExtension}`)+ : null;const resolvedProps = await resolvedPropsPromise;const serializedInputPropsWithCustomSchema = await inputPropsPromise;@@ -188,7 +193,7 @@ const renderHandler = async (onBrowserLog: (log) => {logs.push(log);},- outputLocation,+ outputLocation: videoOutputLocation,codec: chunkCodec,crf: params.crf ?? null,pixelFormat: params.pixelFormat ?? RenderInternals.DEFAULT_PIXEL_FORMAT,@@ -222,6 +227,7 @@ const renderHandler = async (colorSpace: params.colorSpace,finishRenderProgress: () => undefined,binariesDirectory: null,+ separateAudioTo: audioOutputLocation,}).then(({slowestFrames}) => {console.log(`Slowest frames:`);@@ -250,14 +256,34 @@ const renderHandler = async (key: chunkKeyForIndex({renderId: params.renderId,index: params.chunk,+ type: 'video',}),- body: fs.createReadStream(outputLocation),+ body: fs.createReadStream(videoOutputLocation),region: getCurrentRegionInFunction(),privacy: params.privacy,expectedBucketOwner: options.expectedBucketOwner,downloadBehavior: null,customCredentials: null,});++ // TODO: Make it parallel+ if (audioOutputLocation) {+ await lambdaWriteFile({+ bucketName: params.bucketName,+ key: chunkKeyForIndex({+ renderId: params.renderId,+ index: params.chunk,+ type: 'audio',+ }),+ body: fs.createReadStream(audioOutputLocation),+ region: getCurrentRegionInFunction(),+ privacy: params.privacy,+ expectedBucketOwner: options.expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,+ });+ }+RenderInternals.Log.verbose({indent: false, logLevel: params.logLevel},`Wrote chunk to S3 (${Date.now() - writeStart}ms)`,@@ -266,25 +292,30 @@ const renderHandler = async ({indent: false, logLevel: params.logLevel},'Cleaning up and writing timings',);- await Promise.all([- fs.promises.rm(outputLocation, {recursive: true}),- fs.promises.rm(outputPath, {recursive: true}),- lambdaWriteFile({- bucketName: params.bucketName,- body: JSON.stringify(condensedTimingData as ChunkTimingData, null, 2),- key: lambdaTimingsKey({- renderId: params.renderId,- chunk: params.chunk,- rendered: endRendered,- start,+ await Promise.all(+ [+ fs.promises.rm(videoOutputLocation, {recursive: true}),+ audioOutputLocation+ ? fs.promises.rm(audioOutputLocation, {recursive: true})+ : null,+ fs.promises.rm(outputPath, {recursive: true}),+ lambdaWriteFile({+ bucketName: params.bucketName,+ body: JSON.stringify(condensedTimingData as ChunkTimingData, null, 2),+ key: lambdaTimingsKey({+ renderId: params.renderId,+ chunk: params.chunk,+ rendered: endRendered,+ start,+ }),+ region: getCurrentRegionInFunction(),+ privacy: 'private',+ expectedBucketOwner: options.expectedBucketOwner,+ downloadBehavior: null,+ customCredentials: null,}),- region: getCurrentRegionInFunction(),- privacy: 'private',- expectedBucketOwner: options.expectedBucketOwner,- downloadBehavior: null,- customCredentials: null,- }),- ]);+ ].filter(truthy),+ );RenderInternals.Log.verbose({indent: false, logLevel: params.logLevel},'Done!',diff --git a/packages/lambda/src/functions/still.ts b/packages/lambda/src/functions/still.tsindex c4ff37335a..3de54bd92f 100644--- a/packages/lambda/src/functions/still.ts+++ b/packages/lambda/src/functions/still.ts@@ -158,8 +158,6 @@ const innerStillHandler = async ({renderId,outName: lambdaParams.outName ?? undefined,privacy: lambdaParams.privacy,- everyNthFrame: 1,- frameRange: [lambdaParams.frame, lambdaParams.frame],audioCodec: null,deleteAfter: lambdaParams.deleteAfter,numberOfGifLoops: null,diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.tsindex 7ea4ff1fc1..72d3b5144c 100644--- a/packages/lambda/src/shared/constants.ts+++ b/packages/lambda/src/shared/constants.ts@@ -115,10 +115,12 @@ export const chunkKey = (renderId: string) =>export const chunkKeyForIndex = ({renderId,index,+ type,}: {renderId: string;index: number;-}) => `${chunkKey(renderId)}:${String(index).padStart(8, '0')}`;+ type: 'video' | 'audio';+}) => `${chunkKey(renderId)}:${String(index).padStart(8, '0')}:${type}`;export const getErrorKeyPrefix = (renderId: string) =>`${rendersPrefix(renderId)}/errors/`;@@ -450,6 +452,9 @@ type Discriminated =| {type: 'video';imageFormat: VideoImageFormat;+ muted: boolean;+ frameRange: [number, number];+ everyNthFrame: number;};export type RenderMetadata = Discriminated & {@@ -470,8 +475,6 @@ export type RenderMetadata = Discriminated & {renderId: string;outName: OutNameInputWithoutCredentials | undefined;privacy: Privacy;- frameRange: [number, number];- everyNthFrame: number;deleteAfter: DeleteAfter | null;numberOfGifLoops: number | null;audioBitrate: string | null;diff --git a/packages/lambda/src/shared/parse-chunk-key.ts b/packages/lambda/src/shared/parse-chunk-key.tsindex 4762aea01e..da44d11711 100644--- a/packages/lambda/src/shared/parse-chunk-key.ts+++ b/packages/lambda/src/shared/parse-chunk-key.ts@@ -1,5 +1,7 @@export const parseLambdaChunkKey = (key: string) => {- const match = key.match(/^renders\/(.*)\/chunks\/chunk:([0-9]+)$/);+ const match = key.match(+ /^renders\/(.*)\/chunks\/chunk:([0-9]+):(video|audio)$/,+ );if (!match) {throw new Error(`Cannot parse filename ${key} into timing information. Malformed data.`,@@ -9,5 +11,6 @@ export const parseLambdaChunkKey = (key: string) => {return {renderId: match[1],chunk: Number(match[2]),+ type: match[3],};};diff --git a/packages/lambda/src/test/unit/expected-out-name.test.ts b/packages/lambda/src/test/unit/expected-out-name.test.tsindex ac23f384a3..dee5e2162c 100644--- a/packages/lambda/src/test/unit/expected-out-name.test.ts+++ b/packages/lambda/src/test/unit/expected-out-name.test.ts@@ -42,6 +42,7 @@ const testRenderMetadata: RenderMetadata = {numberOfGifLoops: null,downloadBehavior: {type: 'play-in-browser'},audioBitrate: null,+ muted: false,};test('Should get a custom outname', () => {diff --git a/packages/lambda/src/test/unit/lambda-chunk-key.test.ts b/packages/lambda/src/test/unit/lambda-chunk-key.test.tsindex d22e408bb5..8865e9ab90 100644--- a/packages/lambda/src/test/unit/lambda-chunk-key.test.ts+++ b/packages/lambda/src/test/unit/lambda-chunk-key.test.ts@@ -8,10 +8,12 @@ test('Should be able to parse Lambda key', () => {chunkKeyForIndex({index: 1111,renderId: 'abcdef',+ type: 'video',}),),).toEqual({chunk: 1111,renderId: 'abcdef',+ type: 'video',});});diff --git a/packages/lambda/src/test/unit/price-calculation.test.ts b/packages/lambda/src/test/unit/price-calculation.test.tsindex beb5d8b03e..175433c0ba 100644--- a/packages/lambda/src/test/unit/price-calculation.test.ts+++ b/packages/lambda/src/test/unit/price-calculation.test.ts@@ -53,6 +53,7 @@ test('Should not throw while calculating prices when time shifts occur', () => {audioCodec: null,downloadBehavior: {type: 'play-in-browser'},numberOfGifLoops: null,+ muted: false,},outputFileMetadata: {url: 'out.mp4',diff --git a/packages/renderer/src/get-extension-from-audio-codec.ts b/packages/renderer/src/get-extension-from-audio-codec.tsnew file mode 100644index 0000000000..739b0ef1da--- /dev/null+++ b/packages/renderer/src/get-extension-from-audio-codec.ts@@ -0,0 +1,21 @@+import type {AudioCodec} from './audio-codec';++export const getExtensionFromAudioCodec = (audioCodec: AudioCodec) => {+ if (audioCodec === 'aac') {+ return 'aac';+ }++ if (audioCodec === 'opus') {+ return 'opus';+ }++ if (audioCodec === 'mp3') {+ return 'mp3';+ }++ if (audioCodec === 'pcm-16') {+ return 'wav';+ }++ throw new Error(`Unsupported audio codec: ${audioCodec}`);+};diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex 2b737c5950..56e942f143 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -134,6 +134,7 @@ export {OnStartData, RenderFramesOutput} from './types';export {validateOutputFilename} from './validate-output-filename';import {makeDownloadMap} from './assets/download-map';+import {getExtensionFromAudioCodec} from './get-extension-from-audio-codec';import {validatePuppeteerTimeout} from './validate-puppeteer-timeout';import {validateBitrate} from './validate-videobitrate';import {@@ -222,6 +223,7 @@ export const RenderInternals = {getChromiumGpuInformation,getPortConfig,makeDownloadMap,+ getExtensionFromAudioCodec,};// Warn of potential performance issues with Apple Silicon (M1 chip under Rosetta)diff --git a/packages/renderer/src/render-media.ts b/packages/renderer/src/render-media.tsindex 43cd854911..8b80c4b0af 100644--- a/packages/renderer/src/render-media.ts+++ b/packages/renderer/src/render-media.ts@@ -124,6 +124,7 @@ export type InternalRenderMediaOptions = {concurrency: number | string | null;finishRenderProgress: () => void;binariesDirectory: string | null;+ separateAudioTo: string | null;} & MoreRenderMediaOptions;type Prettify<T> = {@@ -179,6 +180,7 @@ export type RenderMediaOptions = Prettify<{colorSpace?: ColorSpace;repro?: boolean;binariesDirectory?: string | null;+ separateAudioTo?: string | null;}> &Partial<MoreRenderMediaOptions>;@@ -238,6 +240,7 @@ const internalRenderMediaRaw = ({repro,finishRenderProgress,binariesDirectory,+ separateAudioTo,}: InternalRenderMediaOptions): Promise<RenderMediaResult> => {if (repro) {enableRepro({@@ -689,6 +692,7 @@ const internalRenderMediaRaw = ({x264Preset: x264Preset ?? null,colorSpace,binariesDirectory,+ separateAudioTo,}),stitchStart,]);@@ -837,6 +841,7 @@ export const renderMedia = ({colorSpace,repro,binariesDirectory,+ separateAudioTo,}: RenderMediaOptions): Promise<RenderMediaResult> => {if (quality !== undefined) {console.warn(@@ -903,5 +908,6 @@ export const renderMedia = ({repro: repro ?? false,finishRenderProgress: () => undefined,binariesDirectory: binariesDirectory ?? null,+ separateAudioTo: separateAudioTo ?? null,});};diff --git a/packages/renderer/src/stitch-frames-to-video.ts b/packages/renderer/src/stitch-frames-to-video.tsindex d95bf4c92f..fa7d44e7b2 100644--- a/packages/renderer/src/stitch-frames-to-video.ts+++ b/packages/renderer/src/stitch-frames-to-video.ts@@ -1,4 +1,4 @@-import {cpSync, promises} from 'node:fs';+import {cpSync, promises, rmSync} from 'node:fs';import path from 'node:path';import {VERSION} from 'remotion/version';import type {RenderMediaOnDownload} from './assets/download-and-map-assets-to-file';@@ -67,6 +67,7 @@ type InternalStitchFramesToVideoOptions = {ffmpegOverride: null | FfmpegOverrideFn;colorSpace: ColorSpace;binariesDirectory: string | null;+ separateAudioTo: string | null;};export type StitchFramesToVideoOptions = {@@ -96,6 +97,7 @@ export type StitchFramesToVideoOptions = {x264Preset?: X264Preset | null;colorSpace?: ColorSpace;binariesDirectory?: string | null;+ separateAudioTo?: string | null;};type ReturnType = Promise<Buffer | null>;@@ -131,6 +133,7 @@ const innerStitchFramesToVideo = async (x264Preset,colorSpace,binariesDirectory,+ separateAudioTo,}: InternalStitchFramesToVideoOptions,remotionRoot: string,): Promise<ReturnType> => {@@ -278,6 +281,12 @@ const innerStitchFramesToVideo = async ();}+ if (separateAudioTo) {+ throw new Error(+ '`separateAudioTo` was set, but this render was audio-only. This option is meant to be used for video renders.',+ );+ }+cpSync(audio, outputLocation ?? (tempFile as string));onProgress?.(expectedFrames);deleteDirectory(path.dirname(audio));@@ -312,7 +321,7 @@ const innerStitchFramesToVideo = async (? ['-filter_complex', 'split[v],palettegen,[v]paletteuse']: null,]),- audio ? ['-i', audio, '-c:a', 'copy'] : null,+ audio && !separateAudioTo ? ['-i', audio, '-c:a', 'copy'] : null,numberOfGifLoops === null? null: ['-loop', convertNumberOfGifLoopsToFfmpegSyntax(numberOfGifLoops)],@@ -391,6 +400,19 @@ const innerStitchFramesToVideo = async (}});+ if (separateAudioTo) {+ if (!audio) {+ throw new Error(+ `\`separateAudioTo\` was set to ${JSON.stringify(+ separateAudioTo,+ )}, but this render included no audio`,+ );+ }++ cpSync(audio, separateAudioTo);+ rmSync(audio);+ }+return new Promise<Buffer | null>((resolve, reject) => {task.once('close', (code, signal) => {if (code === 0) {@@ -472,6 +494,7 @@ export const stitchFramesToVideo = ({x264Preset,colorSpace,binariesDirectory,+ separateAudioTo,}: StitchFramesToVideoOptions): Promise<Buffer | null> => {return internalStitchFramesToVideo({assetsInfo,@@ -503,5 +526,6 @@ export const stitchFramesToVideo = ({x264Preset: x264Preset ?? null,colorSpace: colorSpace ?? 'default',binariesDirectory: binariesDirectory ?? null,+ separateAudioTo: separateAudioTo ?? null,});};