🎥 Make videos programmatically with React
limit cache to 1 second
Jonny Burger75b015ea3802
diff --git a/packages/video/src/keyframe-bank.ts b/packages/video/src/keyframe-bank.tsindex a211a66d8a..6278f11d93 100644--- a/packages/video/src/keyframe-bank.ts+++ b/packages/video/src/keyframe-bank.ts@@ -22,6 +22,7 @@ export type KeyframeBank = {size: number;timestamps: number[];};+ getLastUsed: () => number;};// Round to only 4 digits, because WebM has a timescale of 1_000, e.g. framer.webm@@ -41,6 +42,8 @@ export const makeKeyframeBank = ({const frames: Record<number, VideoSample> = {};const frameTimestamps: number[] = [];+ let lastUsed = Date.now();+let alloctionSize = 0;const hasDecodedEnoughForTimestamp = (timestamp: number) => {@@ -65,6 +68,8 @@ export const makeKeyframeBank = ({frames[frame.timestamp] = frame;frameTimestamps.push(frame.timestamp);alloctionSize += frame.allocationSize();++ lastUsed = Date.now();};const ensureEnoughFramesForTimestamp = async (timestamp: number) => {@@ -79,11 +84,15 @@ export const makeKeyframeBank = ({break;}}++ lastUsed = Date.now();};const getFrameFromTimestamp = async (timestampInSeconds: number,): Promise<VideoSample | null> => {+ lastUsed = Date.now();+if (timestampInSeconds < startTimestampInSeconds) {return Promise.reject(new Error(@@ -183,6 +192,10 @@ export const makeKeyframeBank = ({};};+ const getLastUsed = () => {+ return lastUsed;+ };+const keyframeBank: KeyframeBank = {startTimestampInSeconds,endTimestampInSeconds,@@ -192,6 +205,7 @@ export const makeKeyframeBank = ({addFrame,deleteFramesBeforeTimestamp,getOpenFrameCount,+ getLastUsed,};return keyframeBank;diff --git a/packages/video/src/keyframe-manager.ts b/packages/video/src/keyframe-manager.tsindex 7292be0982..f2eb54e543 100644--- a/packages/video/src/keyframe-manager.ts+++ b/packages/video/src/keyframe-manager.ts@@ -4,6 +4,8 @@ import {type KeyframeBank} from './keyframe-bank';import type {LogLevel} from './log';import {Log} from './log';+const MAX_CACHE_SIZE = 1000 * 1000 * 1000; // 1GB+export const makeKeyframeManager = () => {// src => {[startTimestampInSeconds]: KeyframeBankconst sources: Record<string, Record<number, Promise<KeyframeBank>>> = {};@@ -65,6 +67,50 @@ export const makeKeyframeManager = () => {return {count, totalSize};};+ const getTheKeyframeBankMostInThePast = async () => {+ let mostInThePast = null;+ let mostInThePastBank = null;++ for (const src in sources) {+ for (const b in sources[src]) {+ const bank = await sources[src][b];++ const lastUsed = bank.getLastUsed();+ if (mostInThePast === null || lastUsed < mostInThePast) {+ mostInThePast = lastUsed;+ mostInThePastBank = {src, bank};+ }+ }+ }++ if (!mostInThePastBank) {+ throw new Error('No keyframe bank found');+ }++ return mostInThePastBank;+ };++ const ensureToStayUnderMaxCacheSize = async (logLevel: LogLevel) => {+ let cacheStats = await getCacheStats();+ while (cacheStats.totalSize > MAX_CACHE_SIZE) {+ const {bank: mostInThePastBank, src: mostInThePastSrc} =+ await getTheKeyframeBankMostInThePast();++ if (mostInThePastBank) {+ await mostInThePastBank.prepareForDeletion();+ delete sources[mostInThePastSrc][+ mostInThePastBank.startTimestampInSeconds+ ];+ Log.verbose(+ logLevel,+ `[NewVideo] Deleted frames for src ${mostInThePastSrc} from ${mostInThePastBank.startTimestampInSeconds}sec to ${mostInThePastBank.endTimestampInSeconds}sec to free up memory.`,+ );+ }++ cacheStats = await getCacheStats();+ }+ };+const clearKeyframeBanksBeforeTime = async ({timestampInSeconds,src,@@ -78,8 +124,6 @@ export const makeKeyframeManager = () => {const SAFE_BACK_WINDOW_IN_SECONDS = 1;const threshold = timestampInSeconds - SAFE_BACK_WINDOW_IN_SECONDS;- // TODO: Delete banks of other sources-if (!sources[src]) {return;}@@ -88,13 +132,13 @@ export const makeKeyframeManager = () => {for (const startTimeInSeconds of banks) {const bank = await sources[src][startTimeInSeconds as unknown as number];- const {endTimestampInSeconds} = bank;+ const {endTimestampInSeconds, startTimestampInSeconds} = bank;if (endTimestampInSeconds < threshold) {await bank.prepareForDeletion();Log.verbose(logLevel,- `[NewVideo] Cleared frames for src ${src} from ${bank.startTimestampInSeconds}sec to ${bank.endTimestampInSeconds}sec`,+ `[NewVideo] Cleared frames for src ${src} from ${startTimestampInSeconds}sec to ${endTimestampInSeconds}sec`,);delete sources[src][startTimeInSeconds as unknown as number];} else {@@ -186,6 +230,8 @@ export const makeKeyframeManager = () => {src: string;logLevel: LogLevel;}) => {+ await ensureToStayUnderMaxCacheSize(logLevel);+await clearKeyframeBanksBeforeTime({timestampInSeconds: timestamp,src,diff --git a/packages/video/src/test/browser.test.ts b/packages/video/src/test/browser.test.tsindex db01482bd7..b76f24ce4f 100644--- a/packages/video/src/test/browser.test.ts+++ b/packages/video/src/test/browser.test.ts@@ -31,16 +31,17 @@ test('Should be able to extract a frame', async () => {test('Should manage the cache', async () => {await keyframeManager.clearAll();- for (let i = 0; i < 40; i++) {+ for (let i = 0; i < 50; i++) {await extractFrameAndAudio({src: `/bigbuckbunny.mp4?i=${i}`,timeInSeconds: 1,durationInSeconds: 1 / 30,- logLevel: 'info',+ logLevel: 'verbose',includeAudio: true,});}const cacheStats = await keyframeManager.getCacheStats();- expect(cacheStats.count).toBe(1000);+ expect(cacheStats.count).toBe(725);+ expect(cacheStats.totalSize).toBe(1002240000);});