Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/lambda`: Add `separateAudioTo` to `renderMediaOnLambda()`

Jonny Burgera2e9d3d4a701
diff --git a/packages/docs/docs/lambda/cli/render.mdx b/packages/docs/docs/lambda/cli/render.mdx
index e31a1249b4..9c0833ba8d 100644
--- a/packages/docs/docs/lambda/cli/render.mdx
+++ b/packages/docs/docs/lambda/cli/render.mdx
@@ -233,6 +233,16 @@ A number describing how long the render may take to resolve all [`delayRender()`
The file name of the media output as stored in the S3 bucket. By default, it is `out` plus the appropriate file extension, for example: `out.mp4`. Must match `/([0-9a-zA-Z-!_.*'()/]+)/g`.
+### `--separate-audio-to`<AvailableFrom v="4.0.535" />
+
+Save the mixed audio as a separate file in the render bucket and omit the audio track from the video. The value is a cloud output name, such as `audio.wav`, saved under `renders/{renderId}/audio.wav`.
+
+```bash title="Render separate video and audio outputs"
+bunx remotion lambda render <serve-url> <composition-id> --codec=h264 --out-name=video.mp4 --separate-audio-to=audio.wav
+```
+
+The CLI prints the audio output first, followed by the video, with a link and file size for each. A positional output location downloads the main output. See [`separateAudioTo`](/docs/lambda/rendermediaonlambda#separateaudioto) for supported formats and restrictions.
+
### `--s3-output-provider-endpoint`
The endpoint for an [`s3OutputProvider`](/docs/lambda/custom-destination#saving-to-another-cloud). Use it to save the rendered media to an S3-compatible provider such as Cloudflare R2.
diff --git a/packages/docs/docs/lambda/deleterender.mdx b/packages/docs/docs/lambda/deleterender.mdx
index 6a13eef52d..c886c5a37b 100644
--- a/packages/docs/docs/lambda/deleterender.mdx
+++ b/packages/docs/docs/lambda/deleterender.mdx
@@ -6,7 +6,7 @@ slug: /lambda/deleterender
crumb: 'Lambda API'
---
-Deletes a rendered video, audio or still and its associated metada.
+Deletes a rendered video, audio or still and its associated metadata. If [`separateAudioTo`](/docs/lambda/rendermediaonlambda#separateaudioto) was used, both output files are deleted, including outputs in custom destinations.
```ts twoslash
import {deleteRender} from '@remotion/lambda';
@@ -40,6 +40,10 @@ The ID of the render. You can retrieve this ID by calling [`renderMediaOnLambda(
If the render was saved to a [different cloud](/docs/lambda/custom-destination#saving-to-another-cloud), pass an object with the same `endpoint`, `accessKeyId` and `secretAccessKey` as you passed to [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda#outname) or [`renderStillOnLambda()`](/docs/lambda/renderstillonlambda#outname).
+### `separateAudioCredentials?`<AvailableFrom v="4.0.535" />
+
+Credentials for a separate audio output saved to a different S3-compatible provider. Pass the same `endpoint`, `accessKeyId` and `secretAccessKey` as in [`separateAudioTo.s3OutputProvider`](/docs/lambda/rendermediaonlambda#separateaudioto). Defaults to `customCredentials` when omitted.
+
### `forcePathStyle?`<AvailableFrom v="4.0.202" />
Passes `forcePathStyle` to the AWS S3 client. If you don't know what this is, you probably don't need it.
diff --git a/packages/docs/docs/lambda/downloadmedia.mdx b/packages/docs/docs/lambda/downloadmedia.mdx
index 0d36ba744e..f7074a822b 100644
--- a/packages/docs/docs/lambda/downloadmedia.mdx
+++ b/packages/docs/docs/lambda/downloadmedia.mdx
@@ -47,6 +47,10 @@ The ID of the render. You can retrieve this ID by calling [`renderMediaOnLambda(
Where the video should be saved. Pass an absolute path, or it will be resolved relative to your current working directory.
+### `output?`<AvailableFrom v="4.0.535" />
+
+Select the output to download: `"main"` (the default) or `"separate-audio"` for a render started with [`separateAudioTo`](/docs/lambda/rendermediaonlambda#separateaudioto). Selecting separate audio for a render without that output throws an error.
+
### `onProgress?`
Callback function that gets called with the following properties:
@@ -59,6 +63,8 @@ Callback function that gets called with the following properties:
If the render was saved to a [different cloud](/docs/lambda/custom-destination#saving-to-another-cloud), pass an object with the same `endpoint`, `accessKeyId` and `secretAccessKey` as you passed to [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda#outname) or [`renderStillOnLambda()`](/docs/lambda/renderstillonlambda#outname).
+When downloading `"separate-audio"`, pass the credentials for its destination.
+
### `signal?`<AvailableFrom v="4.0.406" />
An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that allows the download to be cancelled.
diff --git a/packages/docs/docs/lambda/getrenderprogress.mdx b/packages/docs/docs/lambda/getrenderprogress.mdx
index ce13c1866e..08b5053a3c 100644
--- a/packages/docs/docs/lambda/getrenderprogress.mdx
+++ b/packages/docs/docs/lambda/getrenderprogress.mdx
@@ -110,6 +110,26 @@ In which bucket the render and other artifacts get saved.
`null` if the video is not yet rendered, a `string` containing a URL pointing to the final artifact if the video finished rendering.
+### `separateAudio`<AvailableFrom v="4.0.535" />
+
+Details of the audio output when [`separateAudioTo`](/docs/lambda/rendermediaonlambda#separateaudioto) was used. Returns `null` until the render completes, or when no separate audio output was requested. `done` becomes `true` after both outputs have uploaded successfully.
+
+#### `url`
+
+The URL of the audio file. Private outputs require credentials to download.
+
+#### `bucketName`
+
+The bucket containing the audio output.
+
+#### `key`
+
+The storage key of the audio output.
+
+#### `sizeInBytes`
+
+The size of the audio file in bytes. `outputFile` and `outputSizeInBytes` continue to describe the main output.
+
### `outKey`
`null` if the video is not yet rendered, a `string` containing the S3 key where the final artifact is stored.
diff --git a/packages/docs/docs/lambda/rendermediaonlambda.mdx b/packages/docs/docs/lambda/rendermediaonlambda.mdx
index 69793f1a71..751d61b35a 100644
--- a/packages/docs/docs/lambda/rendermediaonlambda.mdx
+++ b/packages/docs/docs/lambda/rendermediaonlambda.mdx
@@ -256,6 +256,32 @@ It can either be:
- A `string` - it will get saved to the same S3 bucket as your site under the key `renders/{renderId}/{outName}`. Make sure to include the file extension at the end of the string.
- An object if you want to render to a different bucket or cloud provider - [see here for detailed instructions](/docs/lambda/custom-destination).
+### `separateAudioTo?`<AvailableFrom v="4.0.535" />
+
+Save the mixed audio as a separate file and omit the audio track from the video. By default, audio is included in the video.
+
+A string such as `"audio.wav"` saves to `renders/{renderId}/audio.wav` in the render bucket. An object with `bucketName`, `key` and an optional `s3OutputProvider` supports a [custom destination](/docs/lambda/custom-destination), using the same rules as [`outName`](/docs/lambda/rendermediaonlambda#outname).
+
+```ts twoslash title="Render video and audio separately"
+import {renderMediaOnLambda} from '@remotion/lambda/client';
+
+await renderMediaOnLambda({
+ region: 'us-east-1',
+ functionName: 'remotion-render-4-0-535-mem2048mb-disk2048mb-120sec',
+ serveUrl: 'https://remotionlambda-example.s3.us-east-1.amazonaws.com/sites/my-site/index.html',
+ composition: 'MyVideo',
+ codec: 'h264',
+ outName: 'video.mp4',
+ separateAudioTo: 'audio.wav',
+});
+```
+
+The filename extension selects the audio format: `.wav` uses PCM, `.aac`, `.m4a`, `.m4b` and `.3gp` use AAC, `.mp3` uses MP3, and `.opus` uses Opus. Existing [audio codec compatibility rules](/docs/audio-codec) apply. Conflicting `audioCodec` or `preferLossless` settings throw an error.
+
+A composition without audio produces a silent audio file. Audio-only renders, codecs without audio support, and `muted: true` cannot be combined with this option. Both outputs use the specified privacy, storage class and overwrite behavior.
+
+Read [`getRenderProgress() -> separateAudio`](/docs/lambda/getrenderprogress#separateaudio) to get the audio destination. Both outputs must be uploaded before the render is complete.
+
### `timeoutInMilliseconds?`
A number describing how long the render may take to resolve all [`delayRender()`](/docs/delay-render) calls [before it times out](/docs/timeout). Default: `30000`
diff --git a/packages/docs/docs/lambda/webhooks.mdx b/packages/docs/docs/lambda/webhooks.mdx
index f8feb1c7da..1da47d9b54 100644
--- a/packages/docs/docs/lambda/webhooks.mdx
+++ b/packages/docs/docs/lambda/webhooks.mdx
@@ -59,6 +59,12 @@ export type WebhookSuccessPayload = StaticWebhookPayload & {
lambdaErrors: EnhancedErrorInfo[];
outputUrl: string | undefined;
outputFile: string | undefined;
+ separateAudio: {
+ url: string;
+ bucketName: string;
+ key: string;
+ sizeInBytes: number;
+ } | null;
timeToFinish: number | undefined;
costs: AfterRenderCost;
};
@@ -104,6 +110,10 @@ The `outputUrl`, `outputFile` and `timeToFinish` keys are only returned if the r
The `errors` array will contain the error message and stack trace of any _fatal_ error that occurs during the render process.
+### `separateAudio`<AvailableFrom v="4.0.535" />
+
+Successful renders include the same [`separateAudio`](/docs/lambda/getrenderprogress#separateaudio) details as [`getRenderProgress()`](/docs/lambda/getrenderprogress). The value is `null` when no separate audio output was requested. A success webhook is sent after both output files have uploaded.
+
## Validate Webhooks
Remotion will sign all webhook requests if you provide a webhook secret in the CLI arguments.
diff --git a/packages/docs/docs/options/separate-audio-to.mdx b/packages/docs/docs/options/separate-audio-to.mdx
index ea58570df0..b76c280202 100644
--- a/packages/docs/docs/options/separate-audio-to.mdx
+++ b/packages/docs/docs/options/separate-audio-to.mdx
@@ -9,7 +9,7 @@ custom_edit_url: https://github.com/remotion-dev/remotion/edit/main/packages/ren
# Separate audio to<AvailableFrom v="4.0.123" />
-If set, the audio will not be included in the main output but rendered as a separate file at the location you pass. If the render contains no audio, a silent audio file is produced even when enforceAudioTrack is false. The muted option still takes precedence. It is recommended to use an absolute path. If a relative path is passed, it is relative to the Remotion Root.
+If set, the audio will not be included in the main output but rendered as a separate file at the location you pass. If the render contains no audio, a silent audio file is produced even when enforceAudioTrack is false. Audio-only renders, muted renders and codecs without audio support cannot use this option. For local renders, use an absolute path; relative paths are resolved against the Remotion Root. On Lambda, pass an output name or custom destination as described in renderMediaOnLambda().
## CLI flag
@@ -20,11 +20,13 @@ If set, the audio will not be included in the main output but rendered as a sepa
The following CLI commands accept this option:
- [`remotion render`](/docs/cli/render)
+- [`remotion lambda render`](/docs/lambda/cli/render)
## APIs that have this option
The following APIs accept this option:
+- [`renderMediaOnLambda()`](/docs/lambda/rendermediaonlambda#separateaudioto)
- [`renderMedia()`](/docs/renderer/render-media#separateaudioto)
- [`stitchFramesToVideo()`](/docs/renderer/stitch-frames-to-video#separateaudioto)
diff --git a/packages/it-tests/src/monorepo/go-package.test.ts b/packages/it-tests/src/monorepo/go-package.test.ts
index 753d9cd7c9..6f1d2cc206 100644
--- a/packages/it-tests/src/monorepo/go-package.test.ts
+++ b/packages/it-tests/src/monorepo/go-package.test.ts
@@ -65,6 +65,7 @@ test(
offthreadVideoCacheSizeInBytes: null,
offthreadVideoThreads: null,
outName: null,
+ separateAudioTo: null,
overwrite: false,
pixelFormat: undefined,
privacy: 'public',
@@ -94,7 +95,12 @@ test(
sampleRate: 48000,
});
- expect(removeUndefined(parsed)).toEqual(removeUndefined(nativeVersion));
+ expect(
+ removeUndefined({
+ ...parsed,
+ separateAudioTo: parsed.separateAudioTo ?? null,
+ }),
+ ).toEqual(removeUndefined(nativeVersion));
},
{timeout: 60000},
);
diff --git a/packages/it-tests/src/monorepo/php-package.test.ts b/packages/it-tests/src/monorepo/php-package.test.ts
index a8cbfa11a5..333106cee5 100644
--- a/packages/it-tests/src/monorepo/php-package.test.ts
+++ b/packages/it-tests/src/monorepo/php-package.test.ts
@@ -133,6 +133,7 @@ class Semantic
offthreadVideoCacheSizeInBytes: null,
offthreadVideoThreads: null,
outName: null,
+ separateAudioTo: null,
overwrite: false,
pixelFormat: undefined,
privacy: 'public',
@@ -168,6 +169,7 @@ class Semantic
expect({
...parsedJson,
+ separateAudioTo: parsedJson.separateAudioTo ?? null,
type: 'start',
}).toEqual(nativeVersion);
});
diff --git a/packages/it-tests/src/monorepo/python-package.test.ts b/packages/it-tests/src/monorepo/python-package.test.ts
index 366d575f38..756743950a 100644
--- a/packages/it-tests/src/monorepo/python-package.test.ts
+++ b/packages/it-tests/src/monorepo/python-package.test.ts
@@ -102,6 +102,7 @@ test('Python package should create the same renderMedia payload as normal Lambda
offthreadVideoCacheSizeInBytes: null,
offthreadVideoThreads: null,
outName: null,
+ separateAudioTo: null,
overwrite: false,
pixelFormat: undefined,
privacy: 'public',
@@ -138,6 +139,7 @@ test('Python package should create the same renderMedia payload as normal Lambda
expect({
...parsedJson,
+ separateAudioTo: parsedJson.separateAudioTo ?? null,
type: 'start',
}).toEqual(nativeVersion);
});
diff --git a/packages/it-tests/src/monorepo/ruby-package.test.ts b/packages/it-tests/src/monorepo/ruby-package.test.ts
index a36ebda96e..e47dc20331 100644
--- a/packages/it-tests/src/monorepo/ruby-package.test.ts
+++ b/packages/it-tests/src/monorepo/ruby-package.test.ts
@@ -114,6 +114,7 @@ test('Render Media payload', async () => {
offthreadVideoCacheSizeInBytes: null,
offthreadVideoThreads: null,
outName: null,
+ separateAudioTo: null,
overwrite: false,
pixelFormat: undefined,
privacy: 'public',
@@ -148,7 +149,11 @@ test('Render Media payload', async () => {
sampleRate: 48000,
});
- expect(JSON.parse(output)).toEqual(nativeVersion);
+ const parsedOutput = JSON.parse(output);
+ expect({
+ ...parsedOutput,
+ separateAudioTo: parsedOutput.separateAudioTo ?? null,
+ }).toEqual(nativeVersion);
});
test('Render Still payload', async () => {
diff --git a/packages/lambda-client/src/delete-render.ts b/packages/lambda-client/src/delete-render.ts
index b1834c3ef7..05f2709c41 100644
--- a/packages/lambda-client/src/delete-render.ts
+++ b/packages/lambda-client/src/delete-render.ts
@@ -17,6 +17,7 @@ export type DeleteRenderInput = {
bucketName: string;
renderId: string;
customCredentials?: CustomCredentials<AwsProvider>;
+ separateAudioCredentials?: CustomCredentials<AwsProvider>;
forcePathStyle?: boolean;
requestHandler?: RequestHandler;
};
@@ -45,21 +46,38 @@ export const internalDeleteRender = async (
return {freedBytes: 0};
}
- const {key, renderBucketName, customCredentials} = getExpectedOutName({
+ const mainOutput = getExpectedOutName({
+ output: 'main',
renderMetadata: progress.renderMetadata,
bucketName: input.bucketName,
customCredentials: input.customCredentials ?? null,
bucketNamePrefix: REMOTION_BUCKET_PREFIX,
});
+ const separateAudioOutput =
+ (progress.renderMetadata.separateAudioTo ?? null) === null
+ ? null
+ : getExpectedOutName({
+ output: 'separate-audio',
+ renderMetadata: progress.renderMetadata,
+ bucketName: input.bucketName,
+ customCredentials:
+ input.separateAudioCredentials ?? input.customCredentials ?? null,
+ bucketNamePrefix: REMOTION_BUCKET_PREFIX,
+ });
- await input.providerSpecifics.deleteFile({
- bucketName: renderBucketName,
- customCredentials,
- key,
- region: input.region,
- forcePathStyle: input.forcePathStyle,
- requestHandler: input.requestHandler,
- });
+ for (const {key, renderBucketName, customCredentials} of [
+ mainOutput,
+ ...(separateAudioOutput === null ? [] : [separateAudioOutput]),
+ ]) {
+ await input.providerSpecifics.deleteFile({
+ bucketName: renderBucketName,
+ customCredentials,
+ key,
+ region: input.region,
+ forcePathStyle: input.forcePathStyle,
+ requestHandler: input.requestHandler,
+ });
+ }
let files = await input.providerSpecifics.listObjects({
bucketName: input.bucketName,
diff --git a/packages/lambda-client/src/get-output-url-from-metadata.ts b/packages/lambda-client/src/get-output-url-from-metadata.ts
index f52ca16442..dc65882fc0 100644
--- a/packages/lambda-client/src/get-output-url-from-metadata.ts
+++ b/packages/lambda-client/src/get-output-url-from-metadata.ts
@@ -9,13 +9,28 @@ export const getOutputUrlFromMetadata: GetOutputUrl<AwsProvider> = ({
bucketName,
customCredentials,
currentRegion,
+ output,
}) => {
- const {key, renderBucketName} = getExpectedOutName({
+ const {
+ key,
+ renderBucketName,
+ customCredentials: credentials,
+ } = getExpectedOutName({
renderMetadata,
bucketName,
customCredentials,
bucketNamePrefix: REMOTION_BUCKET_PREFIX,
+ output,
});
+ if (credentials !== null) {
+ const url = new URL(credentials.endpoint);
+ if (!credentials.forcePathStyle) {
+ url.hostname = `${renderBucketName}.${url.hostname}`;
+ }
+
+ url.pathname = `${url.pathname.replace(/\/$/, '')}/${credentials.forcePathStyle ? `${renderBucketName}/` : ''}${key.split('/').map(encodeURIComponent).join('/')}`;
+ return {url: url.toString(), key};
+ }
const {dnsSuffix} = getAwsRegionMetadata(currentRegion);
return {
diff --git a/packages/lambda-client/src/get-render-progress.ts b/packages/lambda-client/src/get-render-progress.ts
index 330c2aba6c..2db030bcc9 100644
--- a/packages/lambda-client/src/get-render-progress.ts
+++ b/packages/lambda-client/src/get-render-progress.ts
@@ -62,5 +62,5 @@ export const getRenderProgress = async (
timeoutInTest: 120000,
requestHandler: input.requestHandler,
});
- return result;
+ return {...result, separateAudio: result.separateAudio ?? null};
};
diff --git a/packages/lambda-client/src/make-lambda-payload.ts b/packages/lambda-client/src/make-lambda-payload.ts
index 0488419a67..5c04f35e62 100644
--- a/packages/lambda-client/src/make-lambda-payload.ts
+++ b/packages/lambda-client/src/make-lambda-payload.ts
@@ -63,6 +63,7 @@ export type InnerRenderMediaOnLambdaInput = {
logLevel: LogLevel;
frameRange: SingleFrameRange | null;
outName: OutNameInput<AwsProvider> | null;
+ separateAudioTo: OutNameInput<AwsProvider> | null;
timeoutInMilliseconds: number;
chromiumOptions: ChromiumOptions;
scale: number;
@@ -120,6 +121,7 @@ export const makeLambdaRenderMediaPayload = async ({
privacy,
logLevel,
outName,
+ separateAudioTo,
timeoutInMilliseconds,
chromiumOptions,
scale,
@@ -208,6 +210,7 @@ export const makeLambdaRenderMediaPayload = async ({
logLevel,
frameRange,
outName,
+ separateAudioTo,
timeoutInMilliseconds,
chromiumOptions,
scale,
diff --git a/packages/lambda-client/src/render-media-on-lambda.ts b/packages/lambda-client/src/render-media-on-lambda.ts
index a7837cae0a..c74a452923 100644
--- a/packages/lambda-client/src/render-media-on-lambda.ts
+++ b/packages/lambda-client/src/render-media-on-lambda.ts
@@ -55,6 +55,7 @@ export type RenderMediaOnLambdaInput = {
concurrency?: number;
frameRange?: SingleFrameRange;
outName?: OutNameInput<AwsProvider>;
+ separateAudioTo?: OutNameInput<AwsProvider>;
chromiumOptions?: Omit<ChromiumOptions, 'enableMultiProcessOnLinux'>;
scale?: number;
everyNthFrame?: number;
@@ -195,6 +196,7 @@ export const renderMediaOnLambdaOptionalToRequired = (
offthreadVideoCacheSizeInBytes:
options.offthreadVideoCacheSizeInBytes ?? null,
outName: options.outName ?? null,
+ separateAudioTo: options.separateAudioTo ?? null,
overwrite: options.overwrite,
pixelFormat: options.pixelFormat ?? undefined,
privacy: options.privacy ?? 'public',
diff --git a/packages/lambda-client/src/test/aws-china-regions.test.ts b/packages/lambda-client/src/test/aws-china-regions.test.ts
index e2f58c5abe..3086f87152 100644
--- a/packages/lambda-client/src/test/aws-china-regions.test.ts
+++ b/packages/lambda-client/src/test/aws-china-regions.test.ts
@@ -111,10 +111,13 @@ test('AWS service and Console URLs use the region partition metadata', () => {
).toBe('https://bucket.s3.cn-north-1.amazonaws.com.cn/sites/site/index.html');
expect(
getOutputUrlFromMetadata({
+ output: 'main',
bucketName: 'bucket',
customCredentials: null,
currentRegion: 'cn-north-1',
renderMetadata: {
+ separateAudioTo: null,
+ separateAudioOutputFileIsConditional: null,
outputFileIsConditional: null,
outName: 'out.mp4',
privacy: 'public',
diff --git a/packages/lambda-client/src/test/concurrency-payload.test.ts b/packages/lambda-client/src/test/concurrency-payload.test.ts
index 102da2009a..2203de3012 100644
--- a/packages/lambda-client/src/test/concurrency-payload.test.ts
+++ b/packages/lambda-client/src/test/concurrency-payload.test.ts
@@ -27,6 +27,7 @@ test('Should include concurrency field in payload', async () => {
logLevel: 'info',
frameRange: null,
outName: null,
+ separateAudioTo: null,
timeoutInMilliseconds: 30000,
chromiumOptions: {},
scale: 1,
@@ -93,6 +94,7 @@ test('Should handle null concurrency', async () => {
logLevel: 'info',
frameRange: null,
outName: null,
+ separateAudioTo: null,
timeoutInMilliseconds: 30000,
chromiumOptions: {},
scale: 1,
diff --git a/packages/lambda-client/src/test/price-calculation.test.ts b/packages/lambda-client/src/test/price-calculation.test.ts
index a7a947dea5..3d5966f263 100644
--- a/packages/lambda-client/src/test/price-calculation.test.ts
+++ b/packages/lambda-client/src/test/price-calculation.test.ts
@@ -10,6 +10,8 @@ test('Should not throw while calculating prices when time shifts occur', () => {
const price = estimatePriceFromMetadata({
memorySizeInMb: 1024,
renderMetadata: {
+ separateAudioTo: null,
+ separateAudioOutputFileIsConditional: null,
outputFileIsConditional: null,
audioBitrate: null,
codec: 'h264',
diff --git a/packages/lambda/src/api/download-media.ts b/packages/lambda/src/api/download-media.ts
index ab268b3180..0b3c62b3d5 100644
--- a/packages/lambda/src/api/download-media.ts
+++ b/packages/lambda/src/api/download-media.ts
@@ -9,6 +9,7 @@ import {
getExpectedOutName,
getOverallProgressFromStorage,
type CustomCredentials,
+ type RenderOutput,
} from '@remotion/serverless';
import type {LambdaReadFileProgress} from '../functions/helpers/read-with-progress';
import {lambdaDownloadFileWithProgress} from '../functions/helpers/read-with-progress';
@@ -24,6 +25,7 @@ type InternalDownloadMediaInput = {
forcePathStyle: boolean;
requestHandler: RequestHandler | null;
signal: AbortSignal;
+ output: RenderOutput;
};
export type DownloadMediaInput = {
@@ -37,6 +39,7 @@ export type DownloadMediaInput = {
forcePathStyle?: boolean;
requestHandler?: RequestHandler;
signal?: AbortSignal;
+ output?: RenderOutput;
};
export type DownloadMediaOutput = {
@@ -71,6 +74,7 @@ export const internalDownloadMedia = async (
RenderInternals.ensureOutputDirectory(outputPath);
const {key, renderBucketName, customCredentials} = getExpectedOutName({
+ output: input.output,
renderMetadata: overallProgress.renderMetadata,
bucketName: input.bucketName,
customCredentials: input.customCredentials ?? null,
@@ -105,9 +109,18 @@ export const internalDownloadMedia = async (
export const downloadMedia = (
input: DownloadMediaInput,
): Promise<DownloadMediaOutput> => {
+ if (
+ input.output !== undefined &&
+ input.output !== 'main' &&
+ input.output !== 'separate-audio'
+ ) {
+ throw new Error('`output` must be "main" or "separate-audio".');
+ }
+
return internalDownloadMedia({
...input,
providerSpecifics: LambdaClientInternals.awsImplementation,
+ output: input.output ?? 'main',
forcePathStyle: false,
onProgress: input.onProgress ?? (() => undefined),
logLevel: input.logLevel ?? 'info',
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index 85b8dc1c74..96dc9435c4 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -81,6 +81,7 @@ const {
overrideDurationOption,
sampleRateOption,
enableCancellationOption,
+ separateAudioOption,
} = BrowserSafeApis.options;
export const renderCommand = async ({
@@ -349,6 +350,9 @@ export const renderCommand = async ({
s3OutputProvider,
});
const downloadName = args[2] ?? null;
+ const separateAudioTo = separateAudioOption.getValue({
+ commandLine: CliInternals.parsedCli,
+ }).value;
const {value: codec, source: reason} = videoCodecOption.getValue(
{
@@ -415,6 +419,7 @@ export const renderCommand = async ({
logLevel,
frameRange: singleFrameRange,
outName: resolvedOutName,
+ separateAudioTo,
timeoutInMilliseconds,
chromiumOptions,
scale,
@@ -645,6 +650,7 @@ export const renderCommand = async ({
if (downloadName) {
const downloadStart = Date.now();
const download = await internalDownloadMedia({
+ output: 'main',
bucketName: res.bucketName,
outPath: downloadName,
region: getAwsRegion(),
@@ -684,20 +690,23 @@ export const renderCommand = async ({
}
Log.info({indent: false, logLevel});
- Log.info(
- {indent: false, logLevel},
- CliInternals.chalk.blue('+ S3 '.padEnd(CliInternals.LABEL_WIDTH)),
- CliInternals.chalk.blue(
- CliInternals.makeHyperlink({
- fallback: newStatus.outputFile as string,
- text: newStatus.outKey as string,
- url: newStatus.outputFile as string,
- }),
- ),
- CliInternals.chalk.gray(
- CliInternals.formatBytes(newStatus.outputSizeInBytes as number),
- ),
- );
+ const separateAudio = newStatus.separateAudio ?? null;
+ for (const output of [
+ ...(separateAudio === null ? [] : [separateAudio]),
+ {
+ url: newStatus.outputFile as string,
+ key: newStatus.outKey as string,
+ sizeInBytes: newStatus.outputSizeInBytes as number,
+ },
+ ]) {
+ Log.info(
+ {indent: false, logLevel},
+ CliInternals.chalk.blue(
+ `${(separateAudio === null ? '+ S3' : '+').padEnd(CliInternals.LABEL_WIDTH)} ${CliInternals.makeHyperlink({fallback: output.url, text: output.key, url: output.url})}`,
+ ),
+ CliInternals.chalk.gray(CliInternals.formatBytes(output.sizeInBytes)),
+ );
+ }
if (downloadOrNothing) {
const relativeOutputPath = path.relative(
diff --git a/packages/lambda/src/cli/commands/still.ts b/packages/lambda/src/cli/commands/still.ts
index ef89e35835..ebd6437672 100644
--- a/packages/lambda/src/cli/commands/still.ts
+++ b/packages/lambda/src/cli/commands/still.ts
@@ -372,6 +372,7 @@ export const stillCommand = async ({
if (downloadName) {
const {outputPath, sizeInBytes} = await internalDownloadMedia({
+ output: 'main',
bucketName: res.bucketName,
outPath: downloadName,
region,
diff --git a/packages/lambda/src/cli/help.ts b/packages/lambda/src/cli/help.ts
index 5f9454c502..9ffc8eaa82 100644
--- a/packages/lambda/src/cli/help.ts
+++ b/packages/lambda/src/cli/help.ts
@@ -233,6 +233,7 @@ export const lambdaCommandHelp = [
'number-of-gif-loops',
'timeout',
'out-name',
+ 'separate-audio-to',
's3-output-provider-endpoint',
's3-output-provider-region',
's3-output-provider-force-path-style',
@@ -273,6 +274,8 @@ export const lambdaCommandHelp = [
{
'image-format': 'Video Image Format',
port: 'Set a custom port when selecting a composition interactively.',
+ 'separate-audio-to':
+ 'Save the mixed audio as a separate file in the render bucket and omit audio from the video.',
},
'video',
),
diff --git a/packages/lambda/src/test/integration/renders/old-version.test.ts b/packages/lambda/src/test/integration/renders/old-version.test.ts
index 2b22eecb6c..7a87645a31 100644
--- a/packages/lambda/src/test/integration/renders/old-version.test.ts
+++ b/packages/lambda/src/test/integration/renders/old-version.test.ts
@@ -29,6 +29,7 @@ test(
logLevel: 'warn',
maxRetries: 3,
outName: null,
+ separateAudioTo: null,
pixelFormat: 'yuv420p',
privacy: 'public',
proResProfile: null,
diff --git a/packages/lambda/src/test/integration/webhooks.test.ts b/packages/lambda/src/test/integration/webhooks.test.ts
index 5d3675892c..b1806c4146 100644
--- a/packages/lambda/src/test/integration/webhooks.test.ts
+++ b/packages/lambda/src/test/integration/webhooks.test.ts
@@ -56,6 +56,7 @@ test(
logLevel: 'warn',
maxRetries: 3,
outName: 'out.mp4',
+ separateAudioTo: null,
pixelFormat: 'yuv420p',
privacy: 'public',
proResProfile: undefined,
@@ -138,6 +139,7 @@ test(
outputUrl: 'https://s3.mock-region-1.amazonaws.com/bucket/mock.mp4',
lambdaErrors: [],
outputFile: 'https://s3.mock-region-1.amazonaws.com/bucket/mock.mp4',
+ separateAudio: null,
});
await close();
},
@@ -189,6 +191,7 @@ test(
logLevel: 'warn',
maxRetries: 3,
outName: 'out.mp4',
+ separateAudioTo: null,
pixelFormat: 'yuv420p',
privacy: 'public',
proResProfile: null,
diff --git a/packages/lambda/src/test/unit/x264-preset-default.test.ts b/packages/lambda/src/test/unit/x264-preset-default.test.ts
index 5c30cd48c7..292cbc2f51 100644
--- a/packages/lambda/src/test/unit/x264-preset-default.test.ts
+++ b/packages/lambda/src/test/unit/x264-preset-default.test.ts
@@ -39,6 +39,7 @@ const makeStartPayload = ({
logLevel: 'error',
frameRange: null,
outName: null,
+ separateAudioTo: null,
timeoutInMilliseconds: 30_000,
chromiumOptions: {},
scale: 1,
diff --git a/packages/renderer/src/combine-chunks.ts b/packages/renderer/src/combine-chunks.ts
index be286df3f3..0b55c4ca06 100644
--- a/packages/renderer/src/combine-chunks.ts
+++ b/packages/renderer/src/combine-chunks.ts
@@ -1,6 +1,6 @@
// Combine multiple video chunks, useful for decentralized rendering
-import {rmSync} from 'node:fs';
+import {copyFileSync, rmSync} from 'node:fs';
import {join} from 'node:path';
import {
canConcatAudioSeamlessly,
@@ -13,7 +13,9 @@ import {combineVideoStreamsSeamlessly} from './combine-video-streams-seamlessly'
import type {SingleFrameRange} from './frame-range';
import {getFramesToRender} 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 {getMp4BrandForExtension} from './get-mp4-brand';
import {isAudioCodec} from './is-audio-codec';
import type {LogLevel} from './log-level';
import {Log} from './logger';
@@ -89,24 +91,29 @@ export const internalCombineChunks = async ({
frameRange,
compositionDurationInFrames,
sampleRate,
+ separateAudioTo,
}: AllCombineChunksOptions & {
indent: boolean;
+ separateAudioTo: string | null;
}) => {
validateNumberOfGifLoops(numberOfGifLoops, codec);
- const filelistDir = tmpDir(REMOTION_FILELIST_TOKEN);
-
const shouldCreateVideo = !isAudioCodec(codec);
const resolvedAudioCodec = resolveAudioCodec({
setting: audioCodec,
codec,
preferLossless,
- separateAudioTo: null,
+ separateAudioTo,
});
const shouldCreateAudio =
resolvedAudioCodec !== null && audioFiles.length > 0;
+ if (separateAudioTo !== null && (!shouldCreateAudio || !shouldCreateVideo)) {
+ throw new Error(
+ 'Separate audio requires a video render with audio chunks.',
+ );
+ }
const seamlessVideo = canConcatVideoSeamlessly(codec);
const realFrameRange = getRealFrameRange(
@@ -122,11 +129,12 @@ export const internalCombineChunks = async ({
realFrameRange,
everyNthFrame,
).length;
+ const filelistDir = tmpDir(REMOTION_FILELIST_TOKEN);
const videoOutput = shouldCreateVideo
? join(
filelistDir,
- `video.${getFileExtensionFromCodec(codec, resolvedAudioCodec)}`,
+ `video.${getFileExtensionFromCodec(codec, separateAudioTo === null ? resolvedAudioCodec : null)}`,
)
: null;
@@ -172,56 +180,55 @@ export const internalCombineChunks = async ({
: 'normally'
}`,
);
- await Promise.all(
- [
- shouldCreateAudio && audioOutput
- ? createCombinedAudio({
- audioBitrate,
- filelistDir,
- files: audioFiles,
- indent,
- logLevel,
- output: audioOutput,
- resolvedAudioCodec,
- seamless: seamlessAudio,
- chunkDurationInSeconds,
- addRemotionMetadata: !shouldCreateVideo,
- binariesDirectory,
- fps,
- cancelSignal,
- onProgress: (frames) => {
- concatenatedAudio = frames;
- updateProgress();
- },
- sampleRate,
- })
- : null,
-
- shouldCreateVideo && !seamlessVideo && videoOutput
- ? combineVideoStreams({
- codec,
- filelistDir,
- fps,
- indent,
- logLevel,
- numberOfGifLoops,
- output: videoOutput,
- files: videoFiles,
- addRemotionMetadata: !shouldCreateAudio,
- binariesDirectory,
- cancelSignal,
- onProgress: (frames) => {
- concatenatedVideo = frames;
- updateProgress();
- },
- })
- : null,
- ].filter(truthy),
- );
-
try {
+ await Promise.all(
+ [
+ shouldCreateAudio && audioOutput
+ ? createCombinedAudio({
+ audioBitrate,
+ filelistDir,
+ files: audioFiles,
+ indent,
+ logLevel,
+ output: audioOutput,
+ resolvedAudioCodec,
+ seamless: seamlessAudio,
+ chunkDurationInSeconds,
+ addRemotionMetadata: !shouldCreateVideo,
+ binariesDirectory,
+ fps,
+ cancelSignal,
+ onProgress: (frames) => {
+ concatenatedAudio = frames;
+ updateProgress();
+ },
+ sampleRate,
+ })
+ : null,
+
+ shouldCreateVideo && !seamlessVideo && videoOutput
+ ? combineVideoStreams({
+ codec,
+ filelistDir,
+ fps,
+ indent,
+ logLevel,
+ numberOfGifLoops,
+ output: videoOutput,
+ files: videoFiles,
+ addRemotionMetadata: !shouldCreateAudio,
+ binariesDirectory,
+ cancelSignal,
+ onProgress: (frames) => {
+ concatenatedVideo = frames;
+ updateProgress();
+ },
+ })
+ : null,
+ ].filter(truthy),
+ );
await muxVideoAndAudio({
- audioOutput,
+ audioOutput: separateAudioTo === null ? audioOutput : null,
indent,
logLevel,
onProgress: (frames) => {
@@ -240,11 +247,33 @@ export const internalCombineChunks = async ({
audioCodec: resolvedAudioCodec,
sampleRate,
});
+ if (separateAudioTo !== null && audioOutput !== null) {
+ const extension =
+ getExtensionOfFilename(separateAudioTo)?.toLowerCase() ?? null;
+ if (getMp4BrandForExtension(extension)) {
+ await muxVideoAndAudio({
+ videoOutput: null,
+ audioOutput,
+ output: separateAudioTo,
+ indent,
+ logLevel,
+ onProgress: () => undefined,
+ binariesDirectory,
+ fps,
+ cancelSignal,
+ metadata: null,
+ numberOfGifLoops: null,
+ audioCodec: resolvedAudioCodec,
+ sampleRate,
+ });
+ } else {
+ copyFileSync(audioOutput, separateAudioTo);
+ }
+ }
+
onProgress({totalProgress: 1, frames: numberOfFrames});
- rmSync(filelistDir, {recursive: true});
- } catch (err) {
- rmSync(filelistDir, {recursive: true});
- throw err;
+ } finally {
+ rmSync(filelistDir, {recursive: true, force: true});
}
};
@@ -270,5 +299,6 @@ export const combineChunks = (options: CombineChunksOptions) => {
frameRange: options.frameRange ?? null,
compositionDurationInFrames: options.compositionDurationInFrames,
sampleRate: options.sampleRate ?? 48000,
+ separateAudioTo: null,
});
};
diff --git a/packages/renderer/src/options/separate-audio.tsx b/packages/renderer/src/options/separate-audio.tsx
index 9b890ffde5..dfd7ed34e9 100644
--- a/packages/renderer/src/options/separate-audio.tsx
+++ b/packages/renderer/src/options/separate-audio.tsx
@@ -7,7 +7,7 @@ const cliFlag = 'separate-audio-to';
export const separateAudioOption = {
cliFlag,
description: () =>
- `If set, the audio will not be included in the main output but rendered as a separate file at the location you pass. If the render contains no audio, a silent audio file is produced even when enforceAudioTrack is false. The muted option still takes precedence. It is recommended to use an absolute path. If a relative path is passed, it is relative to the Remotion Root.`,
+ `If set, the audio will not be included in the main output but rendered as a separate file at the location you pass. If the render contains no audio, a silent audio file is produced even when enforceAudioTrack is false. Audio-only renders, muted renders and codecs without audio support cannot use this option. For local renders, use an absolute path; relative paths are resolved against the Remotion Root. On Lambda, pass an output name or custom destination as described in renderMediaOnLambda().`,
docLink: 'https://www.remotion.dev/docs/options/separate-audio-to',
getValue: ({commandLine}) => {
if (commandLine[cliFlag]) {
diff --git a/packages/serverless-client/src/constants.ts b/packages/serverless-client/src/constants.ts
index 6ef1e9cd44..77be0fb277 100644
--- a/packages/serverless-client/src/constants.ts
+++ b/packages/serverless-client/src/constants.ts
@@ -58,6 +58,15 @@ export type OutNameInput<Provider extends CloudProvider> =
s3OutputProvider?: CustomCredentials<Provider>;
};
+export type RenderOutput = 'main' | 'separate-audio';
+
+export type SeparateAudioOutput = {
+ url: string;
+ bucketName: string;
+ key: string;
+ sizeInBytes: number;
+};
+
export type SerializedInputProps =
| {
type: 'bucket-url';
@@ -135,6 +144,7 @@ export type ServerlessStartPayload<Provider extends CloudProvider> = {
logLevel: LogLevel;
frameRange: SingleFrameRange | null;
outName: OutNameInput<Provider> | null;
+ separateAudioTo: OutNameInput<Provider> | null;
timeoutInMilliseconds: number;
chromiumOptions: ChromiumOptions;
scale: number;
@@ -202,6 +212,7 @@ export type ServerlessPayloads<Provider extends CloudProvider> = {
logLevel: LogLevel;
frameRange: SingleFrameRange | null;
outName: OutNameInput<Provider> | null;
+ separateAudioTo: OutNameInput<Provider> | null;
timeoutInMilliseconds: number;
// Non-JS SDKs may not set chromiumOptions, may be undefined
chromiumOptions: ChromiumOptions | undefined;
@@ -270,6 +281,7 @@ export type ServerlessPayloads<Provider extends CloudProvider> = {
scale: number;
everyNthFrame: number;
muted: boolean;
+ audioCodec: AudioCodec | null;
audioBitrate: string | null;
videoBitrate: string | null;
encodingBufferSize: string | null;
@@ -397,6 +409,7 @@ export const artifactName = (renderId: string, name: string) =>
export type PostRenderData<Provider extends CloudProvider> = {
cost: AfterRenderCost;
outputFile: string;
+ separateAudio: SeparateAudioOutput | null;
outputSize: number;
renderSize: number;
timeToFinish: number;
diff --git a/packages/serverless-client/src/expected-out-name.ts b/packages/serverless-client/src/expected-out-name.ts
index a0fc33b8ea..dfc33e01c9 100644
--- a/packages/serverless-client/src/expected-out-name.ts
+++ b/packages/serverless-client/src/expected-out-name.ts
@@ -7,6 +7,7 @@ import {
type CustomCredentials,
type OutNameInput,
type OutNameOutput,
+ type RenderOutput,
} from './constants';
import {getCustomOutName} from './get-custom-out-name';
import type {RenderMetadata} from './render-metadata';
@@ -36,27 +37,41 @@ export const getExpectedOutName = <Provider extends CloudProvider>({
bucketName,
customCredentials,
bucketNamePrefix,
+ output,
}: {
renderMetadata: RenderMetadata<Provider>;
bucketName: string;
customCredentials: CustomCredentials<Provider> | null;
bucketNamePrefix: string;
+ output: RenderOutput;
}): OutNameOutput<Provider> => {
const outNameValue = getCustomOutName({
customCredentials,
- renderMetadata,
+ outName:
+ output === 'main'
+ ? (renderMetadata.outName ?? null)
+ : (renderMetadata.separateAudioTo ?? null),
+ privacy: renderMetadata.privacy,
});
+ const separateAudioFilename =
+ typeof renderMetadata.separateAudioTo === 'string'
+ ? renderMetadata.separateAudioTo
+ : (renderMetadata.separateAudioTo?.key ?? null);
if (outNameValue) {
validateOutname({
outName: outNameValue,
- codec: renderMetadata.codec,
+ codec: output === 'main' ? renderMetadata.codec : null,
audioCodecSetting: renderMetadata.audioCodec,
- separateAudioTo: null,
+ separateAudioTo: separateAudioFilename?.toLowerCase() ?? null,
bucketNamePrefix,
});
return customOutName(renderMetadata.renderId, bucketName, outNameValue);
}
+ if (output === 'separate-audio') {
+ throw new Error('This render does not have a separate audio output.');
+ }
+
if (renderMetadata.type === 'still') {
return {
renderBucketName: bucketName,
@@ -72,7 +87,7 @@ export const getExpectedOutName = <Provider extends CloudProvider>({
renderMetadata.renderId,
NoReactAPIs.getFileExtensionFromCodec(
renderMetadata.codec as Codec,
- renderMetadata.audioCodec,
+ separateAudioFilename === null ? renderMetadata.audioCodec : null,
),
),
customCredentials: null,
diff --git a/packages/serverless-client/src/find-output-file-in-bucket.ts b/packages/serverless-client/src/find-output-file-in-bucket.ts
index be9e0db301..84a29dccb6 100644
--- a/packages/serverless-client/src/find-output-file-in-bucket.ts
+++ b/packages/serverless-client/src/find-output-file-in-bucket.ts
@@ -1,4 +1,4 @@
-import type {CustomCredentials} from './constants';
+import type {CustomCredentials, RenderOutput} from './constants';
import {getExpectedOutName} from './expected-out-name';
import type {ProviderSpecifics} from './provider-implementation';
import type {RenderMetadata} from './render-metadata';
@@ -20,6 +20,7 @@ export const findOutputFileInBucket = async <Provider extends CloudProvider>({
providerSpecifics,
forcePathStyle,
requestHandler,
+ output,
}: {
region: Provider['region'];
renderMetadata: RenderMetadata<Provider>;
@@ -29,12 +30,14 @@ export const findOutputFileInBucket = async <Provider extends CloudProvider>({
providerSpecifics: ProviderSpecifics<Provider>;
forcePathStyle: boolean;
requestHandler: Provider['requestHandler'] | null;
+ output: RenderOutput;
}): Promise<OutputFileMetadata | null> => {
const {renderBucketName, key} = getExpectedOutName({
renderMetadata,
bucketName,
customCredentials,
bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ output,
});
try {
@@ -53,6 +56,7 @@ export const findOutputFileInBucket = async <Provider extends CloudProvider>({
bucketName,
customCredentials,
currentRegion,
+ output,
}).url,
sizeInBytes: metadata.ContentLength ?? null,
};
diff --git a/packages/serverless-client/src/get-custom-out-name.ts b/packages/serverless-client/src/get-custom-out-name.ts
index 610d8ec639..6f0e055ebe 100644
--- a/packages/serverless-client/src/get-custom-out-name.ts
+++ b/packages/serverless-client/src/get-custom-out-name.ts
@@ -1,34 +1,40 @@
-import type {CustomCredentials, OutNameInput} from './constants';
-import type {RenderMetadata} from './render-metadata';
+import type {
+ CustomCredentials,
+ OutNameInput,
+ OutNameInputWithoutCredentials,
+ Privacy,
+} from './constants';
import type {CloudProvider} from './types';
export const getCustomOutName = <Provider extends CloudProvider>({
- renderMetadata,
+ outName,
+ privacy,
customCredentials,
}: {
- renderMetadata: RenderMetadata<Provider>;
+ outName: OutNameInputWithoutCredentials | null;
+ privacy: Privacy;
customCredentials: CustomCredentials<Provider> | null;
}): OutNameInput<Provider> | null => {
- if (!renderMetadata.outName) {
+ if (outName === null) {
return null;
}
- if (typeof renderMetadata.outName === 'string') {
- return renderMetadata.outName;
+ if (typeof outName === 'string') {
+ return outName;
}
- if (renderMetadata.outName.s3OutputProvider) {
- if (!customCredentials && renderMetadata.privacy === 'private') {
+ if (outName.s3OutputProvider) {
+ if (!customCredentials && privacy === 'private') {
throw new TypeError(
`The file was rendered with a custom S3 implementation and is not public, but no custom credentials were passed to downloadMedia().`,
);
}
return {
- bucketName: renderMetadata.outName.bucketName,
- key: renderMetadata.outName.key,
+ bucketName: outName.bucketName,
+ key: outName.key,
s3OutputProvider: {
- endpoint: renderMetadata.outName.s3OutputProvider.endpoint,
+ endpoint: outName.s3OutputProvider.endpoint,
accessKeyId: customCredentials?.accessKeyId ?? null,
secretAccessKey: customCredentials?.secretAccessKey ?? null,
region: customCredentials?.region,
@@ -38,7 +44,7 @@ export const getCustomOutName = <Provider extends CloudProvider>({
}
return {
- bucketName: renderMetadata.outName.bucketName,
- key: renderMetadata.outName.key,
+ bucketName: outName.bucketName,
+ key: outName.key,
};
};
diff --git a/packages/serverless-client/src/overall-render-progress.ts b/packages/serverless-client/src/overall-render-progress.ts
index 642f08dcb5..638329ed2d 100644
--- a/packages/serverless-client/src/overall-render-progress.ts
+++ b/packages/serverless-client/src/overall-render-progress.ts
@@ -1,4 +1,4 @@
-import type {PostRenderData} from './constants';
+import type {PostRenderData, SeparateAudioOutput} from './constants';
import type {RenderMetadata} from './render-metadata';
import type {
ChunkRetry,
@@ -23,6 +23,7 @@ export type OverallRenderProgress<Provider extends CloudProvider> = {
lambdasInvoked: number;
retries: ChunkRetry[];
postRenderData: PostRenderData<Provider> | null;
+ separateAudio: SeparateAudioOutput | null;
timings: ParsedTiming[];
renderMetadata: RenderMetadata<Provider> | null;
errors: FunctionErrorInfo[];
diff --git a/packages/serverless-client/src/progress.ts b/packages/serverless-client/src/progress.ts
index c269689145..01c48f4693 100644
--- a/packages/serverless-client/src/progress.ts
+++ b/packages/serverless-client/src/progress.ts
@@ -13,7 +13,6 @@ import {getOverallProgressFromStorage} from './get-overall-progress-from-storage
import {inspectErrors} from './inspect-error';
import {makeTimeoutError} from './make-timeout-error';
import type {ProviderSpecifics} from './provider-implementation';
-import {lambdaRenderHasAudioVideo} from './render-has-audio-video';
import type {CleanupInfo, GenericRenderProgress} from './render-progress';
import {truthy} from './truthy';
import type {CloudProvider} from './types';
@@ -69,6 +68,7 @@ export const getProgress = async <Provider extends CloudProvider>({
}
const outData = getExpectedOutName({
+ output: 'main',
renderMetadata: overallProgress.renderMetadata,
bucketName,
customCredentials,
@@ -107,6 +107,7 @@ export const getProgress = async <Provider extends CloudProvider>({
fatalErrorEncountered: false,
lambdasInvoked: overallProgress.renderMetadata.totalChunks,
outputFile: overallProgress.postRenderData.outputFile,
+ separateAudio: overallProgress.postRenderData.separateAudio ?? null,
renderId,
timeToFinish: overallProgress.postRenderData.timeToFinish,
timeToFinishChunks: overallProgress.postRenderData.timeToRenderChunks,
@@ -139,10 +140,6 @@ export const getProgress = async <Provider extends CloudProvider>({
errors: overallProgress.errors,
});
- const {hasAudio, hasVideo} = renderMetadata
- ? lambdaRenderHasAudioVideo(renderMetadata)
- : {hasAudio: false, hasVideo: false};
-
const chunkCount = overallProgress.chunks.length ?? 0;
const cleanup: CleanupInfo = {
@@ -167,6 +164,7 @@ export const getProgress = async <Provider extends CloudProvider>({
renderMetadata,
bucket: bucketName,
outputFile: null,
+ separateAudio: null,
timeToFinish: null,
errors: errorExplanations,
fatalErrorEncountered: errorExplanations.some(
@@ -217,18 +215,12 @@ export const getProgress = async <Provider extends CloudProvider>({
fatalErrorTimestamp: overallProgress.fatalErrorTimestamp ?? null,
});
- const chunkMultiplier = [hasAudio, hasVideo].filter(truthy).length;
-
if (renderMetadata.type === 'still') {
throw new Error(
"You don't need to call getRenderProgress() on a still render. Once you have obtained the `renderId`, the render is already done! πŸ˜‰",
);
}
- const allChunks =
- (overallProgress.chunks ?? []).length / chunkMultiplier ===
- (renderMetadata.totalChunks ?? Infinity);
-
const frameCount = NoReactAPIs.getFramesToRender(
renderMetadata.frameRange,
renderMetadata.everyNthFrame,
@@ -243,6 +235,7 @@ export const getProgress = async <Provider extends CloudProvider>({
'undefined'
);
});
+ const allChunks = missingChunks.length === 0;
// We add a 20 second buffer for it, since AWS timeshifts can be quite a lot. Once it's 20sec over the limit, we consider it timed out
// 1. If we have missing chunks, we consider it timed out
@@ -257,6 +250,8 @@ export const getProgress = async <Provider extends CloudProvider>({
const shouldCheckForCompletedOutput =
allChunks &&
+ ((renderMetadata.separateAudioTo ?? null) === null ||
+ (overallProgress.separateAudio ?? null) !== null) &&
!errorExplanations.some((error) => error.isFatal && !error.willRetry) &&
(isBeyondTimeoutAndHasStitchTimeout ||
(overallProgress.combinedFrames >= frameCount &&
@@ -264,6 +259,7 @@ export const getProgress = async <Provider extends CloudProvider>({
if (shouldCheckForCompletedOutput) {
const outputFile = await findOutputFileInBucket({
+ output: 'main',
bucketName,
customCredentials,
renderMetadata,
@@ -283,6 +279,7 @@ export const getProgress = async <Provider extends CloudProvider>({
if (outputFile) {
const outData = getExpectedOutName({
+ output: 'main',
renderMetadata,
bucketName,
customCredentials,
@@ -318,6 +315,7 @@ export const getProgress = async <Provider extends CloudProvider>({
fatalErrorEncountered: false,
lambdasInvoked: renderMetadata.totalChunks,
outputFile: outputFile.url,
+ separateAudio: overallProgress.separateAudio ?? null,
renderId,
timeToFinish: now - renderMetadata.startedDate,
timeToFinishChunks,
@@ -376,6 +374,7 @@ export const getProgress = async <Provider extends CloudProvider>({
renderMetadata,
bucket: bucketName,
outputFile: null,
+ separateAudio: null,
timeToFinish: null,
errors: allErrors,
fatalErrorEncountered: allErrors.some((f) => f.isFatal && !f.willRetry),
diff --git a/packages/serverless-client/src/provider-implementation.ts b/packages/serverless-client/src/provider-implementation.ts
index 11a0656428..04e32f54ef 100644
--- a/packages/serverless-client/src/provider-implementation.ts
+++ b/packages/serverless-client/src/provider-implementation.ts
@@ -1,7 +1,12 @@
import type {Readable} from 'node:stream';
import type {LogLevel} from '@remotion/renderer';
import type {DownloadBehavior} from 'remotion';
-import type {CustomCredentials, Privacy, ServerlessRoutines} from './constants';
+import type {
+ CustomCredentials,
+ Privacy,
+ RenderOutput,
+ ServerlessRoutines,
+} from './constants';
import type {BillingCurrency} from './format-costs-info';
import type {RenderMetadata} from './render-metadata';
import type {RendererFunctionTransport} from './renderer-transport';
@@ -175,6 +180,7 @@ export type CallFunctionSync<Provider extends CloudProvider> = <
>;
export type GetOutputUrl<Provider extends CloudProvider> = (options: {
+ output: RenderOutput;
renderMetadata: RenderMetadata<Provider>;
bucketName: string;
customCredentials: CustomCredentials<Provider> | null;
diff --git a/packages/serverless-client/src/render-metadata.ts b/packages/serverless-client/src/render-metadata.ts
index 70e8aed9ac..de0344db1d 100644
--- a/packages/serverless-client/src/render-metadata.ts
+++ b/packages/serverless-client/src/render-metadata.ts
@@ -50,8 +50,10 @@ export type RenderMetadata<Provider extends CloudProvider> = Discriminated & {
region: Provider['region'];
renderId: string;
outName: OutNameInputWithoutCredentials | undefined;
+ separateAudioTo: OutNameInputWithoutCredentials | null;
// Whether the final upload must create a new object without overwriting.
outputFileIsConditional: boolean | null;
+ separateAudioOutputFileIsConditional: boolean | null;
privacy: Privacy;
deleteAfter: DeleteAfter | null;
numberOfGifLoops: number | null;
diff --git a/packages/serverless-client/src/render-progress.ts b/packages/serverless-client/src/render-progress.ts
index 566881b5f9..710c204ab1 100644
--- a/packages/serverless-client/src/render-progress.ts
+++ b/packages/serverless-client/src/render-progress.ts
@@ -1,3 +1,4 @@
+import type {SeparateAudioOutput} from './constants';
import type {ExpensiveChunk} from './most-expensive-chunks';
import type {RenderMetadata} from './render-metadata';
import type {
@@ -29,6 +30,7 @@ export type GenericRenderProgress<Provider extends CloudProvider> = {
renderMetadata: RenderMetadata<Provider> | null;
bucket: string;
outputFile: string | null;
+ separateAudio: SeparateAudioOutput | null;
outKey: string | null;
outBucket: string | null;
timeToFinish: number | null;
diff --git a/packages/serverless-client/src/test/expected-out-name.test.ts b/packages/serverless-client/src/test/expected-out-name.test.ts
index e0769dc2fa..f370efe4cd 100644
--- a/packages/serverless-client/src/test/expected-out-name.test.ts
+++ b/packages/serverless-client/src/test/expected-out-name.test.ts
@@ -17,6 +17,8 @@ type MockProvider = {
};
const testRenderMetadata: RenderMetadata<MockProvider> = {
+ separateAudioTo: null,
+ separateAudioOutputFileIsConditional: null,
outputFileIsConditional: null,
compositionId: 'react-svg',
estimatedRenderLambdaInvokations: 100,
@@ -59,6 +61,7 @@ const testRenderMetadata: RenderMetadata<MockProvider> = {
test('Should get a custom outname', () => {
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: testRenderMetadata,
bucketName,
customCredentials: null,
@@ -81,6 +84,7 @@ test('Should save to a different outname', () => {
};
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
@@ -108,6 +112,7 @@ test('Should preserve custom provider regions outside the built-in AWS list', ()
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: {
@@ -141,6 +146,7 @@ test('For stills', () => {
};
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
@@ -163,6 +169,7 @@ test('Just a custom name', () => {
};
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
@@ -185,6 +192,7 @@ test('Should throw on invalid names', () => {
};
expect(() => {
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
@@ -204,6 +212,7 @@ test('Should allow outName an outname with a slash', () => {
};
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
@@ -227,6 +236,7 @@ test('Should allow outName an outname with colon', () => {
};
expect(
getExpectedOutName({
+ output: 'main',
renderMetadata: newRenderMetadata,
bucketName,
customCredentials: null,
diff --git a/packages/serverless-client/src/test/progress.test.ts b/packages/serverless-client/src/test/progress.test.ts
index 2c642d26af..a42ae5657e 100644
--- a/packages/serverless-client/src/test/progress.test.ts
+++ b/packages/serverless-client/src/test/progress.test.ts
@@ -25,6 +25,8 @@ const bucketName = 'source-bucket';
const startedDate = Date.now() - 30000;
const renderMetadata: RenderMetadata<MockProvider> = {
+ separateAudioTo: null,
+ separateAudioOutputFileIsConditional: null,
outputFileIsConditional: null,
audioBitrate: null,
audioCodec: null,
@@ -68,6 +70,7 @@ const renderMetadata: RenderMetadata<MockProvider> = {
};
const progress: OverallRenderProgress<MockProvider> = {
+ separateAudio: null,
cancellationEnabled: false,
chunks: [0, 1],
combinedFrames: 20,
@@ -135,6 +138,7 @@ const makeProviderSpecifics = ({
currentRegion,
}) => {
const {key, renderBucketName} = getExpectedOutName({
+ output: 'main',
renderMetadata: metadata,
bucketName,
customCredentials,
diff --git a/packages/serverless-client/src/webhook-types.ts b/packages/serverless-client/src/webhook-types.ts
index 55b5d91e84..6efd042989 100644
--- a/packages/serverless-client/src/webhook-types.ts
+++ b/packages/serverless-client/src/webhook-types.ts
@@ -1,4 +1,4 @@
-import type {AfterRenderCost} from './constants';
+import type {AfterRenderCost, SeparateAudioOutput} from './constants';
import type {EnhancedErrorInfo} from './write-error-to-storage';
type StaticWebhookPayload<BucketOwner extends string | null> = {
@@ -24,6 +24,7 @@ export type WebhookSuccessPayload<BucketOwner extends string | null = string> =
lambdaErrors: EnhancedErrorInfo[];
outputUrl: string | undefined;
outputFile: string | undefined;
+ separateAudio: SeparateAudioOutput | null;
timeToFinish: number | undefined;
costs: AfterRenderCost;
};
diff --git a/packages/serverless/src/concat-videos.ts b/packages/serverless/src/concat-videos.ts
index 3c9151dd0e..eab7047b68 100644
--- a/packages/serverless/src/concat-videos.ts
+++ b/packages/serverless/src/concat-videos.ts
@@ -33,6 +33,7 @@ export const concatVideos = async <Provider extends CloudProvider>({
compositionDurationInFrames,
sampleRate,
outputExtension,
+ separateAudioFilename,
}: {
onProgress: CombineChunksOnProgress;
codec: ServerlessCodec;
@@ -54,43 +55,59 @@ export const concatVideos = async <Provider extends CloudProvider>({
frameRange: SingleFrameRange | null;
sampleRate: number;
outputExtension: string | null;
+ separateAudioFilename: string | null;
}) => {
// .m4a, .m4b and .3gp need to be muxed into their container, otherwise the
// ADTS stream would be uploaded as-is under that name.
const extension = RenderInternals.getMp4BrandForExtension(outputExtension)
? (outputExtension as string)
- : RenderInternals.getFileExtensionFromCodec(codec, audioCodec);
- const outfile = join(
- RenderInternals.tmpDir(REMOTION_CONCATENATED_TOKEN),
- `concat.${extension}`,
- );
+ : RenderInternals.getFileExtensionFromCodec(
+ codec,
+ separateAudioFilename === null ? audioCodec : null,
+ );
+ const outputDirectory = RenderInternals.tmpDir(REMOTION_CONCATENATED_TOKEN);
+ const separateAudioFile =
+ separateAudioFilename === null
+ ? null
+ : join(
+ outputDirectory,
+ `audio.${RenderInternals.getExtensionOfFilename(separateAudioFilename)?.toLowerCase()}`,
+ );
+ const outfile = join(outputDirectory, `concat.${extension}`);
const combine = insideFunctionSpecifics.timer('Combine chunks', logLevel);
const audioFiles = files.filter((f) => f.endsWith('audio'));
const videoFiles = files.filter((f) => f.endsWith('video'));
- await RenderInternals.internalCombineChunks({
- outputLocation: outfile,
- onProgress,
- codec,
- fps,
- numberOfGifLoops,
- audioBitrate,
- indent: false,
- logLevel,
- binariesDirectory,
- cancelSignal,
- metadata,
- audioFiles,
- videoFiles,
- framesPerChunk: framesPerLambda,
- audioCodec,
- preferLossless,
- compositionDurationInFrames,
- everyNthFrame,
- frameRange,
- sampleRate,
- });
+ try {
+ await RenderInternals.internalCombineChunks({
+ separateAudioTo: separateAudioFile,
+ outputLocation: outfile,
+ onProgress,
+ codec,
+ fps,
+ numberOfGifLoops,
+ audioBitrate,
+ indent: false,
+ logLevel,
+ binariesDirectory,
+ cancelSignal,
+ metadata,
+ audioFiles,
+ videoFiles,
+ framesPerChunk: framesPerLambda,
+ audioCodec,
+ preferLossless,
+ compositionDurationInFrames,
+ everyNthFrame,
+ frameRange,
+ sampleRate,
+ });
+ } catch (err) {
+ await fs.promises.rm(outputDirectory, {recursive: true, force: true});
+ await fs.promises.rm(outdir, {recursive: true, force: true});
+ throw err;
+ }
combine.end();
@@ -98,5 +115,5 @@ export const concatVideos = async <Provider extends CloudProvider>({
recursive: true,
force: true,
});
- return {outfile, cleanupChunksProm};
+ return {outfile, separateAudioFile, cleanupChunksProm};
};
diff --git a/packages/serverless/src/create-post-render-data.ts b/packages/serverless/src/create-post-render-data.ts
index 1b4e3f1fe5..4224b6994d 100644
--- a/packages/serverless/src/create-post-render-data.ts
+++ b/packages/serverless/src/create-post-render-data.ts
@@ -86,6 +86,7 @@ export const createPostRenderData = <Provider extends CloudProvider>({
).format(cost)}`,
},
outputFile: outputFile.url,
+ separateAudio: overallProgress.separateAudio ?? null,
timeToFinish,
errors: errorExplanations,
startTime: renderMetadata.startedDate,
diff --git a/packages/serverless/src/find-output-file-in-bucket.ts b/packages/serverless/src/find-output-file-in-bucket.ts
index c303321df7..ad7e30d8da 100644
--- a/packages/serverless/src/find-output-file-in-bucket.ts
+++ b/packages/serverless/src/find-output-file-in-bucket.ts
@@ -4,6 +4,7 @@ import type {
OutputFileMetadata,
ProviderSpecifics,
RenderMetadata,
+ RenderOutput,
} from '@remotion/serverless-client';
import {findOutputFileInBucket as findOutputFileInBucketShared} from '@remotion/serverless-client';
@@ -18,6 +19,7 @@ export const findOutputFileInBucket = <Provider extends CloudProvider>({
providerSpecifics,
forcePathStyle,
requestHandler,
+ output,
}: {
region: Provider['region'];
renderMetadata: RenderMetadata<Provider>;
@@ -27,6 +29,7 @@ export const findOutputFileInBucket = <Provider extends CloudProvider>({
providerSpecifics: ProviderSpecifics<Provider>;
forcePathStyle: boolean;
requestHandler: Provider['requestHandler'] | null;
+ output: RenderOutput;
}): Promise<OutputFileMetadata | null> => {
if (!renderMetadata) {
throw new Error('unexpectedly did not get renderMetadata');
@@ -41,5 +44,6 @@ export const findOutputFileInBucket = <Provider extends CloudProvider>({
providerSpecifics,
forcePathStyle,
requestHandler,
+ output,
});
};
diff --git a/packages/serverless/src/finish-render.ts b/packages/serverless/src/finish-render.ts
index 25e170dbdb..928b71104f 100644
--- a/packages/serverless/src/finish-render.ts
+++ b/packages/serverless/src/finish-render.ts
@@ -11,7 +11,7 @@ import type {
WriteFileInput,
SerializedInputProps,
} from '@remotion/serverless-client';
-import {inspectErrors} from '@remotion/serverless-client';
+import {getExpectedOutName, inspectErrors} from '@remotion/serverless-client';
import {cleanupProps} from './cleanup-props';
import {createPostRenderData} from './create-post-render-data';
import type {OverallProgressHelper} from './overall-render-progress';
@@ -37,6 +37,9 @@ export const finishRender = async <Provider extends CloudProvider>({
requestHandler,
outputFile,
timeToCombine,
+ bucketName,
+ separateAudioFile,
+ separateAudioCredentials,
}: {
expectedBucketOwner: string | null;
renderBucketName: string;
@@ -57,42 +60,107 @@ export const finishRender = async <Provider extends CloudProvider>({
requestHandler: Provider['requestHandler'] | null;
outputFile: string;
timeToCombine: number | null;
+ bucketName: string;
+ separateAudioFile: string | null;
+ separateAudioCredentials: CustomCredentials<Provider> | null;
}): Promise<PostRenderData<Provider>> => {
const outputSize = fs.statSync(outputFile).size;
- const writeToBucket = insideFunctionSpecifics.timer(
- `Writing to bucket (${outputSize} bytes)`,
- logLevel,
- );
+ if (
+ (renderMetadata.separateAudioTo ?? null) !== null &&
+ separateAudioFile === null
+ ) {
+ throw new Error('The separate audio output was not created.');
+ }
- const writeOptions: WriteFileInput<Provider> = {
- bucketName: renderBucketName,
- key,
- body: fs.createReadStream(outputFile),
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- privacy,
- expectedBucketOwner,
- downloadBehavior,
- customCredentials,
- forcePathStyle,
- storageClass,
- requestHandler,
- };
+ const separateAudioDestination =
+ separateAudioFile === null
+ ? null
+ : getExpectedOutName({
+ output: 'separate-audio',
+ renderMetadata,
+ bucketName,
+ customCredentials: separateAudioCredentials,
+ bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ });
+ for (const file of [
+ ...(separateAudioFile === null || separateAudioDestination === null
+ ? []
+ : [
+ {
+ output: 'separate-audio' as const,
+ file: separateAudioFile,
+ ...separateAudioDestination,
+ conditional: renderMetadata.separateAudioOutputFileIsConditional,
+ },
+ ]),
+ {
+ output: 'main' as const,
+ file: outputFile,
+ key,
+ renderBucketName,
+ customCredentials,
+ conditional: renderMetadata.outputFileIsConditional,
+ },
+ ]) {
+ const sizeInBytes = fs.statSync(file.file).size;
+ const writeToBucket = insideFunctionSpecifics.timer(
+ `Writing to bucket (${sizeInBytes} bytes)`,
+ logLevel,
+ );
+ const body = fs.createReadStream(file.file);
+ const writeOptions: WriteFileInput<Provider> = {
+ bucketName: file.renderBucketName,
+ key: file.key,
+ body,
+ region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ privacy,
+ expectedBucketOwner,
+ downloadBehavior:
+ file.output === 'separate-audio' && downloadBehavior.type === 'download'
+ ? {...downloadBehavior, fileName: null}
+ : downloadBehavior,
+ customCredentials: file.customCredentials,
+ forcePathStyle,
+ storageClass,
+ requestHandler,
+ };
+ try {
+ if (file.conditional) {
+ if (providerSpecifics.writeFileIfNotExists === null) {
+ throw new Error(
+ 'The provider does not support conditional output uploads',
+ );
+ }
- if (renderMetadata.outputFileIsConditional) {
- if (!providerSpecifics.writeFileIfNotExists) {
- throw new Error(
- 'The provider does not support conditional output uploads',
- );
+ await providerSpecifics.writeFileIfNotExists(writeOptions);
+ } else {
+ await providerSpecifics.writeFile(writeOptions);
+ }
+ } finally {
+ body.destroy();
}
- await providerSpecifics.writeFileIfNotExists(writeOptions);
- } else {
- await providerSpecifics.writeFile(writeOptions);
+ writeToBucket.end();
+ if (file.output === 'separate-audio') {
+ const {url} = providerSpecifics.getOutputUrl({
+ output: 'separate-audio',
+ bucketName,
+ renderMetadata,
+ customCredentials: file.customCredentials,
+ currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ });
+ // Persist the audio upload before publishing the main file so progress
+ // recovery cannot finish a render with a missing audio output.
+ await overallProgress.setSeparateAudio({
+ url,
+ key: file.key,
+ bucketName: file.renderBucketName,
+ sizeInBytes,
+ });
+ }
}
- writeToBucket.end();
-
const errorExplanations = inspectErrors({
errors: overallProgress.get().errors,
});
@@ -106,6 +174,7 @@ export const finishRender = async <Provider extends CloudProvider>({
});
const {url: outputUrl} = providerSpecifics.getOutputUrl({
+ output: 'main',
bucketName: renderBucketName,
currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
customCredentials,
@@ -132,5 +201,9 @@ export const finishRender = async <Provider extends CloudProvider>({
await overallProgress.setPostRenderData(postRenderData);
fs.unlinkSync(outputFile);
+ if (separateAudioFile !== null) {
+ fs.unlinkSync(separateAudioFile);
+ }
+
return postRenderData;
};
diff --git a/packages/serverless/src/handlers/launch.ts b/packages/serverless/src/handlers/launch.ts
index 67745fe123..cde61ff809 100644
--- a/packages/serverless/src/handlers/launch.ts
+++ b/packages/serverless/src/handlers/launch.ts
@@ -4,6 +4,7 @@ import {join} from 'path';
/* eslint-disable @typescript-eslint/no-use-before-define */
import type {LogOptions} from '@remotion/renderer';
import {RenderInternals} from '@remotion/renderer';
+import {NoReactAPIs} from '@remotion/renderer/pure';
import {validateCodec, VERSION} from '@remotion/serverless-client';
import type {
CloudProvider,
@@ -78,6 +79,59 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
throw new Error('Expected launch type');
}
+ validateCodec(params.codec, 'renderMediaOnLambda', 'codec');
+ const separateAudioTo = params.separateAudioTo ?? null;
+ const separateAudioFilename =
+ typeof separateAudioTo === 'string'
+ ? separateAudioTo
+ : (separateAudioTo?.key ?? null);
+ const audioCodec =
+ separateAudioFilename === null
+ ? params.audioCodec
+ : RenderInternals.resolveAudioCodec({
+ codec: params.codec,
+ setting: params.audioCodec,
+ preferLossless: params.preferLossless,
+ separateAudioTo: separateAudioFilename.toLowerCase(),
+ });
+ if (separateAudioTo !== null) {
+ if (NoReactAPIs.isAudioCodec(params.codec)) {
+ throw new Error(
+ '`separateAudioTo` was set, but this render was audio-only. This option is meant to be used for video renders.',
+ );
+ }
+
+ if (params.muted || audioCodec === null) {
+ throw new Error(
+ '`separateAudioTo` requires audio output. Audio output is disabled by the muted option or selected codec.',
+ );
+ }
+
+ const extension =
+ RenderInternals.getExtensionOfFilename(
+ separateAudioFilename,
+ )?.toLowerCase() ?? null;
+ if (
+ extension !== RenderInternals.getExtensionFromAudioCodec(audioCodec) &&
+ !(
+ audioCodec === 'aac' &&
+ RenderInternals.getMp4BrandForExtension(extension)
+ )
+ ) {
+ throw new Error(
+ '`separateAudioTo` must use a supported audio extension: .wav, .aac, .mp3, .opus, .m4a, .m4b or .3gp.',
+ );
+ }
+
+ validateOutname({
+ outName: separateAudioTo,
+ codec: null,
+ audioCodecSetting: audioCodec,
+ separateAudioTo: null,
+ bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ });
+ }
+
const startedDate = Date.now();
const chromiumParams = insideFunctionSpecifics.normalizeChromiumOptions?.({
@@ -200,11 +254,10 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
validateOutname({
outName: params.outName,
codec: params.codec,
- audioCodecSetting: params.audioCodec,
- separateAudioTo: null,
+ audioCodecSetting: audioCodec,
+ separateAudioTo: separateAudioFilename?.toLowerCase() ?? null,
bucketNamePrefix: providerSpecifics.getBucketPrefix(),
});
- validateCodec(params.codec, 'renderMediaOnLambda', 'codec');
validatePrivacy(params.privacy, true);
RenderInternals.validatePuppeteerTimeout(params.timeoutInMilliseconds);
@@ -302,6 +355,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
everyNthFrame: params.everyNthFrame,
concurrencyPerLambda: params.concurrencyPerFunction,
muted: params.muted,
+ audioCodec,
audioBitrate: params.audioBitrate,
videoBitrate: params.videoBitrate,
encodingMaxRate: params.encodingMaxRate,
@@ -341,6 +395,16 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
options.requestContext !== null;
const renderMetadata: RenderMetadata<Provider> = {
+ separateAudioTo:
+ removeOutnameCredentials(separateAudioTo ?? undefined) ?? null,
+ separateAudioOutputFileIsConditional:
+ separateAudioTo === null
+ ? null
+ : !params.overwrite &&
+ providerSpecifics.supportsConditionalOutput({
+ customCredentials: getCredentialsFromOutName(separateAudioTo),
+ }) &&
+ providerSpecifics.writeFileIfNotExists !== null,
outputFileIsConditional:
!params.overwrite &&
providerSpecifics.supportsConditionalOutput({
@@ -370,7 +434,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
privacy: params.privacy,
everyNthFrame: params.everyNthFrame,
frameRange: realFrameRange,
- audioCodec: params.audioCodec,
+ audioCodec,
deleteAfter: params.deleteAfter,
numberOfGifLoops: params.numberOfGifLoops,
downloadBehavior: params.downloadBehavior,
@@ -389,6 +453,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
};
const {key, renderBucketName, customCredentials} = getExpectedOutName({
+ output: 'main',
renderMetadata,
bucketName: params.bucketName,
customCredentials:
@@ -398,36 +463,77 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
: (params.outName?.s3OutputProvider ?? null),
bucketNamePrefix: providerSpecifics.getBucketPrefix(),
});
+ const separateAudioDestination =
+ separateAudioTo === null
+ ? null
+ : getExpectedOutName({
+ output: 'separate-audio',
+ renderMetadata,
+ bucketName: params.bucketName,
+ customCredentials: getCredentialsFromOutName(separateAudioTo),
+ bucketNamePrefix: providerSpecifics.getBucketPrefix(),
+ });
+ if (
+ separateAudioDestination !== null &&
+ separateAudioDestination.key === key &&
+ separateAudioDestination.renderBucketName === renderBucketName &&
+ (separateAudioDestination.customCredentials?.endpoint ?? null) ===
+ (customCredentials?.endpoint ?? null)
+ ) {
+ throw new Error(
+ '`outName` and `separateAudioTo` must point to different output files.',
+ );
+ }
if (!params.overwrite) {
const findOutputFile = insideFunctionSpecifics.timer(
'Checking if output file already exists',
params.logLevel,
);
- const output = await findOutputFileInBucket({
- bucketName: params.bucketName,
- customCredentials,
- renderMetadata,
- region: insideFunctionSpecifics.getCurrentRegionInFunction(),
- currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
- providerSpecifics,
- forcePathStyle: params.forcePathStyle,
- requestHandler: null,
- }).catch((err) => {
- if (
- err instanceof OutputFileAccessDeniedError &&
- renderMetadata.outputFileIsConditional
- ) {
- // The final conditional upload still enforces overwrite: false.
- return null;
- }
+ for (const destination of [
+ {
+ output: 'main' as const,
+ key,
+ renderBucketName,
+ customCredentials,
+ conditional: renderMetadata.outputFileIsConditional,
+ },
+ ...(separateAudioDestination === null
+ ? []
+ : [
+ {
+ output: 'separate-audio' as const,
+ ...separateAudioDestination,
+ conditional: renderMetadata.separateAudioOutputFileIsConditional,
+ },
+ ]),
+ ]) {
+ const output = await findOutputFileInBucket({
+ output: destination.output,
+ bucketName: params.bucketName,
+ customCredentials: destination.customCredentials,
+ renderMetadata,
+ region: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ currentRegion: insideFunctionSpecifics.getCurrentRegionInFunction(),
+ providerSpecifics,
+ forcePathStyle: params.forcePathStyle,
+ requestHandler: null,
+ }).catch((err) => {
+ if (
+ err instanceof OutputFileAccessDeniedError &&
+ destination.conditional
+ ) {
+ // The final conditional upload still enforces overwrite: false.
+ return null;
+ }
- throw err;
- });
- if (output) {
- throw new TypeError(
- `Output file "${key}" in bucket "${renderBucketName}" in region "${insideFunctionSpecifics.getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in renderMediaOnLambda() to overwrite it."`,
- );
+ throw err;
+ });
+ if (output) {
+ throw new TypeError(
+ `Output file "${destination.key}" in bucket "${destination.renderBucketName}" in region "${insideFunctionSpecifics.getCurrentRegionInFunction()}" already exists. Delete it before re-rendering, or set the 'overwrite' option in renderMediaOnLambda() to overwrite it."`,
+ );
+ }
}
findOutputFile.end();
@@ -512,7 +618,7 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
let postRenderData: PostRenderData<Provider>;
if (shouldRenderDirectly) {
const directRender = await renderWithSingleFunction({
- params,
+ params: {...params, audioCodec},
composition: comp,
serializedInputPropsWithCustomSchema,
frameRange: realFrameRange,
@@ -525,6 +631,10 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
});
try {
postRenderData = await finishRender({
+ bucketName: params.bucketName,
+ separateAudioFile: directRender.separateAudioFile,
+ separateAudioCredentials:
+ separateAudioDestination?.customCredentials ?? null,
expectedBucketOwner: options.expectedBucketOwner,
renderBucketName,
customCredentials,
@@ -582,7 +692,10 @@ const innerLaunchHandler = async <Provider extends CloudProvider>({
renderId: params.renderId,
expectedBucketOwner: options.expectedBucketOwner,
numberOfFrames: comp.durationInFrames,
- audioCodec: params.audioCodec,
+ audioCodec,
+ separateAudioFilename,
+ separateAudioCredentials:
+ separateAudioDestination?.customCredentials ?? null,
chunkCount: chunks.length,
codec: params.codec,
customCredentials,
@@ -888,6 +1001,7 @@ export const launchHandler = async <Provider extends CloudProvider>({
outputUrl: postRenderData.outputFile,
lambdaErrors: postRenderData.errors,
outputFile: postRenderData.outputFile,
+ separateAudio: postRenderData.separateAudio,
timeToFinish: postRenderData.timeToFinish,
costs: postRenderData.cost,
},
diff --git a/packages/serverless/src/handlers/renderer.ts b/packages/serverless/src/handlers/renderer.ts
index 22af502a2b..8c8a4eb7fe 100644
--- a/packages/serverless/src/handlers/renderer.ts
+++ b/packages/serverless/src/handlers/renderer.ts
@@ -147,10 +147,12 @@ const renderHandler = async <Provider extends CloudProvider>({
const outdir = RenderInternals.tmpDir(RENDERER_PATH_TOKEN);
const chunk = `localchunk-${String(params.chunk).padStart(8, '0')}`;
- const defaultAudioCodec = RenderInternals.getDefaultAudioCodec({
- codec: params.codec,
- preferLossless: params.preferLossless,
- });
+ const defaultAudioCodec =
+ params.audioCodec ??
+ RenderInternals.getDefaultAudioCodec({
+ codec: params.codec,
+ preferLossless: params.preferLossless,
+ });
const seamlessAudio = RenderInternals.canConcatAudioSeamlessly(
defaultAudioCodec,
diff --git a/packages/serverless/src/handlers/start.ts b/packages/serverless/src/handlers/start.ts
index 50d7057a2b..ec08369ad9 100644
--- a/packages/serverless/src/handlers/start.ts
+++ b/packages/serverless/src/handlers/start.ts
@@ -110,6 +110,7 @@ export const startHandler = async <Provider extends CloudProvider>({
logLevel: params.logLevel,
frameRange: params.frameRange,
outName: params.outName,
+ separateAudioTo: params.separateAudioTo ?? null,
timeoutInMilliseconds: params.timeoutInMilliseconds,
chromiumOptions: params.chromiumOptions,
scale: params.scale,
diff --git a/packages/serverless/src/handlers/still.ts b/packages/serverless/src/handlers/still.ts
index ea8cecfe80..09a4d10e01 100644
--- a/packages/serverless/src/handlers/still.ts
+++ b/packages/serverless/src/handlers/still.ts
@@ -185,6 +185,8 @@ const innerStillHandler = async <Provider extends CloudProvider>(
});
const renderMetadata: RenderMetadata<Provider> = {
+ separateAudioTo: null,
+ separateAudioOutputFileIsConditional: null,
outputFileIsConditional: null,
startedDate: Date.now(),
codec: null,
@@ -242,6 +244,7 @@ const innerStillHandler = async <Provider extends CloudProvider>(
const receivedArtifact: ReceivedArtifact<Provider>[] = [];
const {key, renderBucketName, customCredentials} = getExpectedOutName({
+ output: 'main',
renderMetadata,
bucketName,
customCredentials: getCredentialsFromOutName(params.outName),
@@ -384,6 +387,7 @@ const innerStillHandler = async <Provider extends CloudProvider>(
});
const {key: outKey, url} = providerSpecifics.getOutputUrl({
+ output: 'main',
renderMetadata,
bucketName,
customCredentials,
diff --git a/packages/serverless/src/merge-chunks.ts b/packages/serverless/src/merge-chunks.ts
index 8124131f3e..abd83edabe 100644
--- a/packages/serverless/src/merge-chunks.ts
+++ b/packages/serverless/src/merge-chunks.ts
@@ -1,3 +1,5 @@
+import {rm} from 'node:fs/promises';
+import {dirname} from 'node:path';
import type {
AudioCodec,
CombineChunksOnProgress,
@@ -59,6 +61,8 @@ export const mergeChunksAndFinishRender = async <
storageClass: Provider['storageClass'] | null;
requestHandler: Provider['requestHandler'] | null;
sampleRate: number;
+ separateAudioFilename: string | null;
+ separateAudioCredentials: CustomCredentials<Provider> | null;
}): Promise<PostRenderData<Provider>> => {
const onProgress: CombineChunksOnProgress = ({frames: framesEncoded}) => {
options.overallProgress.setCombinedFrames(framesEncoded);
@@ -73,7 +77,8 @@ export const mergeChunksAndFinishRender = async <
throw new Error('No files to merge');
}
- const {outfile, cleanupChunksProm} = await concatVideos({
+ const {outfile, separateAudioFile, cleanupChunksProm} = await concatVideos({
+ separateAudioFilename: options.separateAudioFilename,
onProgress,
codec: options.codec,
fps: options.fps,
@@ -98,28 +103,33 @@ export const mergeChunksAndFinishRender = async <
const encodingStop = Date.now();
options.overallProgress.setTimeToCombine(encodingStop - encodingStart);
- const postRenderData = await finishRender({
- expectedBucketOwner: options.expectedBucketOwner,
- renderBucketName: options.renderBucketName,
- customCredentials: options.customCredentials,
- downloadBehavior: options.downloadBehavior,
- key: options.key,
- privacy: options.privacy,
- inputProps: options.inputProps,
- serializedResolvedProps: options.serializedResolvedProps,
- renderMetadata: options.renderMetadata,
- logLevel: options.logLevel,
- overallProgress: options.overallProgress,
- startTime: options.startTime,
- providerSpecifics: options.providerSpecifics,
- insideFunctionSpecifics: options.insideFunctionSpecifics,
- forcePathStyle: options.forcePathStyle,
- storageClass: options.storageClass,
- requestHandler: options.requestHandler,
- outputFile: outfile,
- timeToCombine: encodingStop - encodingStart,
- });
-
- await cleanupChunksProm;
- return postRenderData;
+ try {
+ return await finishRender({
+ bucketName: options.bucketName,
+ separateAudioFile,
+ separateAudioCredentials: options.separateAudioCredentials,
+ expectedBucketOwner: options.expectedBucketOwner,
+ renderBucketName: options.renderBucketName,
+ customCredentials: options.customCredentials,
+ downloadBehavior: options.downloadBehavior,
+ key: options.key,
+ privacy: options.privacy,
+ inputProps: options.inputProps,
+ serializedResolvedProps: options.serializedResolvedProps,
+ renderMetadata: options.renderMetadata,
+ logLevel: options.logLevel,
+ overallProgress: options.overallProgress,
+ startTime: options.startTime,
+ providerSpecifics: options.providerSpecifics,
+ insideFunctionSpecifics: options.insideFunctionSpecifics,
+ forcePathStyle: options.forcePathStyle,
+ storageClass: options.storageClass,
+ requestHandler: options.requestHandler,
+ outputFile: outfile,
+ timeToCombine: encodingStop - encodingStart,
+ });
+ } finally {
+ await cleanupChunksProm;
+ await rm(dirname(outfile), {recursive: true, force: true});
+ }
};
diff --git a/packages/serverless/src/overall-render-progress.ts b/packages/serverless/src/overall-render-progress.ts
index b62c91618b..40d62f5d0f 100644
--- a/packages/serverless/src/overall-render-progress.ts
+++ b/packages/serverless/src/overall-render-progress.ts
@@ -8,6 +8,7 @@ import type {
ProviderSpecifics,
ReceivedArtifact,
RenderMetadata,
+ SeparateAudioOutput,
} from '@remotion/serverless-client';
import {overallProgressKey} from '@remotion/serverless-client';
@@ -43,6 +44,7 @@ export type OverallProgressHelper<Provider extends CloudProvider> = {
postRenderData: PostRenderData<Provider>,
) => Promise<void>;
setRenderMetadata: (renderMetadata: RenderMetadata<Provider>) => void;
+ setSeparateAudio: (separateAudio: SeparateAudioOutput) => Promise<void>;
addErrorWithoutUpload: (errorInfo: FunctionErrorInfo) => void;
setExpectedChunks: (expectedChunks: number) => void;
get: () => OverallRenderProgress<Provider>;
@@ -69,6 +71,7 @@ export const makeInitialOverallRenderProgress = <
lambdasInvoked: 0,
retries: [],
postRenderData: null,
+ separateAudio: null,
timings: [],
renderMetadata: null,
errors: [],
@@ -284,6 +287,10 @@ export const makeOverallRenderProgress = <Provider extends CloudProvider>({
renderProgress.postRenderData = postRenderData;
await upload('setPostRenderData');
},
+ async setSeparateAudio(separateAudio) {
+ renderProgress.separateAudio = separateAudio;
+ await upload('setSeparateAudio');
+ },
setRenderMetadata: (renderMetadata) => {
renderProgress.renderMetadata = renderMetadata;
upload('setRenderMetadata');
diff --git a/packages/serverless/src/render-with-single-function.ts b/packages/serverless/src/render-with-single-function.ts
index fd2eb3618a..76b3ec4cd7 100644
--- a/packages/serverless/src/render-with-single-function.ts
+++ b/packages/serverless/src/render-with-single-function.ts
@@ -48,6 +48,7 @@ export const renderWithSingleFunction = async <Provider extends CloudProvider>({
insideFunctionSpecifics: InsideFunctionSpecifics<Provider>;
}): Promise<{
outputFile: string;
+ separateAudioFile: string | null;
cleanup: () => Promise<void>;
}> => {
if (params.type !== ServerlessRoutines.launch) {
@@ -55,11 +56,22 @@ export const renderWithSingleFunction = async <Provider extends CloudProvider>({
}
const outputDirectory = RenderInternals.tmpDir('remotion-direct-render-');
+ const separateAudioFilename =
+ typeof params.separateAudioTo === 'string'
+ ? params.separateAudioTo
+ : (params.separateAudioTo?.key ?? null);
+ const separateAudioFile =
+ separateAudioFilename === null
+ ? null
+ : join(
+ outputDirectory,
+ `audio.${RenderInternals.getExtensionOfFilename(separateAudioFilename)?.toLowerCase()}`,
+ );
const outputFile = join(
outputDirectory,
`output.${RenderInternals.getFileExtensionFromCodec(
params.codec,
- params.audioCodec,
+ separateAudioFile === null ? params.audioCodec : null,
)}`,
);
const cleanup = () =>
@@ -89,6 +101,7 @@ export const renderWithSingleFunction = async <Provider extends CloudProvider>({
serveUrl: params.serveUrl,
codec: params.codec,
outputLocation: outputFile,
+ separateAudioTo: separateAudioFile,
inputProps: JSON.parse(serializedInputPropsWithCustomSchema) as Record<
string,
unknown
@@ -168,7 +181,7 @@ export const renderWithSingleFunction = async <Provider extends CloudProvider>({
overallProgress.addChunkCompleted(0, startedAt, Date.now());
overallProgress.setCombinedFrames(frameCount);
- return {outputFile, cleanup};
+ return {outputFile, separateAudioFile, cleanup};
} catch (err) {
await cleanup();
throw err;
diff --git a/packages/serverless/src/test/overall-render-progress.test.ts b/packages/serverless/src/test/overall-render-progress.test.ts
index 8b6f362493..d3959c1687 100644
--- a/packages/serverless/src/test/overall-render-progress.test.ts
+++ b/packages/serverless/src/test/overall-render-progress.test.ts
@@ -64,6 +64,7 @@ const makeProviderSpecifics = ({
};
const postRenderData: PostRenderData<MockProvider> = {
+ separateAudio: null,
artifactProgress: [],
cost: {
currency: 'USD',