🎥 Make videos programmatically with React
very nice
Jonny Burgerb90740da6cc7
diff --git a/packages/media/src/extract-frame-and-audio.ts b/packages/media/src/extract-frame-and-audio.tsindex db2cfd54a2..e079531408 100644--- a/packages/media/src/extract-frame-and-audio.ts+++ b/packages/media/src/extract-frame-and-audio.ts@@ -35,7 +35,7 @@ export const extractFrameAndAudio = async ({maxCacheSize: number;}): Promise<ExtractFrameViaBroadcastChannelResult> => {try {- const [frame, audio] = await Promise.all([+ const [video, audio] = await Promise.all([includeVideo? extractFrame({src,@@ -66,71 +66,52 @@ export const extractFrameAndAudio = async ({: null,]);- if (frame?.type === 'cannot-decode') {+ if (video?.type === 'cannot-decode') {return {type: 'cannot-decode',- durationInSeconds: frame.durationInSeconds,+ durationInSeconds: video.durationInSeconds,};}- if (frame?.type === 'unknown-container-format') {+ if (video?.type === 'unknown-container-format') {return {type: 'unknown-container-format'};}- if (frame?.type === 'cannot-decode-alpha') {+ if (video?.type === 'cannot-decode-alpha') {return {type: 'cannot-decode-alpha',- durationInSeconds: frame.durationInSeconds,+ durationInSeconds: video.durationInSeconds,};}- if (frame?.type === 'network-error') {+ if (video?.type === 'network-error') {return {type: 'network-error'};}if (audio === 'unknown-container-format') {- if (frame !== null) {- frame?.frame?.close();- }-return {type: 'unknown-container-format'};}if (audio === 'network-error') {- if (frame !== null) {- frame?.frame?.close();- }-return {type: 'network-error'};}if (audio === 'cannot-decode') {- if (frame?.type === 'success' && frame.frame !== null) {- frame?.frame.close();- }-return {type: 'cannot-decode',durationInSeconds:- frame?.type === 'success' ? frame.durationInSeconds : null,- };- }-- if (!frame?.frame) {- return {- type: 'success',- frame: null,- audio: audio?.data ?? null,- durationInSeconds: audio?.durationInSeconds ?? null,+ video?.type === 'success' ? video.durationInSeconds : null,};}return {type: 'success',- frame: await rotateFrame({- frame: frame.frame.toVideoFrame(),- rotation: frame.frame.rotation,- }),+ frame: video.sample+ ? await rotateFrame({+ frame: video.sample.toVideoFrame(),+ rotation: video.sample.rotation,+ })+ : null,audio: audio?.data ?? null,durationInSeconds: audio?.durationInSeconds ?? null,};diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.tsindex 60048714f3..31c1ba4190 100644--- a/packages/media/src/test/browser.test.ts+++ b/packages/media/src/test/browser.test.ts@@ -4,7 +4,7 @@ import {applyVolume} from '../convert-audiodata/apply-volume';import {extractFrameAndAudio} from '../extract-frame-and-audio';test('Should be able to extract a frame', async () => {- await keyframeManager.clearAll('info');+ keyframeManager.clearAll('info');const result = await extractFrameAndAudio({src: '/bigbuckbunny.mp4',@@ -40,11 +40,8 @@ test('Should be able to extract a frame', async () => {const {audio, frame} = result;assert(audio);-assert(frame);- assert(audio);-// duration = 1 / 30// channels = 2// bits = 16@@ -53,12 +50,12 @@ test('Should be able to extract a frame', async () => {// we round down start and round up durationexpect(audio.data.byteLength).toBe(6404);- const cacheStats = await keyframeManager.getCacheStats();- expect(cacheStats.count).toBe(25);+ const cacheStats = keyframeManager.getCacheStats();+ expect(cacheStats.count).toBe(5);});test('Should be able to extract the last frame', async () => {- await keyframeManager.clearAll('info');+ keyframeManager.clearAll('info');const result = await extractFrameAndAudio({src: '/bigbuckbunny.mp4',@@ -95,15 +92,14 @@ test('Should be able to extract the last frame', async () => {const {audio, frame} = result;assert(frame);-assert(!audio);- const cacheStats = await keyframeManager.getCacheStats();+ const cacheStats = keyframeManager.getCacheStats();expect(cacheStats.count).toBe(1);});test('Should manage the cache', async () => {- await keyframeManager.clearAll('info');+ keyframeManager.clearAll('info');for (let i = 0; i < 50; i++) {await extractFrameAndAudio({@@ -123,9 +119,9 @@ test('Should manage the cache', async () => {});}- const cacheStats = await keyframeManager.getCacheStats();- expect(cacheStats.count).toBe(725);- expect(cacheStats.totalSize).toBe(1002240000);+ const cacheStats = keyframeManager.getCacheStats();+ expect(cacheStats.count).toBe(250);+ expect(cacheStats.totalSize).toBe(345600000);});test('Should be apply volume correctly', async () => {diff --git a/packages/media/src/test/looping.test.ts b/packages/media/src/test/looping.test.tsindex 3318eace4a..4d7f632b0e 100644--- a/packages/media/src/test/looping.test.ts+++ b/packages/media/src/test/looping.test.ts@@ -44,7 +44,7 @@ test(});expect(result.type).toBe('success');assert(result.type === 'success');- outputTimestamps.push(result.frame?.timestamp ?? 0);+ outputTimestamps.push(result.sample?.timestamp ?? 0);}expect(realTimestamps).toEqual([diff --git a/packages/media/src/test/video-after-end.test.ts b/packages/media/src/test/video-after-end.test.tsindex 15191bb75d..670a1638b7 100644--- a/packages/media/src/test/video-after-end.test.ts+++ b/packages/media/src/test/video-after-end.test.ts@@ -3,7 +3,7 @@ import {getMaxVideoCacheSize, keyframeManager} from '../caches';import {extractFrame} from '../video-extraction/extract-frame';test('Should render last frame for timestamps after video end', async () => {- await keyframeManager.clearAll('info');+ keyframeManager.clearAll('info');const result = await extractFrame({src: '/video.mp4',@@ -18,7 +18,7 @@ test('Should render last frame for timestamps after video end', async () => {});assert(result.type === 'success');- expect(result.frame?.timestamp).toBe(9.96);+ expect(result.sample?.timestamp).toBe(9.96);- await keyframeManager.clearAll('info');+ keyframeManager.clearAll('info');});diff --git a/packages/media/src/test/video-non-zero-start.test.ts b/packages/media/src/test/video-non-zero-start.test.tsindex bf5b31335c..292ebc25ad 100644--- a/packages/media/src/test/video-non-zero-start.test.ts+++ b/packages/media/src/test/video-non-zero-start.test.ts@@ -24,21 +24,21 @@ test('Should render first frame for videos starting after timestamp 0', async ()// Should successfully extract (no error thrown)expect(result.type).toBe('success');assert(result.type === 'success');- assert(result.frame, 'Frame should be returned');+ assert(result.sample, 'Frame should be returned');// Frame should have valid dimensions- expect(result.frame.codedWidth).toBe(640);- expect(result.frame.codedHeight).toBe(480);+ expect(result.sample.codedWidth).toBe(640);+ expect(result.sample.codedHeight).toBe(480);// Frame timestamp should be at video start (0.15s), NOT at requested time (0s)// This proves we're returning the first actual frame- expect(result.frame.timestamp).toBeCloseTo(0.15, 2);+ expect(result.sample.timestamp).toBeCloseTo(0.15, 2);// Verify frame has pixel data (not completely black)// testsrc generates a test pattern with colors and gradients- const bufferSize = result.frame.codedWidth * result.frame.codedHeight * 4;+ const bufferSize = result.sample.codedWidth * result.sample.codedHeight * 4;const buffer = new Uint8Array(bufferSize);- await result.frame.copyTo(buffer);+ await result.sample.copyTo(buffer);const hasNonZeroPixels = buffer.some((byte) => byte > 0);expect(hasNonZeroPixels).toBe(true);diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.tsindex 10eecb116c..d3ac35ce3b 100644--- a/packages/media/src/video-extraction/extract-frame.ts+++ b/packages/media/src/video-extraction/extract-frame.ts@@ -7,7 +7,7 @@ import {getTimeInSeconds} from '../get-time-in-seconds';type ExtractFrameResult =| {type: 'success';- frame: VideoSample | null;+ sample: VideoSample | null;durationInSeconds: number | null;}| {type: 'cannot-decode'; durationInSeconds: number | null}@@ -80,7 +80,7 @@ const extractFrameInternal = async ({if (timeInSeconds === null) {return {type: 'success',- frame: null,+ sample: null,durationInSeconds: await sink.getDuration(),};}@@ -108,7 +108,7 @@ const extractFrameInternal = async ({if (!keyframeBank) {return {type: 'success',- frame: null,+ sample: null,durationInSeconds: await sink.getDuration(),};}@@ -117,7 +117,7 @@ const extractFrameInternal = async ({return {type: 'success',- frame,+ sample: frame,durationInSeconds: await sink.getDuration(),};} catch (err) {diff --git a/packages/media/src/video-extraction/get-frames-since-keyframe.ts b/packages/media/src/video-extraction/get-frames-since-keyframe.tsindex d10772b27f..3b7eaf867f 100644--- a/packages/media/src/video-extraction/get-frames-since-keyframe.ts+++ b/packages/media/src/video-extraction/get-frames-since-keyframe.ts@@ -1,4 +1,4 @@-import type {EncodedPacket, InputFormat, UrlSourceOptions} from 'mediabunny';+import type {InputFormat, UrlSourceOptions} from 'mediabunny';import {ALL_FORMATS,AudioSampleSink,@@ -9,10 +9,7 @@ import {VideoSampleSink,WEBM,} from 'mediabunny';-import type {LogLevel} from 'remotion';-import {roundTo4Digits} from '../helpers/round-to-4-digits';import {isNetworkError} from '../is-type-of-error';-import {makeKeyframeBank} from './keyframe-bank';import {rememberActualMatroskaTimestamps} from './remember-actual-matroska-timestamps';type VideoSinks = {@@ -156,43 +153,3 @@ export const getSinks = async (src: string) => {};export type GetSink = Awaited<ReturnType<typeof getSinks>>;--export const getFramesSinceKeyframe = async ({- packetSink,- videoSampleSink,- startPacket,- logLevel,- src,- requestedTimestamp,-}: {- packetSink: EncodedPacketSink;- videoSampleSink: VideoSampleSink;- startPacket: EncodedPacket;- logLevel: LogLevel;- src: string;- requestedTimestamp: number;-}) => {- const nextKeyPacket = await packetSink.getNextKeyPacket(startPacket, {- verifyKeyPackets: true,- });-- const sampleIterator = videoSampleSink.samples(- // The start packet timestamp can be higher than the packets following it- // https://discord.com/channels/809501355504959528/1001500302375125055/1456710188865159343- // e.g. key packet timestamp is 0.08sec, but the next packet is 0.04sec-- // Rounding to 4 digits because of https://github.com/Vanilagy/mediabunny/issues/269- roundTo4Digits(requestedTimestamp),- nextKeyPacket ? roundTo4Digits(nextKeyPacket.timestamp) : Infinity,- );-- const keyframeBank = makeKeyframeBank({- startTimestampInSeconds: roundTo4Digits(requestedTimestamp),- endTimestampInSeconds: nextKeyPacket ? nextKeyPacket.timestamp : Infinity,- sampleIterator,- logLevel,- src,- });-- return keyframeBank;-};diff --git a/packages/media/src/video-extraction/keyframe-bank.ts b/packages/media/src/video-extraction/keyframe-bank.tsindex 704ed0ae22..a27b057307 100644--- a/packages/media/src/video-extraction/keyframe-bank.ts+++ b/packages/media/src/video-extraction/keyframe-bank.ts@@ -1,4 +1,4 @@-import type {VideoSample} from 'mediabunny';+import type {VideoSample, VideoSampleSink} from 'mediabunny';import {Internals, type LogLevel} from 'remotion';import {SAFE_WINDOW_OF_MONOTONICITY} from '../caches';import {roundTo4Digits} from '../helpers/round-to-4-digits';@@ -7,8 +7,6 @@ import {getAllocationSize} from './get-allocation-size';export type KeyframeBank = {src: string;- startTimestampInSeconds: number;- endTimestampInSeconds: number;getFrameFromTimestamp: (timestamp: number) => Promise<VideoSample | null>;prepareForDeletion: (logLevel: LogLevel) => {framesDeleted: number};deleteFramesBeforeTimestamp: ({@@ -19,38 +17,51 @@ export type KeyframeBank = {logLevel: LogLevel;}) => void;hasTimestampInSecond: (timestamp: number) => Promise<boolean>;- addFrame: (frame: VideoSample) => void;+ addFrame: (frame: VideoSample, logLevel: LogLevel) => void;getOpenFrameCount: () => {size: number;timestamps: number[];};getLastUsed: () => number;+ canSatisfyTimestamp: (timestamp: number) => boolean;+ getRangeOfTimestamps: () => {+ firstTimestamp: number;+ lastTimestamp: number;+ } | null;};-export const makeKeyframeBank = ({- startTimestampInSeconds,- endTimestampInSeconds,- sampleIterator,+const BIGGEST_ALLOWED_JUMP_FORWARD_SECONDS = 3;++export const makeKeyframeBank = async ({logLevel: parentLogLevel,src,+ videoSampleSink,+ requestedTimestamp,}: {- startTimestampInSeconds: number;- endTimestampInSeconds: number;- sampleIterator: AsyncGenerator<VideoSample, void, unknown>;logLevel: LogLevel;src: string;+ videoSampleSink: VideoSampleSink;+ requestedTimestamp: number;}) => {- Internals.Log.verbose(- {logLevel: parentLogLevel, tag: '@remotion/media'},- `Creating keyframe bank from ${startTimestampInSeconds}sec to ${endTimestampInSeconds}sec`,+ const sampleIterator = videoSampleSink.samples(+ roundTo4Digits(requestedTimestamp),);+const frames: Record<number, VideoSample> = {};const frameTimestamps: number[] = [];- let lastUsed = Date.now();+ let hasReachedEndOfVideo = false;+ let lastUsed = Date.now();let allocationSize = 0;+ const deleteFrameAtTimestamp = (timestamp: number) => {+ allocationSize -= getAllocationSize(frames[timestamp]);+ frameTimestamps.splice(frameTimestamps.indexOf(timestamp), 1);+ frames[timestamp].close();+ delete frames[timestamp];+ };+const deleteFramesBeforeTimestamp = ({logLevel,timestampInSeconds,@@ -60,11 +71,13 @@ export const makeKeyframeBank = ({}) => {const deletedTimestamps = [];for (const frameTimestamp of frameTimestamps.slice()) {- const isLast =- frameTimestamp === frameTimestamps[frameTimestamps.length - 1];// Don't delete the last frame, since it may be the last one in the video!- if (isLast) {- continue;+ if (hasReachedEndOfVideo) {+ const isLast =+ frameTimestamp === frameTimestamps[frameTimestamps.length - 1];+ if (isLast) {+ continue;+ }}if (frameTimestamp < timestampInSeconds) {@@ -72,11 +85,7 @@ export const makeKeyframeBank = ({continue;}- allocationSize -= getAllocationSize(frames[frameTimestamp]);-- frameTimestamps.splice(frameTimestamps.indexOf(frameTimestamp), 1);- frames[frameTimestamp].close();- delete frames[frameTimestamp];+ deleteFrameAtTimestamp(frameTimestamp);deletedTimestamps.push(frameTimestamp);}}@@ -96,7 +105,8 @@ export const makeKeyframeBank = ({}const lastFrame = frames[lastFrameTimestamp];- // Don't decode more, will probably have to re-decode everything+ // Last frame is unavailable, we return true to not continue the loop,+ // since we probably have to re-decode everythingif (!lastFrame) {return true;}@@ -107,12 +117,9 @@ export const makeKeyframeBank = ({);};- const addFrame = (frame: VideoSample) => {+ const addFrame = (frame: VideoSample, logLevel: LogLevel) => {if (frames[frame.timestamp]) {- allocationSize -= getAllocationSize(frames[frame.timestamp]);- frameTimestamps.splice(frameTimestamps.indexOf(frame.timestamp), 1);- frames[frame.timestamp].close();- delete frames[frame.timestamp];+ deleteFrameAtTimestamp(frame.timestamp);}frames[frame.timestamp] = frame;@@ -120,17 +127,25 @@ export const makeKeyframeBank = ({allocationSize += getAllocationSize(frame);lastUsed = Date.now();+ Internals.Log.trace(+ {logLevel, tag: '@remotion/media'},+ `Added frame at ${frame.timestamp}sec to bank`,+ );};- const ensureEnoughFramesForTimestamp = async (timestampInSeconds: number) => {+ const ensureEnoughFramesForTimestamp = async (+ timestampInSeconds: number,+ logLevel: LogLevel,+ ) => {while (!hasDecodedEnoughForTimestamp(timestampInSeconds)) {const sample = await sampleIterator.next();if (sample.value) {- addFrame(sample.value);+ addFrame(sample.value, logLevel);}if (sample.done) {+ hasReachedEndOfVideo = true;break;}@@ -158,12 +173,14 @@ export const makeKeyframeBank = ({// If we request a timestamp after the end of the video, return the last frame// same behavior as <video>if (- roundTo4Digits(adjustedTimestamp) > roundTo4Digits(endTimestampInSeconds)+ hasReachedEndOfVideo &&+ roundTo4Digits(adjustedTimestamp) >+ roundTo4Digits(frameTimestamps[frameTimestamps.length - 1])) {- adjustedTimestamp = endTimestampInSeconds;+ adjustedTimestamp = frameTimestamps[frameTimestamps.length - 1];}- await ensureEnoughFramesForTimestamp(adjustedTimestamp);+ await ensureEnoughFramesForTimestamp(adjustedTimestamp, parentLogLevel);for (let i = frameTimestamps.length - 1; i >= 0; i--) {const sample = frames[frameTimestamps[i]];@@ -189,64 +206,114 @@ export const makeKeyframeBank = ({return (await getFrameFromTimestamp(timestamp)) !== null;};- const prepareForDeletion = (logLevel: LogLevel) => {- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Preparing for deletion of keyframe bank from ${startTimestampInSeconds}sec to ${endTimestampInSeconds}sec`,- );- // Cleanup frames that have been extracted that might not have been retrieved yet- sampleIterator.return().then((result) => {- if (result.value) {- result.value.close();- }+ const getOpenFrameCount = () => {+ return {+ size: allocationSize,+ timestamps: frameTimestamps,+ };+ };++ const getLastUsed = () => {+ return lastUsed;+ };++ let queue = Promise.resolve<unknown>(undefined);++ const firstFrame = await sampleIterator.next();+ if (!firstFrame.value) {+ throw new Error('No first frame found');+ }++ const startTimestampInSeconds = firstFrame.value.timestamp;+ addFrame(firstFrame.value, parentLogLevel);++ Internals.Log.verbose(+ {logLevel: parentLogLevel, tag: '@remotion/media'},+ `Creating keyframe bank from ${startTimestampInSeconds}sec`,+ );+ const getRangeOfTimestamps = () => {+ if (frameTimestamps.length === 0) {return null;- });+ }++ return {+ firstTimestamp: frameTimestamps[0],+ lastTimestamp: frameTimestamps[frameTimestamps.length - 1],+ };+ };++ const prepareForDeletion = (logLevel: LogLevel) => {+ const range = getRangeOfTimestamps();+ if (range) {+ Internals.Log.verbose(+ {logLevel, tag: '@remotion/media'},+ `Preparing for deletion of keyframe bank from ${range?.firstTimestamp}sec to ${range?.lastTimestamp}sec`,+ );+ }let framesDeleted = 0;- for (const frameTimestamp of frameTimestamps) {+ for (const frameTimestamp of frameTimestamps.slice()) {if (!frames[frameTimestamp]) {continue;}- allocationSize -= getAllocationSize(frames[frameTimestamp]);- frames[frameTimestamp].close();- delete frames[frameTimestamp];+ deleteFrameAtTimestamp(frameTimestamp);framesDeleted++;}+ // Cleanup frames that have been extracted that might not have been retrieved yet+ // Must be called after closing the frames+ sampleIterator.return();+frameTimestamps.length = 0;return {framesDeleted};};- const getOpenFrameCount = () => {- return {- size: allocationSize,- timestamps: frameTimestamps,- };- };+ const canSatisfyTimestamp = (timestamp: number) => {+ if (frameTimestamps.length === 0) {+ return false;+ }- const getLastUsed = () => {- return lastUsed;- };+ const roundedTimestamp = roundTo4Digits(timestamp);+ const firstFrameTimestamp = roundTo4Digits(frameTimestamps[0]);+ const lastFrameTimestamp = roundTo4Digits(+ frameTimestamps[frameTimestamps.length - 1],+ );- let queue = Promise.resolve<unknown>(undefined);+ if (hasReachedEndOfVideo && roundedTimestamp > lastFrameTimestamp) {+ return true;+ }++ if (+ roundedTimestamp < firstFrameTimestamp ||+ roundedTimestamp + BIGGEST_ALLOWED_JUMP_FORWARD_SECONDS >+ lastFrameTimestamp+ ) {+ return false;+ }++ return true;+ };const keyframeBank: KeyframeBank = {- startTimestampInSeconds,- endTimestampInSeconds,getFrameFromTimestamp: (timestamp: number) => {queue = queue.then(() => getFrameFromTimestamp(timestamp));return queue as Promise<VideoSample | null>;},prepareForDeletion,- hasTimestampInSecond,+ hasTimestampInSecond: (timestamp: number) => {+ queue = queue.then(() => hasTimestampInSecond(timestamp));+ return queue as Promise<boolean>;+ },addFrame,deleteFramesBeforeTimestamp,src,getOpenFrameCount,getLastUsed,+ canSatisfyTimestamp,+ getRangeOfTimestamps,};return keyframeBank;diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.tsindex df8e9e7567..cefecde400 100644--- a/packages/media/src/video-extraction/keyframe-manager.ts+++ b/packages/media/src/video-extraction/keyframe-manager.ts@@ -3,34 +3,23 @@ import {Internals, type LogLevel} from 'remotion';import {canBrowserUseWebGl2} from '../browser-can-use-webgl2';import {getTotalCacheStats, SAFE_WINDOW_OF_MONOTONICITY} from '../caches';import {renderTimestampRange} from '../render-timestamp-range';-import {getFramesSinceKeyframe} from './get-frames-since-keyframe';-import {type KeyframeBank} from './keyframe-bank';+import {type KeyframeBank, makeKeyframeBank} from './keyframe-bank';export const makeKeyframeManager = () => {- // src => {[startTimestampInSeconds]: KeyframeBank- const sources: Record<string, Record<number, Promise<KeyframeBank>>> = {};+ let sources: Record<string, KeyframeBank[]> = {};- const addKeyframeBank = ({- src,- bank,- startTimestampInSeconds,- }: {- src: string;- bank: Promise<KeyframeBank>;- startTimestampInSeconds: number;- }) => {- sources[src] = sources[src] ?? {};- sources[src][startTimestampInSeconds] = bank;+ const addKeyframeBank = ({src, bank}: {src: string; bank: KeyframeBank}) => {+ sources[src] = sources[src] ?? [];+ sources[src].push(bank);};- const logCacheStats = async (logLevel: LogLevel) => {+ const logCacheStats = (logLevel: LogLevel) => {let count = 0;let totalSize = 0;for (const src in sources) {- for (const bank in sources[src]) {- const v = await sources[src][bank];- const {size, timestamps} = v.getOpenFrameCount();+ for (const bank of sources[src]) {+ const {size, timestamps} = bank.getOpenFrameCount();count += timestamps.length;totalSize += size;if (size === 0) {@@ -50,14 +39,13 @@ export const makeKeyframeManager = () => {);};- const getCacheStats = async () => {+ const getCacheStats = () => {let count = 0;let totalSize = 0;for (const src in sources) {- for (const bank in sources[src]) {- const v = await sources[src][bank];- const {timestamps, size} = v.getOpenFrameCount();+ for (const bank of sources[src]) {+ const {timestamps, size} = bank.getOpenFrameCount();count += timestamps.length;totalSize += size;if (size === 0) {@@ -76,13 +64,13 @@ export const makeKeyframeManager = () => {let numberOfBanks = 0;for (const src in sources) {- for (const b in sources[src]) {- const bank = await sources[src][b];+ for (const bank of sources[src]) {+ const index = sources[src].indexOf(bank);const lastUsed = bank.getLastUsed();if (mostInThePast === null || lastUsed < mostInThePast) {mostInThePast = lastUsed;- mostInThePastBank = {src, bank};+ mostInThePastBank = {src, bank, index};}numberOfBanks++;@@ -100,7 +88,11 @@ export const makeKeyframeManager = () => {logLevel: LogLevel,): Promise<{finish: boolean}> => {const {- mostInThePastBank: {bank: mostInThePastBank, src: mostInThePastSrc},+ mostInThePastBank: {+ bank: mostInThePastBank,+ src: mostInThePastSrc,+ index: mostInThePastIndex,+ },numberOfBanks,} = await getTheKeyframeBankMostInThePast();@@ -109,14 +101,15 @@ export const makeKeyframeManager = () => {}if (mostInThePastBank) {+ const range = mostInThePastBank.getRangeOfTimestamps();const {framesDeleted} = mostInThePastBank.prepareForDeletion(logLevel);- delete sources[mostInThePastSrc][- mostInThePastBank.startTimestampInSeconds- ];- Internals.Log.verbose(- {logLevel, tag: '@remotion/media'},- `Deleted ${framesDeleted} frames for src ${mostInThePastSrc} from ${mostInThePastBank.startTimestampInSeconds}sec to ${mostInThePastBank.endTimestampInSeconds}sec to free up memory.`,- );+ delete sources[mostInThePastSrc][mostInThePastIndex];+ 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};@@ -156,7 +149,7 @@ export const makeKeyframeManager = () => {}};- const clearKeyframeBanksBeforeTime = async ({+ const clearKeyframeBanksBeforeTime = ({timestampInSeconds,src,logLevel,@@ -171,19 +164,24 @@ export const makeKeyframeManager = () => {return;}- const banks = Object.keys(sources[src]);+ const banks = sources[src];- for (const startTimeInSeconds of banks) {- const bank = await sources[src][startTimeInSeconds as unknown as number];- const {endTimestampInSeconds, startTimestampInSeconds} = bank;+ for (const bank of banks) {+ const range = bank.getRangeOfTimestamps();+ if (!range) {+ continue;+ }++ const {firstTimestamp} = range;- if (endTimestampInSeconds < threshold) {+ if (firstTimestamp < threshold) {bank.prepareForDeletion(logLevel);Internals.Log.verbose({logLevel, tag: '@remotion/media'},- `[Video] Cleared frames for src ${src} from ${startTimestampInSeconds}sec to ${endTimestampInSeconds}sec`,+ `[Video] Cleared frames for src ${src} from ${firstTimestamp}sec to ${firstTimestamp}sec`,);- delete sources[src][startTimeInSeconds as unknown as number];+ const bankIndex = banks.indexOf(bank);+ delete sources[src][bankIndex];} else {bank.deleteFramesBeforeTimestamp({timestampInSeconds: threshold,@@ -192,7 +190,9 @@ export const makeKeyframeManager = () => {}}- await logCacheStats(logLevel);+ sources[src] = sources[src].filter((bank) => bank !== undefined);++ logCacheStats(logLevel);};const getKeyframeBankOrRefetch = async ({@@ -211,11 +211,11 @@ export const makeKeyframeManager = () => {// Try to get the keypacket at the requested timestamp.// If it returns null (timestamp is before the first keypacket), fall back to the first packet.// This matches mediabunny's internal behavior and handles videos that don't start at timestamp 0.- const startPacket =- (await packetSink.getKeyPacket(timestamp, {- verifyKeyPackets: true,- })) ?? (await packetSink.getFirstPacket({verifyKeyPackets: true}));+ const startPacket = await packetSink.getFirstPacket({+ verifyKeyPackets: true,+ });+ // TODO: Should move out of this functionconst hasAlpha = startPacket?.sideData.alpha;if (hasAlpha && !canBrowserUseWebGl2()) {return 'has-alpha';@@ -231,27 +231,27 @@ export const makeKeyframeManager = () => {// The start packet timestamp can be higher than the packets following it// https://discord.com/channels/809501355504959528/1001500302375125055/1456710188865159343// e.g. key packet timestamp is 0.08sec, but the next packet is 0.04sec- const startTimestampInSeconds = Math.min(timestamp, startPacket.timestamp);- const existingBank = sources[src]?.[startTimestampInSeconds];+ const existingBanks = sources[src] ?? [];+ const existingBank = existingBanks?.find((bank) =>+ bank.canSatisfyTimestamp(timestamp),+ );// Bank does not yet exist, we need to fetchif (!existingBank) {- const newKeyframeBank = getFramesSinceKeyframe({- packetSink,+ const newKeyframeBank = await makeKeyframeBank({videoSampleSink,- startPacket,logLevel,src,- requestedTimestamp: startTimestampInSeconds,+ requestedTimestamp: timestamp,});- addKeyframeBank({src, bank: newKeyframeBank, startTimestampInSeconds});+ addKeyframeBank({src, bank: newKeyframeBank});return newKeyframeBank;}// Bank exists and still has the frame we want- if (await (await existingBank).hasTimestampInSecond(timestamp)) {+ if (await existingBank.hasTimestampInSecond(timestamp)) {return existingBank;}@@ -262,20 +262,18 @@ export const makeKeyframeManager = () => {// Bank exists but frames have already been evicted!// First delete it entirely- await (await existingBank).prepareForDeletion(logLevel);- delete sources[src][startTimestampInSeconds];+ existingBank.prepareForDeletion(logLevel);+ sources[src] = sources[src].filter((bank) => bank !== existingBank);// Then refetch- const replacementKeybank = getFramesSinceKeyframe({- packetSink,+ const replacementKeybank = await makeKeyframeBank({videoSampleSink,- startPacket,+ requestedTimestamp: timestamp,logLevel,src,- requestedTimestamp: timestamp,});- addKeyframeBank({src, bank: replacementKeybank, startTimestampInSeconds});+ addKeyframeBank({src, bank: replacementKeybank});return replacementKeybank;};@@ -314,19 +312,19 @@ export const makeKeyframeManager = () => {return keyframeBank;};- const clearAll = async (logLevel: LogLevel) => {+ const clearAll = (logLevel: LogLevel) => {const srcs = Object.keys(sources);for (const src of srcs) {- const banks = Object.keys(sources[src]);-- for (const startTimeInSeconds of banks) {- const bank =- await sources[src][startTimeInSeconds as unknown as number];+ const banks = sources[src];+ for (const bank of banks) {bank.prepareForDeletion(logLevel);- delete sources[src][startTimeInSeconds as unknown as number];}++ sources[src] = [];}++ sources = {};};let queue = Promise.resolve<unknown>(undefined);