Skip to content

🎥 Make videos programmatically with React

Consolidate video matting tests

JonnyBurgerb5d4fad75781
diff --git a/packages/video-matting/src/test/model-runtime.test.ts b/packages/video-matting/src/test/model-runtime.test.ts
index 4b5ef181d8..d239247388 100644
--- a/packages/video-matting/src/test/model-runtime.test.ts
+++ b/packages/video-matting/src/test/model-runtime.test.ts
@@ -5,41 +5,19 @@ let initializationStarted: ((count: number) => void) | null = null;
let initializationGate: Promise<void> | null = null;
let initializationOptions: Record<string, unknown> | null = null;
let initializationEnvironment:
- | {
- remoteHost: string;
- remotePathTemplate: string;
- }
+ | {remoteHost: string; remotePathTemplate: string}
| undefined;
-let initializationEnvironmentAfterLoading:
- | {
- remoteHost: string;
- remotePathTemplate: string;
- }
- | undefined;
-let initializedModelId: string | null = null;
const initializedModelIds: string[] = [];
const initializedProcessorModelIds: string[] = [];
-let pipelineConstructionCount = 0;
let pipelineRunCount = 0;
let livePipelineCount = 0;
-let maxLivePipelineCount = 0;
let disposeCalls = 0;
-let disposalStarted: ((pipeline: number) => void) | null = null;
-let disposalGate: Promise<void> | null = null;
let cacheCheck:
- | {
- task: string;
- modelId: string;
- options: Record<string, unknown>;
- }
+ | {task: string; modelId: string; options: Record<string, unknown>}
| undefined;
let cacheCheckEnvironment:
- | {
- remoteHost: string;
- remotePathTemplate: string;
- }
+ | {remoteHost: string; remotePathTemplate: string}
| undefined;
-let cacheCheckError: Error | null = null;
const originalTransformersEnvironment = {
remoteHost: 'https://huggingface.co/',
@@ -58,11 +36,8 @@ Object.defineProperty(
{value: preexistingWhisperModelHostState},
);
-function FakeBackgroundRemovalPipeline() {
- const pipeline = ++pipelineConstructionCount;
+function BackgroundRemovalPipeline() {
livePipelineCount++;
- maxLivePipelineCount = Math.max(maxLivePipelineCount, livePipelineCount);
-
return Object.assign(
() => {
pipelineRunCount++;
@@ -74,11 +49,10 @@ function FakeBackgroundRemovalPipeline() {
});
},
{
- dispose: async () => {
+ dispose: () => {
disposeCalls++;
- disposalStarted?.(pipeline);
- await disposalGate;
livePipelineCount--;
+ return Promise.resolve();
},
},
);
@@ -92,47 +66,29 @@ mock.module('@huggingface/transformers', () => ({
options: Record<string, unknown>,
) => {
initializationCount++;
- initializedModelId = modelId;
initializedModelIds.push(modelId);
initializationOptions = options;
initializationEnvironment = {...transformersEnvironment};
initializationStarted?.(initializationCount);
await initializationGate;
- initializationEnvironmentAfterLoading = {...transformersEnvironment};
-
const onProgress = options.progress_callback as
| ((event: Record<string, unknown>) => void)
| undefined;
- onProgress?.({
- status: 'progress',
- file: 'config.json',
- loaded: 83,
- });
onProgress?.({
status: 'progress',
file: 'onnx/model.onnx',
- loaded: 25_888_640,
+ loaded: 25_889_088,
});
- return {
- dispose: () => Promise.resolve(),
- };
+ return {dispose: () => Promise.resolve()};
},
},
AutoProcessor: {
- from_pretrained: (modelId: string, options: Record<string, unknown>) => {
+ from_pretrained: (modelId: string) => {
initializedProcessorModelIds.push(modelId);
- const onProgress = options.progress_callback as
- | ((event: Record<string, unknown>) => void)
- | undefined;
- onProgress?.({
- status: 'progress',
- file: 'preprocessor_config.json',
- loaded: 365,
- });
return Promise.resolve({});
},
},
- BackgroundRemovalPipeline: FakeBackgroundRemovalPipeline,
+ BackgroundRemovalPipeline,
ModelRegistry: {
is_pipeline_cached: (
task: string,
@@ -141,10 +97,6 @@ mock.module('@huggingface/transformers', () => ({
) => {
cacheCheck = {task, modelId, options};
cacheCheckEnvironment = {...transformersEnvironment};
- if (cacheCheckError) {
- return Promise.reject(cacheCheckError);
- }
-
return Promise.resolve(true);
},
},
@@ -153,36 +105,26 @@ mock.module('@huggingface/transformers', () => ({
const getRuntime = () => import('../load-video-matting-model');
beforeEach(async () => {
- disposalGate = null;
- initializationGate = null;
const {disposeVideoMattingModel} = await getRuntime();
await disposeVideoMattingModel();
-
initializationCount = 0;
initializationStarted = null;
initializationGate = null;
initializationOptions = null;
initializationEnvironment = undefined;
- initializationEnvironmentAfterLoading = undefined;
- initializedModelId = null;
initializedModelIds.length = 0;
initializedProcessorModelIds.length = 0;
- pipelineConstructionCount = 0;
pipelineRunCount = 0;
livePipelineCount = 0;
- maxLivePipelineCount = 0;
disposeCalls = 0;
- disposalStarted = null;
- disposalGate = null;
cacheCheck = undefined;
cacheCheckEnvironment = undefined;
- cacheCheckError = null;
preexistingWhisperModelHostState.activeOperations = 0;
preexistingWhisperModelHostState.previousRemoteConfiguration = null;
Object.assign(transformersEnvironment, originalTransformersEnvironment);
});
-test('coalesces initialization and defers disposal until active work is done', async () => {
+test('shares loading, reports progress, and defers disposal while in use', async () => {
const {
disposeVideoMattingModel,
loadVideoMattingModel,
@@ -190,7 +132,6 @@ test('coalesces initialization and defers disposal until active work is done', a
} = await getRuntime();
const {isVideoMattingModelCached} =
await import('../is-video-matting-model-cached');
-
let releaseInitialization: () => void = () => undefined;
initializationGate = new Promise<void>((resolve) => {
releaseInitialization = resolve;
@@ -198,90 +139,41 @@ test('coalesces initialization and defers disposal until active work is done', a
const started = new Promise<void>((resolve) => {
initializationStarted = () => resolve();
});
- const firstProgress: number[] = [];
- const firstLoadedBytes: number[] = [];
- const firstTotalBytes: number[] = [];
- const secondProgress: number[] = [];
+ const progress: number[] = [];
const first = loadVideoMattingModel({
model: 'modnet',
- onProgress: ({loadedBytes, progress, totalBytes}) => {
- if (progress !== null) {
- firstProgress.push(progress);
- }
-
- if (loadedBytes !== null) {
- firstLoadedBytes.push(loadedBytes);
- }
-
- if (totalBytes !== null) {
- firstTotalBytes.push(totalBytes);
- }
- },
- });
- const second = loadVideoMattingModel({
- model: 'modnet',
- onProgress: ({progress}) => {
- if (progress !== null) {
- secondProgress.push(progress);
+ onProgress: (event) => {
+ if (event.progress !== null) {
+ progress.push(event.progress);
}
},
});
+ const second = loadVideoMattingModel({model: 'modnet'});
await started;
expect(initializationCount).toBe(1);
- expect(initializedModelId).toBe('modnet-v1');
expect(initializationEnvironment).toEqual({
remoteHost: 'https://remotion.media/',
remotePathTemplate: 'models/{model}/',
});
- expect(transformersEnvironment).toEqual({
- remoteHost: 'https://remotion.media/',
- remotePathTemplate: 'models/{model}/',
- });
- expect(
- (
- transformersEnvironment as typeof transformersEnvironment &
- Record<symbol, unknown>
- )[Symbol.for('@remotion/whisper-webgpu/model-host-state')],
- ).toBe(preexistingWhisperModelHostState);
- expect(preexistingWhisperModelHostState).toMatchObject({
- activeOperations: 1,
- previousRemoteConfiguration: originalTransformersEnvironment,
- });
expect(await isVideoMattingModelCached({model: 'modnet'})).toBe(true);
expect(cacheCheck).toEqual({
task: 'background-removal',
modelId: 'modnet-v1',
- options: {
- device: 'webgpu',
- dtype: 'fp32',
- },
- });
- expect(cacheCheckEnvironment).toEqual({
- remoteHost: 'https://remotion.media/',
- remotePathTemplate: 'models/{model}/',
- });
- expect(transformersEnvironment).toEqual({
- remoteHost: 'https://remotion.media/',
- remotePathTemplate: 'models/{model}/',
+ options: {device: 'webgpu', dtype: 'fp32'},
});
+ expect(cacheCheckEnvironment).toEqual(initializationEnvironment);
releaseInitialization();
expect(await Promise.all([first, second])).toEqual([
{alreadyLoaded: false},
{alreadyLoaded: true},
]);
- expect(initializationEnvironmentAfterLoading).toEqual(
- initializationEnvironment,
- );
expect(initializationOptions).toMatchObject({
device: 'webgpu',
dtype: 'fp32',
});
expect(initializationOptions).not.toHaveProperty('revision');
- expect(firstProgress.at(-1)).toBe(1);
- expect(secondProgress.at(-1)).toBe(1);
- expect(Math.max(...firstLoadedBytes)).toBe(25_889_088);
- expect(new Set(firstTotalBytes)).toEqual(new Set([25_889_088]));
+ expect(progress.at(-1)).toBe(1);
expect(transformersEnvironment).toEqual(originalTransformersEnvironment);
let releaseUse: () => void = () => undefined;
@@ -306,15 +198,10 @@ test('coalesces initialization and defers disposal until active work is done', a
const disposal = disposeVideoMattingModel({model: 'modnet'});
await Promise.resolve();
expect(disposeCalls).toBe(0);
-
releaseUse();
- expect(await use).toEqual({
- data: new Uint8ClampedArray([10, 20, 30, 128]),
- width: 1,
- height: 1,
- channels: 4,
- });
+ expect((await use).data).toEqual(new Uint8ClampedArray([10, 20, 30, 128]));
await disposal;
+ expect(pipelineRunCount).toBe(1);
expect(disposeCalls).toBe(1);
expect(livePipelineCount).toBe(0);
});
@@ -335,13 +222,9 @@ test('loads every public model from its immutable hosted model ID', async () =>
'Xenova/modnet',
'onnx-community/BEN2-ONNX',
]);
- expect(models.map(({webGpuDownloadSize}) => webGpuDownloadSize)).toEqual([
- 25_889_088, 219_122_146,
- ]);
- expect(transformersEnvironment).toEqual(originalTransformersEnvironment);
});
-test('keeps the shared hosted environment active for concurrent model loads', async () => {
+test('coordinates the shared Transformers environment across model loads', async () => {
const {disposeVideoMattingModel, loadVideoMattingModel} = await getRuntime();
let releaseInitialization: () => void = () => undefined;
initializationGate = new Promise<void>((resolve) => {
@@ -354,8 +237,10 @@ test('keeps the shared hosted environment active for concurrent model loads', as
}
};
});
- const modnet = loadVideoMattingModel({model: 'modnet'});
- const ben2 = loadVideoMattingModel({model: 'ben2-base'});
+ const loads = [
+ loadVideoMattingModel({model: 'modnet'}),
+ loadVideoMattingModel({model: 'ben2-base'}),
+ ];
await bothStarted;
const environmentWithState =
@@ -365,215 +250,15 @@ test('keeps the shared hosted environment active for concurrent model loads', as
environmentWithState[
Symbol.for('@remotion/whisper-webgpu/model-host-state')
];
- expect(sharedState).toMatchObject({
- activeOperations: 2,
- previousRemoteConfiguration: originalTransformersEnvironment,
- });
+ expect(sharedState).toMatchObject({activeOperations: 2});
expect(
environmentWithState[Symbol.for('@remotion/transformers/model-host-state')],
).toBe(sharedState);
- expect(transformersEnvironment).toEqual({
- remoteHost: 'https://remotion.media/',
- remotePathTemplate: 'models/{model}/',
- });
-
releaseInitialization();
- expect(await Promise.all([modnet, ben2])).toEqual([
+ expect(await Promise.all(loads)).toEqual([
{alreadyLoaded: false},
{alreadyLoaded: false},
]);
expect(transformersEnvironment).toEqual(originalTransformersEnvironment);
-
await disposeVideoMattingModel();
});
-
-test('restores the Transformers environment after a hosted operation fails', async () => {
- const {isVideoMattingModelCached} =
- await import('../is-video-matting-model-cached');
- cacheCheckError = new Error('Could not read the model cache');
-
- try {
- await expect(
- isVideoMattingModelCached({model: 'ben2-base'}),
- ).rejects.toThrow('Could not read the model cache');
- expect(cacheCheck).toMatchObject({
- modelId: 'ben2-base-v1',
- options: {device: 'webgpu', dtype: 'fp16'},
- });
- expect(cacheCheckEnvironment).toEqual({
- remoteHost: 'https://remotion.media/',
- remotePathTemplate: 'models/{model}/',
- });
- expect(transformersEnvironment).toEqual(originalTransformersEnvironment);
- } finally {
- cacheCheckError = null;
- }
-});
-
-test('only restores Transformers environment fields left unchanged by the consumer', async () => {
- const {disposeVideoMattingModel, loadVideoMattingModel} = await getRuntime();
- let releaseInitialization: () => void = () => undefined;
- initializationGate = new Promise<void>((resolve) => {
- releaseInitialization = resolve;
- });
- const started = new Promise<void>((resolve) => {
- initializationStarted = () => resolve();
- });
- const loading = loadVideoMattingModel({model: 'modnet'});
-
- try {
- await started;
- transformersEnvironment.remoteHost = 'https://models.example.com/';
- releaseInitialization();
- await loading;
- expect(transformersEnvironment).toEqual({
- remoteHost: 'https://models.example.com/',
- remotePathTemplate: '{model}/resolve/{revision}/',
- });
- await disposeVideoMattingModel({model: 'modnet'});
- } finally {
- releaseInitialization();
- initializationGate = null;
- initializationStarted = null;
- Object.assign(transformersEnvironment, originalTransformersEnvironment);
- }
-});
-
-test('isolates throwing progress observers from shared loading', async () => {
- const {disposeVideoMattingModel, loadVideoMattingModel} = await getRuntime();
-
- let throwingObserverCalls = 0;
- const successfulProgress: number[] = [];
- const throwingLoad = loadVideoMattingModel({
- model: 'modnet',
- onProgress: () => {
- throwingObserverCalls++;
- throw new Error('observer failed');
- },
- });
- const successfulLoad = loadVideoMattingModel({
- model: 'modnet',
- onProgress: ({progress}) => {
- if (progress !== null) {
- successfulProgress.push(progress);
- }
- },
- });
-
- expect(await Promise.all([throwingLoad, successfulLoad])).toEqual([
- {alreadyLoaded: false},
- {alreadyLoaded: true},
- ]);
- expect(throwingObserverCalls).toBeGreaterThan(0);
- expect(successfulProgress.at(-1)).toBe(1);
- expect(initializationCount).toBe(1);
- expect(disposeCalls).toBe(0);
-
- let replayCalls = 0;
- expect(
- await loadVideoMattingModel({
- model: 'modnet',
- onProgress: () => {
- replayCalls++;
- throw new Error('replayed observer failed');
- },
- }),
- ).toEqual({alreadyLoaded: true});
- expect(replayCalls).toBe(1);
-
- await disposeVideoMattingModel({model: 'modnet'});
- expect(disposeCalls).toBe(1);
- expect(livePipelineCount).toBe(0);
-});
-
-test('aborts a caller waiting for shared initialization without canceling it', async () => {
- const {
- disposeVideoMattingModel,
- loadVideoMattingModel,
- withLoadedVideoMattingPipeline,
- } = await getRuntime();
-
- let releaseInitialization: () => void = () => undefined;
- initializationGate = new Promise<void>((resolve) => {
- releaseInitialization = resolve;
- });
- const started = new Promise<void>((resolve) => {
- initializationStarted = () => resolve();
- });
- const controller = new AbortController();
- const abortReason = new Error('stop waiting');
- let runCalls = 0;
- let progressCalls = 0;
- const use = withLoadedVideoMattingPipeline({
- model: 'modnet',
- onProgress: () => {
- progressCalls++;
- },
- signal: controller.signal,
- run: () => {
- runCalls++;
- return Promise.resolve();
- },
- });
-
- await started;
- const progressCallsBeforeAbort = progressCalls;
- controller.abort(abortReason);
- await expect(use).rejects.toBe(abortReason);
- expect(runCalls).toBe(0);
-
- const sharedLoad = loadVideoMattingModel({model: 'modnet'});
- releaseInitialization();
- expect(await sharedLoad).toEqual({alreadyLoaded: true});
- expect(initializationCount).toBe(1);
- expect(progressCalls).toBe(progressCallsBeforeAbort);
-
- const result = await withLoadedVideoMattingPipeline({
- model: 'modnet',
- signal: null,
- run: (pipeline) => pipeline({} as OffscreenCanvas),
- });
- expect(result.data).toEqual(new Uint8ClampedArray([10, 20, 30, 128]));
- expect(pipelineRunCount).toBe(1);
-
- await disposeVideoMattingModel({model: 'modnet'});
- expect(disposeCalls).toBe(1);
- expect(livePipelineCount).toBe(0);
-});
-
-test('waits for disposal before constructing a replacement pipeline', async () => {
- const {disposeVideoMattingModel, loadVideoMattingModel} = await getRuntime();
-
- await loadVideoMattingModel({model: 'modnet'});
- expect(initializationCount).toBe(1);
- expect(livePipelineCount).toBe(1);
-
- let releaseDisposal: () => void = () => undefined;
- disposalGate = new Promise<void>((resolve) => {
- releaseDisposal = resolve;
- });
- const disposalHasStarted = new Promise<void>((resolve) => {
- disposalStarted = () => resolve();
- });
- const disposal = disposeVideoMattingModel({model: 'modnet'});
- await disposalHasStarted;
-
- const replacement = loadVideoMattingModel({model: 'modnet'});
- await new Promise<void>((resolve) => {
- setTimeout(resolve, 0);
- });
- expect(initializationCount).toBe(1);
- expect(pipelineConstructionCount).toBe(1);
-
- releaseDisposal();
- await Promise.all([disposal, replacement]);
- expect(initializationCount).toBe(2);
- expect(pipelineConstructionCount).toBe(2);
- expect(maxLivePipelineCount).toBe(1);
- expect(livePipelineCount).toBe(1);
-
- disposalGate = null;
- await disposeVideoMattingModel({model: 'modnet'});
- expect(disposeCalls).toBe(2);
- expect(livePipelineCount).toBe(0);
-});
diff --git a/packages/video-matting/src/test/models.test.ts b/packages/video-matting/src/test/models.test.ts
index 7ae4a99503..eae26adf9e 100644
--- a/packages/video-matting/src/test/models.test.ts
+++ b/packages/video-matting/src/test/models.test.ts
@@ -3,7 +3,7 @@ import {
canUseVideoMatting,
VideoMattingUnsupportedReason,
} from '../can-use-video-matting';
-import {getAvailableModels, getVideoMattingModelInfo} from '../models';
+import {getAvailableModels} from '../models';
test('returns public metadata without mutable internal model settings', () => {
const models = getAvailableModels();
@@ -27,15 +27,6 @@ test('returns public metadata without mutable internal model settings', () => {
expect(getAvailableModels()[0].purpose).toBe('person');
});
-test('rejects unsupported runtime model values', () => {
- expect(() => getVideoMattingModelInfo('not-a-model' as never)).toThrow(
- 'Unsupported video matting model "not-a-model". Available models: modnet, ben2-base.',
- );
- expect(() => getVideoMattingModelInfo('toString' as never)).toThrow(
- 'Unsupported video matting model "toString". Available models: modnet, ben2-base.',
- );
-});
-
test('requires shader-f16 only for the fp16 BEN2 model', async () => {
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
const originalNavigator = Object.getOwnPropertyDescriptor(
@@ -85,70 +76,3 @@ test('requires shader-f16 only for the fp16 BEN2 model', async () => {
}
}
});
-
-test('supports a secure worker with OffscreenCanvas and WebGPU', async () => {
- const originalWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
- const originalNavigator = Object.getOwnPropertyDescriptor(
- globalThis,
- 'navigator',
- );
- const originalOffscreenCanvas = Object.getOwnPropertyDescriptor(
- globalThis,
- 'OffscreenCanvas',
- );
- const originalSecureContext = Object.getOwnPropertyDescriptor(
- globalThis,
- 'isSecureContext',
- );
- delete (globalThis as {window?: unknown}).window;
- Object.defineProperty(globalThis, 'OffscreenCanvas', {
- configurable: true,
- value: class FakeOffscreenCanvas {},
- });
- Object.defineProperty(globalThis, 'isSecureContext', {
- configurable: true,
- value: true,
- });
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- value: {
- gpu: {
- requestAdapter: () => Promise.resolve({features: new Set<string>()}),
- },
- },
- });
-
- try {
- expect(await canUseVideoMatting()).toEqual({supported: true});
- } finally {
- if (originalWindow) {
- Object.defineProperty(globalThis, 'window', originalWindow);
- }
-
- if (originalNavigator) {
- Object.defineProperty(globalThis, 'navigator', originalNavigator);
- } else {
- delete (globalThis as {navigator?: unknown}).navigator;
- }
-
- if (originalOffscreenCanvas) {
- Object.defineProperty(
- globalThis,
- 'OffscreenCanvas',
- originalOffscreenCanvas,
- );
- } else {
- delete (globalThis as {OffscreenCanvas?: unknown}).OffscreenCanvas;
- }
-
- if (originalSecureContext) {
- Object.defineProperty(
- globalThis,
- 'isSecureContext',
- originalSecureContext,
- );
- } else {
- delete (globalThis as {isSecureContext?: unknown}).isSecureContext;
- }
- }
-});
diff --git a/packages/video-matting/src/test/output-target.test.ts b/packages/video-matting/src/test/output-target.test.ts
index 5728095fd5..083860f765 100644
--- a/packages/video-matting/src/test/output-target.test.ts
+++ b/packages/video-matting/src/test/output-target.test.ts
@@ -1,5 +1,5 @@
import {afterEach, describe, expect, test} from 'bun:test';
-import {Output, WebMOutputFormat, type StreamTargetChunk} from 'mediabunny';
+import {WebMOutputFormat, type StreamTargetChunk} from 'mediabunny';
import {createVideoLayerOutput} from '../create-video-layer-output';
import type {VideoLayerOutputOptions} from '../output-target';
@@ -9,113 +9,58 @@ type FakeFile = {
bytes: Uint8Array<ArrayBuffer>;
position: number;
closed: boolean;
- aborted: boolean;
seekPositions: number[];
};
-const makeFakeFile = (): FakeFile => ({
- bytes: new Uint8Array(),
- position: 0,
- closed: false,
- aborted: false,
- seekPositions: [],
-});
-
-const makeFakeOpfs = ({
- createWritableError,
- closeError,
- abortError,
-}: {
- createWritableError?: Error;
- closeError?: Error;
- abortError?: Error;
-} = {}) => {
+const makeFakeOpfs = () => {
const files = new Map<string, FakeFile>();
const removedNames: string[] = [];
-
- const getFileHandle = (
- name: string,
- options?: FileSystemGetFileOptions,
- ): Promise<FileSystemFileHandle> => {
- if (!files.has(name)) {
- if (!options?.create) {
- throw new DOMException('File not found', 'NotFoundError');
+ const directory = {
+ getFileHandle: (name: string) => {
+ if (!files.has(name)) {
+ files.set(name, {
+ bytes: new Uint8Array(),
+ position: 0,
+ closed: false,
+ seekPositions: [],
+ });
}
- files.set(name, makeFakeFile());
- }
-
- const file = files.get(name)!;
- return Promise.resolve({
- kind: 'file',
- name,
- isSameEntry: () => Promise.resolve(false),
- createWritable: () => {
- if (createWritableError !== undefined) {
- return Promise.reject(createWritableError);
- }
-
- return Promise.resolve({
- seek: (position: number) => {
- file.position = position;
- file.seekPositions.push(position);
- return Promise.resolve();
- },
- write: (chunk: StreamTargetChunk) => {
- const end = file.position + chunk.data.byteLength;
- if (end > file.bytes.byteLength) {
- const resized = new Uint8Array(end);
- resized.set(file.bytes);
- file.bytes = resized;
- }
-
- file.bytes.set(chunk.data, file.position);
- file.position = end;
- return Promise.resolve();
- },
- close: () => {
- file.closed = true;
- return closeError === undefined
- ? Promise.resolve()
- : Promise.reject(closeError);
- },
- abort: () => {
- file.aborted = true;
- return abortError === undefined
- ? Promise.resolve()
- : Promise.reject(abortError);
- },
- } as unknown as FileSystemWritableFileStream);
- },
- getFile: () => Promise.resolve(new File([file.bytes], name)),
- } as FileSystemFileHandle);
- };
-
- const directory = {
- kind: 'directory',
- name: '',
- isSameEntry: () => Promise.resolve(false),
- getFileHandle,
+ const file = files.get(name)!;
+ return Promise.resolve({
+ createWritable: () =>
+ Promise.resolve({
+ seek: (position: number) => {
+ file.position = position;
+ file.seekPositions.push(position);
+ },
+ write: (chunk: StreamTargetChunk) => {
+ const end = file.position + chunk.data.byteLength;
+ if (end > file.bytes.byteLength) {
+ const resized = new Uint8Array(end);
+ resized.set(file.bytes);
+ file.bytes = resized;
+ }
+
+ file.bytes.set(chunk.data, file.position);
+ file.position = end;
+ },
+ close: () => {
+ file.closed = true;
+ },
+ abort: () => undefined,
+ } as unknown as FileSystemWritableFileStream),
+ getFile: () => Promise.resolve(new File([file.bytes], name)),
+ } as FileSystemFileHandle);
+ },
removeEntry: (name: string) => {
removedNames.push(name);
- if (!files.delete(name)) {
- return Promise.reject(
- new DOMException('File not found', 'NotFoundError'),
- );
- }
-
+ files.delete(name);
return Promise.resolve();
},
- async *entries() {
- for (const name of files.keys()) {
- yield [name, await getFileHandle(name)] as const;
- }
- },
} as unknown as FileSystemDirectoryHandle;
- const seedFile = (name: string) => files.set(name, makeFakeFile());
-
- return {directory, files, removedNames, seedFile};
+ return {directory, files, removedNames};
};
afterEach(() => {
@@ -128,7 +73,7 @@ afterEach(() => {
});
describe('video layer output targets', () => {
- test('creates an in-memory Blob result', async () => {
+ test('returns an in-memory WebM Blob', async () => {
const created = await createVideoLayerOutput({
format: new WebMOutputFormat(),
options: {outputTarget: 'arraybuffer'},
@@ -137,396 +82,69 @@ describe('video layer output targets', () => {
await created.output.start();
const result = await created.finalize();
const blob = await result.getBlob();
- await result.dispose();
- await result.dispose();
expect(blob.type).toBe('application/webm');
expect(blob.size).toBeGreaterThan(0);
});
- test('writes to and closes an outputWritable', async () => {
- const chunks: StreamTargetChunk[] = [];
+ test('writes to and closes a caller-provided stream', async () => {
+ let bytesWritten = 0;
let closed = false;
- const outputWritable = new WritableStream<StreamTargetChunk>({
- write: (chunk) => {
- chunks.push(chunk);
- },
- close: () => {
- closed = true;
- },
- });
const created = await createVideoLayerOutput({
format: new WebMOutputFormat(),
- options: {outputWritable},
+ options: {
+ outputWritable: new WritableStream<StreamTargetChunk>({
+ write: (chunk) => {
+ bytesWritten += chunk.data.byteLength;
+ },
+ close: () => {
+ closed = true;
+ },
+ }),
+ },
});
await created.output.start();
const result = await created.finalize();
- expect(chunks.length).toBeGreaterThan(0);
+ expect(bytesWritten).toBeGreaterThan(0);
expect(closed).toBe(true);
await expect(result.getBlob()).rejects.toThrow(
'getBlob() is unavailable when outputWritable is used',
);
- await result.dispose();
- await result.dispose();
- });
-
- test('rejects finalization when cancellation is requested during stream close', async () => {
- let cancelOutput: (() => Promise<void>) | null = null;
- let cancellationPromise: Promise<void> | null = null;
- const outputWritable = new WritableStream<StreamTargetChunk>({
- close: () => {
- if (cancelOutput === null) {
- throw new Error('Expected output cancellation to be initialized');
- }
-
- cancellationPromise = cancelOutput();
- },
- });
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputWritable},
- });
- cancelOutput = created.cancel;
-
- await created.output.start();
- await expect(created.finalize()).rejects.toThrow(
- 'Video layer output was canceled',
- );
- await Promise.allSettled([cancellationPromise]);
- });
-
- test('aborts an outputWritable when canceled before starting', async () => {
- let closed = false;
- let abortReason: unknown = null;
- const outputWritable = new WritableStream<StreamTargetChunk>({
- close: () => {
- closed = true;
- },
- abort: (reason) => {
- abortReason = reason;
- },
- });
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputWritable},
- });
-
- await created.cancel();
- expect(closed).toBe(false);
- expect(abortReason).toBeInstanceOf(Error);
- expect((abortReason as Error).message).toBe(
- 'Video layer output was canceled',
- );
- });
-
- test('aborts an outputWritable when canceled after starting', async () => {
- let closed = false;
- let abortReason: unknown = null;
- const outputWritable = new WritableStream<StreamTargetChunk>({
- close: () => {
- closed = true;
- },
- abort: (reason) => {
- abortReason = reason;
- },
- });
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputWritable},
- });
- await created.output.start();
-
- await created.cancel();
- expect(closed).toBe(false);
- expect(abortReason).toBeInstanceOf(Error);
- expect((abortReason as Error).message).toBe(
- 'Video layer output was canceled',
- );
- });
-
- test('aborts an outputWritable when discarded after starting', async () => {
- let closed = false;
- let abortReason: unknown = null;
- const outputWritable = new WritableStream<StreamTargetChunk>({
- close: () => {
- closed = true;
- },
- abort: (reason) => {
- abortReason = reason;
- },
- });
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputWritable},
- });
- await created.output.start();
-
- await created.discard();
- expect(closed).toBe(false);
- expect(abortReason).toBeInstanceOf(Error);
- expect((abortReason as Error).message).toBe(
- 'Video layer output was discarded',
- );
});
- test('uses OPFS automatically and honors positional writes', async () => {
+ test('uses OPFS by default and removes the file on disposal', async () => {
const {directory, files, removedNames} = makeFakeOpfs();
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
- enumerable: true,
value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
});
-
const created = await createVideoLayerOutput({
format: new WebMOutputFormat(),
options: undefined,
});
+
await created.output.start();
const result = await created.finalize();
const blob = await result.getBlob();
const [filename, file] = [...files.entries()][0];
- expect(files.size).toBe(1);
expect(file.closed).toBe(true);
expect(file.seekPositions.length).toBeGreaterThan(0);
expect(blob.size).toBeGreaterThan(0);
- expect(blob.type).toBe('application/webm');
- const bytesBeforeDisposal = new Uint8Array(await blob.arrayBuffer());
-
- await Promise.all([result.dispose(), result.dispose()]);
- expect(files.size).toBe(0);
- expect(removedNames.filter((name) => name === filename)).toHaveLength(1);
- const blobAfterDisposal = await result.getBlob();
- expect(blobAfterDisposal).toBe(blob);
- expect(new Uint8Array(await blobAfterDisposal.arrayBuffer())).toEqual(
- bytesBeforeDisposal,
- );
- });
-
- test('does not remove an OPFS output owned by another session', async () => {
- const {directory, files, seedFile} = makeFakeOpfs();
- const otherSessionFilename =
- '__remotion_video_matting:another-session:existing-output';
- seedFile(otherSessionFilename);
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
-
- expect(files.has(otherSessionFilename)).toBe(true);
- expect(files.size).toBe(2);
- await created.cancel();
- expect(files.has(otherSessionFilename)).toBe(true);
- expect(files.size).toBe(1);
- });
-
- test('can discard a finalized OPFS output internally', async () => {
- const {directory, files, removedNames} = makeFakeOpfs();
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- await created.output.start();
- await created.finalize();
- const [filename] = files.keys();
-
- await created.discard();
- await created.discard();
- expect(files.size).toBe(0);
- expect(removedNames.filter((name) => name === filename)).toHaveLength(1);
- });
-
- test('can retry OPFS disposal after a transient removal failure', async () => {
- const {directory, files} = makeFakeOpfs();
- const removeEntry = directory.removeEntry.bind(directory);
- let removalAttempts = 0;
- Object.defineProperty(directory, 'removeEntry', {
- value: (name: string) => {
- removalAttempts++;
- if (removalAttempts === 1) {
- return Promise.reject(new Error('temporary removal failure'));
- }
-
- return removeEntry(name);
- },
- });
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- await created.output.start();
- const result = await created.finalize();
-
- await expect(result.dispose()).rejects.toThrow('temporary removal failure');
- expect(files.size).toBe(1);
- await expect(result.dispose()).resolves.toBeUndefined();
- expect(files.size).toBe(0);
- expect(removalAttempts).toBe(2);
- });
-
- test('removes a partial OPFS output when canceled', async () => {
- const {directory, files} = makeFakeOpfs();
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- await created.output.start();
- expect(files.size).toBe(1);
-
- await created.cancel();
- expect(files.size).toBe(0);
- });
-
- test('removes an OPFS output even when Mediabunny cancellation fails', async () => {
- const {directory, files} = makeFakeOpfs();
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- Object.defineProperty(created.output, 'cancel', {
- value: () => Promise.reject(new Error('cancel failed')),
- });
-
- await expect(created.cancel()).rejects.toThrow('cancel failed');
- expect(files.size).toBe(0);
- });
-
- test('removes a partial OPFS output when finalization fails', async () => {
- const {directory, files} = makeFakeOpfs();
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- expect(files.size).toBe(1);
-
- await expect(created.finalize()).rejects.toThrow(
- 'Cannot finalize before starting',
- );
- expect(files.size).toBe(0);
- });
-
- test('removes an OPFS output when close and cancellation both fail', async () => {
- const {directory, files} = makeFakeOpfs({
- closeError: new Error('close failed'),
- });
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- });
- await created.output.start();
- Object.defineProperty(created.output, 'cancel', {
- value: () => Promise.reject(new Error('cancel failed')),
- });
-
- await expect(created.finalize()).rejects.toThrow('close failed');
- expect(files.size).toBe(0);
- });
-
- test('removes the created OPFS entry if createWritable fails', async () => {
- const {directory, files} = makeFakeOpfs({
- createWritableError: new Error('createWritable failed'),
- });
- Object.defineProperty(globalThis, 'navigator', {
- configurable: true,
- enumerable: true,
- value: {storage: {getDirectory: () => Promise.resolve(directory)}},
- writable: true,
- });
-
- await expect(
- createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'web-fs'},
- }),
- ).rejects.toThrow('createWritable failed');
+ await result.dispose();
expect(files.size).toBe(0);
- });
-
- test('rejects conflicting destinations at runtime', async () => {
- await expect(
- createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {
- outputTarget: 'arraybuffer',
- outputWritable: new WritableStream<StreamTargetChunk>(),
- } as unknown as VideoLayerOutputOptions,
- }),
- ).rejects.toThrow(
- 'outputTarget and outputWritable cannot both be specified for a video layer',
- );
+ expect(removedNames.at(-1)).toBe(filename);
});
});
const acceptOutputOptions = (_options: VideoLayerOutputOptions) => undefined;
acceptOutputOptions({outputTarget: 'arraybuffer'});
-acceptOutputOptions({
- outputWritable: new WritableStream<StreamTargetChunk>(),
-});
+acceptOutputOptions({outputWritable: new WritableStream<StreamTargetChunk>()});
// @ts-expect-error outputTarget and outputWritable are mutually exclusive.
acceptOutputOptions({
outputTarget: 'web-fs',
outputWritable: new WritableStream<StreamTargetChunk>(),
});
-
-test('the created output exposes the Mediabunny Output primitive', async () => {
- const created = await createVideoLayerOutput({
- format: new WebMOutputFormat(),
- options: {outputTarget: 'arraybuffer'},
- });
-
- expect(created.output).toBeInstanceOf(Output);
- await created.cancel();
-});
diff --git a/packages/video-matting/src/test/prepare-audio.test.ts b/packages/video-matting/src/test/prepare-audio.test.ts
index a6a6c52cd1..f52e6dca99 100644
--- a/packages/video-matting/src/test/prepare-audio.test.ts
+++ b/packages/video-matting/src/test/prepare-audio.test.ts
@@ -14,18 +14,23 @@ import {
} from 'mediabunny';
import {prepareAudio} from '../prepare-audio';
-test('packet-copies Opus audio to both outputs and rebases its timestamps', async () => {
- const fixture = Bun.file(
- new URL('../../../example/public/opus.webm', import.meta.url),
- );
+const getAudioFixture = async () => {
const input = new Input({
formats: ALL_FORMATS,
- source: new BlobSource(fixture),
+ source: new BlobSource(
+ Bun.file(new URL('../../../example/public/opus.webm', import.meta.url)),
+ ),
});
- const inputAudioTrack = await input.getPrimaryAudioTrack();
- expect(inputAudioTrack).not.toBeNull();
- const audioStartTimestamp = await inputAudioTrack!.getFirstTimestamp();
+ const track = await input.getPrimaryAudioTrack();
+ if (track === null) {
+ throw new Error('Expected an audio track in the fixture');
+ }
+ return {input, track, start: await track.getFirstTimestamp()};
+};
+
+test('copies and rebases Opus audio to both outputs', async () => {
+ const {input, start} = await getAudioFixture();
const baseTarget = new BufferTarget();
const foregroundTarget = new BufferTarget();
const baseOutput = new Output({
@@ -41,46 +46,34 @@ test('packet-copies Opus audio to both outputs and rebases its timestamps', asyn
baseOutput,
foregroundOutput,
destination: 'both',
- videoStartTimestamp: audioStartTimestamp,
- videoEndTimestamp: audioStartTimestamp + 0.25,
+ videoStartTimestamp: start,
+ videoEndTimestamp: start + 0.25,
audioQuality: null,
forceTranscode: false,
});
await Promise.all([baseOutput.start(), foregroundOutput.start()]);
await audio.prime();
- await audio.writeAudioUntil(0);
await audio.finishAudio();
await Promise.all([baseOutput.finalize(), foregroundOutput.finalize()]);
- expect(baseTarget.buffer).not.toBeNull();
- expect(foregroundTarget.buffer).not.toBeNull();
- for (const buffer of [baseTarget.buffer!, foregroundTarget.buffer!]) {
+ for (const buffer of [baseTarget.buffer, foregroundTarget.buffer]) {
+ expect(buffer).not.toBeNull();
const outputInput = new Input({
formats: ALL_FORMATS,
- source: new BufferSource(buffer),
+ source: new BufferSource(buffer!),
});
- const outputAudioTrack = await outputInput.getPrimaryAudioTrack();
- expect(await outputAudioTrack?.getCodec()).toBe('opus');
- expect(await outputAudioTrack?.getFirstTimestamp()).toBe(0);
+ const outputTrack = await outputInput.getPrimaryAudioTrack();
+ expect(await outputTrack?.getCodec()).toBe('opus');
+ expect(await outputTrack?.getFirstTimestamp()).toBe(0);
outputInput.dispose();
}
input.dispose();
});
-test('primes delayed audio so queued video data can be muxed', async () => {
- const fixture = Bun.file(
- new URL('../../../example/public/opus.webm', import.meta.url),
- );
- const input = new Input({
- formats: ALL_FORMATS,
- source: new BlobSource(fixture),
- });
- const inputAudioTrack = await input.getPrimaryAudioTrack();
- expect(inputAudioTrack).not.toBeNull();
- const audioStartTimestamp = await inputAudioTrack!.getFirstTimestamp();
-
+test('primes delayed audio so the muxer can emit queued video', async () => {
+ const {input, start} = await getAudioFixture();
let bytesWritten = 0;
const baseOutput = new Output({
format: new WebMOutputFormat(),
@@ -97,21 +90,19 @@ test('primes delayed audio so queued video data can be muxed', async () => {
target: new BufferTarget(),
});
const videoSource = new EncodedVideoPacketSource('vp9');
- const videoDecoderConfig: VideoDecoderConfig = {
+ const decoderConfig: VideoDecoderConfig = {
codec: 'vp09.00.10.08',
codedWidth: 2,
codedHeight: 2,
};
- baseOutput.addVideoTrack(videoSource, {
- decoderConfig: videoDecoderConfig,
- });
+ baseOutput.addVideoTrack(videoSource, {decoderConfig});
const audio = await prepareAudio({
input,
baseOutput,
foregroundOutput,
destination: 'base',
- videoStartTimestamp: audioStartTimestamp - 1,
- videoEndTimestamp: audioStartTimestamp + 0.25,
+ videoStartTimestamp: start - 1,
+ videoEndTimestamp: start + 0.25,
audioQuality: null,
forceTranscode: false,
});
@@ -119,114 +110,23 @@ test('primes delayed audio so queued video data can be muxed', async () => {
await baseOutput.start();
await videoSource.add(
new EncodedPacket(new Uint8Array([0]), 'key', 0, 0.04),
- {decoderConfig: videoDecoderConfig},
+ {decoderConfig},
);
await Promise.resolve();
- const bytesWrittenBeforePrime = bytesWritten;
-
+ const bytesBeforePrime = bytesWritten;
await audio.prime();
await Promise.resolve();
- expect(bytesWritten).toBeGreaterThan(bytesWrittenBeforePrime);
+ expect(bytesWritten).toBeGreaterThan(bytesBeforePrime);
await audio.cancel();
await Promise.all([baseOutput.cancel(), foregroundOutput.cancel()]);
input.dispose();
});
-test('cancel is idempotent before the outputs start', async () => {
- const fixture = Bun.file(
- new URL('../../../example/public/opus.webm', import.meta.url),
- );
- const input = new Input({
- formats: ALL_FORMATS,
- source: new BlobSource(fixture),
- });
- const inputAudioTrack = await input.getPrimaryAudioTrack();
- expect(inputAudioTrack).not.toBeNull();
- const audioStartTimestamp = await inputAudioTrack!.getFirstTimestamp();
- const baseOutput = new Output({
- format: new WebMOutputFormat(),
- target: new BufferTarget(),
- });
- const foregroundOutput = new Output({
- format: new WebMOutputFormat(),
- target: new BufferTarget(),
- });
- const audio = await prepareAudio({
- input,
- baseOutput,
- foregroundOutput,
- destination: 'both',
- videoStartTimestamp: audioStartTimestamp,
- videoEndTimestamp: audioStartTimestamp + 0.25,
- audioQuality: null,
- forceTranscode: false,
- });
-
- await audio.cancel();
- await audio.cancel();
- await Promise.all([baseOutput.cancel(), foregroundOutput.cancel()]);
-
- expect(baseOutput.state).toBe('canceled');
- expect(foregroundOutput.state).toBe('canceled');
- input.dispose();
-});
-
-test('does not attach audio when it does not overlap the video', async () => {
- const fixture = Bun.file(
- new URL('../../../example/public/opus.webm', import.meta.url),
- );
- const input = new Input({
- formats: ALL_FORMATS,
- source: new BlobSource(fixture),
- });
- const inputAudioTrack = await input.getPrimaryAudioTrack();
- expect(inputAudioTrack).not.toBeNull();
- const audioEndTimestamp = await inputAudioTrack!.computeDuration();
- const baseOutput = new Output({
- format: new WebMOutputFormat(),
- target: new BufferTarget(),
- });
- const foregroundOutput = new Output({
- format: new WebMOutputFormat(),
- target: new BufferTarget(),
- });
- const audio = await prepareAudio({
- input,
- baseOutput,
- foregroundOutput,
- destination: 'both',
- videoStartTimestamp: audioEndTimestamp + 1,
- videoEndTimestamp: audioEndTimestamp + 2,
- audioQuality: null,
- forceTranscode: false,
- });
-
- expect(baseOutput.tracks).toHaveLength(0);
- expect(foregroundOutput.tracks).toHaveLength(0);
- await audio.prime();
- await audio.finishAudio();
- await Promise.all([baseOutput.cancel(), foregroundOutput.cancel()]);
- input.dispose();
-});
-
-test('explicit bitrate requests force transcoding instead of Opus packet copy', async () => {
- const fixture = Bun.file(
- new URL('../../../example/public/opus.webm', import.meta.url),
- );
- const input = new Input({
- formats: ALL_FORMATS,
- source: new BlobSource(fixture),
- });
- const inputAudioTrack = await input.getPrimaryAudioTrack();
- expect(inputAudioTrack).not.toBeNull();
- const audioStartTimestamp = await inputAudioTrack!.getFirstTimestamp();
- let decodeChecks = 0;
- Object.defineProperty(inputAudioTrack, 'canDecode', {
- value: () => {
- decodeChecks++;
- return Promise.resolve(false);
- },
+test('uses the transcoding path when packet copying is disabled', async () => {
+ const {input, track, start} = await getAudioFixture();
+ Object.defineProperty(track, 'canDecode', {
+ value: () => Promise.resolve(false),
});
const baseOutput = new Output({
format: new WebMOutputFormat(),
@@ -243,13 +143,13 @@ test('explicit bitrate requests force transcoding instead of Opus packet copy',
baseOutput,
foregroundOutput,
destination: 'base',
- videoStartTimestamp: audioStartTimestamp,
- videoEndTimestamp: audioStartTimestamp + 0.25,
+ videoStartTimestamp: start,
+ videoEndTimestamp: start + 0.25,
audioQuality: null,
forceTranscode: true,
}),
).rejects.toThrow('cannot be decoded');
- expect(decodeChecks).toBe(1);
+
await Promise.all([baseOutput.cancel(), foregroundOutput.cancel()]);
input.dispose();
});
diff --git a/packages/video-matting/src/test/separate-video-layers-options.test.ts b/packages/video-matting/src/test/separate-video-layers-options.test.ts
index d6ae689607..322c367b95 100644
--- a/packages/video-matting/src/test/separate-video-layers-options.test.ts
+++ b/packages/video-matting/src/test/separate-video-layers-options.test.ts
@@ -1,98 +1,32 @@
-import {describe, expect, test} from 'bun:test';
+import {expect, test} from 'bun:test';
import {separateVideoLayers} from '../separate-video-layers';
-describe('separateVideoLayers() option validation', () => {
- test('rejects an invalid audio destination before loading a model', async () => {
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- audio: 'background' as never,
- }),
- ).rejects.toThrow('audio must be one of base, foreground, both, or none.');
- });
-
- test('rejects invalid encoding options before loading a model', async () => {
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- videoBitrate: 0,
- }),
- ).rejects.toThrow('A numeric bitrate must be a positive integer.');
-
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- keyframeIntervalInSeconds: 0,
- }),
- ).rejects.toThrow(
- 'keyframeIntervalInSeconds must be a positive finite number.',
- );
- });
-
- test('rejects conflicting layer destinations before loading a model', async () => {
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- outputs: {
- base: {
- outputTarget: 'arraybuffer',
- outputWritable: new WritableStream(),
- } as never,
- },
- }),
- ).rejects.toThrow(
- 'outputs.base cannot specify both outputTarget and outputWritable.',
- );
- });
-
- test('rejects invalid, locked, and shared output streams before loading a model', async () => {
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- outputs: {
- base: {outputWritable: {} as WritableStream},
- },
- }),
- ).rejects.toThrow('outputs.base.outputWritable must be a WritableStream.');
-
- const locked = new WritableStream();
- const writer = locked.getWriter();
- try {
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- outputs: {base: {outputWritable: locked}},
- }),
- ).rejects.toThrow(
- 'outputs.base.outputWritable must not already be locked.',
- );
- } finally {
- writer.releaseLock();
- }
-
- const shared = new WritableStream();
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- outputs: {
- base: {outputWritable: shared},
- foreground: {outputWritable: shared},
- },
- }),
- ).rejects.toThrow(
- 'outputs.base and outputs.foreground must not use the same outputWritable.',
- );
- });
-
- test('honors an already-aborted signal before loading a model', async () => {
- const controller = new AbortController();
- controller.abort(new Error('stop now'));
-
- await expect(
- separateVideoLayers({
- src: 'video.mp4',
- signal: controller.signal,
- }),
- ).rejects.toThrow('stop now');
- });
+test('validates public options before reading the input', async () => {
+ await expect(
+ separateVideoLayers({src: 'unreadable.mp4', audio: 'background' as never}),
+ ).rejects.toThrow('audio must be one of base, foreground, both, or none.');
+
+ await expect(
+ separateVideoLayers({src: 'unreadable.mp4', videoBitrate: 0}),
+ ).rejects.toThrow('A numeric bitrate must be a positive integer.');
+
+ await expect(
+ separateVideoLayers({
+ src: 'unreadable.mp4',
+ outputs: {
+ base: {
+ outputTarget: 'arraybuffer',
+ outputWritable: new WritableStream(),
+ } as never,
+ },
+ }),
+ ).rejects.toThrow(
+ 'outputs.base cannot specify both outputTarget and outputWritable.',
+ );
+
+ const controller = new AbortController();
+ controller.abort(new Error('stop now'));
+ await expect(
+ separateVideoLayers({src: 'unreadable.mp4', signal: controller.signal}),
+ ).rejects.toThrow('stop now');
});
diff --git a/packages/video-matting/src/test/video-matting-quality.test.ts b/packages/video-matting/src/test/video-matting-quality.test.ts
deleted file mode 100644
index dd12995107..0000000000
--- a/packages/video-matting/src/test/video-matting-quality.test.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import {describe, expect, test} from 'bun:test';
-import {resolveVideoMattingQuality} from '../video-matting-quality';
-
-describe('video matting quality', () => {
- test('accepts named qualities and bitrates', () => {
- expect(resolveVideoMattingQuality('very-high')).toBeDefined();
- expect(resolveVideoMattingQuality(2_000_000)).toBeDefined();
- });
-
- test('rejects invalid numeric bitrates', () => {
- expect(() => resolveVideoMattingQuality(0)).toThrow(
- 'A numeric bitrate must be a positive integer.',
- );
- expect(() => resolveVideoMattingQuality(1.5)).toThrow(
- 'A numeric bitrate must be a positive integer.',
- );
- });
-});
diff --git a/packages/video-matting/src/test/video-timing.test.ts b/packages/video-matting/src/test/video-timing.test.ts
index 4a363fbf67..96095cbf7b 100644
--- a/packages/video-matting/src/test/video-timing.test.ts
+++ b/packages/video-matting/src/test/video-timing.test.ts
@@ -1,81 +1,52 @@
-import {describe, expect, test} from 'bun:test';
+import {expect, test} from 'bun:test';
import {
getClippedVideoFrameTiming,
getVideoProcessingProgress,
rebaseVideoTimestamp,
} from '../video-timing';
-describe('video timing', () => {
- test('rebases a non-zero input timeline without rounding', () => {
- expect(
- rebaseVideoTimestamp({
- timestamp: 4.979,
- firstVideoTimestamp: 4.045,
- }),
- ).toBeCloseTo(0.934, 12);
- });
-
- test('uses frame timestamps and durations for VFR progress', () => {
- expect(
- getVideoProcessingProgress({
- timestamp: 10.125,
- duration: 0.125,
- firstVideoTimestamp: 10,
- durationInSeconds: 1,
- }),
- ).toEqual({processedDurationInSeconds: 0.25, progress: 0.25});
- });
-
- test('clamps the final frame to the video duration', () => {
- expect(
- getVideoProcessingProgress({
- timestamp: 2.9,
- duration: 0.2,
- firstVideoTimestamp: 2,
- durationInSeconds: 1,
- }),
- ).toEqual({processedDurationInSeconds: 1, progress: 1});
- });
-
- test('discards frames outside the presentation range', () => {
- expect(
- getClippedVideoFrameTiming({
- timestamp: -0.5,
- duration: 0.25,
- videoStartTimestamp: 0,
- videoEndTimestamp: 1,
- }),
- ).toBeNull();
- });
-
- test('clips frames crossing the start and end boundaries', () => {
- expect(
- getClippedVideoFrameTiming({
- timestamp: -0.25,
- duration: 0.5,
- videoStartTimestamp: 0,
- videoEndTimestamp: 1,
- }),
- ).toEqual({timestamp: 0, duration: 0.25});
-
- expect(
- getClippedVideoFrameTiming({
- timestamp: 0.875,
- duration: 0.25,
- videoStartTimestamp: 0,
- videoEndTimestamp: 1,
- }),
- ).toEqual({timestamp: 0.875, duration: 0.125});
- });
-
- test('preserves a frame inside a positive VFR presentation range', () => {
- expect(
- getClippedVideoFrameTiming({
- timestamp: 4.25,
- duration: 0.125,
- videoStartTimestamp: 4,
- videoEndTimestamp: 5,
- }),
- ).toEqual({timestamp: 0.25, duration: 0.125});
- });
+test('rebases and clips variable-frame-rate video timing', () => {
+ expect(
+ rebaseVideoTimestamp({timestamp: 4.979, firstVideoTimestamp: 4.045}),
+ ).toBeCloseTo(0.934, 12);
+ expect(
+ getVideoProcessingProgress({
+ timestamp: 10.125,
+ duration: 0.125,
+ firstVideoTimestamp: 10,
+ durationInSeconds: 1,
+ }),
+ ).toEqual({processedDurationInSeconds: 0.25, progress: 0.25});
+ expect(
+ getVideoProcessingProgress({
+ timestamp: 2.9,
+ duration: 0.2,
+ firstVideoTimestamp: 2,
+ durationInSeconds: 1,
+ }),
+ ).toEqual({processedDurationInSeconds: 1, progress: 1});
+ expect(
+ getClippedVideoFrameTiming({
+ timestamp: -0.5,
+ duration: 0.25,
+ videoStartTimestamp: 0,
+ videoEndTimestamp: 1,
+ }),
+ ).toBeNull();
+ expect(
+ getClippedVideoFrameTiming({
+ timestamp: -0.25,
+ duration: 0.5,
+ videoStartTimestamp: 0,
+ videoEndTimestamp: 1,
+ }),
+ ).toEqual({timestamp: 0, duration: 0.25});
+ expect(
+ getClippedVideoFrameTiming({
+ timestamp: 0.875,
+ duration: 0.25,
+ videoStartTimestamp: 0,
+ videoEndTimestamp: 1,
+ }),
+ ).toEqual({timestamp: 0.875, duration: 0.125});
});