Skip to content

πŸŽ₯ Make videos programmatically with React

`@remotion/media`: Share Input across MediaPlayers of the same source (#8912)

Praveen Chukkaae327ffe05aa
diff --git a/packages/media/src/get-shared-input.ts b/packages/media/src/get-shared-input.ts
new file mode 100644
index 0000000000..f5b8a566de
--- /dev/null
+++ b/packages/media/src/get-shared-input.ts
@@ -0,0 +1,96 @@
+import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
+import {
+ getMediaRequestInitFingerprint,
+ normalizeMediaRequestInit,
+ resolveRequestInit,
+ type MediaRequestInit,
+} from './request-init';
+
+// A single mediabunny `Input` (backed by one `UrlSource`) is expensive to spin
+// up for network media: on creation it must fetch and parse the container
+// header, and its `UrlSource` keeps a byte cache + demuxer state that is warm
+// only for that instance.
+//
+// Previously every `MediaPlayer` created its own `Input`, so mounting a new
+// range (jump cut / play-range) meant a cold container re-parse and cold seek β€”
+// which is exactly the loader that shows at each cut. Since all ranges of the
+// 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,
+ requestInit,
+}: {
+ src: string;
+ credentials: RequestCredentials | undefined;
+ requestInit: MediaRequestInit | undefined;
+}): string =>
+ JSON.stringify([
+ src,
+ credentials ?? null,
+ getMediaRequestInitFingerprint(requestInit),
+ ]);
+
+export const acquireSharedInput = ({
+ src,
+ credentials,
+ requestInit,
+}: {
+ src: string;
+ credentials: RequestCredentials | undefined;
+ requestInit: MediaRequestInit | undefined;
+}): {input: Input; cacheKey: string} => {
+ const normalizedRequestInit = normalizeMediaRequestInit(requestInit);
+ const cacheKey = getSharedInputCacheKey({
+ src,
+ credentials,
+ 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,
+ 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;
+ }
+
+ entry.refCount--;
+ if (entry.refCount <= 0) {
+ delete sharedInputs[cacheKey];
+ entry.input.dispose();
+ }
+};
diff --git a/packages/media/src/media-player.ts b/packages/media/src/media-player.ts
index 5e3e224ae0..2a92b2bebc 100644
--- a/packages/media/src/media-player.ts
+++ b/packages/media/src/media-player.ts
@@ -1,4 +1,4 @@
-import {ALL_FORMATS, Input, UrlSource} from 'mediabunny';
+import type {Input} from 'mediabunny';
import type {
EffectChainState,
EffectDefinitionAndStack,
@@ -19,6 +19,7 @@ import {
} from './audio/get-scheduled-time';
import {drawPreviewOverlay} from './debug-overlay/preview-overlay';
import {getDurationOrCompute} from './get-duration-or-compute';
+import {acquireSharedInput, releaseSharedInput} 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';
@@ -26,7 +27,6 @@ import type {Nonce, NonceManager} from './nonce-manager';
import {makeNonceManager} from './nonce-manager';
import {PremountAwareDelayPlayback} from './premount-aware-delay-playback';
import type {MediaRequestInit} from './request-init';
-import {resolveRequestInit} from './request-init';
import type {SharedAudioContextForMediaPlayer} from './shared-audio-context-for-media-player';
import type {VideoIteratorManager} from './video-iterator-manager';
import {videoIteratorManager} from './video-iterator-manager';
@@ -163,18 +163,16 @@ export class MediaPlayer {
this.onVideoFrameCallback = onVideoFrameCallback;
this.playing = playing;
this.sequenceOffset = sequenceOffset;
- const resolvedRequestInit = resolveRequestInit({credentials, requestInit});
- this.input = new Input({
- source: new UrlSource(
- this.src,
- resolvedRequestInit
- ? {
- requestInit: resolvedRequestInit,
- }
- : undefined,
- ),
- formats: ALL_FORMATS,
+ // 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({
+ src: this.src,
+ credentials,
+ requestInit,
});
+ this.input = input;
+ this.inputCacheKey = cacheKey;
this.tagType = tagType;
this.getEffects = getEffects;
this.getEffectChainState = getEffectChainState;
@@ -196,9 +194,16 @@ export class MediaPlayer {
}
private input: Input;
+ // Key into the shared-input cache; released (ref count decremented) on dispose.
+ private inputCacheKey: string;
+ // 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
+ // own lifecycle instead.
+ private disposed = false;
private isDisposalError(): boolean {
- return this.input.disposed === true;
+ return this.disposed || this.input.disposed === true;
}
public initialize(
@@ -251,7 +256,7 @@ export class MediaPlayer {
): Promise<MediaPlayerInitResult> {
using _ = this.delayPlaybackHandleIfNotPremounting();
try {
- if (this.input.disposed) {
+ if (this.isDisposalError()) {
return {type: 'disposed'};
}
@@ -282,7 +287,7 @@ export class MediaPlayer {
this.input.getPrimaryVideoTrack(),
this.input.getAudioTracks(),
]);
- if (this.input.disposed) {
+ if (this.isDisposalError()) {
return {type: 'disposed'};
}
@@ -319,7 +324,7 @@ export class MediaPlayer {
return {type: 'cannot-decode'};
}
- if (this.input.disposed) {
+ if (this.isDisposalError()) {
return {type: 'disposed'};
}
@@ -367,7 +372,7 @@ export class MediaPlayer {
return {type: 'cannot-decode'};
}
- if (this.input.disposed) {
+ if (this.isDisposalError()) {
return {type: 'disposed'};
}
@@ -675,6 +680,15 @@ export class MediaPlayer {
}
public async dispose(): Promise<void> {
+ // Guard against double-dispose: releasing the shared Input twice would
+ // over-decrement its ref count and tear it down while other players still
+ // use it.
+ if (this.disposed) {
+ return;
+ }
+
+ this.disposed = true;
+
if (this.initializationPromise) {
try {
// wait for the init to finished
@@ -690,7 +704,9 @@ export class MediaPlayer {
this.nonceManager.createAsyncOperation();
this.videoIteratorManager?.destroy();
this.audioIteratorManager?.destroyIterator();
- this.input.dispose();
+ // Release our reference to the shared Input; it is only disposed once the
+ // last MediaPlayer using this src releases it.
+ releaseSharedInput(this.inputCacheKey);
}
private getTargetTime = (