π₯ Make videos programmatically with React
`@remotion/studio`: Share Mediabunny inputs with `@remotion/media` (#10647)
Jonny Burgerb49e41787238
diff --git a/bun.lock b/bun.lockindex 08f05ad788..cf186d1cf8 100644--- a/bun.lock+++ b/bun.lock@@ -2625,6 +2625,7 @@"version": "4.0.514","dependencies": {"mediabunny": "catalog:",+ "remotion": "workspace:*",},"devDependencies": {"@mediabunny/server": "catalog:",diff --git a/packages/core/src/internals.ts b/packages/core/src/internals.tsindex db4ed43f9a..f1a8ad9bf5 100644--- a/packages/core/src/internals.ts+++ b/packages/core/src/internals.ts@@ -121,6 +121,12 @@ import type {LoggingContextValue} from './log-level-context.js';import {LogLevelContext, useLogLevel} from './log-level-context.js';import {Log} from './log.js';import {MaxMediaCacheSizeContext} from './max-video-cache-size.js';+import {+ getMediabunnyInputResourceKey,+ globalMediaResourceManager,+ makeMediaResourceManager,+ MEDIABUNNY_DURATION_VALUE_KEY,+} from './media-resource-manager.js';import type {NonceHistory} from './nonce.js';import {NonceContext} from './nonce.js';import {playbackLogging} from './playback-logging.js';@@ -293,6 +299,10 @@ const compositionSelectorRef = createRef<{export const Internals = {AbsoluteFillElement,MaxMediaCacheSizeContext,+ getMediabunnyInputResourceKey,+ globalMediaResourceManager,+ makeMediaResourceManager,+ MEDIABUNNY_DURATION_VALUE_KEY,makeRenderResourceManager,RenderResourceManagerContext,useUnsafeVideoConfig,diff --git a/packages/core/src/media-resource-manager.ts b/packages/core/src/media-resource-manager.tsnew file mode 100644index 0000000000..c7a5671cc7--- /dev/null+++ b/packages/core/src/media-resource-manager.ts@@ -0,0 +1,173 @@+type MediaResource = {+ resource: unknown;+ dispose: () => void;+ refCount: number;+ disposeGeneration: number;+ disposed: boolean;+ values: Map<string, unknown>;+};++export type MediaResourceLease<T> = {+ resource: T;+ getOrCreateValue: <Value>(key: string, create: () => Value) => Value;+ release: () => void;+};++export type MediaResourceManager = {+ acquire: <T>({+ key,+ create,+ }: {+ key: string;+ create: () => {resource: T; dispose: () => void};+ }) => MediaResourceLease<T>;+ invalidate: (key: string) => void;+ dispose: () => void;+};++const disposeResource = (resource: MediaResource) => {+ if (resource.disposed) {+ return;+ }++ resource.disposed = true;+ resource.values.clear();+ resource.dispose();+};++export const makeMediaResourceManager = (): MediaResourceManager => {+ const resources = new Map<string, MediaResource>();+ let disposed = false;++ return {+ acquire: <T>({+ key,+ create,+ }: {+ key: string;+ create: () => {resource: T; dispose: () => void};+ }) => {+ if (disposed) {+ throw new Error('Media resource manager has already been disposed');+ }++ let entry = resources.get(key);+ if (!entry) {+ const created = create();+ entry = {+ resource: created.resource,+ dispose: created.dispose,+ refCount: 0,+ disposeGeneration: 0,+ disposed: false,+ values: new Map(),+ };+ resources.set(key, entry);+ }++ entry.refCount++;+ entry.disposeGeneration++;+ let released = false;++ return {+ resource: entry.resource as T,+ getOrCreateValue: <Value>(+ valueKey: string,+ createValue: () => Value,+ ) => {+ if (entry.values.has(valueKey)) {+ return entry.values.get(valueKey) as Value;+ }++ const value = createValue();+ entry.values.set(valueKey, value);+ return value;+ },+ release: () => {+ if (released) {+ return;+ }++ released = true;+ entry.refCount--;+ if (entry.refCount !== 0) {+ return;+ }++ const disposeGeneration = ++entry.disposeGeneration;+ queueMicrotask(() => {+ if (+ entry.refCount !== 0 ||+ entry.disposeGeneration !== disposeGeneration+ ) {+ return;+ }++ if (resources.get(key) === entry) {+ resources.delete(key);+ }++ disposeResource(entry);+ });+ },+ };+ },+ invalidate: (key) => {+ const entry = resources.get(key);+ if (!entry) {+ return;+ }++ resources.delete(key);+ entry.disposeGeneration++;+ if (entry.refCount === 0) {+ disposeResource(entry);+ }+ },+ dispose: () => {+ if (disposed) {+ return;+ }++ disposed = true;+ const entries = Array.from(resources.values());+ resources.clear();++ let firstError: unknown = null;+ for (const entry of entries) {+ try {+ disposeResource(entry);+ } catch (error) {+ firstError ??= error;+ }+ }++ if (firstError !== null) {+ throw firstError;+ }+ },+ };+};++export const getMediabunnyInputResourceKey = ({+ src,+ credentials,+ requestInitFingerprint,+ revision,+}: {+ src: string;+ credentials: RequestCredentials | null;+ requestInitFingerprint: unknown;+ revision: string | null;+}) =>+ JSON.stringify([+ 'mediabunny-input',+ src,+ credentials,+ requestInitFingerprint,+ revision,+ ]);++export const MEDIABUNNY_DURATION_VALUE_KEY = 'mediabunny-duration';++export const globalMediaResourceManager = makeMediaResourceManager();diff --git a/packages/core/src/test/media-resource-manager.test.ts b/packages/core/src/test/media-resource-manager.test.tsnew file mode 100644index 0000000000..6052626692--- /dev/null+++ b/packages/core/src/test/media-resource-manager.test.ts@@ -0,0 +1,76 @@+import {expect, test} from 'bun:test';+import {makeMediaResourceManager} from '../media-resource-manager';++test('shares active media resources and their computed values', async () => {+ const manager = makeMediaResourceManager();+ let creations = 0;+ let disposals = 0;+ let valueComputations = 0;++ const acquire = () =>+ manager.acquire({+ key: 'video.mp4',+ create: () => {+ creations++;+ return {+ resource: {creation: creations},+ dispose: () => disposals++,+ };+ },+ });++ const metadataLease = acquire();+ const playbackLease = acquire();+ const metadataDuration = metadataLease.getOrCreateValue('duration', () => {+ valueComputations++;+ return Promise.resolve(10);+ });+ const playbackDuration = playbackLease.getOrCreateValue<Promise<number>>(+ 'duration',+ () => {+ throw new Error('Duration should be shared');+ },+ );++ expect(playbackLease.resource).toBe(metadataLease.resource);+ expect(playbackDuration).toBe(metadataDuration);+ expect(await playbackDuration).toBe(10);+ expect({creations, disposals, valueComputations}).toEqual({+ creations: 1,+ disposals: 0,+ valueComputations: 1,+ });++ metadataLease.release();+ metadataLease.release();+ await Promise.resolve();+ expect(disposals).toBe(0);++ playbackLease.release();+ const handoffLease = acquire();+ await Promise.resolve();+ expect(handoffLease.resource).toBe(playbackLease.resource);+ expect(disposals).toBe(0);++ handoffLease.release();+ await Promise.resolve();+ expect(disposals).toBe(1);++ const nextLease = acquire();+ expect(nextLease.resource).not.toBe(playbackLease.resource);+ expect(creations).toBe(2);++ manager.invalidate('video.mp4');+ expect(disposals).toBe(1);+ const replacementLease = acquire();+ expect(replacementLease.resource).not.toBe(nextLease.resource);+ expect(creations).toBe(3);++ nextLease.release();+ await Promise.resolve();+ expect(disposals).toBe(2);++ replacementLease.release();+ await Promise.resolve();+ expect(disposals).toBe(3);+});diff --git a/packages/media/src/get-shared-input.ts b/packages/media/src/get-shared-input.tsindex 8c52a83334..2fe7f83e45 100644--- a/packages/media/src/get-shared-input.ts+++ b/packages/media/src/get-shared-input.ts@@ -1,5 +1,6 @@import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';-import type {LogLevel} from 'remotion';+import {Internals, type LogLevel} from 'remotion';+import {getDurationOrCompute} from './get-duration-or-compute';import {getMaxSourceCacheSize} from './max-cache-size';import {getMediaRequestInitFingerprint,@@ -19,18 +20,6 @@ import {// same media share the same `src`, they can share ONE `Input`: the container is// parsed once and subsequent seeks are served from the warm byte cache.//-// The Input is reference counted: `acquireSharedInput` hands out the cached-// Input and bumps a count; `releaseSharedInput` decrements it and only disposes-// (and evicts) the Input once the last holder releases it. This mirrors the-// sink cache in `get-sink.ts`, but for the preview `MediaPlayer` path.--type SharedInputEntry = {- input: Input;- refCount: number;-};--const sharedInputs: Record<string, SharedInputEntry> = {};-const getSharedInputCacheKey = ({src,credentials,@@ -40,11 +29,12 @@ const getSharedInputCacheKey = ({credentials: RequestCredentials | undefined;requestInit: MediaRequestInit | undefined;}): string =>- JSON.stringify([+ Internals.getMediabunnyInputResourceKey({src,- credentials ?? null,- getMediaRequestInitFingerprint(requestInit),- ]);+ credentials: credentials ?? null,+ requestInitFingerprint: getMediaRequestInitFingerprint(requestInit),+ revision: null,+ });export const acquireSharedInput = ({src,@@ -56,7 +46,11 @@ export const acquireSharedInput = ({credentials: RequestCredentials | undefined;requestInit: MediaRequestInit | undefined;logLevel: LogLevel;-}): {input: Input; cacheKey: string} => {+}): {+ input: Input;+ getDuration: () => Promise<number>;+ release: () => void;+} => {const normalizedRequestInit = normalizeMediaRequestInit(requestInit);const cacheKey = getSharedInputCacheKey({src,@@ -64,37 +58,33 @@ export const acquireSharedInput = ({requestInit: normalizedRequestInit,});- const existing = sharedInputs[cacheKey];- if (existing) {- existing.refCount++;- return {input: existing.input, cacheKey};- }-const resolvedRequestInit = resolveRequestInit({credentials,requestInit: normalizedRequestInit,});- const input = new Input({- source: new UrlSource(src, {- maxCacheSize: getMaxSourceCacheSize(logLevel),- ...(resolvedRequestInit ? {requestInit: resolvedRequestInit} : undefined),- }),- formats: ALL_FORMATS,- });+ const lease = Internals.globalMediaResourceManager.acquire<Input>({+ key: cacheKey,+ create: () => {+ const input = new Input({+ source: new UrlSource(src, {+ maxCacheSize: getMaxSourceCacheSize(logLevel),+ ...(resolvedRequestInit+ ? {requestInit: resolvedRequestInit}+ : undefined),+ }),+ formats: ALL_FORMATS,+ });- sharedInputs[cacheKey] = {input, refCount: 1};- return {input, cacheKey};-};--export const releaseSharedInput = (cacheKey: string): void => {- const entry = sharedInputs[cacheKey];- if (!entry) {- return;- }+ return {resource: input, dispose: () => input.dispose()};+ },+ });- entry.refCount--;- if (entry.refCount <= 0) {- delete sharedInputs[cacheKey];- entry.input.dispose();- }+ return {+ input: lease.resource,+ getDuration: () =>+ lease.getOrCreateValue(Internals.MEDIABUNNY_DURATION_VALUE_KEY, () =>+ getDurationOrCompute(lease.resource),+ ),+ release: lease.release,+ };};diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.tsindex 3f9cf7a0f7..55ab1aa4a6 100644--- a/packages/media/src/media-player.ts+++ b/packages/media/src/media-player.ts@@ -19,8 +19,7 @@ import {} from './audio/get-scheduled-time';import {processNext} from './audio/sort-by-priority';import {drawPreviewOverlay} from './debug-overlay/preview-overlay';-import {getDurationOrCompute} from './get-duration-or-compute';-import {acquireSharedInput, releaseSharedInput} from './get-shared-input';+import {acquireSharedInput} from './get-shared-input';import {calculateEndTime, getTimeInSeconds} from './get-time-in-seconds';import {resolveAudioTrack} from './helpers/resolve-audio-track';import {isNetworkError} from './is-type-of-error';@@ -168,14 +167,15 @@ export class MediaPlayer {// Reuse a shared, reference-counted Input per (src, credentials,// requestInit) so mounting a new range does not re-parse the container or// cold-seek β the byte cache and demuxer state stay warm across ranges.- const {input, cacheKey} = acquireSharedInput({+ const {input, getDuration, release} = acquireSharedInput({src: this.src,credentials,requestInit,logLevel,});this.input = input;- this.inputCacheKey = cacheKey;+ this.getDuration = getDuration;+ this.releaseInput = release;this.tagType = tagType;this.getEffects = getEffects;this.getEffectChainState = getEffectChainState;@@ -196,8 +196,8 @@ export class MediaPlayer {}private input: Input;- // Key into the shared-input cache; released (ref count decremented) on dispose.- private inputCacheKey: string;+ private getDuration: () => Promise<number>;+ private releaseInput: () => void;// Per-player disposal flag. The Input is now shared and reference counted, so// `this.input.disposed` no longer tells us whether THIS player was disposed// (the Input stays alive while other players hold it). This flag tracks our@@ -285,7 +285,7 @@ export class MediaPlayer {}const [durationInSeconds, videoTrack, audioTracks] = await Promise.all([- getDurationOrCompute(this.input),+ this.getDuration(),this.input.getPrimaryVideoTrack(),this.input.getAudioTracks(),]);@@ -710,7 +710,7 @@ export class MediaPlayer {this.audioIteratorManager?.destroyIterator();// Release our reference to the shared Input; it is only disposed once the// last MediaPlayer using this src releases it.- releaseSharedInput(this.inputCacheKey);+ this.releaseInput();}private getTargetTime = (diff --git a/packages/media/src/test/shared-input.test.ts b/packages/media/src/test/shared-input.test.tsnew file mode 100644index 0000000000..9189ef87a4--- /dev/null+++ b/packages/media/src/test/shared-input.test.ts@@ -0,0 +1,34 @@+import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';+import {Internals} from 'remotion';+import {expect, test} from 'vitest';+import {acquireSharedInput} from '../get-shared-input';++test('shares a main-thread Input acquired outside @remotion/media', async () => {+ const src = 'https://example.com/shared-input.mp4';+ const input = new Input({+ formats: ALL_FORMATS,+ source: new UrlSource(src),+ });+ const studioLease = Internals.globalMediaResourceManager.acquire<Input>({+ key: Internals.getMediabunnyInputResourceKey({+ src,+ credentials: null,+ requestInitFingerprint: null,+ revision: null,+ }),+ create: () => ({resource: input, dispose: () => input.dispose()}),+ });+ const mediaLease = acquireSharedInput({+ src,+ credentials: undefined,+ requestInit: undefined,+ logLevel: 'info',+ });++ expect(mediaLease.input).toBe(studioLease.resource);++ mediaLease.release();+ studioLease.release();+ await Promise.resolve();+ expect(input.disposed).toBe(true);+});diff --git a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsxindex cf94f92de2..e611ad1863 100644--- a/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx+++ b/packages/studio/src/components/Timeline/TimelineVideoInfo.tsx@@ -16,7 +16,7 @@ import {} from '@remotion/timeline-utils';import React, {useEffect, useMemo, useRef, useState} from 'react';import type {LoopDisplay} from 'remotion';-import {useVideoConfig} from 'remotion';+import {Internals, useVideoConfig} from 'remotion';import {BLACK_ALPHA_30} from '../../helpers/colors';import {TIMELINE_LAYER_FILMSTRIP_HEIGHT,@@ -81,6 +81,7 @@ const TimelineVideoInfoSegment: React.FC<{extendLastFrame,}) => {const {fps} = useVideoConfig();+ const resolvedSrc = Internals.usePreload(src);const ref = useRef<HTMLDivElement>(null);const [error, setError] = useState<Error | null>(null);const aspectRatio = useRef<number | null>(getAspectRatioFromCache(src));@@ -189,7 +190,7 @@ const TimelineVideoInfoSegment: React.FC<{return [times.timestampInSeconds];},- src,+ src: resolvedSrc,onVideoSample: (sample) => {let frame: VideoFrame | undefined;try {@@ -348,7 +349,7 @@ const TimelineVideoInfoSegment: React.FC<{.filter((timestamp) => filledSlots.get(timestamp) === undefined).map((timestamp) => timestamp / WEBCODECS_TIMESCALE);},- src,+ src: resolvedSrc,onVideoSample: (sample) => {let frame: VideoFrame | undefined;try {@@ -437,6 +438,7 @@ const TimelineVideoInfoSegment: React.FC<{frozenMediaFrame,mediaStartFrame,playbackRate,+ resolvedSrc,src,tiledLoop,visualizationWidth,diff --git a/packages/studio/src/helpers/use-max-media-duration.ts b/packages/studio/src/helpers/use-max-media-duration.tsindex 51c2bd8888..1175e335ef 100644--- a/packages/studio/src/helpers/use-max-media-duration.ts+++ b/packages/studio/src/helpers/use-max-media-duration.ts@@ -1,5 +1,5 @@import {useEffect, useState} from 'react';-import {type TSequence} from 'remotion';+import {Internals, type TSequence} from 'remotion';import {isVideoWithLastFrameHold} from './is-video-with-last-frame-hold';import {getMediaMetadata} from './use-media-metadata';@@ -22,7 +22,8 @@ const getSrc = (s: TSequence) => {export const useMaxMediaDuration = (s: TSequence, fps: number) => {const holdsLastFrame = isVideoWithLastFrameHold(s);const src = holdsLastFrame ? null : getSrc(s);- const cacheKey = src ? getCacheKey(src, fps) : null;+ const resolvedSrc = Internals.usePreload(src ?? '');+ const cacheKey = src ? getCacheKey(resolvedSrc, fps) : null;const [maxMediaDuration, setMaxMediaDuration] = useState(cacheKey ? (cache.get(cacheKey) ?? null) : Infinity,@@ -42,7 +43,7 @@ export const useMaxMediaDuration = (s: TSequence, fps: number) => {let cancelled = false;- getMediaMetadata(src)+ getMediaMetadata(resolvedSrc).then((metadata) => {if (cancelled || !metadata) {return;@@ -63,7 +64,7 @@ export const useMaxMediaDuration = (s: TSequence, fps: number) => {return () => {cancelled = true;};- }, [cacheKey, fps, src]);+ }, [cacheKey, fps, resolvedSrc, src]);if (holdsLastFrame) {return Infinity;diff --git a/packages/studio/src/helpers/use-media-metadata.ts b/packages/studio/src/helpers/use-media-metadata.tsindex f874da2a5c..b2a442354c 100644--- a/packages/studio/src/helpers/use-media-metadata.ts+++ b/packages/studio/src/helpers/use-media-metadata.ts@@ -2,6 +2,7 @@ import {getVideoMetadata} from '@remotion/media-utils';import type {InputAudioTrack, InputVideoTrack} from 'mediabunny';import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';import {useEffect, useState} from 'react';+import {Internals} from 'remotion';import {getDurationOrCompute} from './get-duration-or-compute';export type MediaMetadata = {@@ -36,20 +37,45 @@ const safeCall = async <T>(fn: () => Promise<T>): Promise<T | null> => {const getMediabunnyMetadata = async (src: string,): Promise<MediaMetadata | null> => {- let input: Input;+ const lease = (() => {+ try {+ return Internals.globalMediaResourceManager.acquire<Input>({+ key: Internals.getMediabunnyInputResourceKey({+ src,+ credentials: null,+ requestInitFingerprint: null,+ revision: null,+ }),+ create: () => {+ const createdInput = new Input({+ formats: ALL_FORMATS,+ source: new UrlSource(src),+ });++ return {+ resource: createdInput,+ dispose: () => createdInput.dispose(),+ };+ },+ });+ } catch {+ return null;+ }+ })();- try {- input = new Input({- formats: ALL_FORMATS,- source: new UrlSource(src),- });- } catch {+ if (lease === null) {return null;}+ const input = lease.resource;+try {const [duration, format, videoTrack, audioTrack] = await Promise.all([- safeCall(() => getDurationOrCompute(input)),+ safeCall(() =>+ lease.getOrCreateValue(Internals.MEDIABUNNY_DURATION_VALUE_KEY, () =>+ getDurationOrCompute(input),+ ),+ ),safeCall(() => input.getFormat()),safeCall(() => input.getPrimaryVideoTrack()),safeCall(() => input.getPrimaryAudioTrack()),@@ -91,11 +117,7 @@ const getMediabunnyMetadata = async (hasAudioTrack: Boolean(audioTrack),};} finally {- try {- input.dispose();- } catch {- // ignore- }+ lease.release();}};@@ -158,21 +180,23 @@ export const getMediaMetadata = (};export const useMediaMetadata = (src: string | null): MediaMetadata | null => {+ const resolvedSrc = Internals.usePreload(src ?? '');+ const metadataSrc = src === null ? null : resolvedSrc;const [mediaMetadata, setMediaMetadata] = useState<MediaMetadata | null>(- src ? getCachedMediaMetadata(src) : null,+ metadataSrc ? getCachedMediaMetadata(metadataSrc) : null,);useEffect(() => {- const cached = src ? getCachedMediaMetadata(src) : null;+ const cached = metadataSrc ? getCachedMediaMetadata(metadataSrc) : null;setMediaMetadata(cached);- if (!src || cached) {+ if (!metadataSrc || cached) {return;}let cancelled = false;- getMediaMetadata(src)+ getMediaMetadata(metadataSrc).then((metadata) => {if (cancelled) {return;@@ -191,7 +215,7 @@ export const useMediaMetadata = (src: string | null): MediaMetadata | null => {return () => {cancelled = true;};- }, [src]);+ }, [metadataSrc]);return mediaMetadata;};diff --git a/packages/timeline-utils/bundle.ts b/packages/timeline-utils/bundle.tsindex 72fe2b2b4a..cb50b11f6c 100644--- a/packages/timeline-utils/bundle.ts+++ b/packages/timeline-utils/bundle.ts@@ -7,7 +7,7 @@ if (process.env.NODE_ENV !== 'production') {const output = await build({entrypoints: ['src/index.ts', 'src/audio-waveform-worker.ts'],naming: '[name].mjs',- external: ['mediabunny'],+ external: ['mediabunny', 'remotion'],});for (const file of output.outputs) {diff --git a/packages/timeline-utils/package.json b/packages/timeline-utils/package.jsonindex 7d8d10b4c7..a00ad5fac3 100644--- a/packages/timeline-utils/package.json+++ b/packages/timeline-utils/package.json@@ -21,7 +21,8 @@"url": "https://github.com/remotion-dev/remotion/issues"},"dependencies": {- "mediabunny": "catalog:"+ "mediabunny": "catalog:",+ "remotion": "workspace:*"},"devDependencies": {"@mediabunny/server": "catalog:",diff --git a/packages/timeline-utils/src/extract-frames.ts b/packages/timeline-utils/src/extract-frames.tsindex 47ee62ea27..2d47cdeaf9 100644--- a/packages/timeline-utils/src/extract-frames.ts+++ b/packages/timeline-utils/src/extract-frames.ts@@ -6,6 +6,7 @@ import {UrlSource,VideoSampleSink,} from 'mediabunny';+import {Internals} from 'remotion';import {clampTimestampsToDuration} from './clamp-timestamps-to-duration';import {getDurationOrCompute} from './get-duration-or-compute';@@ -34,25 +35,39 @@ export async function extractFrames({signal,repeatLastFrame = false,}: ExtractFramesProps): Promise<void> {- const input = new Input({- formats: ALL_FORMATS,- source: new UrlSource(src),+ const lease = Internals.globalMediaResourceManager.acquire<Input>({+ key: Internals.getMediabunnyInputResourceKey({+ src,+ credentials: null,+ requestInitFingerprint: null,+ revision: null,+ }),+ create: () => {+ const createdInput = new Input({+ formats: ALL_FORMATS,+ source: new UrlSource(src),+ });++ return {+ resource: createdInput,+ dispose: () => createdInput.dispose(),+ };+ },});-- const dispose = () => {- input.dispose();- };-- if (signal) {- signal.addEventListener('abort', dispose, {once: true});- }+ const input = lease.resource;try {const [durationInSeconds, format, videoTrack] = await Promise.all([- getDurationOrCompute(input),+ lease.getOrCreateValue(Internals.MEDIABUNNY_DURATION_VALUE_KEY, () =>+ getDurationOrCompute(input),+ ),input.getFormat(),input.getPrimaryVideoTrack(),]);+ if (signal?.aborted) {+ return;+ }+if (!videoTrack) {throw new Error('No video track found in the input');}@@ -125,9 +140,6 @@ export async function extractFrames({throw error;} finally {- dispose();- if (signal) {- signal.removeEventListener('abort', dispose);- }+ lease.release();}}diff --git a/packages/timeline-utils/src/test/extract-frames-server.test.ts b/packages/timeline-utils/src/test/extract-frames-server.test.tsindex 61a8216938..33752a7dcd 100644--- a/packages/timeline-utils/src/test/extract-frames-server.test.ts+++ b/packages/timeline-utils/src/test/extract-frames-server.test.ts@@ -1,5 +1,7 @@import {beforeAll, expect, test} from 'bun:test';import {registerMediabunnyServer} from '@mediabunny/server';+import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';+import {Internals} from 'remotion';import {extractFrames} from '../extract-frames';import {ensureSlots, WEBCODECS_TIMESCALE} from '../render-frame-strip';@@ -11,6 +13,19 @@ beforeAll(() => {});test('extractFrames decodes MP4 frames for the timeline film strip', async () => {+ const source = new UrlSource(SAMPLE_MEDIA_URL);+ let sourceReads = 0;+ source.on('read', () => sourceReads++);+ const input = new Input({formats: ALL_FORMATS, source});+ const playbackLease = Internals.globalMediaResourceManager.acquire<Input>({+ key: Internals.getMediabunnyInputResourceKey({+ src: SAMPLE_MEDIA_URL,+ credentials: null,+ requestInitFingerprint: null,+ revision: null,+ }),+ create: () => ({resource: input, dispose: () => input.dispose()}),+ });const filledSlots = new Map<number, number | undefined>();const extractedSamples: Array<{timestamp: number;@@ -19,37 +34,42 @@ test('extractFrames decodes MP4 frames for the timeline film strip', async () =>displayHeight: number;}> = [];- await extractFrames({- src: SAMPLE_MEDIA_URL,- timestampsInSeconds: ({track, container, durationInSeconds}) => {- expect(track).toEqual({width: 1920, height: 1080});- expect(container).toBe('MP4');- expect(durationInSeconds).toBe(10);+ try {+ await extractFrames({+ src: SAMPLE_MEDIA_URL,+ timestampsInSeconds: ({track, container, durationInSeconds}) => {+ expect(track).toEqual({width: 1920, height: 1080});+ expect(container).toBe('MP4');+ expect(durationInSeconds).toBe(10);- ensureSlots({- filledSlots,- naturalWidth: 180,- fromSeconds: 0,- toSeconds: 1,- aspectRatio: track.width / track.height,- frameHeight: 50,- });+ ensureSlots({+ filledSlots,+ naturalWidth: 180,+ fromSeconds: 0,+ toSeconds: 1,+ aspectRatio: track.width / track.height,+ frameHeight: 50,+ });- return Array.from(filledSlots.keys()).map(- (timestamp) => timestamp / WEBCODECS_TIMESCALE,- );- },- onVideoSample: (sample) => {- extractedSamples.push({- timestamp: sample.timestamp,- duration: sample.duration,- displayWidth: sample.displayWidth,- displayHeight: sample.displayHeight,- });- sample.close();- },- });+ return Array.from(filledSlots.keys()).map(+ (timestamp) => timestamp / WEBCODECS_TIMESCALE,+ );+ },+ onVideoSample: (sample) => {+ extractedSamples.push({+ timestamp: sample.timestamp,+ duration: sample.duration,+ displayWidth: sample.displayWidth,+ displayHeight: sample.displayHeight,+ });+ sample.close();+ },+ });+ } finally {+ playbackLease.release();+ }+ expect(sourceReads).toBeGreaterThan(0);expect(extractedSamples.length).toBe(filledSlots.size);expect(extractedSamples.length).toBeGreaterThan(1);diff --git a/packages/timeline-utils/tsconfig.json b/packages/timeline-utils/tsconfig.jsonindex c80d66921c..a240a1c212 100644--- a/packages/timeline-utils/tsconfig.json+++ b/packages/timeline-utils/tsconfig.json@@ -4,5 +4,6 @@"rootDir": "src","outDir": "dist"},- "include": ["src"]+ "include": ["src"],+ "references": [{"path": "../core"}]}