Skip to content

🎥 Make videos programmatically with React

manage caceh

Jonny Burgera4d3c7c0e7f8
diff --git a/packages/media/src/audio-extraction/audio-iterator.ts b/packages/media/src/audio-extraction/audio-iterator.ts
index 8dd5dac3fb..c0f3fd34d1 100644
--- a/packages/media/src/audio-extraction/audio-iterator.ts
+++ b/packages/media/src/audio-extraction/audio-iterator.ts
@@ -1,4 +1,5 @@
import type {AudioSample, AudioSampleSink} from 'mediabunny';
+import {SAFE_BACK_WINDOW_IN_SECONDS} from '../caches';
import type {LogLevel} from '../log';
import {Log} from '../log';
import type {RememberActualMatroskaTimestamps} from '../video-extraction/remember-actual-matroska-timestamps';
@@ -38,7 +39,11 @@ export const makeAudioIterator = ({
const cache = makeAudioCache();
+ let lastUsed = Date.now();
+
const getNextSample = async () => {
+ lastUsed = Date.now();
+
const {value: sample, done} = await sampleIterator.next();
if (done) {
fullDuration = cache.getNewestTimestamp() ?? null;
@@ -64,13 +69,15 @@ export const makeAudioIterator = ({
};
const getSamples = async (timestamp: number, durationInSeconds: number) => {
+ lastUsed = Date.now();
+
if (fullDuration !== null && timestamp > fullDuration) {
return [];
}
// Clear all samples before the timestamp
// Do this in the while loop because samples might start from 0
- cache.clearBeforeThreshold(timestamp - 1);
+ cache.clearBeforeThreshold(timestamp - SAFE_BACK_WINDOW_IN_SECONDS);
const samples: AudioSample[] = cache.getSamples(
timestamp,
@@ -109,6 +116,13 @@ export const makeAudioIterator = ({
);
};
+ const getCacheStats = () => {
+ return {
+ count: cache.getOpenTimestamps().length,
+ size: cache.getOpenTimestamps().reduce((acc, t) => acc + t, 0),
+ };
+ };
+
const canSatisfyRequestedTime = (timestamp: number) => {
const oldestTimestamp = cache.getOldestTimestamp() ?? startTimestamp;
if (fullDuration !== null && timestamp > fullDuration) {
@@ -120,6 +134,16 @@ export const makeAudioIterator = ({
);
};
+ const prepareForDeletion = async () => {
+ cache.deleteAll();
+ const {value} = await sampleIterator.return();
+ if (value) {
+ value.close();
+ }
+
+ fullDuration = null;
+ };
+
let op = Promise.resolve<AudioSample[]>([]);
return {
@@ -134,6 +158,9 @@ export const makeAudioIterator = ({
},
canSatisfyRequestedTime,
logOpenFrames,
+ getCacheStats,
+ getLastUsed: () => lastUsed,
+ prepareForDeletion,
};
};
diff --git a/packages/media/src/audio-extraction/audio-manager.ts b/packages/media/src/audio-extraction/audio-manager.ts
index 4d029b256f..e8ac4f2525 100644
--- a/packages/media/src/audio-extraction/audio-manager.ts
+++ b/packages/media/src/audio-extraction/audio-manager.ts
@@ -1,4 +1,5 @@
import type {AudioSampleSink} from 'mediabunny';
+import {getTotalCacheStats, MAX_CACHE_SIZE} from '../caches';
import type {RememberActualMatroskaTimestamps} from '../video-extraction/remember-actual-matroska-timestamps';
import type {AudioSampleIterator} from './audio-iterator';
import {makeAudioIterator} from './audio-iterator';
@@ -32,6 +33,28 @@ export const makeAudioManager = () => {
return iterator;
};
+ const getIteratorMostInThePast = () => {
+ let mostInThePast = null;
+ let mostInThePastIterator = null;
+ for (const iterator of iterators) {
+ const lastUsed = iterator.getLastUsed();
+ if (mostInThePast === null || lastUsed < mostInThePast) {
+ mostInThePast = lastUsed;
+ mostInThePastIterator = iterator;
+ }
+ }
+
+ return mostInThePastIterator;
+ };
+
+ const deleteOldestIterator = async () => {
+ const iterator = getIteratorMostInThePast();
+ if (iterator) {
+ await iterator.prepareForDeletion();
+ iterators.splice(iterators.indexOf(iterator), 1);
+ }
+ };
+
const getIterator = async ({
src,
timeInSeconds,
@@ -45,6 +68,10 @@ export const makeAudioManager = () => {
isMatroska: boolean;
actualMatroskaTimestamps: RememberActualMatroskaTimestamps;
}) => {
+ while ((await getTotalCacheStats()).totalSize > MAX_CACHE_SIZE) {
+ await deleteOldestIterator();
+ }
+
for (const iterator of iterators) {
if (
iterator.src === src &&
@@ -64,8 +91,22 @@ export const makeAudioManager = () => {
});
};
+ const getCacheStats = () => {
+ let totalCount = 0;
+ let totalSize = 0;
+ for (const iterator of iterators) {
+ const {count, size} = iterator.getCacheStats();
+ totalCount += count;
+ totalSize += size;
+ }
+
+ return {count: totalCount, totalSize};
+ };
+
return {
makeIterator,
getIterator,
+ getCacheStats,
+ getIteratorMostInThePast,
};
};
diff --git a/packages/media/src/audio-extraction/extract-audio.ts b/packages/media/src/audio-extraction/extract-audio.ts
index 830afe235d..4422898db9 100644
--- a/packages/media/src/audio-extraction/extract-audio.ts
+++ b/packages/media/src/audio-extraction/extract-audio.ts
@@ -1,3 +1,4 @@
+import {audioManager} from '../caches';
import {combineAudioDataAndClosePrevious} from '../convert-audiodata/combine-audiodata';
import type {PcmS16AudioData} from '../convert-audiodata/convert-audiodata';
import {convertAudioData} from '../convert-audiodata/convert-audiodata';
@@ -8,9 +9,6 @@ import {
import type {LogLevel} from '../log';
import {sinkPromises} from '../video-extraction/extract-frame';
import {getSinks} from '../video-extraction/get-frames-since-keyframe';
-import {makeAudioManager} from './audio-manager';
-
-const audioManager = makeAudioManager();
export const extractAudio = async ({
src,
diff --git a/packages/media/src/caches.ts b/packages/media/src/caches.ts
new file mode 100644
index 0000000000..46fda30722
--- /dev/null
+++ b/packages/media/src/caches.ts
@@ -0,0 +1,20 @@
+import {makeAudioManager} from './audio-extraction/audio-manager';
+import {makeKeyframeManager} from './video-extraction/keyframe-manager';
+
+export const MAX_CACHE_SIZE = 1000 * 1000 * 1000; // 1GB
+// TODO: make it dependent on the fps and concurrency
+export const SAFE_BACK_WINDOW_IN_SECONDS = 1;
+
+export const keyframeManager = makeKeyframeManager();
+export const audioManager = makeAudioManager();
+
+export const getTotalCacheStats = async () => {
+ const keyframeManagerCacheStats = await keyframeManager.getCacheStats();
+ const audioManagerCacheStats = audioManager.getCacheStats();
+
+ return {
+ count: keyframeManagerCacheStats.count + audioManagerCacheStats.count,
+ totalSize:
+ keyframeManagerCacheStats.totalSize + audioManagerCacheStats.totalSize,
+ };
+};
diff --git a/packages/media/src/test/browser.test.ts b/packages/media/src/test/browser.test.ts
index 25ec6d7dbb..e48c292e87 100644
--- a/packages/media/src/test/browser.test.ts
+++ b/packages/media/src/test/browser.test.ts
@@ -1,6 +1,6 @@
import {assert, expect, test} from 'vitest';
+import {keyframeManager} from '../caches';
import {extractFrameAndAudio} from '../extract-frame-and-audio';
-import {keyframeManager} from '../video-extraction/extract-frame';
test('Should be able to extract a frame', async () => {
await keyframeManager.clearAll();
diff --git a/packages/media/src/video-extraction/extract-frame.ts b/packages/media/src/video-extraction/extract-frame.ts
index 5578ca9e66..827ca4b709 100644
--- a/packages/media/src/video-extraction/extract-frame.ts
+++ b/packages/media/src/video-extraction/extract-frame.ts
@@ -1,8 +1,7 @@
+import {keyframeManager} from '../caches';
import type {LogLevel} from '../log';
import {getSinks, type GetSink} from './get-frames-since-keyframe';
-import {makeKeyframeManager} from './keyframe-manager';
-export const keyframeManager = makeKeyframeManager();
export const sinkPromises: Record<string, Promise<GetSink>> = {};
export const extractFrame = async ({
diff --git a/packages/media/src/video-extraction/keyframe-manager.ts b/packages/media/src/video-extraction/keyframe-manager.ts
index 3fb3c0513b..d019d4802d 100644
--- a/packages/media/src/video-extraction/keyframe-manager.ts
+++ b/packages/media/src/video-extraction/keyframe-manager.ts
@@ -1,11 +1,14 @@
import type {EncodedPacketSink, VideoSampleSink} from 'mediabunny';
+import {
+ getTotalCacheStats,
+ MAX_CACHE_SIZE,
+ SAFE_BACK_WINDOW_IN_SECONDS,
+} from '../caches';
import type {LogLevel} from '../log';
import {Log} from '../log';
import {getFramesSinceKeyframe} from './get-frames-since-keyframe';
import {type KeyframeBank} from './keyframe-bank';
-const MAX_CACHE_SIZE = 1000 * 1000 * 1000; // 1GB
-
export const makeKeyframeManager = () => {
// src => {[startTimestampInSeconds]: KeyframeBank
const sources: Record<string, Record<number, Promise<KeyframeBank>>> = {};
@@ -26,6 +29,7 @@ export const makeKeyframeManager = () => {
const logCacheStats = async (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];
@@ -52,6 +56,7 @@ export const makeKeyframeManager = () => {
const getCacheStats = async () => {
let count = 0;
let totalSize = 0;
+
for (const src in sources) {
for (const bank in sources[src]) {
const v = await sources[src][bank];
@@ -90,24 +95,28 @@ export const makeKeyframeManager = () => {
return mostInThePastBank;
};
+ const deleteOldestKeyframeBank = async (logLevel: LogLevel) => {
+ const {bank: mostInThePastBank, src: mostInThePastSrc} =
+ await getTheKeyframeBankMostInThePast();
+
+ if (mostInThePastBank) {
+ await mostInThePastBank.prepareForDeletion();
+ delete sources[mostInThePastSrc][
+ mostInThePastBank.startTimestampInSeconds
+ ];
+ Log.verbose(
+ logLevel,
+ `[Video] Deleted frames for src ${mostInThePastSrc} from ${mostInThePastBank.startTimestampInSeconds}sec to ${mostInThePastBank.endTimestampInSeconds}sec to free up memory.`,
+ );
+ }
+ };
+
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,
- `[Video] Deleted frames for src ${mostInThePastSrc} from ${mostInThePastBank.startTimestampInSeconds}sec to ${mostInThePastBank.endTimestampInSeconds}sec to free up memory.`,
- );
- }
+ let cacheStats = await getTotalCacheStats();
- cacheStats = await getCacheStats();
+ while (cacheStats.totalSize > MAX_CACHE_SIZE) {
+ await deleteOldestKeyframeBank(logLevel);
+ cacheStats = await getTotalCacheStats();
}
};
@@ -120,8 +129,6 @@ export const makeKeyframeManager = () => {
src: string;
logLevel: LogLevel;
}) => {
- // TODO: make it dependent on the fps and concurrency
- const SAFE_BACK_WINDOW_IN_SECONDS = 1;
const threshold = timestampInSeconds - SAFE_BACK_WINDOW_IN_SECONDS;
if (!sources[src]) {