Skip to content

🎥 Make videos programmatically with React

`@remotion/media`: Preserve keyframe banks used by active playheads (#10234)

Alec Watts48b4c5d5f186
diff --git a/packages/media/src/test/multi-playhead-clearing.test.ts b/packages/media/src/test/multi-playhead-clearing.test.ts
new file mode 100644
index 0000000000..49426fea04
--- /dev/null
+++ b/packages/media/src/test/multi-playhead-clearing.test.ts
@@ -0,0 +1,184 @@
+import {VideoSample, type VideoSampleSink} from 'mediabunny';
+import {expect, test} from 'vitest';
+// Importing `keyframe-manager` directly would hit the import cycle with
+// `caches.ts`, so use the singleton it exports.
+import {keyframeManager} from '../caches';
+
+const FPS = 10;
+
+const makeSample = (timestamp: number) => {
+ return new VideoSample(new Uint8Array(4), {
+ format: 'RGBA',
+ codedWidth: 1,
+ codedHeight: 1,
+ timestamp,
+ duration: 1 / FPS,
+ });
+};
+
+// Simulates a video with a keyframe every second: a seek to `start` begins
+// decoding at floor(start). Records every seek so tests can detect when a
+// bank had to be rebuilt.
+const makeSeekTrackingSink = () => {
+ const seeks: number[] = [];
+ const sink: VideoSampleSink = {
+ getSample() {
+ return Promise.reject(new Error('Not implemented'));
+ },
+ async *samples(start = 0) {
+ seeks.push(start);
+ for (let i = Math.round(Math.floor(start) * FPS); ; i++) {
+ yield makeSample(i / FPS);
+ }
+ },
+ async *samplesAtTimestamps() {
+ yield* [];
+ },
+ };
+
+ return {sink, seeks};
+};
+
+test('concurrent playheads on the same src do not clear each other`s banks', async () => {
+ const manager = keyframeManager;
+ manager.clearAll('error');
+ const {sink, seeks} = makeSeekTrackingSink();
+ const src = 'same-video.mp4';
+
+ // Two <Video> tags with the same src, mounted 30 seconds apart in the
+ // timeline, advancing frame by frame in lockstep - like a
+ // picture-in-picture or delayed-copy composition during a render.
+ const playheads = [1, 31];
+
+ for (let step = 0; step < 20; step++) {
+ for (const base of playheads) {
+ const timestamp = base + step / FPS;
+ const bank = await manager.requestKeyframeBank({
+ timestamp,
+ videoSampleSink: sink,
+ src,
+ logLevel: 'error',
+ maxCacheSize: 100 * 1024 * 1024,
+ fps: FPS,
+ });
+ if (bank === null) {
+ throw new Error('Expected an active keyframe bank');
+ }
+
+ const frame = await bank.getFrameFromTimestamp(timestamp, FPS);
+ expect(frame?.timestamp).toBeCloseTo(timestamp, 3);
+ }
+ }
+
+ // One seek per playhead. Previously, every request from the playhead that
+ // was further ahead in the file would delete the other playhead's bank,
+ // forcing a re-seek and re-decode from the previous keyframe for every
+ // single frame.
+ expect(seeks).toEqual([1, 31]);
+
+ manager.clearAll('error');
+});
+
+test('banks that are no longer being read still get cleared', async () => {
+ const manager = keyframeManager;
+ manager.clearAll('error');
+ const {sink, seeks} = makeSeekTrackingSink();
+ const src = 'same-video.mp4';
+
+ const request = async (timestamp: number) => {
+ const bank = await manager.requestKeyframeBank({
+ timestamp,
+ videoSampleSink: sink,
+ src,
+ logLevel: 'error',
+ maxCacheSize: 100 * 1024 * 1024,
+ fps: FPS,
+ });
+ if (bank === null) {
+ throw new Error('Expected an active keyframe bank');
+ }
+
+ await bank.getFrameFromTimestamp(timestamp, FPS);
+ };
+
+ // A bank is created at the start of the file, then abandoned: the
+ // playhead seeks far ahead and keeps going.
+ await request(0);
+ for (let step = 0; step < 60; step++) {
+ await request(100 + step / FPS);
+ }
+
+ // Once the first bank has not been touched for more than the recency
+ // window, it is cleared - so going back to it requires a fresh seek.
+ await request(0);
+ expect(seeks).toEqual([0, 100, 0]);
+
+ manager.clearAll('error');
+});
+
+test('a bank is not cleared while it is decoding a frame', async () => {
+ const manager = keyframeManager;
+ manager.clearAll('error');
+ const seeks: number[] = [];
+ let resumeDecoding: () => void = () => undefined;
+ let decodingPaused: () => void = () => undefined;
+ const waitForResume = new Promise<void>((resolve) => {
+ resumeDecoding = resolve;
+ });
+ const waitForDecodingToPause = new Promise<void>((resolve) => {
+ decodingPaused = resolve;
+ });
+ const sink: VideoSampleSink = {
+ getSample() {
+ return Promise.reject(new Error('Not implemented'));
+ },
+ async *samples(start = 0) {
+ seeks.push(start);
+ for (let i = Math.round(Math.floor(start) * FPS); ; i++) {
+ const timestamp = i / FPS;
+ if (start === 0 && timestamp === 0.5) {
+ decodingPaused();
+ await waitForResume;
+ }
+
+ yield makeSample(timestamp);
+ }
+ },
+ async *samplesAtTimestamps() {
+ yield* [];
+ },
+ };
+ const requestBank = (timestamp: number) =>
+ manager.requestKeyframeBank({
+ timestamp,
+ videoSampleSink: sink,
+ src: 'same-video.mp4',
+ logLevel: 'error',
+ maxCacheSize: 100 * 1024 * 1024,
+ fps: FPS,
+ });
+
+ const firstBank = await requestBank(0);
+ if (firstBank === null) {
+ throw new Error('Expected an active keyframe bank');
+ }
+
+ const frameAtOneSecond = firstBank.getFrameFromTimestamp(1, FPS);
+ await waitForDecodingToPause;
+
+ // Age the first bank out of the recency window while it is still decoding.
+ // This exercises the real race: frame extraction runs outside the manager's
+ // request queue, so timestamp clearing can overlap it.
+ for (let i = 0; i < 60; i++) {
+ await requestBank(100);
+ }
+
+ resumeDecoding();
+ expect((await frameAtOneSecond)?.timestamp).toBe(1);
+
+ const reusedBank = await requestBank(1);
+ expect(reusedBank).toBe(firstBank);
+ expect(seeks).toEqual([0, 100]);
+
+ manager.clearAll('error');
+});
diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.ts
index ced44d7346..ec519d705a 100644
--- a/packages/media/src/video-extraction/keyframe-bank.ts
+++ b/packages/media/src/video-extraction/keyframe-bank.ts
@@ -33,6 +33,7 @@ export type KeyframeBank = {
timestamps: number[];
};
getLastUsed: () => number;
+ isBusy: () => boolean;
canSatisfyTimestamp: (timestamp: number) => boolean;
getRangeOfTimestamps: () => {
firstTimestamp: number;
@@ -64,6 +65,7 @@ export const makeKeyframeBank = async ({
let lastUsed = Date.now();
let allocationSize = 0;
+ let pendingOperations = 0;
const getMeasuredDurationOfFrame = (timestamp: number) => {
const index = frameTimestamps.indexOf(timestamp);
@@ -384,12 +386,22 @@ export const makeKeyframeBank = async ({
const keyframeBank: KeyframeBank = {
getFrameFromTimestamp: (timestamp: number, fps: number) => {
- queue = queue.then(() => getFrameFromTimestamp(timestamp, fps));
+ pendingOperations++;
+ queue = queue
+ .then(() => getFrameFromTimestamp(timestamp, fps))
+ .finally(() => {
+ pendingOperations--;
+ });
return queue as Promise<VideoSample | null>;
},
prepareForDeletion,
hasTimestampInSecond: (timestamp: number, fps: number) => {
- queue = queue.then(() => hasTimestampInSecond(timestamp, fps));
+ pendingOperations++;
+ queue = queue
+ .then(() => hasTimestampInSecond(timestamp, fps))
+ .finally(() => {
+ pendingOperations--;
+ });
return queue as Promise<boolean>;
},
addFrame,
@@ -397,6 +409,7 @@ export const makeKeyframeBank = async ({
src,
getOpenFrameCount,
getLastUsed,
+ isBusy: () => pendingOperations > 0,
canSatisfyTimestamp,
getRangeOfTimestamps,
};
diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.ts
index 0cbb069f69..49552f703a 100644
--- a/packages/media/src/video-extraction/keyframe-manager.ts
+++ b/packages/media/src/video-extraction/keyframe-manager.ts
@@ -4,6 +4,17 @@ import {getSafeWindowOfMonotonicity} from '../caches';
import {renderTimestampRange} from '../render-timestamp-range';
import {type KeyframeBank, makeKeyframeBank} from './keyframe-bank';
+// A bank that was returned within the last N requests for the same src is
+// treated as belonging to another active playhead (a second <Video> of the
+// same src, mounted at a different timeline position) and is exempt from
+// timestamp-based clearing. Without this, the layer furthest ahead in the
+// file deletes the other layers' banks on every request, forcing each of
+// them to re-seek and re-decode from the previous keyframe for every frame.
+// Memory is still bounded: banks that age out of the window are cleared
+// here as before, and `ensureToStayUnderMaxCacheSize()` evicts
+// least-recently-used banks whenever the cache exceeds its budget.
+const RECENTLY_USED_REQUEST_COUNT = 50;
+
export const makeKeyframeManager = ({
getTotalCacheStats,
}: {
@@ -12,6 +23,12 @@ export const makeKeyframeManager = ({
let sources: Record<string, KeyframeBank[]> = {};
let disposed = false;
+ // How many times a bank has been requested for a given src, and at which
+ // request each bank was last handed out. Used to detect banks that other
+ // concurrently-mounted components are actively reading from.
+ let requestCountForSrc: Record<string, number> = {};
+ const lastRequestForBank = new WeakMap<KeyframeBank, number>();
+
const addKeyframeBank = ({
src,
bank,
@@ -83,6 +100,11 @@ export const makeKeyframeManager = ({
for (const src in sources) {
for (const bank of sources[src]) {
+ numberOfBanks++;
+ if (bank.isBusy()) {
+ continue;
+ }
+
const index = sources[src].indexOf(bank);
const lastUsed = bank.getLastUsed();
@@ -90,45 +112,36 @@ export const makeKeyframeManager = ({
mostInThePast = lastUsed;
mostInThePastBank = {src, bank, index};
}
-
- numberOfBanks++;
}
}
if (!mostInThePastBank) {
- throw new Error('No keyframe bank found');
+ return {mostInThePastBank: null, numberOfBanks};
}
return {mostInThePastBank, numberOfBanks};
};
const deleteOldestKeyframeBank = (logLevel: LogLevel): {finish: boolean} => {
- const {
- mostInThePastBank: {
- bank: mostInThePastBank,
- src: mostInThePastSrc,
- index: mostInThePastIndex,
- },
- numberOfBanks,
- } = getTheKeyframeBankMostInThePast();
-
- if (numberOfBanks < 2) {
+ const {mostInThePastBank, numberOfBanks} =
+ getTheKeyframeBankMostInThePast();
+
+ if (numberOfBanks < 2 || mostInThePastBank === null) {
return {finish: true};
}
- if (mostInThePastBank) {
- const range = mostInThePastBank.getRangeOfTimestamps();
- const {framesDeleted} = mostInThePastBank.prepareForDeletion(
- logLevel,
- 'deleted oldest keyframe bank to stay under max cache size',
+ const {bank, src, index} = mostInThePastBank;
+ const range = bank.getRangeOfTimestamps();
+ const {framesDeleted} = bank.prepareForDeletion(
+ logLevel,
+ 'deleted oldest keyframe bank to stay under max cache size',
+ );
+ sources[src].splice(index, 1);
+ if (range) {
+ Internals.Log.verbose(
+ {logLevel, tag: '@remotion/media'},
+ `Deleted ${framesDeleted} frames for src ${src} from ${range?.firstTimestamp}sec to ${range?.lastTimestamp}sec to free up memory.`,
);
- sources[mostInThePastSrc].splice(mostInThePastIndex, 1);
- if (range) {
- Internals.Log.verbose(
- {logLevel, tag: '@remotion/media'},
- `Deleted ${framesDeleted} frames for src ${mostInThePastSrc} from ${range?.firstTimestamp}sec to ${range?.lastTimestamp}sec to free up memory.`,
- );
- }
}
return {finish: false};
@@ -186,13 +199,31 @@ export const makeKeyframeManager = ({
}
const banks = sources[src];
+ const currentRequest = requestCountForSrc[src] ?? 0;
for (const bank of banks) {
+ // Decoding happens after the manager hands out a bank and therefore
+ // outside the manager queue. Deleting a busy bank would close frames and
+ // its sample iterator while that operation is still using them.
+ if (bank.isBusy()) {
+ continue;
+ }
+
const range = bank.getRangeOfTimestamps();
if (!range) {
continue;
}
+ // Don't clear (or trim) a bank another playhead is actively reading
+ // from, even if it lies behind this request's timestamp.
+ const lastRequest = lastRequestForBank.get(bank);
+ if (
+ lastRequest !== undefined &&
+ currentRequest - lastRequest < RECENTLY_USED_REQUEST_COUNT
+ ) {
+ continue;
+ }
+
if (range.lastTimestamp < threshold) {
bank.prepareForDeletion(
logLevel,
@@ -309,6 +340,8 @@ export const makeKeyframeManager = ({
return null;
}
+ requestCountForSrc[src] = (requestCountForSrc[src] ?? 0) + 1;
+
ensureToStayUnderMaxCacheSize(logLevel, maxCacheSize);
clearKeyframeBanksBeforeTime({
@@ -325,6 +358,10 @@ export const makeKeyframeManager = ({
logLevel,
});
+ if (keyframeBank) {
+ lastRequestForBank.set(keyframeBank, requestCountForSrc[src]);
+ }
+
return keyframeBank;
};
@@ -341,6 +378,7 @@ export const makeKeyframeManager = ({
}
sources = {};
+ requestCountForSrc = {};
};
const dispose = (logLevel: LogLevel) => {