🎥 Make videos programmatically with React
Keep layer separation as the public video matting API
Jonny Burger470f492743c3
diff --git a/packages/docs/docs/video-matting/index.mdx b/packages/docs/docs/video-matting/index.mdxindex 9e4172a8b2..2985d733cc 100644--- a/packages/docs/docs/video-matting/index.mdx+++ b/packages/docs/docs/video-matting/index.mdx@@ -1,12 +1,12 @@---image: /generated/articles-docs-video-matting-index.pngtitle: '@remotion/video-matting'-crumb: 'Remove a video background'+crumb: 'Separate a video into layers'---# @remotion/video-matting<AvailableFrom v="4.0.523" />-Remove a video's background or separate it into background and foreground layers, locally in the browser or [Node.js](/docs/video-matting/node) using WebGPU.+Separate a video into opaque base and transparent foreground layers, locally in the browser or [Node.js](/docs/video-matting/node) using WebGPU.import {TableOfContents} from './table-of-contents';@@ -14,27 +14,11 @@ import {TableOfContents} from './table-of-contents';<Installation pkg="@remotion/video-matting @huggingface/transformers" />-## Example+## Studio-```ts twoslash title="remove-video-background.ts"-import {downloadVideoMattingModel, removeVideoBackground} from '@remotion/video-matting';+Remotion Studio offers **Remove background** for a selected video. It replaces the video's source with a transparent WebM. Duplicate the layer first if you want to keep the original alongside it.-export const matteVideo = async (file: File) => {- await downloadVideoMattingModel({- model: 'modnet',- onProgress: ({progress}) => console.log('Downloading model:', progress),- });- await using result = await removeVideoBackground({- src: file,- model: 'modnet',- onProgress: ({progress}) => console.log('Removing background:', progress),- });-- return result.video.getBlob();-};-```--To preserve the original video alongside the transparent result, duplicate its layer in Studio before removing the background.+For programmatic base and foreground outputs, see [`separateVideoLayers()`](/docs/video-matting/separate-video-layers).## Model hosting@@ -52,7 +36,7 @@ A GPU is needed for this.Use [`canUseVideoMatting()`](/docs/video-matting/can-use-video-matting) to check whether your system can use video matting.The browser must also be able to decode the input video and encode VP9 with alpha through WebCodecs.-[`removeVideoBackground()`](/docs/video-matting/remove-video-background) and [`separateVideoLayers()`](/docs/video-matting/separate-video-layers) check these media capabilities for the selected input.+[`separateVideoLayers()`](/docs/video-matting/separate-video-layers) checks these media capabilities for the selected input.## Licensediff --git a/packages/docs/docs/video-matting/node.mdx b/packages/docs/docs/video-matting/node.mdxindex 6b6cb27448..f589d6f4e4 100644--- a/packages/docs/docs/video-matting/node.mdx+++ b/packages/docs/docs/video-matting/node.mdx@@ -14,17 +14,11 @@ Register [`@mediabunny/server`](https://mediabunny.dev/guide/extensions/server)<Installation pkg="@remotion/video-matting @huggingface/transformers mediabunny @mediabunny/server" />-## Example+## Setup-```ts twoslash title="separate-video.ts"+```ts twoslash title="video-matting-setup.ts"import {registerMediabunnyServer} from '@mediabunny/server';-import {- canUseVideoMatting,- downloadVideoMattingModel,- loadVideoMattingModel,- separateVideoLayers,-} from '@remotion/video-matting';-import {writeFile} from 'node:fs/promises';+import {canUseVideoMatting} from '@remotion/video-matting';registerMediabunnyServer();@@ -34,26 +28,6 @@ if (!support.supported) {throw new Error(support.detailedReason);}-await downloadVideoMattingModel({model});--// In long-running apps, put this code in an async function so resources-// are released when that function finishes.-await using modelHandle = await loadVideoMattingModel({model});-await using layers = await separateVideoLayers({- src: './input.mp4',- model,- audio: 'base',- onProgress: ({processedFrames}) => console.log(processedFrames),-});--await writeFile(- 'base.webm',- new Uint8Array(await (await layers.base.getBlob()).arrayBuffer()),-);-await writeFile(- 'foreground.webm',- new Uint8Array(await (await layers.foreground.getBlob()).arrayBuffer()),-);```[`separateVideoLayers()`](/docs/video-matting/separate-video-layers) accepts local file paths, `file:` URLs, remote URLs, and `Blob` inputs. Outputs are held in memory by default. Use `outputWritable` to stream large outputs; handle each chunk's `position` because writes are not necessarily append-only.diff --git a/packages/docs/docs/video-matting/remove-video-background.mdx b/packages/docs/docs/video-matting/remove-video-background.mdxdeleted file mode 100644index 324b851182..0000000000--- a/packages/docs/docs/video-matting/remove-video-background.mdx+++ /dev/null@@ -1,82 +0,0 @@-----image: /generated/articles-docs-video-matting-remove-video-background.png-title: removeVideoBackground()-crumb: '@remotion/video-matting'------# removeVideoBackground()<AvailableFrom v="4.0.528" />--Removes a video's background and returns one transparent WebM. The original audio is kept by default.--```ts twoslash title="remove-background.ts"-import {downloadVideoMattingModel, removeVideoBackground} from '@remotion/video-matting';--await downloadVideoMattingModel({model: 'modnet'});-const file = new File([], 'input.mp4');--await using result = await removeVideoBackground({src: file, model: 'modnet'});-const transparentVideo = await result.video.getBlob();-```--## Options--### src--A `string`, `URL`, or `Blob` containing the input video. A `File` may be passed because it extends `Blob`. In [Node.js](/docs/video-matting/node), strings can also be local file paths.--### model?--The model to use. Default: `modnet`. See [`getAvailableModels()`](/docs/video-matting/get-available-models).--### audio?--`keep` retains the input video's primary audio track in the output. `none` produces a silent video. Default: `keep`.--### output?--Configures the output destination using `VideoLayerOutputOptions`. Default: `web-fs` when available, otherwise `arraybuffer`.--#### output.outputTarget?--Set to `arraybuffer` to keep the encoded video in memory, or `web-fs` to store it in the browser's origin-private file system. Default: automatic selection.--#### output.outputWritable?--A `WritableStream<StreamTargetChunk>` receiving the encoded video. It cannot be combined with `outputTarget`. When set, `result.video.getBlob()` rejects because the bytes were sent to the stream.--### videoBitrate?--The VP9 video quality. Default: `very-high`. Accepts `very-low`, `low`, `medium`, `high`, `very-high`, or a positive integer bitrate in bits per second.--### audioBitrate?--The Opus audio quality when transcoding. Default: `medium`.--### keyframeIntervalInSeconds?--The maximum time between video keyframes. Default: `1`.--### signal?--An `AbortSignal` to cancel processing.--### onModelLoadProgress?--Called while initializing a downloaded model.--### onProgress?--Called while processing and finalizing the output. The callback receives the same progress shape as [`separateVideoLayers()`](/docs/video-matting/separate-video-layers).--## Return value--The result includes `video`, a `VideoLayerOutput` with `getBlob()` and `dispose()` methods, plus `model`, `width`, `height`, `durationInSeconds`, and `processedFrames`. Dispose the result after use. `await using` does this automatically.--## Compatibility--<CompatibilityTable chrome firefox safari nodejs bun="" serverlessFunctions={false} clientSideRendering={false} serverSideRendering player studio />--## See also--- [`separateVideoLayers()`](/docs/video-matting/separate-video-layers)-- [`canUseVideoMatting()`](/docs/video-matting/can-use-video-matting)diff --git a/packages/docs/docs/video-matting/separate-video-layers.mdx b/packages/docs/docs/video-matting/separate-video-layers.mdxindex 82958a130e..280df4402b 100644--- a/packages/docs/docs/video-matting/separate-video-layers.mdx+++ b/packages/docs/docs/video-matting/separate-video-layers.mdx@@ -8,26 +8,7 @@ crumb: '@remotion/video-matting'Separates a video into an opaque base WebM and a foreground WebM with alpha.-The downloaded model is loaded automatically if needed.--```ts twoslash title="separate-video.ts"-import {downloadVideoMattingModel, separateVideoLayers} from '@remotion/video-matting';--await downloadVideoMattingModel({model: 'modnet'});-const file = new File([], 'input.mp4');--await using result = await separateVideoLayers({- src: file,- model: 'modnet',- audio: 'base',- onProgress: (progress) => {- console.log(progress);- },-});--const baseBlob = await result.base.getBlob();-const foregroundBlob = await result.foreground.getBlob();-```+The downloaded model is loaded automatically if needed. Call [`downloadVideoMattingModel()`](/docs/video-matting/download-video-matting-model) first to cache the model files.Place inserted content between the base and foreground. The base remains opaque and includes the original subject; the foreground repeats the subject with alpha so it appears in front of the inserted content.diff --git a/packages/docs/docs/video-matting/table-of-contents.tsx b/packages/docs/docs/video-matting/table-of-contents.tsxindex 648a74530a..0e4a81d1ea 100644--- a/packages/docs/docs/video-matting/table-of-contents.tsx+++ b/packages/docs/docs/video-matting/table-of-contents.tsx@@ -33,10 +33,6 @@ export const TableOfContents: React.FC = () => {<strong>separateVideoLayers()</strong><div>Create base and foreground WebM layers</div></TOCItem>- <TOCItem link="/docs/video-matting/remove-video-background">- <strong>removeVideoBackground()</strong>- <div>Create a transparent WebM</div>- </TOCItem><TOCItem link="/docs/video-matting/dispose-video-matting-model"><strong>disposeVideoMattingModel()</strong><div>Release model memory</div>diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 44a74e0f15..96073a98ce 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -971,7 +971,6 @@ const sidebars: SidebarsConfig = {'video-matting/download-video-matting-model','video-matting/load-video-matting-model','video-matting/remove-video-matting-model',- 'video-matting/remove-video-background','video-matting/separate-video-layers','video-matting/dispose-video-matting-model',],diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.tsindex 736a09ef2c..a8a940d1c0 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -8994,15 +8994,6 @@ export const articles = [noAi: false,slug: 'video-matting/node',},- {- id: 'video-matting/remove-video-background',- title: 'removeVideoBackground()',- relativePath: 'docs/video-matting/remove-video-background.mdx',- compId: 'articles-docs-video-matting-remove-video-background',- crumb: '@remotion/video-matting',- noAi: false,- slug: 'video-matting/remove-video-background',- },{id: 'video-matting/remove-video-matting-model',title: 'removeVideoMattingModel()',diff --git a/packages/docs/static/generated/articles-docs-video-matting-remove-video-background.png b/packages/docs/static/generated/articles-docs-video-matting-remove-video-background.pngdeleted file mode 100644index 990237ecb8..0000000000Binary files a/packages/docs/static/generated/articles-docs-video-matting-remove-video-background.png and /dev/null differdiff --git a/packages/studio/src/components/RenderQueue/VideoMattingQueueProcessor.tsx b/packages/studio/src/components/RenderQueue/VideoMattingQueueProcessor.tsxindex 771bb52149..a216ebd546 100644--- a/packages/studio/src/components/RenderQueue/VideoMattingQueueProcessor.tsx+++ b/packages/studio/src/components/RenderQueue/VideoMattingQueueProcessor.tsx@@ -4,8 +4,7 @@ import {downloadVideoMattingModel,isVideoMattingModelCached,loadVideoMattingModel,- removeVideoBackground,- type RemoveVideoBackgroundResult,+ VideoMattingInternals,type SeparateVideoLayersProgress,} from '@remotion/video-matting';import {useCallback, useContext, useEffect} from 'react';@@ -30,7 +29,9 @@ export const VideoMattingQueueProcessor: React.FC = () => {const processJob = useCallback(async (job: VideoMattingJob) => {const {signal} = getAbortController(job.id);- let output: RemoveVideoBackgroundResult | null = null;+ let output: Awaited<+ ReturnType<typeof VideoMattingInternals.removeVideoBackground>+ > | null = null;let processingError: Error | null = null;try {signal.throwIfAborted();@@ -85,7 +86,7 @@ export const VideoMattingQueueProcessor: React.FC = () => {});},};- output = await removeVideoBackground({+ output = await VideoMattingInternals.removeVideoBackground({...mattingOptions,audio: job.audio,});diff --git a/packages/studio/src/test/video-matting-queue-processor.test.tsx b/packages/studio/src/test/video-matting-queue-processor.test.tsxindex 0c7db37a1b..3cdca04688 100644--- a/packages/studio/src/test/video-matting-queue-processor.test.tsx+++ b/packages/studio/src/test/video-matting-queue-processor.test.tsx@@ -27,23 +27,25 @@ mock.module('@remotion/video-matting', () => ({calls.push('load-model');return Promise.resolve({alreadyLoaded: false});},- removeVideoBackground: ({- onProgress,- }: {- onProgress: (progress: {- stage: string;- progress: number;- processedFrames: number;- }) => void;- }) => {- calls.push('remove-background');- onProgress({stage: 'processing', progress: 0.5, processedFrames: 42});- return Promise.resolve({- video: {- getBlob: () => Promise.resolve(new Blob(['video'])),- dispose: () => Promise.resolve(),- },- });+ VideoMattingInternals: {+ removeVideoBackground: ({+ onProgress,+ }: {+ onProgress: (progress: {+ stage: string;+ progress: number;+ processedFrames: number;+ }) => void;+ }) => {+ calls.push('remove-background');+ onProgress({stage: 'processing', progress: 0.5, processedFrames: 42});+ return Promise.resolve({+ video: {+ getBlob: () => Promise.resolve(new Blob(['video'])),+ dispose: () => Promise.resolve(),+ },+ });+ },},disposeVideoMattingModel: () => {calls.push('dispose-model');diff --git a/packages/video-matting/src/index.ts b/packages/video-matting/src/index.tsindex 0e7e779616..ee889b978c 100644--- a/packages/video-matting/src/index.ts+++ b/packages/video-matting/src/index.ts@@ -34,13 +34,11 @@ export type {VideoLayerOutputOptions,VideoLayerOutputTarget,} from './output-target';-export {- removeVideoBackground,- separateVideoLayers,-} from './separate-video-layers';+import {removeVideoBackground} from './separate-video-layers';++export const VideoMattingInternals = {removeVideoBackground};+export {separateVideoLayers} from './separate-video-layers';export type {- RemoveVideoBackgroundOptions,- RemoveVideoBackgroundResult,SeparateVideoLayersOptions,SeparateVideoLayersProgress,SeparateVideoLayersResult,