🎥 Make videos programmatically with React
`@remotion/web-renderer`: Support writable output streams (#10197)
Alec Watts1d609104c804
diff --git a/packages/docs/docs/web-renderer/render-media-on-web.mdx b/packages/docs/docs/web-renderer/render-media-on-web.mdxindex 0fbd1e05ab..636f79dfb6 100644--- a/packages/docs/docs/web-renderer/render-media-on-web.mdx+++ b/packages/docs/docs/web-renderer/render-media-on-web.mdx@@ -295,6 +295,57 @@ Controls how the output is stored:By default, Remotion will automatically choose `"web-fs"` if available, otherwise `"arraybuffer"`.+### `outputWritable?`<AvailableFrom v="4.0.508" />++_WritableStream<StreamTargetChunk>_++Writes rendered media progressively to a `WritableStream` as data becomes available, instead of buffering the complete output in memory or the Origin Private File System.+This is useful for large renders and for streaming the output to a file, server, or native application.++The stream receives [Mediabunny `StreamTargetChunk`](https://mediabunny.dev/api/StreamTargetChunk) objects containing the data and its byte position.+[`FileSystemWritableFileStream`](https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream) is compatible with this format.++For example, you can render directly to a file selected by the user without keeping the finished video in memory:++```tsx title="RenderButton.tsx"+import {renderMediaOnWeb} from '@remotion/web-renderer';++const Component: React.FC = () => null;++const renderToFile = async () => {+ const fileHandle = await window.showSaveFilePicker({+ suggestedName: 'video.mp4',+ types: [+ {+ description: 'MP4 video',+ accept: {'video/mp4': ['.mp4']},+ },+ ],+ });+ const outputWritable = await fileHandle.createWritable();++ await renderMediaOnWeb({+ composition: {+ component: Component,+ durationInFrames: 100,+ fps: 30,+ width: 1920,+ height: 1080,+ id: 'my-composition',+ },+ outputWritable,+ });+};++export const RenderButton: React.FC = () => (+ <button onClick={renderToFile}>Render video</button>+);+```++`renderMediaOnWeb()` writes chunks at their correct byte positions and closes the stream when the render finishes. Do not call `getBlob()` when using `outputWritable`.++If both `outputWritable` and `outputTarget` are specified, `outputWritable` takes precedence.+### `schema?`_Zod v4 schema_ <TsType type="$ZodObject" source="zod/v4/core" />@@ -323,6 +374,8 @@ Returns a promise resolving to an object with the following properties:A function that returns a `Promise<Blob>` containing the rendered video. Call this function to retrieve the final video file.+If `outputWritable` was specified, the rendered media has already been written to the stream and `getBlob()` rejects.+```tsx twoslash title="Download the video"const Component: React.FC = () => null;const composition = {diff --git a/packages/web-renderer/src/render-media-on-web.tsx b/packages/web-renderer/src/render-media-on-web.tsxindex c80311bfe3..c174ab428d 100644--- a/packages/web-renderer/src/render-media-on-web.tsx+++ b/packages/web-renderer/src/render-media-on-web.tsx@@ -1,4 +1,4 @@-import {BufferTarget, StreamTarget} from 'mediabunny';+import {BufferTarget, StreamTarget, type StreamTargetChunk} from 'mediabunny';import type {CalculateMetadataFunction} from 'remotion';import {Internals, type LogLevel} from 'remotion';import {VERSION} from 'remotion/version';@@ -133,6 +133,7 @@ type OptionalRenderMediaOnWebOptions<Schema extends $ZodObject> = {onFrame: OnFrameCallback | null;pageResponsiveness: WebRendererPageResponsiveness;outputTarget: WebRendererOutputTarget | null;+ outputWritable: WritableStream<StreamTargetChunk> | null;licenseKey: string | null;isProduction: boolean;muted: boolean;@@ -182,6 +183,7 @@ const internalRenderMediaOnWeb = async <onFrame,pageResponsiveness,outputTarget: userDesiredOutputTarget,+ outputWritable,licenseKey,muted,scale,@@ -216,11 +218,13 @@ const internalRenderMediaOnWeb = async <};const outputTarget =- userDesiredOutputTarget === null- ? (await canUseWebFsWriter())- ? 'web-fs'- : 'arraybuffer'- : userDesiredOutputTarget;+ outputWritable !== null+ ? null+ : userDesiredOutputTarget === null+ ? (await canUseWebFsWriter())+ ? 'web-fs'+ : 'arraybuffer'+ : userDesiredOutputTarget;if (outputTarget === 'web-fs') {await cleanupStaleOpfsFiles();@@ -384,9 +388,11 @@ const internalRenderMediaOnWeb = async <const webFsTarget =outputTarget === 'web-fs' ? await createWebFsTarget() : null;- const target = webFsTarget- ? new StreamTarget(webFsTarget.stream)- : new BufferTarget()!;+ const target = outputWritable+ ? new StreamTarget(outputWritable)+ : webFsTarget+ ? new StreamTarget(webFsTarget.stream)+ : new BufferTarget()!;using outputWithCleanup = makeOutputWithCleanup({format,@@ -646,6 +652,24 @@ const internalRenderMediaOnWeb = async <`Render timings: waitForReady=${internalState.getWaitForReadyTime().toFixed(2)}ms, createFrame=${internalState.getCreateFrameTime().toFixed(2)}ms, addSample=${internalState.getAddSampleTime().toFixed(2)}ms, audioMixing=${internalState.getAudioMixingTime().toFixed(2)}ms`,);+ if (outputWritable) {+ sendUsageEvent({+ licenseKey: licenseKey ?? null,+ succeeded: true,+ apiName: 'renderMediaOnWeb',+ isStill: false,+ isProduction: isProduction ?? true,+ });++ return {+ getBlob: () =>+ Promise.reject(+ new Error('getBlob() is unavailable when outputWritable is used'),+ ),+ internalState,+ };+ }+if (webFsTarget) {sendUsageEvent({licenseKey: licenseKey ?? null,@@ -745,6 +769,7 @@ export const renderMediaOnWeb = <onFrame: options.onFrame ?? null,pageResponsiveness: options.pageResponsiveness ?? 'medium',outputTarget: options.outputTarget ?? null,+ outputWritable: options.outputWritable ?? null,licenseKey: options.licenseKey ?? null,muted: options.muted ?? false,scale: options.scale ?? 1,diff --git a/packages/web-renderer/src/test/render-media.test.tsx b/packages/web-renderer/src/test/render-media.test.tsxindex e2fe06f639..51652fa358 100644--- a/packages/web-renderer/src/test/render-media.test.tsx+++ b/packages/web-renderer/src/test/render-media.test.tsx@@ -1,4 +1,9 @@-import {ALL_FORMATS, BlobSource, Input} from 'mediabunny';+import {+ ALL_FORMATS,+ BlobSource,+ Input,+ type StreamTargetChunk,+} from 'mediabunny';import {interpolateColors, useCurrentFrame} from 'remotion';import {VERSION} from 'remotion/version';import {expect, test} from 'vitest';@@ -52,6 +57,69 @@ test('should render media on web', async (t) => {});});+test('should render media to a writable stream', async (t) => {+ if (t.task.file.projectName === 'webkit') {+ t.skip();+ return;+ }++ const chunks: StreamTargetChunk[] = [];+ let streamClosed = false;+ let firstFrameRendered = false;+ let receivedChunkBeforeFirstFrame = false;+ const outputWritable = new WritableStream<StreamTargetChunk>({+ write: (chunk) => {+ if (!firstFrameRendered) {+ receivedChunkBeforeFirstFrame = true;+ }++ chunks.push(chunk);+ },+ close: () => {+ streamClosed = true;+ },+ });++ const result = await renderMediaOnWeb({+ composition: {+ component: () => null,+ id: 'writable-stream-test',+ width: 100,+ height: 100,+ fps: 30,+ durationInFrames: 1,+ },+ inputProps: {},+ outputWritable,+ onFrame: (frame) => {+ firstFrameRendered = true;+ return frame;+ },+ });++ expect(streamClosed).toBe(true);+ expect(chunks.length).toBeGreaterThan(0);+ expect(receivedChunkBeforeFirstFrame).toBe(true);++ const size = Math.max(+ ...chunks.map((chunk) => chunk.position + chunk.data.byteLength),+ );+ const output = new Uint8Array(size);+ for (const chunk of chunks) {+ output.set(chunk.data, chunk.position);+ }++ expect(output.byteLength).toBeGreaterThan(0);+ using input = new Input({+ formats: ALL_FORMATS,+ source: new BlobSource(new Blob([output])),+ });+ expect(await input.getPrimaryVideoTrack()).not.toBeNull();+ await expect(result.getBlob()).rejects.toThrow(+ 'getBlob() is unavailable when outputWritable is used',+ );+});+test('should reject invalid page responsiveness values', async () => {const Component: React.FC = () => null;