🎥 Make videos programmatically with React
Add video matting model management
JonnyBurgerbcb3c81c1176
diff --git a/packages/docs/docs/video-matting/dispose-video-matting-model.mdx b/packages/docs/docs/video-matting/dispose-video-matting-model.mdxindex 00a46e2bae..3e7adf5573 100644--- a/packages/docs/docs/video-matting/dispose-video-matting-model.mdx+++ b/packages/docs/docs/video-matting/dispose-video-matting-model.mdx@@ -34,3 +34,4 @@ A `Promise<void>` that resolves after the selected models have been disposed.- [`loadVideoMattingModel()`](/docs/video-matting/load-video-matting-model)- [`isVideoMattingModelCached()`](/docs/video-matting/is-video-matting-model-cached)+- [`removeVideoMattingModel()`](/docs/video-matting/remove-video-matting-model)diff --git a/packages/docs/docs/video-matting/get-available-models.mdx b/packages/docs/docs/video-matting/get-available-models.mdxindex efd8965d4c..d685248131 100644--- a/packages/docs/docs/video-matting/get-available-models.mdx+++ b/packages/docs/docs/video-matting/get-available-models.mdx@@ -52,3 +52,4 @@ The total size in bytes of all runtime files downloaded for WebGPU.- [`isVideoMattingModelCached()`](/docs/video-matting/is-video-matting-model-cached)- [`loadVideoMattingModel()`](/docs/video-matting/load-video-matting-model)+- [`removeVideoMattingModel()`](/docs/video-matting/remove-video-matting-model)diff --git a/packages/docs/docs/video-matting/is-video-matting-model-cached.mdx b/packages/docs/docs/video-matting/is-video-matting-model-cached.mdxindex a39d561519..20d886cd7b 100644--- a/packages/docs/docs/video-matting/is-video-matting-model-cached.mdx+++ b/packages/docs/docs/video-matting/is-video-matting-model-cached.mdx@@ -34,3 +34,4 @@ A `Promise<boolean>` resolving to `true` if every required model file is cached.- [`getAvailableModels()`](/docs/video-matting/get-available-models)- [`loadVideoMattingModel()`](/docs/video-matting/load-video-matting-model)+- [`removeVideoMattingModel()`](/docs/video-matting/remove-video-matting-model)diff --git a/packages/docs/docs/video-matting/load-video-matting-model.mdx b/packages/docs/docs/video-matting/load-video-matting-model.mdxindex d7696bd31e..5cc0d7b1a3 100644--- a/packages/docs/docs/video-matting/load-video-matting-model.mdx+++ b/packages/docs/docs/video-matting/load-video-matting-model.mdx@@ -73,4 +73,5 @@ The hosted files are byte-identical to files from the pinned upstream Hugging Fa- [`disposeVideoMattingModel()`](/docs/video-matting/dispose-video-matting-model)- [`isVideoMattingModelCached()`](/docs/video-matting/is-video-matting-model-cached)+- [`removeVideoMattingModel()`](/docs/video-matting/remove-video-matting-model)- [`separateVideoLayers()`](/docs/video-matting/separate-video-layers)diff --git a/packages/docs/docs/video-matting/remove-video-matting-model.mdx b/packages/docs/docs/video-matting/remove-video-matting-model.mdxnew file mode 100644index 0000000000..7fedf0bdac--- /dev/null+++ b/packages/docs/docs/video-matting/remove-video-matting-model.mdx@@ -0,0 +1,33 @@+---+image: /generated/articles-docs-video-matting-remove-video-matting-model.png+title: removeVideoMattingModel()+crumb: '@remotion/video-matting'+---++# removeVideoMattingModel()<AvailableFrom v="4.0.523" />++Removes a video matting model from memory and the persistent browser cache.++If the model is still loading or separating a video, removal waits for the operation to finish.++```ts twoslash title="remove-model.ts"+import {removeVideoMattingModel} from '@remotion/video-matting';++await removeVideoMattingModel({model: 'modnet'});+```++## Options++### model++One of the names returned by [`getAvailableModels()`](/docs/video-matting/get-available-models).++## Compatibility++<CompatibilityTable chrome firefox safari nodejs="" bun="" serverlessFunctions="" clientSideRendering={false} serverSideRendering player studio hideServers />++## See also++- [`disposeVideoMattingModel()`](/docs/video-matting/dispose-video-matting-model)+- [`isVideoMattingModelCached()`](/docs/video-matting/is-video-matting-model-cached)+- [`loadVideoMattingModel()`](/docs/video-matting/load-video-matting-model)diff --git a/packages/docs/docs/video-matting/table-of-contents.tsx b/packages/docs/docs/video-matting/table-of-contents.tsxindex dc42596af2..45896f1fc5 100644--- a/packages/docs/docs/video-matting/table-of-contents.tsx+++ b/packages/docs/docs/video-matting/table-of-contents.tsx@@ -21,6 +21,10 @@ export const TableOfContents: React.FC = () => {<strong>loadVideoMattingModel()</strong><div>Download and initialize a model</div></TOCItem>+ <TOCItem link="/docs/video-matting/remove-video-matting-model">+ <strong>removeVideoMattingModel()</strong>+ <div>Remove a model from the browser cache</div>+ </TOCItem><TOCItem link="/docs/video-matting/separate-video-layers"><strong>separateVideoLayers()</strong><div>Create base and foreground WebM layers</div>diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.tsindex 89090803b4..b7e0b2fd89 100644--- a/packages/docs/sidebars.ts+++ b/packages/docs/sidebars.ts@@ -957,6 +957,7 @@ const sidebars: SidebarsConfig = {'video-matting/get-available-models','video-matting/is-video-matting-model-cached','video-matting/load-video-matting-model',+ 'video-matting/remove-video-matting-model','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 61b07c9eb4..0d87ce75fd 100644--- a/packages/docs/src/data/articles.ts+++ b/packages/docs/src/data/articles.ts@@ -8516,6 +8516,15 @@ export const articles = [noAi: false,slug: 'video-matting/load-video-matting-model',},+ {+ id: 'video-matting/remove-video-matting-model',+ title: 'removeVideoMattingModel()',+ relativePath: 'docs/video-matting/remove-video-matting-model.mdx',+ compId: 'articles-docs-video-matting-remove-video-matting-model',+ crumb: '@remotion/video-matting',+ noAi: false,+ slug: 'video-matting/remove-video-matting-model',+ },{id: 'video-matting/separate-video-layers',title: 'separateVideoLayers()',diff --git a/packages/docs/static/generated/articles-docs-video-matting-remove-video-matting-model.png b/packages/docs/static/generated/articles-docs-video-matting-remove-video-matting-model.pngnew file mode 100644index 0000000000..fbc597fc3cBinary files /dev/null and b/packages/docs/static/generated/articles-docs-video-matting-remove-video-matting-model.png differdiff --git a/packages/example/e2e/transcription-modal.test.mts b/packages/example/e2e/transcription-modal.test.mtsindex 8f79c6a0b3..75b42841ac 100644--- a/packages/example/e2e/transcription-modal.test.mts+++ b/packages/example/e2e/transcription-modal.test.mts@@ -62,20 +62,23 @@ test.describe('transcription modal', () => {});await expect(mattingDialog.getByTitle('Model')).toContainText('modnet');await expect(- mattingDialog.getByRole('button', {name: 'Separate'}),+ mattingDialog.getByRole('button', {name: 'Separate'}).first(),).toBeVisible();+ await mattingDialog.getByRole('button', {name: 'Models'}).click();+ await expect(+ mattingDialog+ .getByRole('list', {name: 'Video matting models'})+ .getByRole('listitem'),+ ).toHaveCount(2);+ await mattingDialog.getByRole('button', {name: 'Separate'}).last().click();await expect(mattingDialog.getByRole('textbox', {name: 'Base video output file'}),- ).toHaveValue(- 'vp8-vorbis-base.webm',- );+ ).toHaveValue('vp8-vorbis-base.webm');await expect(mattingDialog.getByRole('textbox', {name: 'Foreground video output file',}),- ).toHaveValue(- 'vp8-vorbis-foreground.webm',- );+ ).toHaveValue('vp8-vorbis-foreground.webm');await page.keyboard.press('Escape');await expect(mattingDialog).toBeHidden();diff --git a/packages/studio/src/components/ModelManager.tsx b/packages/studio/src/components/ModelManager.tsxnew file mode 100644index 0000000000..1ffb4fc57b--- /dev/null+++ b/packages/studio/src/components/ModelManager.tsx@@ -0,0 +1,309 @@+import {formatBytes} from '@remotion/studio-shared';+import React, {useCallback, useEffect, useRef, useState} from 'react';+import {+ BLUE,+ BORDER_WHITE_ALPHA_12,+ LIGHT_TEXT,+ WHITE,+} from '../helpers/colors';+import {CheckCircleFilled} from '../icons/check-circle-filled';+import {CloudDownloadIcon} from '../icons/cloud-download';+import {Minus} from '../icons/minus';+import {TrashIcon} from '../icons/trash';+import type {RenderInlineAction} from './InlineAction';+import {InlineAction} from './InlineAction';+import {VERTICAL_SCROLLBAR_CLASSNAME} from './Menu/is-menu-item';+import {ValidationMessage} from './NewComposition/ValidationMessage';+import {optionsPanel} from './RenderModal/render-modals';+import {Spinner} from './Spinner';++const modelPanel: React.CSSProperties = {+ ...optionsPanel,+ flexDirection: 'column',+};+const hiddenPanel: React.CSSProperties = {display: 'none'};+const container: React.CSSProperties = {+ alignSelf: 'flex-start',+ boxSizing: 'border-box',+ flex: 1,+ fontFamily: 'sans-serif',+ minWidth: 0,+ padding: '16px 16px 0',+};+const descriptionStyle: React.CSSProperties = {+ color: LIGHT_TEXT,+ fontSize: 13,+ lineHeight: 1.5,+ margin: 0,+};+const list: React.CSSProperties = {marginTop: 14};+const modelRow: React.CSSProperties = {+ alignItems: 'center',+ borderBottom: BORDER_WHITE_ALPHA_12,+ display: 'flex',+ gap: 10,+ minHeight: 38,+ padding: '0 10px',+};+const lastModelRow: React.CSSProperties = {+ ...modelRow,+ borderBottom: 'none',+};+const statusIcon: React.CSSProperties = {+ flexShrink: 0,+ height: 14,+ width: 14,+};+const modelName: React.CSSProperties = {+ color: WHITE,+ flex: 1,+ fontFamily: 'monospace',+ fontSize: 13,+ lineHeight: 1.4,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+};+const status: React.CSSProperties = {+ color: LIGHT_TEXT,+ fontSize: 12,+ fontVariantNumeric: 'tabular-nums',+ lineHeight: 1.4,+ whiteSpace: 'nowrap',+};+const actionIcon: React.CSSProperties = {height: 14, width: 14};++type ModelInfo<Model extends string> = {+ readonly name: Model;+ readonly webGpuDownloadSize: number;+};++type ModelActionState<Model extends string> =+ | {type: 'idle'}+ | {type: 'downloading'; model: Model; progress: number | null}+ | {type: 'removing'; model: Model}+ | {type: 'error'; model: Model; message: string};++export const ModelManager = <Model extends string>({+ ariaLabel,+ availableModels,+ description,+ isModelCached,+ loadModel,+ prepare,+ removeModel,+ visible,+}: {+ readonly ariaLabel: string;+ readonly availableModels: readonly ModelInfo<Model>[];+ readonly description: string;+ readonly isModelCached: (model: Model) => Promise<boolean>;+ readonly loadModel: (+ model: Model,+ onProgress: (progress: number | null) => void,+ ) => Promise<unknown>;+ readonly prepare: (() => Promise<void>) | null;+ readonly removeModel: (model: Model) => Promise<void>;+ readonly visible: boolean;+}) => {+ const mounted = useRef(true);+ const initialized = useRef(false);+ const [cachedModels, setCachedModels] = useState<ReadonlySet<Model> | null>(+ null,+ );+ const [actionState, setActionState] = useState<ModelActionState<Model>>({+ type: 'idle',+ });+ const [cacheCheckError, setCacheCheckError] = useState<string | null>(null);++ useEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);++ useEffect(() => {+ if (!visible || initialized.current) {+ return;+ }++ initialized.current = true;+ Promise.resolve()+ .then(() => prepare?.())+ .then(() =>+ Promise.all(+ availableModels.map(async ({name}) =>+ (await isModelCached(name)) ? name : null,+ ),+ ),+ )+ .then((models) => {+ if (mounted.current) {+ const cached = new Set<Model>();+ for (const model of models) {+ if (model !== null) {+ cached.add(model as Model);+ }+ }++ setCachedModels(cached);+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setCachedModels(new Set());+ setCacheCheckError(+ error instanceof Error ? error.message : String(error),+ );+ }+ });+ }, [availableModels, isModelCached, prepare, visible]);++ const downloadModel = useCallback(+ (model: Model) => {+ setActionState({type: 'downloading', model, progress: 0});+ loadModel(model, (progress) => {+ if (mounted.current) {+ setActionState({type: 'downloading', model, progress});+ }+ })+ .then(() => {+ if (mounted.current) {+ setCachedModels((current) => new Set([...(current ?? []), model]));+ setActionState({type: 'idle'});+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setActionState({+ type: 'error',+ model,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ });+ },+ [loadModel],+ );++ const remove = useCallback(+ (model: Model) => {+ setActionState({type: 'removing', model});+ removeModel(model)+ .then(() => {+ if (mounted.current) {+ setCachedModels((current) => {+ const next = new Set(current ?? []);+ next.delete(model);+ return next;+ });+ setActionState({type: 'idle'});+ }+ })+ .catch((error) => {+ if (mounted.current) {+ setActionState({+ type: 'error',+ model,+ message: error instanceof Error ? error.message : String(error),+ });+ }+ });+ },+ [removeModel],+ );++ const renderDownloadIcon: RenderInlineAction = useCallback((color) => {+ return <CloudDownloadIcon color={color} style={actionIcon} />;+ }, []);+ const renderRemoveIcon: RenderInlineAction = useCallback((color) => {+ return <TrashIcon color={color} style={actionIcon} />;+ }, []);+ const actionInProgress =+ actionState.type === 'downloading' || actionState.type === 'removing';++ return (+ <div+ style={visible ? modelPanel : hiddenPanel}+ className={VERTICAL_SCROLLBAR_CLASSNAME}+ >+ <div style={container}>+ <p style={descriptionStyle}>{description}</p>+ {cacheCheckError ? (+ <ValidationMessage+ align="flex-start"+ message={cacheCheckError}+ type="error"+ />+ ) : null}+ <div style={list} role="list" aria-label={ariaLabel}>+ {availableModels.map((model, index) => {+ const cached = cachedModels?.has(model.name) ?? false;+ const processingThisModel =+ actionState.type !== 'idle' &&+ actionState.type !== 'error' &&+ actionState.model === model.name;+ const progress =+ actionState.type === 'downloading' &&+ actionState.model === model.name+ ? actionState.progress+ : null;+ const modelStatus = processingThisModel+ ? actionState.type === 'removing'+ ? 'Removing…'+ : `Downloading${progress === null ? '…' : ` ${Math.round(progress * 100)}%`}`+ : actionState.type === 'error' && actionState.model === model.name+ ? actionState.message+ : cached+ ? `${formatBytes(model.webGpuDownloadSize)} · Downloaded`+ : formatBytes(model.webGpuDownloadSize);++ return (+ <div+ key={model.name}+ role="listitem"+ style={+ index === availableModels.length - 1 ? lastModelRow : modelRow+ }+ >+ {cached ? (+ <CheckCircleFilled+ aria-hidden+ style={{...statusIcon, fill: BLUE}}+ />+ ) : (+ <Minus aria-hidden color={LIGHT_TEXT} style={statusIcon} />+ )}+ <span style={modelName}>{model.name}</span>+ <span style={status} title={modelStatus}>+ {modelStatus}+ </span>+ {processingThisModel ? (+ <Spinner duration={0.5} size={14} />+ ) : cached ? (+ <InlineAction+ disabled={actionInProgress}+ onClick={() => remove(model.name)}+ renderAction={renderRemoveIcon}+ title={`Remove ${model.name}`}+ variant={null}+ />+ ) : (+ <InlineAction+ disabled={cachedModels === null || actionInProgress}+ onClick={() => downloadModel(model.name)}+ renderAction={renderDownloadIcon}+ title={`Download ${model.name}`}+ variant={null}+ />+ )}+ </div>+ );+ })}+ </div>+ </div>+ </div>+ );+};diff --git a/packages/studio/src/components/Transcription/Models.tsx b/packages/studio/src/components/Transcription/Models.tsxindex 6ec3bc4e18..b2ef80cef9 100644--- a/packages/studio/src/components/Transcription/Models.tsx+++ b/packages/studio/src/components/Transcription/Models.tsx@@ -1,4 +1,3 @@-import {formatBytes} from '@remotion/studio-shared';import {clearStaleModels,getAvailableModels,@@ -6,320 +5,43 @@ import {loadWhisperModel,removeWhisperModel,type WhisperWebGpuModel,- type WhisperWebGpuModelLoadProgress,} from '@remotion/whisper-webgpu';-import React, {useCallback, useEffect, useRef, useState} from 'react';-import {- BLUE,- BORDER_WHITE_ALPHA_12,- LIGHT_TEXT,- WHITE,-} from '../../helpers/colors';-import {CheckCircleFilled} from '../../icons/check-circle-filled';-import {CloudDownloadIcon} from '../../icons/cloud-download';-import {Minus} from '../../icons/minus';-import {TrashIcon} from '../../icons/trash';-import type {RenderInlineAction} from '../InlineAction';-import {InlineAction} from '../InlineAction';-import {VERTICAL_SCROLLBAR_CLASSNAME} from '../Menu/is-menu-item';-import {ValidationMessage} from '../NewComposition/ValidationMessage';-import {optionsPanel} from '../RenderModal/render-modals';-import {Spinner} from '../Spinner';+import React, {useCallback} from 'react';+import {ModelManager} from '../ModelManager';const AVAILABLE_MODELS = getAvailableModels();-const modelPanel: React.CSSProperties = {- ...optionsPanel,- flexDirection: 'column',-};--const hiddenPanel: React.CSSProperties = {- display: 'none',-};--const container: React.CSSProperties = {- alignSelf: 'flex-start',- boxSizing: 'border-box',- flex: 1,- fontFamily: 'sans-serif',- minWidth: 0,- padding: '16px 16px 0',-};--const description: React.CSSProperties = {- color: LIGHT_TEXT,- fontSize: 13,- lineHeight: 1.5,- margin: 0,-};--const list: React.CSSProperties = {- marginTop: 14,-};--const modelRow: React.CSSProperties = {- alignItems: 'center',- borderBottom: BORDER_WHITE_ALPHA_12,- display: 'flex',- gap: 10,- minHeight: 38,- padding: '0 10px',-};--const lastModelRow: React.CSSProperties = {- ...modelRow,- borderBottom: 'none',-};--const statusIcon: React.CSSProperties = {- flexShrink: 0,- height: 14,- width: 14,-};--const modelName: React.CSSProperties = {- color: WHITE,- flex: 1,- fontFamily: 'monospace',- fontSize: 13,- lineHeight: 1.4,- minWidth: 0,- overflow: 'hidden',- textOverflow: 'ellipsis',- whiteSpace: 'nowrap',-};--const status: React.CSSProperties = {- color: LIGHT_TEXT,- fontSize: 12,- fontVariantNumeric: 'tabular-nums',- lineHeight: 1.4,- whiteSpace: 'nowrap',-};--const actionIcon: React.CSSProperties = {- height: 14,- width: 14,-};--type ModelActionState =- | {type: 'idle'}- | {- type: 'downloading';- model: WhisperWebGpuModel;- progress: WhisperWebGpuModelLoadProgress;- }- | {type: 'removing'; model: WhisperWebGpuModel}- | {type: 'error'; model: WhisperWebGpuModel; message: string};-export const Models: React.FC<{readonly visible: boolean}> = ({visible}) => {- const mounted = useRef(true);- const initialized = useRef(false);- const [cachedModels, setCachedModels] =- useState<ReadonlySet<WhisperWebGpuModel> | null>(null);- const [actionState, setActionState] = useState<ModelActionState>({- type: 'idle',- });- const [cacheCheckError, setCacheCheckError] = useState<string | null>(null);-- useEffect(() => {- return () => {- mounted.current = false;- };- }, []);-- useEffect(() => {- if (!visible || initialized.current) {- return;- }-- initialized.current = true;- clearStaleModels()- .then(() => {- return Promise.all(- AVAILABLE_MODELS.map(async ({name}) => {- return (await isWhisperModelCached({model: name})) ? name : null;- }),- );- })- .then((models) => {- if (mounted.current) {- setCachedModels(- new Set(- models.filter(- (model): model is WhisperWebGpuModel => model !== null,- ),- ),- );- }- })- .catch((error) => {- if (mounted.current) {- setCachedModels(new Set());- setCacheCheckError(- error instanceof Error ? error.message : String(error),- );- }- });- }, [visible]);-- const downloadModel = useCallback((model: WhisperWebGpuModel) => {- setActionState({- type: 'downloading',- model,- progress: {- file: null,- loadedBytes: 0,- progress: 0,- status: 'loading',- totalBytes:- AVAILABLE_MODELS.find(({name}) => name === model)- ?.webGpuDownloadSize ?? null,- },- });- loadWhisperModel({- model,- onProgress: (progress) => {- if (mounted.current) {- setActionState({type: 'downloading', model, progress});- }- },- })- .then(() => {- if (mounted.current) {- setCachedModels((current) => new Set([...(current ?? []), model]));- setActionState({type: 'idle'});- }- })- .catch((error) => {- if (mounted.current) {- setActionState({- type: 'error',- model,- message: error instanceof Error ? error.message : String(error),- });- }- });- }, []);-- const removeModel = useCallback((model: WhisperWebGpuModel) => {- setActionState({type: 'removing', model});- removeWhisperModel({model})- .then(() => {- if (mounted.current) {- setCachedModels((current) => {- const next = new Set(current ?? []);- next.delete(model);- return next;- });- setActionState({type: 'idle'});- }- })- .catch((error) => {- if (mounted.current) {- setActionState({- type: 'error',- model,- message: error instanceof Error ? error.message : String(error),- });- }- });- }, []);-- const renderDownloadIcon: RenderInlineAction = useCallback((color) => {- return <CloudDownloadIcon color={color} style={actionIcon} />;- }, []);- const renderRemoveIcon: RenderInlineAction = useCallback((color) => {- return <TrashIcon color={color} style={actionIcon} />;- }, []);- const actionInProgress =- actionState.type === 'downloading' || actionState.type === 'removing';+ const isModelCached = useCallback(+ (model: WhisperWebGpuModel) => isWhisperModelCached({model}),+ [],+ );+ const loadModel = useCallback(+ (+ model: WhisperWebGpuModel,+ onProgress: (progress: number | null) => void,+ ) =>+ loadWhisperModel({+ model,+ onProgress: (progress) => onProgress(progress.progress),+ }),+ [],+ );+ const removeModel = useCallback(+ (model: WhisperWebGpuModel) => removeWhisperModel({model}),+ [],+ );return (- <div- style={visible ? modelPanel : hiddenPanel}- className={VERTICAL_SCROLLBAR_CLASSNAME}- >- <div style={container}>- <p style={description}>- Models are downloaded automatically when a transcription starts. You- can also manage the browser cache here.- </p>- {cacheCheckError ? (- <ValidationMessage- align="flex-start"- message={cacheCheckError}- type="error"- />- ) : null}- <div style={list} role="list" aria-label="Whisper models">- {AVAILABLE_MODELS.map((model, index) => {- const cached = cachedModels?.has(model.name) ?? false;- const processingThisModel =- actionState.type !== 'idle' &&- actionState.type !== 'error' &&- actionState.model === model.name;- const progress =- actionState.type === 'downloading' &&- actionState.model === model.name- ? actionState.progress.progress- : null;- const modelStatus = processingThisModel- ? actionState.type === 'removing'- ? 'Removing…'- : `Downloading${progress === null ? '…' : ` ${Math.round(progress * 100)}%`}`- : actionState.type === 'error' && actionState.model === model.name- ? actionState.message- : cached- ? `${formatBytes(model.webGpuDownloadSize)} · Downloaded`- : formatBytes(model.webGpuDownloadSize);-- return (- <div- key={model.name}- role="listitem"- style={- index === AVAILABLE_MODELS.length - 1- ? lastModelRow- : modelRow- }- >- {cached ? (- <CheckCircleFilled- aria-hidden- style={{...statusIcon, fill: BLUE}}- />- ) : (- <Minus aria-hidden color={LIGHT_TEXT} style={statusIcon} />- )}- <span style={modelName}>{model.name}</span>- <span style={status} title={modelStatus}>- {modelStatus}- </span>- {processingThisModel ? (- <Spinner duration={0.5} size={14} />- ) : cached ? (- <InlineAction- disabled={actionInProgress}- onClick={() => removeModel(model.name)}- renderAction={renderRemoveIcon}- title={`Remove ${model.name}`}- variant={null}- />- ) : (- <InlineAction- disabled={cachedModels === null || actionInProgress}- onClick={() => downloadModel(model.name)}- renderAction={renderDownloadIcon}- title={`Download ${model.name}`}- variant={null}- />- )}- </div>- );- })}- </div>- </div>- </div>+ <ModelManager+ ariaLabel="Whisper models"+ availableModels={AVAILABLE_MODELS}+ description="Models are downloaded automatically when a transcription starts. You can also manage the browser cache here."+ isModelCached={isModelCached}+ loadModel={loadModel}+ prepare={clearStaleModels}+ removeModel={removeModel}+ visible={visible}+ />);};diff --git a/packages/studio/src/components/VideoMatting/Models.tsx b/packages/studio/src/components/VideoMatting/Models.tsxnew file mode 100644index 0000000000..8ba1950ba4--- /dev/null+++ b/packages/studio/src/components/VideoMatting/Models.tsx@@ -0,0 +1,43 @@+import {+ getAvailableModels,+ isVideoMattingModelCached,+ loadVideoMattingModel,+ removeVideoMattingModel,+ type VideoMattingModel,+} from '@remotion/video-matting';+import React, {useCallback} from 'react';+import {ModelManager} from '../ModelManager';++const AVAILABLE_MODELS = getAvailableModels();++export const Models: React.FC<{readonly visible: boolean}> = ({visible}) => {+ const isModelCached = useCallback(+ (model: VideoMattingModel) => isVideoMattingModelCached({model}),+ [],+ );+ const loadModel = useCallback(+ (model: VideoMattingModel, onProgress: (progress: number | null) => void) =>+ loadVideoMattingModel({+ model,+ onProgress: (progress) => onProgress(progress.progress),+ }),+ [],+ );+ const removeModel = useCallback(+ (model: VideoMattingModel) => removeVideoMattingModel({model}),+ [],+ );++ return (+ <ModelManager+ ariaLabel="Video matting models"+ availableModels={AVAILABLE_MODELS}+ description="Models are downloaded automatically when video separation starts. You can also manage the browser cache here."+ isModelCached={isModelCached}+ loadModel={loadModel}+ prepare={null}+ removeModel={removeModel}+ visible={visible}+ />+ );+};diff --git a/packages/studio/src/components/VideoMatting/VideoMattingModal.tsx b/packages/studio/src/components/VideoMatting/VideoMattingModal.tsxindex c28a9bc974..d14b353d6d 100644--- a/packages/studio/src/components/VideoMatting/VideoMattingModal.tsx+++ b/packages/studio/src/components/VideoMatting/VideoMattingModal.tsx@@ -15,6 +15,8 @@ import React, {} from 'react';import {BLUE_DISABLED} from '../../helpers/colors';import {Checkmark} from '../../icons/Checkmark';+import {CubeIcon} from '../../icons/cube';+import {EffectsIcon} from '../../icons/effects';import type {VideoMattingModalState} from '../../state/modals';import {SetSelectedModalContext} from '../../state/modals';import {SidebarContext} from '../../state/sidebar';@@ -36,13 +38,20 @@ import {buttonStyle,container,flexer,+ horizontalLayout,+ horizontalTab,+ icon,+ iconContainer,+ leftSidebar,optionsPanel,outerModalStyle,} from '../RenderModal/render-modals';import {RenderModalHr} from '../RenderModal/RenderModalHr';import {RenderModalOutputName} from '../RenderModal/RenderModalOutputName';import {RenderQueueContext} from '../RenderQueue/context';+import {VerticalTab} from '../Tabs/vertical';import {useStaticFiles} from '../use-static-files';+import {Models} from './Models';const MODELS = getAvailableModels();const controlStyle: React.CSSProperties = {width: 330, maxWidth: '100%'};@@ -57,6 +66,11 @@ const modalStyle: React.CSSProperties = {maxHeight: 'calc(100vh - 40px)',outline: 'none',};+const modalLayout: React.CSSProperties = {+ ...horizontalLayout,+ flex: '1 1 auto',+};+const hiddenPanel: React.CSSProperties = {display: 'none'};const validationStyle: React.CSSProperties = {padding: '0 16px 8px'};const outputInputContainerStyle: React.CSSProperties = {maxWidth: 330};@@ -65,6 +79,8 @@ type SupportState =| {type: 'supported'}| {type: 'unsupported'; message: string};+type Tab = 'separate' | 'models';+const makeOptions = <Value extends string>({items,selected,@@ -91,6 +107,7 @@ export const VideoMattingModal: React.FC<VideoMattingModalState> = ({displayName,src,}) => {+ const [tab, setTab] = useState<Tab>('separate');const baseName = useMemo(() => getDefaultOutputBaseName(src, displayName, 'video'),[displayName, src],@@ -254,83 +271,118 @@ export const VideoMattingModal: React.FC<VideoMattingModalState> = ({Separate</Button></div>- <div style={panelStyle} className={VERTICAL_SCROLLBAR_CLASSNAME}>- <RenderModalOutputName- ariaLabel="Base video output file"- existingOutputPath={- window.remotion_publicFolderExists- ? `${window.remotion_publicFolderExists}/${baseOutName}`- : null- }- existence={baseExists}- inputContainerStyle={outputInputContainerStyle}- inputStyle={{...input, ...controlStyle}}- label="Base output in public/"- onValueChange={(event) => setBaseOutName(event.target.value)}- outName={baseOutName}- validationMessage={baseError}- />- <RenderModalOutputName- ariaLabel="Foreground video output file"- existingOutputPath={- window.remotion_publicFolderExists- ? `${window.remotion_publicFolderExists}/${foregroundOutName}`- : null- }- existence={foregroundExists}- inputContainerStyle={outputInputContainerStyle}- inputStyle={{...input, ...controlStyle}}- label="Foreground output in public/"- onValueChange={(event) => setForegroundOutName(event.target.value)}- outName={foregroundOutName}- validationMessage={foregroundError}- />- <RenderModalHr />- <div style={optionRow}>- <div style={label}>Model</div>- <div style={rightRow}>- <Combobox- values={modelOptions}- selectedId={model}- title="Model"- disabled={false}- style={controlStyle}- />- </div>+ <div style={modalLayout}>+ <div style={leftSidebar}>+ <VerticalTab+ autoFocus+ onClick={() => setTab('separate')}+ renderIcon={(color) => (+ <div style={iconContainer}>+ <EffectsIcon color={color} style={icon} />+ </div>+ )}+ selected={tab === 'separate'}+ style={horizontalTab}+ >+ Separate+ </VerticalTab>+ <VerticalTab+ onClick={() => setTab('models')}+ renderIcon={(color) => (+ <div style={iconContainer}>+ <CubeIcon color={color} style={icon} />+ </div>+ )}+ selected={tab === 'models'}+ style={horizontalTab}+ >+ Models+ </VerticalTab></div>- {support.type === 'unsupported' ? (- <div style={validationStyle}>- <ValidationMessage- align="flex-end"- message={support.message}- type="error"- />+ <div+ style={tab === 'separate' ? panelStyle : hiddenPanel}+ className={VERTICAL_SCROLLBAR_CLASSNAME}+ >+ <RenderModalOutputName+ ariaLabel="Base video output file"+ existingOutputPath={+ window.remotion_publicFolderExists+ ? `${window.remotion_publicFolderExists}/${baseOutName}`+ : null+ }+ existence={baseExists}+ inputContainerStyle={outputInputContainerStyle}+ inputStyle={{...input, ...controlStyle}}+ label="Base output in public/"+ onValueChange={(event) => setBaseOutName(event.target.value)}+ outName={baseOutName}+ validationMessage={baseError}+ />+ <RenderModalOutputName+ ariaLabel="Foreground video output file"+ existingOutputPath={+ window.remotion_publicFolderExists+ ? `${window.remotion_publicFolderExists}/${foregroundOutName}`+ : null+ }+ existence={foregroundExists}+ inputContainerStyle={outputInputContainerStyle}+ inputStyle={{...input, ...controlStyle}}+ label="Foreground output in public/"+ onValueChange={(event) =>+ setForegroundOutName(event.target.value)+ }+ outName={foregroundOutName}+ validationMessage={foregroundError}+ />+ <RenderModalHr />+ <div style={optionRow}>+ <div style={label}>Model</div>+ <div style={rightRow}>+ <Combobox+ values={modelOptions}+ selectedId={model}+ title="Model"+ disabled={false}+ style={controlStyle}+ />+ </div></div>- ) : null}- <div style={optionRow}>- <div style={label}>Audio</div>- <div style={rightRow}>- <Combobox- values={audioOptions}- selectedId={audio}- title="Audio"- disabled={false}- style={controlStyle}- />+ {support.type === 'unsupported' ? (+ <div style={validationStyle}>+ <ValidationMessage+ align="flex-end"+ message={support.message}+ type="error"+ />+ </div>+ ) : null}+ <div style={optionRow}>+ <div style={label}>Audio</div>+ <div style={rightRow}>+ <Combobox+ values={audioOptions}+ selectedId={audio}+ title="Audio"+ disabled={false}+ style={controlStyle}+ />+ </div></div>- </div>- <div style={optionRow}>- <div style={label}>Video quality</div>- <div style={rightRow}>- <Combobox- values={qualityOptions}- selectedId={String(videoBitrate)}- title="Video quality"- disabled={false}- style={controlStyle}- />+ <div style={optionRow}>+ <div style={label}>Video quality</div>+ <div style={rightRow}>+ <Combobox+ values={qualityOptions}+ selectedId={String(videoBitrate)}+ title="Video quality"+ disabled={false}+ style={controlStyle}+ />+ </div></div></div>+ <Models visible={tab === 'models'} /></div></div></DismissableModal>diff --git a/packages/studio/src/test/model-manager.test.tsx b/packages/studio/src/test/model-manager.test.tsxnew file mode 100644index 0000000000..bb00c18457--- /dev/null+++ b/packages/studio/src/test/model-manager.test.tsx@@ -0,0 +1,45 @@+import {afterEach, expect, mock, test} from 'bun:test';+import {act, cleanup, fireEvent, render, waitFor} from '@testing-library/react';+import {ModelManager} from '../components/ModelManager';++afterEach(cleanup);++test('downloads and removes models through the shared manager', async () => {+ let finishDownload: () => void = () => undefined;+ const downloadFinished = new Promise<void>((resolve) => {+ finishDownload = resolve;+ });+ const removeModel = mock(() => Promise.resolve());+ const {getByRole, getByText} = render(+ <ModelManager+ ariaLabel="Test models"+ availableModels={[{name: 'test-model', webGpuDownloadSize: 100}]}+ description="Manage models."+ isModelCached={() => Promise.resolve(false)}+ loadModel={(_model, onProgress) => {+ onProgress(0.5);+ return downloadFinished;+ }}+ prepare={null}+ removeModel={removeModel}+ visible+ />,+ );++ const download = await waitFor(() =>+ getByRole('button', {name: 'Download test-model'}),+ );+ fireEvent.click(download);+ expect(getByText('Downloading 50%')).toBeDefined();++ act(() => finishDownload());+ const remove = await waitFor(() =>+ getByRole('button', {name: 'Remove test-model'}),+ );+ fireEvent.click(remove);++ await waitFor(() =>+ expect(getByRole('button', {name: 'Download test-model'})).toBeDefined(),+ );+ expect(removeModel).toHaveBeenCalledWith('test-model');+});diff --git a/packages/video-matting/src/index.ts b/packages/video-matting/src/index.tsindex 6bb3fbde92..8aea58a0d1 100644--- a/packages/video-matting/src/index.ts+++ b/packages/video-matting/src/index.ts@@ -19,6 +19,8 @@ export type {} from './load-video-matting-model';export {isVideoMattingModelCached} from './is-video-matting-model-cached';export type {IsVideoMattingModelCachedOptions} from './is-video-matting-model-cached';+export {removeVideoMattingModel} from './remove-video-matting-model';+export type {RemoveVideoMattingModelOptions} from './remove-video-matting-model';export {getAvailableModels} from './models';export type {VideoMattingModel, VideoMattingModelInfo} from './models';export type {diff --git a/packages/video-matting/src/remove-video-matting-model.ts b/packages/video-matting/src/remove-video-matting-model.tsnew file mode 100644index 0000000000..4352b2b478--- /dev/null+++ b/packages/video-matting/src/remove-video-matting-model.ts@@ -0,0 +1,28 @@+import {disposeVideoMattingModel} from './load-video-matting-model';+import {+ getHostedVideoMattingModelId,+ getVideoMattingModelInfo,+ type VideoMattingModel,+} from './models';+import {withRemotionModelHost} from './with-remotion-model-host';++export type RemoveVideoMattingModelOptions = {+ model: VideoMattingModel;+};++export const removeVideoMattingModel = async ({+ model,+}: RemoveVideoMattingModelOptions): Promise<void> => {+ const modelInfo = getVideoMattingModelInfo(model);+ await disposeVideoMattingModel({model});+ await withRemotionModelHost(({ModelRegistry}) => {+ return ModelRegistry.clear_pipeline_cache(+ 'background-removal',+ getHostedVideoMattingModelId(model),+ {+ device: 'webgpu',+ dtype: modelInfo.dtype,+ },+ );+ });+};diff --git a/packages/video-matting/src/test/model-runtime.test.ts b/packages/video-matting/src/test/model-runtime.test.tsindex d239247388..da4b1c7105 100644--- a/packages/video-matting/src/test/model-runtime.test.ts+++ b/packages/video-matting/src/test/model-runtime.test.ts@@ -15,6 +15,9 @@ let disposeCalls = 0;let cacheCheck:| {task: string; modelId: string; options: Record<string, unknown>}| undefined;+let cacheClear:+ | {task: string; modelId: string; options: Record<string, unknown>}+ | undefined;let cacheCheckEnvironment:| {remoteHost: string; remotePathTemplate: string}| undefined;@@ -90,6 +93,14 @@ mock.module('@huggingface/transformers', () => ({},BackgroundRemovalPipeline,ModelRegistry: {+ clear_pipeline_cache: (+ task: string,+ modelId: string,+ options: Record<string, unknown>,+ ) => {+ cacheClear = {task, modelId, options};+ return Promise.resolve();+ },is_pipeline_cached: (task: string,modelId: string,@@ -118,6 +129,7 @@ beforeEach(async () => {livePipelineCount = 0;disposeCalls = 0;cacheCheck = undefined;+ cacheClear = undefined;cacheCheckEnvironment = undefined;preexistingWhisperModelHostState.activeOperations = 0;preexistingWhisperModelHostState.previousRemoteConfiguration = null;@@ -224,6 +236,21 @@ test('loads every public model from its immutable hosted model ID', async () =>]);});+test('removes a model from memory and the persistent cache', async () => {+ const {loadVideoMattingModel} = await getRuntime();+ const {removeVideoMattingModel} =+ await import('../remove-video-matting-model');+ await loadVideoMattingModel({model: 'modnet'});+ await removeVideoMattingModel({model: 'modnet'});++ expect(disposeCalls).toBe(1);+ expect(cacheClear).toEqual({+ task: 'background-removal',+ modelId: 'modnet-v1',+ options: {device: 'webgpu', dtype: 'fp32'},+ });+});+test('coordinates the shared Transformers environment across model loads', async () => {const {disposeVideoMattingModel, loadVideoMattingModel} = await getRuntime();let releaseInitialization: () => void = () => undefined;