Skip to content

🎥 Make videos programmatically with React

Merge branch 'main' of https://github.com/remotion-dev/remotion into feature/web-renderer-audio-codecs

Igor Samokhovets4d08ea91021b
diff --cc packages/web-renderer/src/index.ts
index 34dcda2915,10d5602fa6..a75f78c408
--- a/packages/web-renderer/src/index.ts
+++ b/packages/web-renderer/src/index.ts
@@@ -1,11 -1,8 +1,13 @@@
+ import './symbol-dispose';
+
export type {EmittedArtifact, WebRendererOnArtifact} from './artifact';
export type {FrameRange} from './frame-range';
+export {
+ getDefaultAudioCodecForContainer,
+ getSupportedAudioCodecsForContainer,
+} from './mediabunny-mappings';
export type {
+ WebRendererAudioCodec,
WebRendererContainer,
WebRendererQuality,
WebRendererVideoCodec,
diff --cc packages/web-renderer/src/render-media-on-web.tsx
index 56b6aac5a7,bf7312c951..710ad982fb
--- a/packages/web-renderer/src/render-media-on-web.tsx
+++ b/packages/web-renderer/src/render-media-on-web.tsx
@@@ -1,11 -1,4 +1,4 @@@
- import {
- AudioSampleSource,
- BufferTarget,
- canEncodeAudio,
- Output,
- StreamTarget,
- VideoSampleSource,
- } from 'mediabunny';
-import {BufferTarget, StreamTarget} from 'mediabunny';
++import {BufferTarget, canEncodeAudio, StreamTarget} from 'mediabunny';
import type {CalculateMetadataFunction} from 'remotion';
import {Internals, type LogLevel} from 'remotion';
import type {AnyZodObject, z} from 'zod';
@@@ -15,10 -8,14 +8,15 @@@ import {onlyInlineAudio} from './audio'
import {canUseWebFsWriter} from './can-use-webfs-target';
import {createScaffold} from './create-scaffold';
import {getRealFrameRange, type FrameRange} from './frame-range';
-import {addAudioSampleSource} from './get-audio-sample-source';
++import {createAudioSampleSource} from './get-audio-sample-source';
import type {InternalState} from './internal-state';
import {makeInternalState} from './internal-state';
+ import {
+ makeOutputWithCleanup,
+ makeVideoSampleSourceCleanup,
+ } from './mediabunny-cleanups';
import type {
+ WebRendererAudioCodec,
WebRendererContainer,
WebRendererQuality,
} from './mediabunny-mappings';
@@@ -186,10 -176,6 +183,11 @@@ const internalRenderMediaOnWeb = async
);
}
+ const audioCodec =
+ unresolvedAudioCodec ?? getDefaultAudioCodecForContainer(container);
- const userSpecifiedAudioCodec = unresolvedAudioCodec !== undefined;
++ const userSpecifiedAudioCodec =
++ unresolvedAudioCodec !== undefined && unresolvedAudioCodec !== null;
+
const resolved = await Internals.resolveVideoConfig({
calculateMetadata:
(composition.calculateMetadata as CalculateMetadataFunction<
@@@ -292,99 -267,14 +279,89 @@@
alpha: transparent ? 'keep' : 'discard',
});
- cleanupFns.push(() => {
- videoSampleSource.close();
- });
-
- output.addVideoTrack(videoSampleSource);
+ outputWithCleanup.output.addVideoTrack(videoSampleSource.videoSampleSource);
- let audioSampleSource: AudioSampleSource | null = null;
- using audioSampleSource = await addAudioSampleSource({
++ const resolvedAudioBitrate =
++ typeof audioBitrate === 'number'
++ ? audioBitrate
++ : getQualityForWebRendererQuality(audioBitrate);
+
++ // Resolve audio codec (with fallback if needed)
++ let finalAudioCodec: WebRendererAudioCodec | null = null;
+ if (!muted) {
+ const supportedAudioCodecs =
+ getSupportedAudioCodecsForContainer(container);
+ if (!supportedAudioCodecs.includes(audioCodec)) {
+ return Promise.reject(
+ new Error(
+ `Audio codec "${audioCodec}" is not supported for container "${container}". Supported audio codecs: ${supportedAudioCodecs.join(', ')}`,
+ ),
+ );
+ }
+
- const resolvedAudioBitrate =
- typeof audioBitrate === 'number'
- ? audioBitrate
- : getQualityForWebRendererQuality(audioBitrate);
-
- let finalAudioCodec = audioCodec;
++ finalAudioCodec = audioCodec;
+ const mediabunnyAudioCodec = audioCodecToMediabunnyAudioCodec(audioCodec);
+ const canEncode = await canEncodeAudio(mediabunnyAudioCodec, {
+ bitrate: resolvedAudioBitrate,
+ });
+
+ if (!canEncode) {
+ if (userSpecifiedAudioCodec) {
- let errorMessage = `Audio codec "${audioCodec}" cannot be encoded by this browser.`;
- const isFirefox =
- typeof navigator !== 'undefined' &&
- /firefox/i.test(navigator.userAgent);
- if (audioCodec === 'aac' && isFirefox) {
- errorMessage +=
- ' AAC encoding is not supported in Firefox. Try using "opus" instead.';
- } else {
- errorMessage +=
- ' This is common for AAC on Firefox. Try using "opus" instead.';
- }
-
- return Promise.reject(new Error(errorMessage));
++ return Promise.reject(
++ new Error(
++ `Audio codec "${audioCodec}" cannot be encoded by this browser. This is common for AAC on Firefox. Try using "opus" instead.`,
++ ),
++ );
+ }
+
+ let fallbackCodec: WebRendererAudioCodec | null = null;
+ for (const supportedCodec of supportedAudioCodecs) {
+ if (supportedCodec !== audioCodec) {
+ const fallbackMediabunnyCodec =
+ audioCodecToMediabunnyAudioCodec(supportedCodec);
+ const canEncodeFallback = await canEncodeAudio(
+ fallbackMediabunnyCodec,
+ {
+ bitrate: resolvedAudioBitrate,
+ },
+ );
+ if (canEncodeFallback) {
+ fallbackCodec = supportedCodec;
+ break;
+ }
+ }
+ }
+
- Internals.Log.warn(
- {logLevel, tag: '@remotion/web-renderer'},
- `Falling back from audio codec "${audioCodec}" to "${fallbackCodec}" for container "${container}" because the original codec cannot be encoded by this browser.`,
- );
+ if (!fallbackCodec) {
+ return Promise.reject(
+ new Error(
+ `No audio codec can be encoded by this browser for container "${container}".`,
+ ),
+ );
+ }
+
++ Internals.Log.warn(
++ {logLevel, tag: '@remotion/web-renderer'},
++ `Falling back from audio codec "${audioCodec}" to "${fallbackCodec}" for container "${container}" because the original codec cannot be encoded by this browser.`,
++ );
+ finalAudioCodec = fallbackCodec;
+ }
++ }
+
- audioSampleSource = new AudioSampleSource({
- codec: audioCodecToMediabunnyAudioCodec(finalAudioCodec),
- bitrate: resolvedAudioBitrate,
- });
-
- cleanupFns.push(() => {
- audioSampleSource?.close();
- });
-
- output.addAudioTrack(audioSampleSource);
++ using audioSampleSource = createAudioSampleSource({
+ muted,
- output: outputWithCleanup.output,
++ codec: finalAudioCodec
++ ? audioCodecToMediabunnyAudioCodec(finalAudioCodec)
++ : null,
++ bitrate: resolvedAudioBitrate,
+ });
++ if (audioSampleSource.audioSampleSource) {
++ outputWithCleanup.output.addAudioTrack(
++ audioSampleSource.audioSampleSource,
++ );
+ }
- await output.start();
+ await outputWithCleanup.output.start();
if (signal?.aborted) {
throw new Error('renderMediaOnWeb() was cancelled');
@@@ -473,11 -345,34 +432,34 @@@
});
}
+ const audioCombineStart = performance.now();
+ const assets = collectAssets.current!.collectAssets();
+ if (onArtifact) {
+ await artifactsHandler.handle({
+ imageData,
+ frame,
+ assets,
+ onArtifact,
+ });
+ }
+
+ if (signal?.aborted) {
+ throw new Error('renderMediaOnWeb() was cancelled');
+ }
+
+ const audio = muted
+ ? null
+ : onlyInlineAudio({assets, fps: resolved.fps, frame});
+ internalState.addAudioMixingTime(performance.now() - audioCombineStart);
+
const addSampleStart = performance.now();
await Promise.all([
- addVideoSampleAndCloseFrame(frameToEncode, videoSampleSource),
- audio && audioSampleSource
- ? addAudioSample(audio, audioSampleSource)
+ addVideoSampleAndCloseFrame(
+ frameToEncode,
+ videoSampleSource.videoSampleSource,
+ ),
- audio && audioSampleSource
++ audio && audioSampleSource.audioSampleSource
+ ? addAudioSample(audio, audioSampleSource.audioSampleSource)
: Promise.resolve(),
]);
internalState.addAddSampleTime(performance.now() - addSampleStart);
@@@ -493,9 -388,9 +475,9 @@@
// Call progress one final time to ensure final state is reported
onProgress?.({...progress});
- videoSampleSource.close();
- audioSampleSource?.close();
- await output.finalize();
+ videoSampleSource.videoSampleSource.close();
- audioSampleSource?.audioSampleSource.close();
++ audioSampleSource.audioSampleSource?.close();
+ await outputWithCleanup.output.finalize();
Internals.Log.verbose(
{logLevel, tag: 'web-renderer'},